Re: True of False

2007-09-27 Thread Casey
On Sep 27, 12:48 pm, "Simon Brunning" <[EMAIL PROTECTED]>
wrote:
> On 9/27/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> > I tried writing a true and false If statement and didn't get
> > anything?  I read some previous posts, but I must be missing
> > something.  I just tried something easy:
>
> > a = ["a", "b", "c", "d", "e", "f"]
>
> > if "c" in a == True:
> >  Print "Yes"
>
> > When I run this, it runs, but nothing prints.  What am I doing wrong?
>
> Just use
>
> if "c" in a:
>
> and all will be well. The True object isn't the only truthy value in
> Python - see .

I would recommend the OP try this:

run the (I)python shell and try the following:

>>> a = [x for x in "abcdefg"]
>>> a
['a','b','c','d','e','f','g']
>>> "c" in a
True
>>> "c" in a == True
False
>>> ("c" in a) == True
True

The reason your conditional failed is that it was interpreted as "c"
in (a == True) which is False.
the "==" operator binds at a higher precedence level than the "in"
operator, just as multiplication
binds higher than addition


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


Re: True of False

2007-09-27 Thread Casey
On Sep 27, 1:12 pm, "Richard Thomas" <[EMAIL PROTECTED]> wrote:
> On 27/09/2007, Casey <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Sep 27, 12:48 pm, "Simon Brunning" <[EMAIL PROTECTED]>
> > wrote:
> > > On 9/27/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> > > > I tried writing a true and false If statement and didn't get
> > > > anything?  I read some previous posts, but I must be missing
> > > > something.  I just tried something easy:
>
> > > > a = ["a", "b", "c", "d", "e", "f"]
>
> > > > if "c" in a == True:
> > > >  Print "Yes"
>
> > > > When I run this, it runs, but nothing prints.  What am I doing wrong?
>
> > > Just use
>
> > > if "c" in a:
>
> > > and all will be well. The True object isn't the only truthy value in
> > > Python - see <http://docs.python.org/lib/truth.html>.
>
> > I would recommend the OP try this:
>
> > run the (I)python shell and try the following:
>
> > >>> a = [x for x in "abcdefg"]
> > >>> a
> > ['a','b','c','d','e','f','g']
> > >>> "c" in a
> > True
> > >>> "c" in a == True
> > False
> > >>> ("c" in a) == True
> > True
>
> > The reason your conditional failed is that it was interpreted as "c"
> > in (a == True) which is False.
> > the "==" operator binds at a higher precedence level than the "in"
> > operator, just as multiplication
> > binds higher than addition
>
> Actually it evaluates '("c" in a) and (a == True)'. You can check like so:
>
> import dis
> a = list("abcdef")
> dis.dis(lambda: "c" in a == True)
>
> And just follow the bytecode operations.
>
> -- Richard.
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list

Doh, I forgot about operator chaining here.  I'm so used to just
seeing a < b < c that I forget about arbitrary operator chaining and
think like a C++ programmer!

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


getopt with negative numbers?

2007-09-27 Thread Casey
Is there an easy way to use getopt and still allow negative numbers as
args?  I can easily write a workaround (pre-process the tail end of
the arguments, stripping off any non-options including negative
numbers into a separate sequence and ignore the (now empty) args list
returned by getopt, but it would seem this is such a common
requirement that there would be an option to treat a negative value as
an argument.  Note that this is only a problem if the first non-option
is a negative value, since getopt stops processing options as soon as
it identifies the first argument value.

Alternatively, does optparse handle this?  I haven't used optparse (I
know it is more powerful and OO, but you tend to stick with what you
know, especially when it is part of my normal python programming
template), but if it handles negative numbers I'm willing to learn it.

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


Re: getopt with negative numbers?

2007-09-27 Thread Casey
On Sep 27, 1:34 pm, Peter Otten <[EMAIL PROTECTED]> wrote:
> optparse can handle options with a negative int value; "--" can be used to
> signal that no more options will follow:

Thanks, Peter.  getopt supports the POSIX "--" end of options
indicator as well, but that seems a little less elegant than being
able to simply set a value that tells the parser "I don't use any
numeric values as options, and I want to allow negative values as
arguments".  At the parser level implemening this would be trivial and
I frankly was hoping it had been implemented and it just wasn't
mentioned in the spares Python getopt library reference.

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


Re: getopt with negative numbers?

2007-09-27 Thread Casey
On Sep 27, 2:21 pm, "J. Clifford Dyer" <[EMAIL PROTECTED]> wrote:
> If you can access the argument list manually, you could scan it for a 
> negative integer,
> and then insert a '--' argument before that, if needed, before passing it to 
> getopt/optparse.
> Then you wouldn't have to worry about it on the command line.
>
> Cheers,
> Cliff

Brilliant!

# Look for the first negative number (if any)
for i,arg in enumerate(sys.argv[1:]):
# stop if a non-argument is detected
if arg[0] != "-": break
# if a valid number is found insert a "--" string before it which
# explicitly flags to getopt the end of options
try:
f = float(arg)
sys.argv.insert(i+1,"--")
break;
except ValueError:
pass

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


Re: getopt with negative numbers?

2007-09-27 Thread Casey
On Sep 27, 2:21 pm, "J. Clifford Dyer" <[EMAIL PROTECTED]> wrote:
> If you can access the argument list manually, you could scan it for a 
> negative integer, and then insert a '--' argument before that,
> if needed, before passing it to getopt/optparse.  Then you wouldn't have to 
> worry about it on the command line.
>
> Cheers,
> Cliff

Brilliant!


# Look for the first negative number (if any)
for i,arg in enumerate(sys.argv[1:]):
# stop if
if arg[0] != "-": break
# if a valid number is found insert a "--" string before it
which
# explicitly flags to getopt the end of options
try:
f = float(arg)
sys.argv.insert(i+1,"--")
break;
except ValueError:
pass


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


Re: getopt with negative numbers?

2007-09-27 Thread Casey
On Sep 27, 7:57 pm, Neal Becker <[EMAIL PROTECTED]> wrote:
> One person's "brilliant" is another's "kludge".
Well, it is a hack and certainly not as clean as having getopt or
optparse handle this natively (which I believe they should).  But I
think it is a simple and clever hack and still allows getopt or
optparse to function normally.  So I wouldn't call it a kludge, which
implies a more clumsy hack. As you say, it is all a matter of
perspective.

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


Re: getopt with negative numbers?

2007-09-28 Thread Casey
On Sep 27, 10:47 pm, Ben Finney <[EMAIL PROTECTED]>
wrote:
> I believe they shouldn't because the established interface is that a
> hyphen always introduced an option unless (for those programs that
> support it) a '--' option is used, as discussed.
Not "THE" established interface; "AN" established interface.  There
are other established interfaces that have different behaviors. I'm a
pragmatist; I write software for users, not techies.  I suspect most
users would expect a command like "abc -a -921 351 175" to treat the
"-921" as a negative integer and not abort the program with some
obscure error about option 921 not being known.
>
> > But I think it is a simple and clever hack and still allows getopt
> > or optparse to function normally.
>
> Except that they *don't* function normally under that hack; they
> function in a way contradictory to the normal way.
Again, it depends on who is defining "normal" and what they are basing
it on. I suspect many (probably most) users who are familiar with
command line input are unaware of the "--" switch which was mainly
designed to support arbitrary arguments that might have an initial
hyphen, a much broader problem than supporting negative values.  I'm
not asking that the default behavior of getopt or optparse change;
only that they provide an option to support this behavior for those of
us who find it useful. Software libraries should be tools that support
the needs of the developer, not rigid enforcers of arbitrary rules.

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


What does the syntax [::-1] really mean?

2007-10-04 Thread Casey
I've used [::-1] as a shorthand for reverse on several occasions, but
it occurred to me yesterday I never really thought about why it
works.  First, I checked out the documentation.

>From section 3.6 of the Python Library Reference:

"The slice of s from i to j with step k is defined as the sequence of
items with index x = i + n*k such that 0 <= n < (j-i)/k. In other
words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j
is reached (but never including j). If i or j  is greater than len(s),
use len(s). If i or j are omitted or None, they become ``end'' values
(which end depends on the sign of k). Note, k cannot be zero. If k is
None, it is treated like 1."

>From Section 5.3.3 of the Python Language Reference (x[::-1] is a
"proper slice" in the BNF, hence the excerpt):

"The conversion of a proper slice is a slice object (see section 3.2)
whose start, stop and step attributes are the values of the
expressions given as lower bound, upper bound and stride,
respectively, substituting None for missing expressions."

Following the reference to section 3.2 provides a (non-rigorous)
description of what a slice object is, in terms of the extended
slicing semantics.  But it doesn't shed any additional light on the
meaning of [::-1].

>From this, I would expect that x[::-1] would be identical to x[n:0:-1]
(n and 0 being the "end" values, with the order switched due to the
negative step value).  But the clause that "(but never including j)"
means that x[n:0:-1] excludes the 1st element of x, x[0].  A quick
test in ipython confirms that "abc"[3:0:-1] => "cb", not "cba".
Changing the "end" value  to x[n:-1:-1] results in an empty string.

So my question is: "what exactly is [::-1] shorthand for"?  Or is it a
special case, in which case why isn't it  defined as such in the
library?

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


Re: What does the syntax [::-1] really mean?

2007-10-04 Thread Casey
On Oct 4, 1:41 pm, "Kurt Smith" <[EMAIL PROTECTED]> wrote:
> >>> 'abc'[None:None:-1]
> 'cba'
> Kurt

Thanks!

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


Re: What does the syntax [::-1] really mean?

2007-10-04 Thread Casey
On Oct 4, 4:32 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> Duncan Booth <[EMAIL PROTECTED]> wrote:
> > the invariant that you are looking for is that for all non-negative a, b:
> >x[a:b:1] reversed is x[-len(x)+b-1:-len(x)+a-1:-1]
>
> I should of course have said "all a, b in the range 0 <= a <= len(x) and 0
> <= b <= len(x)".

Thanks, again! I figured it out from Fred's and your initial posts.
IM(ns)HO, this is non-intuitive.

I would expect that the reverse of x[i,j,k] would be x[j,i,-k]; eg;
x[0:len(x):1] would be x[len(x):0:-1].  This representation is little
more than syntactic sugar for x[y for y in range(i,j,k)], with a -1
adjustment to i and j if k is < 0 (due to the way range operates) and
with appropriate boundary checking on i and j.  The default values for
i and j would become (0,len(x)), flopped for k < 0.

There may be a good (or not-so-good) reason this representation
wouldn't have worked or would have caused problems.  Or maybe it is
just personal preference.

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


Re: What does the syntax [::-1] really mean?

2007-10-04 Thread Casey
On Oct 4, 4:58 pm, Casey <[EMAIL PROTECTED]> wrote:
> Thanks, again! I figured it out from Fred's and your initial posts.

Oops - I meant Kurt, not Fred.  Sorry for the mis-attribution!

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


Re: Is there a nicer way to do this?

2007-10-04 Thread Casey
Not sure if this is really better or even more pythonic, but if you
like one-liners that exercise the language:

attributeNames = dict( [("AttributeName.%d" % (n+1), attribute) for
n,attribute in enumerate(attributes)] )

What this does is create a list (using a list comprehension and the
enumerate function) of ("AttributeName.x", attribute) tuples which is
then be used to initialize a dictionary.

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


Re: Is there a nicer way to do this?

2007-10-04 Thread Casey
On Oct 4, 5:42 pm, Casey <[EMAIL PROTECTED]> wrote:
> Not sure if this is really better or even more pythonic, but if you
> like one-liners that exercise the language:

Hmm, I guess it WAS more pythonic, since three of us gave essentially
identical responses in a 10-minute period.  That being said, I'd
recommend a good comment before the one-liner describing what the
output dictionary is going to look like. Anyone who reads your code
(including yourself, two weeks later) will thank you!

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


Re: Py3 - converting bytes to ascii

2009-01-15 Thread Casey
On Jan 15, 9:54 am, "Anjanesh Lekshminarayanan" 
wrote:
> Using Python 3.0
>
> So how do I to convert res.read() to ascii on opening the file in
> ascii mode f = open('file.txt', 'w')?
>

I think this is what you are looking for:

res = urllib.request.urlopen(url)
f = open('file.txt', 'w')
f.write(res.read().decode('ascii'))
--
http://mail.python.org/mailman/listinfo/python-list


Re: Regular expression that skips single line comments?

2009-01-19 Thread Casey
Another option (I cheated a little and turned sInput into a sequence
of lines, similar to what you would get reading a text file):

sInput = [
'; $1 test1',
'; test2 $2',
'test3 ; $3 $3 $3',
'test4',
'$5 test5',
'   $6',
'  test7 $7 test7',
]

import re
re_exp = re.compile(r'(\$.)')
re_cmt = re.compile(r'\s*;')
expansions = [exp for line in sInput for exp in re_exp.findall(line)
if not re_cmt.match(line)]
print(expansions)

>>> ['$3', '$3', '$3', '$5', '$6', '$7']
--
http://mail.python.org/mailman/listinfo/python-list


Re: printing bytes to stdout in Py3

2009-02-17 Thread Casey
On Feb 17, 7:28 am, Christian Heimes  wrote:
> Peter Billam schrieb:
>
> > Greetings. (Newbie warning as usual) In Python3, sys.stdout is a
> > io.TextIOWrapper object; but I want to output bytes
> >   (e.g. muscript -midi t > t.mid )
> > and they're coming out stringified :-(  How can I either change the
> > encoding on sys.stdout, or close sys.stdout and reopen it in 'b'
> > mode, or dup(fd) it first, or whatever the right thing to do is ?
>
> The official API to write binary data to stdout is:
>
> >>> count = sys.stdout.buffer.write(b"abc\n")
>
> abc
>
> Christian

Is this really the 'official' way to do this?  This isn't meant to be
confrontational or trolling; I honestly don't know the answer and I
had similar questions when I first started with the 3.0 release
candidates and I have yet to find a good answer in the Python v3.0
documentation.  Why wouldn't you just use:

print(bytes.decode(b'abc\n'), end='')
--
http://mail.python.org/mailman/listinfo/python-list


Re: printing bytes to stdout in Py3

2009-02-17 Thread Casey
On Feb 17, 12:33 pm, Christian Heimes  wrote:
> Yes, it's really the official way. You can google up the discussion
> between me and Guido on the python-dev list if you don't trust me. ;)
> The docs concur with me, too.
>
> http://docs.python.org/3.0/library/sys.html#sys.stdin
>
> Note: The standard streams are in text mode by default. To write or read
> binary data to these, use the underlying binary buffer. For example, to
> write bytes to stdout, use sys.stdout.buffer.write(b'abc').

Thanks! Incidentally, the 'Note:' section you reference in the HTML
docs doesn't appear to be in the .CHM file that installs with the
windows version of 3.01.  That would have made my search a lot
easier :-%
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is this a bug in Python or something I do not understand.

2009-01-01 Thread Casey
L1 is a list of three different lists, although each list holds the
same values.

L2 is a list of three references to the same list (the '*' operator
doesn't do a deep copy).  So when you modify any of the referenced
lists, you modify all of them.

Try this:

>>> q = [1, 1, 1]
>>> r = [q, q, q]
>>> r
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
>>> r[0][0] = 999
>>> r
[[999, 1, 1], [999, 1, 1], [999, 1, 1]]

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


Python 3.0 nonlocal statement

2009-01-06 Thread Casey
In PEP 3104 the nonlocal statement was proposed and accepted for
implementation in Python 3.0 for access to names in outer scopes.  The
proposed syntax included an optional assignment or augmented
assignment to the outer name, such as:

nonlocal x += 1

This syntax doesn't appear to be supported in the 3.0 implementation.
My question is: was this intentional or was it missed in the initial
release?  If it was intentional, is there any plan to support it in a
later 3.x release?  I realize it is a very small convenience feature
but I have already come across a couple of cases where I use nested
functions where it does make the code seem a little cleaner.

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


Re: Python 3.0 nonlocal statement

2009-01-06 Thread Casey
On Jan 6, 11:10 am, Matimus  wrote:

> `nonlocal` should behave just like `global` does. It doesn't support
> that syntax either. So, yes it was intentional. No, there probably is
> no plan to support it in a later release.
>
> Matt

>From my perspective, that's an unfortunate decision and I question the
rationale.  First, nonlocal doesn't behave exactly like global (you
cannot declare a previously undefined variable nonlocal as you can
with global).  Second, the PEP 3104 description explicitly mentions
that Guido favored adding this behavior to global; I would have
preferred that approach to not providing the extended assignment
support for nonlocal.  Third, I believe that it adds some clarity to
the code.  Seeing 'nonlocal x += 1' immediately tells me that I'm
incrementing a variable defined in an outer scope.  Having 'nonlocal
x' on one line and 'x += 1' on another makes it a little less clear.

But I do appreciate the reply!

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


Re: Python 3.0 nonlocal statement

2009-01-06 Thread Casey
On Jan 6, 11:46 am, Rob Williscroft  wrote:
> Matimus wrote in news:2a3d6700-85f0-4861-84c9-9f269791f044

> Searching (AKA googling) for: nonlocal site:bugs.python.org
> leads to:http://bugs.python.org/issue4199
>
> Rob.
> --http://www.victim-prime.dsl.pipex.com/

Doh. I looked at the PEP and the 3.0 BNF syntax and never thought to
search the online bugs.

Thanks, Rob!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite Python System Administration Examples

2008-10-06 Thread Casey
On Oct 6, 3:05 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> I'm giving a talk at LISA this year, and while the slides are ready I
> would like to go armed with as many examples of good system
> administration code as possible.
>
> If you have a favorite administration tool that you wouldn't mind me
> using I'd love to know about it. Feel free to email me personally or
> submit via the list.
>
> regards
>  Steve
> --
> Steve Holden        +1 571 484 6266   +1 800 494 3119
> Holden Web LLC              http://www.holdenweb.com/

You might look at the presentation (and code samples) David M. Beazley
gave at PyCon focusing on using Python generators to automate sysadm
tasks.  http://www.dabeaz.com/generators/index.html
--
http://mail.python.org/mailman/listinfo/python-list


Winsound Problems on Vista 64

2009-03-06 Thread Casey
I have a new laptop that came with Vista 64 and I'm having problems
with some of my older code that I use for multimedia processing.  I
narrowed the problem down to the winsound library; any attempt to play
sounds results in a fatal error.  The simplest case is:

>>> from winsound import Beep
>>> Beep(440, 2)
Traceback (most recent call last):
  File "", line 1, in 
RuntimeError: Failed to beep

I have been able to recreate this problem in Python 2.6.1 (32-bit),
3.0.1 (32-bit) and 3.0.1 (AMD64 bit, which I hope is compliant with my
IA64 CPU).  I didn't find any open issues in the Python issue
tracker.  I would appreciate it if someone would confirm the issue on
Vista 64 (I want to rule out that it is something with my audio
configuration).  Also, if someone with Vista 32 could try this?
--
http://mail.python.org/mailman/listinfo/python-list


Making Variable Text Output More Pythonic?

2008-05-15 Thread Casey
Hi,

I have some classes that print variable outputs depending on their
internal state, like so:

def __str__(self):
out = []
if self.opt1: out += ['option 1 is %s' % self.opt1']
if self.opt2: out += ['option 2 is %s' % self.opt2']

return '\n'.join(out)

Is there any way to make this cleaner?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Harry Potter?

2008-06-05 Thread Casey
Python fan??? Harry speaks Python fluently.  We should all be so
lucky!

I'm told Harry is looking forward to Py3K and getting rid of all the
old (hog)warts 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Anyone happen to have optimization hints for this loop?

2008-07-09 Thread Casey
On Jul 9, 12:04 pm, dp_pearce <[EMAIL PROTECTED]> wrote:
> I have some code that takes data from an Access database and processes
> it into text files for another application. At the moment, I am using
> a number of loops that are pretty slow. I am not a hugely experienced
> python user so I would like to know if I am doing anything
> particularly wrong or that can be hugely improved through the use of
> another method.
>
> Currently, all of the values that are to be written to file are pulled
> from the database and into a list called "domainVa". These values
> represent 3D data and need to be written to text files using line
> breaks to seperate 'layers'. I am currently looping through the list
> and appending a string, which I then write to file. This list can
> regularly contain upwards of half a million values...
>
> count = 0
> dmntString = ""
> for z in range(0, Z):
>     for y in range(0, Y):
>         for x in range(0, X):
>             fraction = domainVa[count]
>             dmntString += "  "
>             dmntString += fraction
>             count = count + 1
>         dmntString += "\n"
>     dmntString += "\n"
> dmntString += "\n***\n
>
> dmntFile     = open(dmntFilename, 'wt')
> dmntFile.write(dmntString)
> dmntFile.close()
>
> I have found that it is currently taking ~3 seconds to build the
> string but ~1 second to write the string to file, which seems wrong (I
> would normally guess the CPU/Memory would out perform disc writing
> speeds).
>
> Can anyone see a way of speeding this loop up? Perhaps by changing the
> data format? Is it wrong to append a string and write once, or should
> hold a file open and write at each instance?
>
> Thank you in advance for your time,
>
> Dan

Maybe try something like this ...

count = 0
dmntList = []
for z in xrange(Z):
for y in xrange(Y):
dmntList.extend(["  "+domainVa[count+x] for x in xrange(X)])
dmntList.append("\n")
count += X
dmntList.append("\n")
dmntList.append("\n***\n")
dmntString = ''.join(dmntList)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Perfect hashing for Py

2008-07-11 Thread Casey
On Jul 11, 8:01 am, [EMAIL PROTECTED] wrote:
> Following links from this 
> thread:http://groups.google.com/group/comp.lang.python/browse_thread/thread/...
>
> I have found this perfect hash (minimal too) 
> implementation:http://burtleburtle.net/bob/hash/perfect.html
>
> I have already translated part of it to D, and it seems to work well
> enough. As discussed in the PyConDue, I think this may be used in
> frozenset (and frozendict) to build a (minimal too?) perfect hash on
> the fly, to allow (hopefully) faster retrieval of items that don't
> change.
> That code is C and I think it's public domain, so if experiments show
> it gives enough speed up, it may be added to CPython 2.6/3.
>
> Bye,
> bearophile

It would be interesting to see if such an algorithm could actually
provide any significant performance improvements for the size of sets
that I suspect are most often used in practice. The chance of a hash
collision for a good 32-bit general is fairly low even for a set of
1,000,000 unique elements, which seems to me to be a pretty large
memory-based set.  Compare that with the cost of determining a perfect
hash (O(n**2)?).

>From my perspective, a perfect hash would certainly be a welcome
addition to the Python library or even as an optional algorithm
supporting
hash-based collections.
--
http://mail.python.org/mailman/listinfo/python-list


Re: screencapture with PIL question

2008-07-14 Thread Casey
On Jul 14, 11:11 am, greg <[EMAIL PROTECTED]> wrote:
> I am able to use the PIL module to capture a screen or specific
> window.  My problem is when capturing a window (on windows XP) I can
> only capture the "visible" portion of the window.  Is there any way to
> capture the entire window?  specifically the scrolled portion of a
> window that is not visible on the screen.
>
> Thanks for any help.

You might want to check out
http://wiki.wxpython.org/index.cgi/WorkingWithImages#head-e962ac20ad55c25bc069523cd7e0246068110233
.
wxPython supports different types of device contexts including
wx.ClientDC (the client area of a window), wx.WindowDC (a specific
window), and wx.ScreenDC (anywhere or everywhere on the underlying
screen).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where is the correct round() method?

2008-07-28 Thread Casey
On Jul 28, 12:34 am, Gary Herron <[EMAIL PROTECTED]> wrote:

> This will work as you wish:
>   math.floor(x+0.5)

This works fine for positive x but what about negative:

>>> round(2.5)
3.0
>>> floor(2.5 + 0.5)
3.0
>>> round(-2.5)
-3.0
>>> floor(-2.5 + 0.5)
-2.0

Maybe:

def round2(x):
return math.floor(x + (0.5 if x >= 0 else -0.5))
--
http://mail.python.org/mailman/listinfo/python-list


Re: paretovariate

2008-08-11 Thread Casey
On Aug 11, 3:14 am, "zhjchen" <[EMAIL PROTECTED]> wrote:
> I want to realize a list of numbers. They follow pareto distribution.
> For instance, the average value is 10 and alpha is 1.0
> I do not know how to use the function of paretovariate(alpha). It only 
> provides
> alpha parameter. How should I set the average value?

I'm guessing that paretovalue(alpha) treats alpha as the shape
parameter and assumes a mode of 1.0, in which case you would multiply
by 10 for your example.

Alternatively, you could define your own Pareto function:

# pareto for mode, shape > 0.0
def pareto(mode, shape): return mode * pow(1.0 - random.random(),
-1.0 / shape)
--
http://mail.python.org/mailman/listinfo/python-list


Re: for x,y in word1, word2 ?

2008-08-11 Thread Casey
My first thought is that you should be looking at implementations of
Hamming Distance.  If you are actually looking for something like
SOUNDEX you might also want to look at the double metaphor algorithm,
which is significantly harder to implement but provides better
matching and is less susceptible to differences based on name origins.
--
http://mail.python.org/mailman/listinfo/python-list


Problem with help() in python/ipython interpreters

2008-05-09 Thread Casey
I'm running python 2.5.2 on WinXP.  I've always used a GUI for
interactive development, but I wanted to try out ipython which better
supports matplotlib in this mode.  Unfortunately, whenever I try to
use help() I get the following error:

(Sys) The system cannot find the file specified.
 "C:\documents"

It turns out that the regular (python.exe) interpreter has the same
problem.  I have the HTML docs installed, my PYTHONDOCS environment
variable points to the HTML directory, and I actually uninstalled and
reinstalled every library I use from scratch to make sure it wasn't
some random config issue.

The error message leads me to believe that the help() function is
trying to access something in my windows user directory structure (C:
\Documents and Settings\\...) and is having problems with
the embedded space.  The really strange thing is that my python
directory is rooted at c:\python25 including my html docs. I know that
ipython does by default create a profile directory in %HOME%\_ipython
but that doesn't seem to be a problem and wouldn't impact the default
python.exe interpreter.

Any ideas?
--
http://mail.python.org/mailman/listinfo/python-list


PIL Question: Inverse of .load()?

2008-08-15 Thread Casey
I'm doing some image processing that requires accessing the individual
pixels of the image.  I'm using PIL 1.1.6 and creating a 2D array of
pixel RGB tuples using the Image class instance load() method.
Unfortunately, I can't seem to find a reciprocal function that
converts the 2D array of RGB tuples back to an image.  I've gone
through all of the online documentation and can't seem to find what
should be an obvious solution.

Any thoughts?
--
http://mail.python.org/mailman/listinfo/python-list


Re: PIL Question: Inverse of .load()?

2008-08-16 Thread Casey
On Aug 16, 3:53 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Casey wrote:
> > I'm doing some image processing that requires accessing the individual
> > pixels of the image.  I'm using PIL 1.1.6 and creating a 2D array of
> > pixel RGB tuples using the Image class instance load() method.
>
> load returns an access object that's attached to the image; to modify
> the image, just assign to the object:
>
>   pix = im.load()
>
>   v = pix[x, y]
>   pix[x, y] = v
>
> to do bulk loads, you can use the getdata/putdata methods instead.
>
> 

Ah - I didn't realize from the docs that the results of load() is an
in situ edit to the original buffer.  Thanks!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Usual practice: running/testing modules in a package

2008-08-27 Thread Casey
On Aug 12, 9:57 pm, alito <[EMAIL PROTECTED]> wrote:
>
> A wrapper on the level up works:
>
> ~/python$ cat importercaller.py
> from testpackage import config
> config.hello()
>
> ~/python$ python importercaller.py
> hello
>
> So, how do I run these modules without writing a wrapper script for
> each one?

I just ran into this problem trying to run a package from a local
directory.  I agree creating another script just to import the local
package is a bad solution. Without another option, I would recommend
using a Makefile and creating a target to import the package and
kickoff the execution:

hello:
python -c 'from testpackage import config; config.hello()'

and then "make hello" to execute the command.

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


Re: Usual practice: running/testing modules in a package

2008-09-03 Thread Casey
On Aug 26, 10:21 pm, Casey <[EMAIL PROTECTED]> wrote:
> On Aug 12, 9:57 pm, alito <[EMAIL PROTECTED]> wrote:
>
>
>
> > A wrapper on the level up works:
>
> > ~/python$ cat importercaller.py
> > from testpackage import config
> > config.hello()
>
> > ~/python$ python importercaller.py
> > hello
>
> > So, how do I run these modules without writing a wrapper script for
> > each one?
>


It looks like PEP 366 [http://www.python.org/dev/peps/pep-0366/] will
solve this issue.
--
http://mail.python.org/mailman/listinfo/python-list


Threading.py Class Syntax and Super

2009-09-16 Thread Casey
Hi,

I noticed that the many (if not all) classes in threading.py[1] all
inherit from object, yet non of the init methods call super(). I am
curious as to why this is the chosen implementation? If the benefit of
new-style classes is to support multiple inheritance, then isn't this
"broken" if the class __init__ method does not make a call to super?

[1] http://svn.python.org/view/python/trunk/Lib/threading.py?view=markup

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


Re: BadValueError: Property title is required

2011-06-03 Thread Casey Dwyer
On May 31, 1:21 am, "michal.bulla"  wrote:
> Hello,
>
> I'm trying to create simple method to create category. I set the model
> category:
>
> class Category(db.Model):
>   title = db.StringProperty(required=True)
>   clashes_count = db.IntegerProperty(default=0)
>
> And the class New Category as well :
>
> class NewCategoryPage(webapp.RequestHandler):
>   def get(self):
>     categories = Category.all().order('-title')
>
>     template_values = { }
>     path = os.path.join(os.path.dirname(__file__), 'templates',
> 'category_new.html')
>     self.response.out.write(template.render(path, template_values))
>
>   def post(self):
>     category = Category()
>     category.title = self.request.get('title')
>     category.put()
>     self.redirect('/')
>
> Here is the template:
>
> {%extends "base.html"%}
> {%block body%}
>
> Add New Category
>
> 
>   Title: 
>   
> 
>
> {%endblock%}
>
> The problem is that I'm getting an error BadValueError: Property title
> is required. Can you help me with that ? Thanks

Required properties must be declared in the constructor. Try this
instead:

category = Category(title=self.request.get('title'))
category.put()
-- 
http://mail.python.org/mailman/listinfo/python-list


logging and PyQt4

2011-03-14 Thread Adrian Casey
I have a multi-threaded PyQt4 application which has both a GUI and command-
line interface.  I am using Qt4's threading because from what I have read, 
it is more efficient than the native python threading module.  Also, given 
most users will probably use the GUI, it seemed to make sense.  

I want a flexible, threadsafe logging facility for my application so I was 
thinking of using python's logging module.  I need a logger that can log to 
the GUI or a terminal depending on how the application is invoked.

So, my question is -:

Is it wise to use python's logging module in conjunction with Qt4 threads?  
If not, what are my options apart from writing my own logging module?

If it is OK, then I would like to know how to subclass the logging class so 
that instead of sending output to stdout (as in StreamHandler), it emits Qt4 
signals instead.

Any help would be appreciated.

Thank you.
Adrian Casey.
-- 
http://mail.python.org/mailman/listinfo/python-list


QCoreApplication will not quit

2011-04-01 Thread Adrian Casey
Can someone please explain why this simple PyQt4 application never exits?

#!/usr/bin/env python
from PyQt4 import QtCore
import sys
class foo(QtCore.QObject):
def __init__(self, parent):
QtCore.QObject.__init__(self, parent)
self.parent = parent
self.end_job()

def end_job(self):
QtCore.QCoreApplication.quit()

if __name__ == '__main__':
app = QtCore.QCoreApplication(sys.argv)
myFoo = foo(parent=None)
sys.exit(app.exec_())

This is just a very simple, cut-down example to demonstrate a problem I have 
with an application I am writing.  If I call 
QCoreApplication.hasPendingEvents(), the result is always True.  Even if I 
call QCoreApplication.processEvents(), the application still does not quit.  
It just hangs forever.

I'd appreciate some help in finding out how to make it quit.

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


Re: QCoreApplication will not quit

2011-04-02 Thread Adrian Casey
Dennis Lee Bieber wrote:

> On Sat, 02 Apr 2011 14:12:38 +0930, Adrian Casey 
> declaimed the following in gmane.comp.python.general:
> 
>> Can someone please explain why this simple PyQt4 application never exits?
>> 
>> #!/usr/bin/env python
>> from PyQt4 import QtCore
>> import sys
>> class foo(QtCore.QObject):
>> def __init__(self, parent):
>> QtCore.QObject.__init__(self, parent)
>> self.parent = parent
>> self.end_job()
>> 
>> def end_job(self):
>> QtCore.QCoreApplication.quit()
>> 
>> if __name__ == '__main__':
>> app = QtCore.QCoreApplication(sys.argv)
>> myFoo = foo(parent=None)
>> sys.exit(app.exec_())
>> 
> Uhm... Could it be because you've shut down the application before
> ever starting it?
> 
> Note that your __init__() method -- invoked when you create "myFoo",
> ENDS with a call to end_job() which invokes the framework quit() method.
> 
> THEN after all this framework shut down, you invoke the app.exec_()
> on a framework that has nothing left to run?
Thanks Dennis. I should have seen that!

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


pexpect: TIMEOUT no longer clears child.before

2011-05-19 Thread Adrian Casey
The behaviour of pexpect has changed between version 2.1 and 2.3.  In 
version 2.1, the following code would result in child.before being 
cleared -:


>>>child.expect(pexpect.TIMEOUT,1)


In version 2.3, this is no longer the case.  No matter how many times 
the above code is run, child.before continues to hold the output from 
previous commands.  It is important to be able to clear the contents of 
child.before between each command.  What is the correct way to do this 
in version 2.3?


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


Re: Vancouver Python and Zope: Next Meeting Oct 2nd

2005-09-26 Thread Casey Hawthorne
Where is ActiveState?

On Mon, 26 Sep 2005 11:58:33 -0700, you wrote:

>The Vancouver Python and Zope user groups next meeting is on Oct 4th, at 
>the usual place, ActiveState at 7.
>
>Mishtu Banerjee will be giving a talked entitled "Desperately Seeking 
>Abstraction"
>
>"I built an SQL query generator (as part of a larger project) based on 
>the underlying abstraction of representing data models as "networks". 
>It's a nice illustration of abstracting a particular analysis pattern 
>(in this case, we're abstracting the pattern of multi-table inner joins, 
>which is one of the most common ad-hoc query types)"
>
>For more information see our website: http://www.vanpyz.org
>
>Mailing list: http://www.agmweb.ca/cgi-bin/mailman/listinfo/list
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


Return Text from popen

2005-10-15 Thread Casey Bralla
I know this problem has a very simple answer, but I've checked the web and I
don't understand the answers that I've found.

How do I return text from a standard Linux command?

For example:  I want to read the stdout results of a typical linux command
(such as "df") into a Python variable.

I've tried these techniques:

 result = os.system("df")
 It dumps the stdout to a screen and puts the result code into "result"

 result = popen2("df")
 It gives me a tuple of the stdin & stdout pipes, which I don't know how to
harvest into the actual stdout result.


Can someone give me a brief code example of how to get the actual text
result from the linux command into a Python variable?  Thanks!

-- 
Casey Bralla
Chief Nerd in Residence
The NerdWorld Organisation
http://www.NerdWorld.org
-- 
http://mail.python.org/mailman/listinfo/python-list


The value of Big-O notation is for scale ability and the value of the constant of proportionality!

2005-10-16 Thread Casey Hawthorne
The value of Big-O notation is for scale ability, since quite often a
an algorithm used for small N is forgotten about in a large program
and not changed when the program has to deal with larger inputs.

It's also useful to know the constant of proportionality, for
different platforms, for code optimization issues.
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python vs Ruby

2005-10-20 Thread Casey Hawthorne
What languages do you know already?

What computer science concepts do you know?

What computer programming concepts do you know?


Have you heard of Scheme?


Ruby is a bit Perl like -- so if you like Perl, chances are you might
like Ruby.

Python is more like Java.

I have heard, but have not been able to verify that if a program is
about
10,000 lines in C++
it is about
5,000 lines in Java
and it is about
3,000 lines in Python (Ruby to?)



Roy Smith <[EMAIL PROTECTED]> wrote:

>In article <[EMAIL PROTECTED]>,
> "Amol Vaidya" <[EMAIL PROTECTED]> wrote:
>
>> Hi. I am interested in learning a new programming language, and have been 
>> debating whether to learn Ruby or Python. How do these compare and contrast 
>> with one another, and what advantages does one language provide over the 
>> other? I would like to consider as many opinions as I can on this matter 
>> before I start studying either language in depth. Any help/comments are 
>> greatly appreciated. Thanks in advance for your help. 
>
>Of all the common scripting languages, Ruby has the highest vowel to 
>consonant ratio.
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What can I do with Python ??

2005-01-02 Thread Casey Hawthorne
Aren't games using full screen mode to address only 320 by 240
resolution for faster screen painting?

If one used only 320 by 240 in a window, then that would be 1/4 of the
screen or less!

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


Command line and GUI tools : need a single threading solution

2005-01-10 Thread Adrian Casey
I have a collection of multi-threaded command line tools which I want wrap a
PyQt gui around.  I'm using queues to route messages from the command line
tools to the PyQt gui. The command line tools use python threads to do
their work.  The gui uses a QThread object to read incoming messages.

This does not work consistently - and I've since read that mixing python
threads and QThreads is a bad idea.  The command line tools work well using
python threads.

I don't want to maintain two copies of the tools - one for command line and
another for the PyQt version.

I'm thinking it may be possible to modify the command line tools to use qt
threads instead of native python threads.  Is this the way to go?  Are
there other options?

Adrian.


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


Re: Command line and GUI tools : need a single threading solution

2005-01-11 Thread Adrian Casey
Diez B. Roggisch wrote:

>> I'm thinking it may be possible to modify the command line tools to use
>> qt
>> threads instead of native python threads.  Is this the way to go?  Are
>> there other options?
> 
> Why don't you use python threads in qt - I do so and so far it didn't make
> any troubles for me. And I would strongly advise against using qthreads
> with your commandline-tools, as these then would only run on machines
> where pyqt is installed - which opens a small part of "dependency hell"
> for your users.
> 
I have a QThread which polls a queue object via queue.get().  The command
line tools spawn a number of threads each of which writes its output to
this queue using queue.put().  As soon as the gui gets something off the
queue, it creates a QCustomEvent and sets the data property with the data
read from the queue.  My application has a customEvent() method which reads
the data item from the customEvent and processes it accordingly.  

The odd thing is, I have a non-threaded version of the command line tools
which work 100% with the gui.  The multi-threaded version of the command
line tools all work OK at the console - just not with the gui.

I will try your suggestion and replace my QCustomEvent mechanism with a
plain python queue.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Command line and GUI tools : need a single threading solution

2005-01-11 Thread Adrian Casey
Phil Thompson wrote:

>> I have a collection of multi-threaded command line tools which I want
>> wrap a
>> PyQt gui around.  I'm using queues to route messages from the command
>> line tools to the PyQt gui. The command line tools use python threads to
>> do
>> their work.  The gui uses a QThread object to read incoming messages.
>>
>> This does not work consistently - and I've since read that mixing python
>> threads and QThreads is a bad idea.  The command line tools work well
>> using
>> python threads.
> 
> How well mixing the two threading APIs works depends on version numbers. A
> PyQt generated with SIP v4.x (rather than SIP v3.x) with Python v2.4
> should be Ok.
> 
>> I don't want to maintain two copies of the tools - one for command line
>> and
>> another for the PyQt version.
>>
>> I'm thinking it may be possible to modify the command line tools to use
>> qt
>> threads instead of native python threads.  Is this the way to go?  Are
>> there other options?
> 
> Using QThreads only should work - just tell the QApplication ctor that you
> have a console application.
> 
> Phil
Phil,

I'm running python 2.4, sip-4.0 and PyQt-x11-gpl-3.11 (or .13 - not sure as
I'm not at work).

A little more detail.

My script, if invoked from the command line, creates a queue object (let's
call it logQueue) which is used to take the output from each individual
thread.  If invoked via the gui, the script is passed a logQueue created by
the gui.  Each thread dumps its output using logQueue.put().  There are
other queues which are used to service threaded access to a database etc.

The scripts use the pexpect module to login to remote systems and do
sysadmin tasks (e.g. reset passwords).  This works like a charm in console
mode.

The gui uses a QThread to poll logQueue (logQueue.get()).  When it gets
something, it creates a QCustomEvent and sets the data portion using the
data read from the logQueue.  I have a customEvent method in my application
which grabs the data from the customEvent and processes it accrodingly
(writing output to a QTable).

The gui locks up after an arbitrary number of rows have been inserted in the
QTable.  It is not consistent.  Sometimes it does not lock at all.

I have a non-threaded set of the command line tools which run perfectly with
the gui.

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


Re: Command line and GUI tools : need a single threading solution

2005-01-12 Thread Adrian Casey
Adrian Casey wrote:

> Diez B. Roggisch wrote:
> 
>>> I'm thinking it may be possible to modify the command line tools to use
>>> qt
>>> threads instead of native python threads.  Is this the way to go?  Are
>>> there other options?
>> 
>> Why don't you use python threads in qt - I do so and so far it didn't
>> make any troubles for me. And I would strongly advise against using
>> qthreads with your commandline-tools, as these then would only run on
>> machines where pyqt is installed - which opens a small part of
>> "dependency hell" for your users.
>> 
> I have a QThread which polls a queue object via queue.get().  The command
> line tools spawn a number of threads each of which writes its output to
> this queue using queue.put().  As soon as the gui gets something off the
> queue, it creates a QCustomEvent and sets the data property with the data
> read from the queue.  My application has a customEvent() method which
> reads the data item from the customEvent and processes it accordingly.
> 
> The odd thing is, I have a non-threaded version of the command line tools
> which work 100% with the gui.  The multi-threaded version of the command
> line tools all work OK at the console - just not with the gui.
> 
> I will try your suggestion and replace my QCustomEvent mechanism with a
> plain python queue.
I tried replacing the QThread part with native python threads and, although
it worked for a few minutes, I started to see XWindow errors and my
application would then crash.

On Phil Thompson's advice, I updated PyQt and sip.  The problem appears to
be fixed.

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


Re: short programming projects for kids

2005-01-24 Thread Adrian Casey
André Roberge wrote:

> bobdc wrote:
>> I will be teaching an "Introduction to Programming" class to some
>> middle school aged children and will be using Python, obviously. Does
>> anyone have suggestions for simple little programs to create and
>> analyze with them after I get past turtle graphics?
>> 
>> Turtle graphics will be plenty for the first session, and I will leave
>> time to ask them what they'd like to do in later sessions, but I was
>> curious if anyone on the list has experience picking pedagogical
>> programming examples appropriate for twelve-year-olds' attention spans.
>> thanks,
>> 
>> Bob
>> 
> While it is not python per se, I suggest you have a look at GvR
> (Guido van Robot) (The app is written in Python but is too complicated
> for beginners).  It is hosted on sourceforge (gvr.sourceforge.net).
> It is a very interesting way (imho) to learn about programming, in
> a pythonic way.
> 
> (somewhat shameless plug follows:)
> A 'more advanced version' of GvR which uses the full Python syntax
> is RUR-PLE  (rur-ple.sourceforge.net).  The version currently hosted
> there does NOT work under Linux (untested on Mac).
> It uses wxPython 2.4 and will not work with 2.5.
> An updated release that will work under both Linux and Windows,
> and under both wxPython 2.4 and 2.5 will come out very soon, I hope.
> 
> I'm working on it :-)  I have two kids (ages 11 and 13) and plan to use
> rur-ple to teach them about programming.   Note that, even though
> I plan it to be suitable for motivated children (with some guidance),
> the end product (to be finished in a year?) is planned to be suitable
> for a complete first-year university computer science.
> 
> Andre Roberge

I started teaching my 11 year old first of all by doing silly stuff like -:
for i in range(10):
print "Silly me!"

Moving on to more useful stuff like times tables (which they have to learn
anyway).

After times tables, I plan to work on a simple number guessing game where
the computer picks a random number between 1 and 100 and asks the user to
take a guess.  This will help demonstrate many basic programming concepts.

Not sure how to introduce graphics though as so much is relatively abstract.

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


Re: python without OO

2005-01-26 Thread Casey Hawthorne
"The object-oriented programming paradigm has an undeserved reputation
as being complicated; most of the complexity of languages such as C++
and Java has nothing to do with their object orientation but comes
instead from the type declarations and the mechanisms to work around
them.  This is a prime example of how Scheme's approach of removing
restrictions compares with the "piling feature on top of feature"
needed in other languages, such as the C++ template mechanism."

"Handbook of Programming Languages, Volume IV: Functional and Logic
Programming Languages"
Peter H. Salus, editor
1998
page 63

Similarly, now, Java's generics!

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


What platforms have Python Virtual Machines and what version(s) of Python do they support?

2005-06-18 Thread Casey Hawthorne
What platforms have Python Virtual Machines and what version(s) of
Python do they support?
In particular:
Palm OS
PocketPC

What version of Python does Jython support?
Does any machine running a JVM support Jython?
Does it depend on the JVM version and if it's J2ME?

Thank you for your time!

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


Re: Looking For Geodetic Python Software

2005-06-22 Thread Casey Hawthorne
Tim Daneliuk <[EMAIL PROTECTED]> wrote:

>Is anyone aware of freely available Python modules that can do any of
>the following tasks:
>
>1) Given the latitude/longitude of two locations, compute the distance
>between them.  "Distance" in this case would be either the straight-line
>flying distance, or the actual over-ground distance that accounts for
>the earth's curvature.

Do your planes fly over the earth's surface or through the ground?


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


Re: Newbie: Help Figger Out My Problem

2005-06-28 Thread Casey Hawthorne
It may be shorter but it keeps the entire list in memory and has to
iterate over the list twice!
Does he/she need the entire list?

import random
heads = 0
flips = 100
for i in xrange(flips):
if random.randint(0,1): heads += 1
print "Heads:%s" % heads
print "Tails:%s" % (flips - heads)


"Devan L" <[EMAIL PROTECTED]> wrote:

>import random
>flips = 100
>results = [random.randint(0,1) for i in range(flips)]
>heads = results.count(0)
>tails = results.count(1)
>print "Heads:%s" % heads
>print "Tails:%s" % tails
>I think this is more compact.

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


Re: What are __slots__ used for?

2005-07-04 Thread Casey Hawthorne
To save a a few bytes (10?) per instance instead of having a dict to
hold attributes one has slots!

Designed for having lots of instances (millions?) at the same time to
save space!

"Ric Da Force" <[EMAIL PROTECTED]> wrote:

>I am a C# programmer and new to the language and I am trying to debug some 
>code which uses this feature.  Can anyone elaborate on what it is and how it 
>is used?
>
>Regards,
>
>Ric 
>

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


Re: What is Expresiveness in a Computer Language?

2005-07-10 Thread Casey Hawthorne
It is easier to write code a computer can understand than others can
understand!

It is harder to read code than to write code!

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


Re: IDLE in Jython

2005-07-15 Thread Casey Hawthorne
How about the following:

- making Jython mostly work up to Python 2.4?

- making a PVM (Python Virtual Machine) for the Palm?


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


Re: Strange os.path.exists() behaviour

2005-07-20 Thread Casey Hawthorne
Does this work differently under other platforms?

Pierre Quentel <[EMAIL PROTECTED]> wrote:

>os.path.exists(path) returns True if "path" exists
>
>But on Windows it also returns True for "path" followed by any number of 
>dots :
>
>Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
>Type "help", "copyright", "credits" or "license" for more information.
> >>> import os
> >>> os.path.exists('Lib/os.py')
>True# expected
> >>> os.path.exists('Lib/os.py.')
>True# unexpected
> >>> os.path.exists('Lib/os.py.')
>True# unexpected
> >>>
>
>Is there a reason for this ? Is there a test that returns True only for 
>the really existing path ?
>
>Pierre

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


Is there a way to determine -- when parsing -- if a word contains a builtin name or other imported system module name?

2005-08-03 Thread Casey Hawthorne
Is there a way to determine -- when parsing -- if a word contains a
builtin name or other imported system module name?

Like "iskeyword" determines if a word is a keyword!

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


Re: Creating Palm OS programs with python?

2005-08-10 Thread Casey Hawthorne
Apparently there is a PVM (Python Virtual Machine) for the Palm OS,
but it is several versions back!

Jython, might be better, but it is also a few versions back!

[EMAIL PROTECTED] wrote:

>QUick question:
>
>Is it possible to create a palm os program to use on a PDA with
>python?
>
>
>THanks
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Permutation Generator

2005-08-14 Thread Casey Hawthorne
It's hard to make "complete" permutation generators, Knuth has a whole
fascicle on it - "The Art of Computer Programming - Volume 4 Fascicle
2 - Generating All Tuples and Permutations" - 2005
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: up to date books?

2005-08-22 Thread Casey Hawthorne
Would you consider releasing an ebook in the mean time?

[EMAIL PROTECTED] wrote:

>Glad to hear that my efforts to cover some of 2.3's release features in
>a mostly-2.2 book were appreciated.  I'm probably going to do the same
>thing for the 2nd edition of the Nutshell: wait until 2.5 alpha's out
>so I can mention _its_ feechurz in a mostly-2.4 book... meaning the 2nd
>ed of the Nutshell may be almost a year away...
>
>
>Alex
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing, was Re: Bug in slice type

2005-08-24 Thread Casey Hawthorne
>contained in the range [start, end)

Does range(start, end) generate negative integers in Python if start
>= 0 and end >= start?
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Kill GIL

2005-02-15 Thread Adrian Casey
Aahz wrote:

> In article <[EMAIL PROTECTED]>,
> Frans Englich  <[EMAIL PROTECTED]> wrote:
>>
>>Personally I need a solution which touches this discussion. I need to run
>>multiple processes, which I communicate with via stdin/out,
>>simultaneously, and my plan was to do this with threads. Any favorite
>>document pointers, common traps, or something else which could be good to
>>know?
> 
> Threads and forks tend to be problematic.  This is one case I'd recommend
> against threads.

Multiple threads interacting with stdin/stdout?  I've done it with 2 queues. 
One for feeding the threads input and one for them to use for output.  In
fact, using queues takes care of the serialization problems generally
associated with many threads trying to access a single resource (e.g.
stdout).  Python Queues are thread-safe so you don't have to worry about
such issues.
-- 
http://mail.python.org/mailman/listinfo/python-list


Passing arguments to python from URL

2005-03-22 Thread Casey Bralla
I've got a python cgi-bin application which produces an apache web page.  I
want to pass arguments to it on the URL line, but the parameters are not
getting passed along to python properly.

I've been using sys.argv to pick up command line arguments, and it works
fine when I call the python program from the command line.  Unfortunately,
when I pass data to the program from the URL, many of the parameters are
being clobbered and **NOT** passed to python.


For example:  "http://www.nobody.com/cgi-bin/program.py?sort=ascending"; only
passes the parameter "/usr/lib/cgi-bin/program.py".  

However, "http://www.nobody.com/cgi-bin/program.py?sort%20ascending"; passes
a 2-place tuple of ("/usr/lib/cgi-bin/program.py", "sort ascending").

Somehow, adding the "=" in the argument list prevents **ANY** parameters
from being passed to python.  I could re-write the python program to work
around this, but I sure would like to understand it first.


Can anybody explain this weird behavior?

(Please reply to the news group...  my eMail address is a phony to prevent
spam.)


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


Read from Serial Port

2006-01-20 Thread Casey Bralla
I'd like to read ASCII data from a serial port, but (once again) I'm having
trouble getting started.  (Can't seem to find the basic level of docs to
get going )

I'd like to use only standard "built-in" modules if possible.

Could somebody offer a simple code-snippet to get me started reading from a
serial port?

Thanks!
-- 
Casey Bralla
Chief Nerd in Residence
The NerdWorld Organisation
http://www.NerdWorld.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Since there was talk of if-then-else not being allowed in lambda expressions, the following is from "Dive into Python"

2006-07-20 Thread Casey Hawthorne
Since there was talk of if-then-else not being allowed in lambda
expressions, the following is from "Dive into Python"

The and-or conditional expression trick from page 41 of "Dive into
Python"

Wrap the arguments in lists and then take the first element.

>>> a = ""
>>> b = "second"
>>> (1 and [a] or [b])[0]
''

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


Re: Fastest Way To Loop Through Every Pixel

2006-07-27 Thread Casey Hawthorne
Have you tried PIL? (Python Imaging Library)

"Chaos" <[EMAIL PROTECTED]> wrote:

>As my first attempt to loop through every pixel of an image, I used
>
>for thisY in range(0, thisHeight):
>for thisX in range(0, thisWidth):
>  #Actions here for Pixel thisX, thisY
>
>But it takes 450-1000 milliseconds
>
>I want speeds less than 10 milliseconds
>
>I have tried using SWIG, and pypy but they all are unsuccessfull in
>compiling my files.
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


Can Your Programming Language Do This? Joel on functional programming and briefly on anonymous functions!

2006-08-02 Thread Casey Hawthorne
Can Your Programming Language Do This?

Joel on functional programming and briefly on anonymous functions!

http://www.joelonsoftware.com/items/2006/08/01.html

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


Using signal.alarm to terminate a thread

2006-11-13 Thread Adrian Casey
I have a multi-threaded python application which uses pexpect to connect to
multiple systems concurrently.  Each thread within my application is a
connection to a remote system.  The problem is when one of the child
threads runs a command which generates an unlimited amount of output.  The
classic example of this is the "yes" command.  If you
execute "pexpect.run('yes')", your cpu will sit at 100% forever.

Here is a simple multi-threaded program using pexpect which demonstrates the
problem.  The command 'yes' is run in a thread.  The parent says that when
the alarm goes off, run the handler function.  The thread sets the alarm to
trigger after 5 seconds.

#!/usr/bin/env python
import signal, os, pexpect, threading

def handler(signum, frame):
# This should get called after 5 seconds when the alarm fires.
os.system('killall yes')
print "The yes command has been killed!"

def runyes():
# Run the 'yes' command in a thread.  Set an alarm
# to fire in 5 seconds.
signal.alarm(5)
print "Running yes command..."
# If you run 'sleep 10' instead, this works.
pexpect.run('yes')
# Re-set the alarm.  (This is never reached.  The 'yes'
# command runs forever and is not interrupted by the alarm)
signal.alarm(0)

signal.signal(signal.SIGALRM, handler)
t = threading.Thread(target=runyes)
t.start()
t.join()
# END of code

Note that if the 'yes' command is substituted for 'sleep 10', the code works
perfectly.

Why can't the 'yes' command be interrupted using the SIGALRM method when the
sleep command can?  I realize that noone would really run 'yes' but what if
a user account has a buggy .bashrc and loops forever?  Just one thread
locking up like this holds up all the others.

Any ideas or suggestions on how to handle such situations in a
multi-threaded way would be appreciated.

Cheers.
Adrian Casey.
Alice Springs Linux User Goup.
http://www.aslug.org.au
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using signal.alarm to terminate a thread

2006-11-14 Thread Adrian Casey
Nick Craig-Wood wrote:

> Adrian Casey <[EMAIL PROTECTED]> wrote:
>>  I have a multi-threaded python application which uses pexpect to connect
>>  to
>>  multiple systems concurrently.  Each thread within my application is a
>>  connection to a remote system.  The problem is when one of the child
>>  threads runs a command which generates an unlimited amount of output. 
>>  The
>>  classic example of this is the "yes" command.  If you
>>  execute "pexpect.run('yes')", your cpu will sit at 100% forever.
>> 
>>  Here is a simple multi-threaded program using pexpect which demonstrates
>>  the
>>  problem.  The command 'yes' is run in a thread.  The parent says that
>>  when
>>  the alarm goes off, run the handler function.  The thread sets the alarm
>>  to trigger after 5 seconds.
> 
> 1) Don't ever mix threads and signals - you are heading for trouble!
> 
> 2) pexpect has a timeout parameter exactly for this case
> 
> import os, pexpect, threading
> 
> def runyes():
> print "Running yes command..."
> pexpect.run('yes', timeout=5)
> 
> t = threading.Thread(target=runyes)
> t.start()
> t.join()
> 
The timeout parameter will not work in this case.  If you run the sample
code above, it will run forever.  The 'yes' command presents a class of
command which can not be easily be handled by pexpect.  As far as I know,
mixing threads and signals is OK provided the parent creates the alarm.

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


Re: Using signal.alarm to terminate a thread

2006-11-15 Thread Adrian Casey
Nick Craig-Wood wrote:

> Adrian Casey <[EMAIL PROTECTED]> wrote:
>> > Adrian Casey <[EMAIL PROTECTED]> wrote:
>> > import os, pexpect, threading
>> > 
>> > def runyes():
>> > print "Running yes command..."
>> > pexpect.run('yes', timeout=5)
>> > 
>> > t = threading.Thread(target=runyes)
>> > t.start()
>> > t.join()
>> > 
>>  The timeout parameter will not work in this case.  If you run the sample
>>  code above, it will run forever.
> 
> The above runs just fine for me, stopping after 5 seconds.  Did you
> try it?
> 
>>  The 'yes' command presents a class of command which can not be
>>  easily be handled by pexpect.
> 
> Worked for me under Debian/testing.
> 
>> As far as I know, mixing threads and signals is OK provided the
>> parent creates the alarm.
> 
> There are so many pitfalls here that I advise you not to try.  From
> the linuxthreads FAQ
> 
>   J.3: How shall I go about mixing signals and threads in my program?
> 
>   The less you mix them, the better. Notice that all pthread_*
>   functions are not async-signal safe, meaning that you should not
>   call them from signal handlers. This recommendation is not to be
>   taken lightly: your program can deadlock if you call a pthread_*
>   function from a signal handler!
> 
>   The only sensible things you can do from a signal handler is set a
>   global flag, or call sem_post on a semaphore, to record the delivery
>   of the signal. The remainder of the program can then either poll the
>   global flag, or use sem_wait() and sem_trywait() on the semaphore.
> 
>   Another option is to do nothing in the signal handler, and dedicate
>   one thread (preferably the initial thread) to wait synchronously for
>   signals, using sigwait(), and send messages to the other threads
>   accordingly.
> 
> Note also that the signal can be delivered to any thread which
> complicates things.
> 
I'm running Kubuntu 06-06 with python 2.4.3 and the above code runs forever
at 100% cpu utilization.  I shall look into semaphores. However, that means
another thread whose sole purpose is to watch the semaphore.

Thanks for you help.

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


PyPy with a smaller PVM for the full Python?

2006-09-10 Thread Casey Hawthorne
Currently PyPy is working toward compiling to C a restricted subset of
Python, called RPython.

Would it be possible for PyPy to "compile" the full subset of Python
by also using a lot smaller version of the PVM (Python Virtual
Machine) to go with the "compiled" code?
So, the user would be running the C object code and also a smaller
PVM!

Or would this completely remove or severely reduce any speed advantage
of the compiled code?


Similarly, for JPython (which is at Python 2.2?), could one also use a
lot smaller accompanying PVM with the JPython source code and JVM to
use Python 2.5 in its entirety?

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


curses won't refresh screen

2006-01-28 Thread Casey Bralla
For some reason, I can't get curses to refresh the screen.  Can someone
offer a suggestion to try to debug this?

Here is my python code snippet:

stdscr=curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
global screen
screen = stdscr.subwin(23, 79, 0, 0)
screen.border()

while 1 == 1:
screen.addstr(5,5, str(time.localtime()))
screen.refresh()



When  run this, the local time is displayed ONCE, and then never changes. 
Why isn't the screen.refresh() command refreshing the display?

I'm running a terminal session from within KDE, but I didn't think this
would matter.

Any ideas to suggest?
-- 
Casey Bralla
Chief Nerd in Residence
The NerdWorld Organisation
http://www.NerdWorld.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Curses won't update screen - Solved!

2006-01-28 Thread Casey Bralla
My problem was caused by a getch() function which paused, waiting for the
character.  Live and learn.  

For some reason, I can't get curses to refresh the screen.  Can someone
offer a suggestion to try to debug this?

Here is my python code snippet:

stdscr=curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
global screen
screen = stdscr.subwin(23, 79, 0, 0)
screen.border()

while 1 == 1:
        screen.addstr(5,5, str(time.localtime()))
        screen.refresh()

KeyPress = screen.getch()



When  run this, the local time is displayed ONCE, and then never changes. 
Why isn't the screen.refresh() command refreshing the display?

I'm running a terminal session from within KDE, but I didn't think this
would matter.

Any ideas to suggest?
-- 
Casey Bralla
Chief Nerd in Residence
The NerdWorld Organisation
http://www.NerdWorld.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Too Many if Statements?

2006-02-07 Thread Casey Hawthorne
Try the state(s) pattern!

"slogging_away" <[EMAIL PROTECTED]> wrote:

>Hi - I'm running Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310
>32 bit (Intel)] on win32, and have a script that makes numerous checks
>on text files, (configuration files), so discrepancies can be reported.
> The script works fine but it appears that I may have hit a wall with
>'if' statements.
>
>Due to the number of checks perfromed by the script on the text files,
>(over 500), there are quite a few 'if' statements in the script, (over
>1150).  It seems that it is at the point that when I add any additional
>'if' statements the script will not run.  No error is produced - it
>just returns to the python prompt much the same as when a successful
>'Check Module' command is selected.  If I delete some other 'if'
>statements the new ones work so it appears that it has hit a limit on
>the number of 'if' statements.  This has stunted any further checks for
>the script to make on the text files.
>
>Hs anyone ever run into this sort of thing?
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a question regarding call-by-reference

2006-02-08 Thread Casey Hawthorne
Don't send the whole list or parts of the list to the server unless
actually needed!

If the server has to do an append, have the server send back the new
elements to be appended and then do the appending on the client side!

Or

Does the homework specify that the entire mutable type be sent to the
server?


"enjoying the view" <[EMAIL PROTECTED]> wrote:

>I am working on a school project, trying to build a simple RPC stub
>generator. The idea is that the generator takes a normal python file
>with functions defined in it and produces a client and server stub. The
>client stub has the same functions defined, but they just connect to
>the server and ask it to call the desired functions. The server stub is
>a server listening for incoming requests and dispatching them to the
>appropriate functions and sending back the results. Extremely simple
>and I've gotten it to mostly work, but I have one problem:
>call-by-reference parameters. An example:
>
>A function like this:
>def sum(a, b):
>  return a + b
>
>would yield a client stub like this (simplified):
>def sum(a, b):
>   send_message({'funcname': 'sum', 'args': (a, b)})
>   result = receive_message()
>   return result
>
>Now, this works just fine. I get problems when I try to do something
>like this:
>def add_elm(list):
>   list.append('elm')
>   return
>
>Imported normally this would work fine. The list given as a parameter
>would be one element larger. But when the stubs are generated, the
>function doesn't return anything and the list is appended in the server
>and the client-side list is left untouched. At first I thought the
>solution was easy, just return the changed parameters and place them in
>the parameter variables in the client stub:
>def add_elm(list):
>   send_message({'funcname': 'add_elm', 'args': (list)})
>   response = receive_message()
>   (list) = response.get('args')
>   return response.get('result')
>
>The problem is, this doesn't work. The original list doesn't point to
>the changed list. I have been trying to figure this out and it seems
>that if I just assign to the list variable it just modifies the local
>(to the function) name space, and that those changes aren't reflected
>in the list in the original name space.
>
>I believe there are some ways around this, but I haven't found one that
>would not require any special handling in either the code calling the
>client stub or the original functions. I want to maintain transparency.
>
>etv
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: May i customize basic operator (such as 1==3)?

2006-02-21 Thread Casey Hawthorne
I believe you are asking for a side effect from the "==" operator.

Add print statements to the __eq__ method.

"kanchy kang" <[EMAIL PROTECTED]> wrote:

>Hi,all
>as we know, we can override the operator of one object(for example __eq__).
>my question is, how to override the basic operator?
>for example,
>
>for any object comparison operator(including litterals),
>for example,
>a = "123"
>b = "321"
>
>the boolean equation a == b,
>i need override "==" operator like this:
>first display a and b
>
>then return real boolean result (a == b).
>
>thanks!
>
>
>---
>Best regards,
>kangzz
>
>mailto:[EMAIL PROTECTED]
>Tel : 021-65407754
>MP: 13916928084
>
>_
>Express yourself instantly with MSN Messenger! Download today - it's FREE! 
>http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: May i customize basic operator (such as 1==3)?

2006-02-22 Thread Casey Hawthorne
Cannot one subclass the builtin types?

I have heard, that one should always use objects when programming and
avoid the builtin types!

Then one is prepared to change objects at will and not rely on any
special properties of the builtin types!


Robert Kern <[EMAIL PROTECTED]> wrote:

>Casey Hawthorne wrote:
>> I believe you are asking for a side effect from the "==" operator.
>> 
>> Add print statements to the __eq__ method.
>
>The things is, he wants to make those modifications to builtin types, which he
>can't do.
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


pexpect: TIMEOUT exception never raised

2005-05-12 Thread Adrian Casey
I have a python script which uses pexpect and I want to timeout (i.e. raise
pexpect.TIMEOUT) if a long running command does not produce the output I am
expecting.  To simulate the 'long running command', consider the following
example which simply runs the 'yes' command which prints an endless series
of 'y' characters to the terminal.  I want to timeout after 10 seconds -:

child=pexpect.spawn('ssh [EMAIL PROTECTED]')
child.sendline('yes')
child.expect([pexpect.TIMEOUT, "the pattern I'm expecting"],10)

In this situation, pexpect.TIMEOUT will never be raised.  The TIMEOUT
exception is only raised if *no* output is received or the output has
completed and the pattern expected is not matched within the timeout
period.  But what about situations where a command produces an infinite
amount of output?  In the above example, the child.expect statement will
hang forever.

I thought about using signal.signal to set an alarm that fires a few seconds
after timeout and explicitly closes the session.  However, my application
is multi-threaded (i.e. each thread respresents a connection to a remote
host) and signals can not be used outside the main thread :-(

Any ideas?

Cheers.
Adrian Casey.
-- 
http://mail.python.org/mailman/listinfo/python-list


Is there a better way to delete the image from a Tkinter button other than the following:

2005-05-12 Thread Casey Hawthorne
Is there a better way to delete the image from a Tkinter button other
than the following:

- reconstructing the button

- image=blank.gif


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


Re: Information about Python Codyng Projects Ideas

2005-06-01 Thread Casey Hawthorne
The slightly slower startup time makes no difference for apps running
24 hours a day, except when reloading changed source modules!

I imagine reloading modules is also slower -- but I could be 
mis  t
  ak
   en!

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


Re: [ANN] Update to Python Quick Reference Card (for Python 2.4) (v0.67)

2007-05-02 Thread Casey Hawthorne
PC-cillin flagged this as a dangerous web site.

Laurent Pointal <[EMAIL PROTECTED]> wrote:

>PQRC (Python Quick Reference Card) is a condensed documentation for 
>Python and its main libraries, targetting production of printed quick 

>http://www.limsi.fr/Individu/pointal/python/pqrc/
>
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a better solution for GUI in python

2007-03-11 Thread Casey Hawthorne
For a browser interface have you thought of Ajax and possibly WPF/E?

http://en.wikipedia.org/wiki/AJAX

http://en.wikipedia.org/wiki/Windows_Presentation_Foundation
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which is better, string concatentation or substitution?

2006-05-08 Thread Casey Hawthorne
[EMAIL PROTECTED] (Roy Smith) wrote:

>O(n^0), which is almost always written as O(1).  This is a "constant
>time" algorithm, one which takes the same amount of steps to execute
>no matter how big the input is.  For example, in python, you can
>write, "x = 'foo'".  That assignment statement takes the same amount
>of time no matter how long the string is.  All of these execute in the
>same number of steps:
>
>   x = ''
>   x = 'foo'
>   x = 'a very long string with lots and lots of characters'
>
>We can say that "assignment is constant time", or "assignment is
>O(1)".

Constant time if converted to byte code or compiled?

O(n) in string length if being interpreted?
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New tail recursion decorator

2006-05-12 Thread Casey Hawthorne
Your examples are not tail recursive because an extra step is needed
before returning from the function call and that step cannot be thrown
away!

Alexander Schmolck <[EMAIL PROTECTED]> wrote:

>def even(n):
>return n == 0 or not odd(n-1)
>
>def odd(n):
>return n == 1 or not even(n-1)
>

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


Tail Call Optimization Decorator?

2006-05-13 Thread Casey Hawthorne
Tail Call Optimization and Recursion are separate concepts!
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


For Large Dictionaries Could One Use Separate Dictionaries Where Each Dictionary Covers an Interval of the Input Range?

2006-05-16 Thread Casey Hawthorne
For Large Dictionaries Could One Use Separate Dictionaries Where Each
Dictionary Covers an Interval of the Input Range? 

You would need to know something of the input range and its
uniformity!

Self-balancing between dictionaries for separate dictionaries?
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


Is the only way to connect Python and Lua through a C interface?

2006-05-16 Thread Casey Hawthorne
Is the only way to connect Python and Lua through a C interface?
--
Regards,
Casey
-- 
http://mail.python.org/mailman/listinfo/python-list


Extending the readline module?

2008-01-16 Thread Casey Rodarmor
Hi everyone,

I'm writing a little curses-mode utility for renaming files using regexes,
and I want to use GNU readline to get user input. However, it looks like the
readline module doesn't support all of readline's functionality. I've looked
around, and it looks like the best thing to do would be to try to extend the
readline module myself to expose the functions I need. I'm exited to try to
tackle the project, and it would be nice to get in touch with the maintainer
of the module, so that I can get some advice and maybe try to get my
additions included in the main branch.

What is the best way to go about doing this?

Best regards,
Casey Rodarmor
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Replace stop words (remove words from a string)

2008-01-17 Thread Casey Rodarmor
That's much better than what I was about to post:

for s in stoplist:
   string.join(mystr.split(s, ""))

Berlin: Why are you keen on avoiding split()?

On 1/17/08, Karthik <[EMAIL PROTECTED]> wrote:
>
> How about -
>
> for s in stoplist:
> string.replace(mystr, s, "")
>
> Hope this should work.
>
> -Original Message-
> From: [EMAIL PROTECTED]
> [mailto:[EMAIL PROTECTED] On Behalf Of
> BerlinBrown
> Sent: Thursday, January 17, 2008 1:55 PM
> To: [email protected]
> Subject: Replace stop words (remove words from a string)
>
> if I have an array of "stop" words, and I want to replace those values
> with something else; in a string, how would I go about doing this.  I
> have this code that splits the string and then does a difference but I
> think there is an easier approach:
>
> E.g.
>
> mystr =
>
> kljsldkfjksjdfjsdjflkdjslkf[BAD]Kkjjkkjk[BAD]LSKJFKSFJKSJF;L[BAD2]kjsldf
> sd;
>
> if I have an array stop_list = [ "[BAD]", "[BAD2]" ]
>
> I want to replace the values in that list with a zero length string.
>
> I had this before, but I don't want to use this approach; I don't want
> to use the split.
>
> line_list = line.lower().split()
> res = list(set(keywords_list).difference(set(ENTITY_IGNORE_LIST)))
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Stop tab-completing empty lines!

2008-01-17 Thread Casey Rodarmor
Hi everybody,

I have the following in my python startup file:

import readline, rlcompleter
readline.parse_and_bind("tab: complete")

This lets me tab complete identifiers in the interpreter beautifully, but
there's a tiny problem... If I'm sitting at the beginning of a blank line
and just want a tab, it tries to tab complete, which kind of a pain.

-=SIMULATED PYTHON PROMPT=-
>>> def mega_awesome_function(cool_stuff, **some_sweet_kwargs):
... X

(The X is where I press tab and get super annoyed)

I could just rebind the key, but i like tab ;-) Any suggestions?

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

Different results when running script from IDLE versus Command Line

2008-03-12 Thread Casey T
Hi,

I'm new to Python and I'm having some problems with getting different
results from my script when I run it from IDLE versus just double-
clicking the .py file and having it run through the command line.
Basically, my script reads some CSV files, assembles a text files,
then uploads that test file to an ftp site. When I run the script from
IDLE, everything works fine. But when it runs from the command line,
the file that gets uploaded is empty. It seems that it is creating a
new file to upload, rather than using the existing file (or at least
that's what I think is going on.) Below is my script. I apologize for
any ugly code. Thanks for your help.

import sys,os,linecache,csv,ftplib,time

starttime = time.time()

#***
#Summary file assembling
#***
currentdir = "//folder/"

reg_sum = open('reg_sum.txt','w')
reg_sum.close

for files in os.listdir(currentdir):
reg_file = csv.reader(open(currentdir + files))
for row in reg_file:
reg_sum = open('reg_sum.txt','a')
reg_sum.write(",".join(row) + ',\n')

reg_sum.close

#***
#Summary file processing
#***
coordList = [
["F10",40.0053,-75.0927],
["T10",40.0272,-75.1123],
["D22",39.9811,-75.0998],
["P02",40.0437,-75.0217],
["D68",39.9203,-75.1388],
["D51",39.9534,-75.1405],
["S43",39.9217,-75.2275],
["S33",39.9360,-75.2077],
["S42A",39.9215,-75.1937],
["S05",39.9617,-75.1782],
["T14",40.0165,-75.1077]]

coordList_index =
["F10","T10","D22","P02","D68","D51","S43","S33","S42A","S05","T14"]
#coordList_index is a list containing

in_text = open('reg_sum.txt','r')

out_text = open('reg_out.txt','w')
out_text.close

out_text = open('reg_out.txt','a')

for line in in_text:
split_line = line.split(',')
if (split_line[0]) in coordList_index:
   i = coordList_index.index(split_line[0])
   coords = str(coordList[i][1]) + "," + str(coordList[i][2])
   last_update = str(split_line[2])
print str(split_line[0])
if split_line[1] == "1":
   out_text.write(split_line[0] + ",Test1: " + last_update +
"," + coords + ",1" + "\n")
elif split_line[1] == "0":
   out_text.write(split_line[0] + ",Test2.Last updated: "
+ last_update + ","  + coords + ",0" + "\n")
else:
   out_text.write(split_line[0] + ",No data.," + coords +
"\n")

in_text.close

###***
###Uploads file via FTP
###***
s = ftplib.FTP('ftp.blah123.org,'user','pass')

f.open('reg_out.txt','r')
s.storlines('STOR reg_out.txt', f)

f.close()
s.quit()

print  "Processed in " + str(((time.time() - starttime) / 60) *60) + "
seconds!" #prints elapsed time
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Different results when running script from IDLE versus Command Line

2008-03-13 Thread Casey T
On Mar 12, 5:28 pm, Chris <[EMAIL PROTECTED]> wrote:
> On Mar 12, 8:10 pm, Casey T <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi,
>
> > I'm new to Python and I'm having some problems with getting different
> > results from my script when I run it from IDLE versus just double-
> > clicking the .py file and having it run through the command line.
> > Basically, my script reads some CSV files, assembles a text files,
> > then uploads that test file to an ftp site. When I run the script from
> > IDLE, everything works fine. But when it runs from the command line,
> > the file that gets uploaded is empty. It seems that it is creating a
> > new file to upload, rather than using the existing file (or at least
> > that's what I think is going on.) Below is my script. I apologize for
> > any ugly code. Thanks for your help.
>
> > import sys,os,linecache,csv,ftplib,time
>
> > starttime = time.time()
>
> > #***
> > #Summary file assembling
> > #***
> > currentdir = "//folder/"
>
> > reg_sum = open('reg_sum.txt','w')
> > reg_sum.close
>
> > for files in os.listdir(currentdir):
> >     reg_file = csv.reader(open(currentdir + files))
> >     for row in reg_file:
> >         reg_sum = open('reg_sum.txt','a')
> >         reg_sum.write(",".join(row) + ',\n')
>
> > reg_sum.close
>
> > #***
> > #Summary file processing
> > #***
> > coordList = [
> >     ["F10",40.0053,-75.0927],
> >     ["T10",40.0272,-75.1123],
> >     ["D22",39.9811,-75.0998],
> >     ["P02",40.0437,-75.0217],
> >     ["D68",39.9203,-75.1388],
> >     ["D51",39.9534,-75.1405],
> >     ["S43",39.9217,-75.2275],
> >     ["S33",39.9360,-75.2077],
> >     ["S42A",39.9215,-75.1937],
> >     ["S05",39.9617,-75.1782],
> >     ["T14",40.0165,-75.1077]]
>
> > coordList_index =
> > ["F10","T10","D22","P02","D68","D51","S43","S33","S42A","S05","T14"]
> > #coordList_index is a list containing
>
> > in_text = open('reg_sum.txt','r')
>
> > out_text = open('reg_out.txt','w')
> > out_text.close
>
> > out_text = open('reg_out.txt','a')
>
> > for line in in_text:
> >     split_line = line.split(',')
> >     if (split_line[0]) in coordList_index:
> >        i = coordList_index.index(split_line[0])
> >        coords = str(coordList[i][1]) + "," + str(coordList[i][2])
> >        last_update = str(split_line[2])
> >     print str(split_line[0])
> >     if split_line[1] == "1":
> >        out_text.write(split_line[0] + ",Test1: " + last_update +
> > "," + coords + ",1" + "\n")
> >     elif split_line[1] == "0":
> >        out_text.write(split_line[0] + ",Test2.Last updated: "
> > + last_update + ","  + coords + ",0" + "\n")
> >     else:
> >        out_text.write(split_line[0] + ",No data.," + coords +
> > "\n")
>
> > in_text.close
>
> > ###***
> > ###Uploads file via FTP
> > ###***
> > s = ftplib.FTP('ftp.blah123.org,'user','pass')
>
> > f.open('reg_out.txt','r')
> > s.storlines('STOR reg_out.txt', f)
>
> > f.close()
> > s.quit()
>
> > print  "Processed in " + str(((time.time() - starttime) / 60) *60) + "
> > seconds!" #prints elapsed time
>
> You never closed your file.
>
> file_object.close
> 
>
> try adding '()' at the end of your close calls.
> As to why it differs, I can't think offhand why it wouldn't.

wow. thank you so much. it was the '()'. I now get consistent results.
In all the sample code I saw, I never saw the '()' after close. thanks
again

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


Is there anyway Vpython and pyODE can be made to work with newer versions of Python 2.6.1 etc. without a lot of changes to source code?

2009-01-23 Thread Casey Hawthorne
Is there anyway Vpython and pyODE can be made to work with newer
versions of Python 2.6.1 etc. without a lot of changes to source code?

I suppose I'm thinking of an extra layer of indirection, which might
slow things down to much.

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


Re: Google App Engine Code Challenge - write a tetris playing algorithm

2008-12-01 Thread Casey McGinty
On Sun, Nov 30, 2008 at 2:41 PM, russ.au <[EMAIL PROTECTED]> wrote:

> I've got more features to add, depending on how
> popular it is.. 
>

Are you going to create a leader board to track the high scores?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Google App Engine Code Challenge - write a tetris playing algorithm

2008-12-01 Thread Casey McGinty
Well, I think its a cool idea. I might try it out if I can find some free
cycles.

And does the game logic assume the pieces come straight down? For example,
what if you wanted to move a piece to the left or right after its past some
vertical obstruction? For example If you place and upside down 'j' or 'l',
is there any way to fill in the two blocked squares, without removing the
top portion first?

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


  1   2   >