AIX Subversion Python Swig Bindings fix for core dump

2007-12-05 Thread Reedick, Andrew
If you're on AIX and Python immediately dumps core when trying to import
any SVN module, then adding "-Wl,-brtl" to LINKFORSHARED in the Makefile
seems to fix the problem.
 
Bad:   > LINKFORSHARED=-Wl,-bE:Modules/python.exp -lld
Good:  < LINKFORSHARED=-Wl,-bE:Modules/python.exp -lld -Wl,-brtl

1.  unset PYTHONPATH
2.  ./configure --without-gcc --disable-ipv6 --with-thread
CC=/usr/vac/bin/xlc_r CXX=/usr/vacpp/bin/xlC_r 
3.  Edit Makefile:  LINKFORSHARED=  -Wl,-bE:Modules/python.exp -lld
-Wl,-brtl 
4.  make CC=/usr/vac/bin/xlc_r CXX=/usr/vacpp/bin/xlC_r OPT="-O2
-qmaxmem=4000"
5.  make install

Oddly enough, there was no need to build Python using shared libraries.
("#*shared* in Modules/Setup was left commented out and --enable-shared
was not used.)  The OPT="..." is described in
Python-2.5.1/Misc/AIX-NOTES.

This was on AIX 5.3, xlc_r 9.0, Python 5.2.1, Subversion 1.4.5.  It also
appears to work using gcc and Python 2.4.4.

Thanks to Andy Nocera for figuring it out before 'Plan B: Blood
Sacrifice While Doing the Hokey-Pokey' was implemented.




*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


dictionary/hash and '1' versus 1

2008-01-03 Thread Reedick, Andrew
As a Perl monkey in the process of learning Python, I just stepped on
the "'1' (string) is not the same as 1 (integer) in regards to keys for
dictionaries/hashes" landmine.  Is there a good way to ensure that
numbers represented as strings or ints do not get mixed up as keys?

Example of the problem:
>>> h2 = { 1 : ''}
>>> print h2.has_key(1)
True
>>> print h2.has_key('1')
False

The problem occurred because a method used to generate keys was
returning a string instead of a number without an explicit conversion
taking place.  And since I was using hash.get(i, default_value) to avoid
having to pair every key lookup with a hash.has_key(), no exception was
thrown when the key wasn't found.

It's fugly to wrap every key reference in str(), ex:
foo[str(some_func(i))].  It's tedious to add a has_key before every key
lookup.  And I have no real desire to stuff every hash inside a class in
order to ensure that keys are converted to strings.

Any good solutions or accepted practices to prevent the intermixing of
number strings and integers as hash keys?  A hash wrapper class seems to
be the best bet so far.



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


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


RE: dictionary/hash and '1' versus 1

2008-01-04 Thread Reedick, Andrew
> From: Stephen Hansen [mailto:[EMAIL PROTECTED] 
> Sent: Thursday, January 03, 2008 7:39 PM
> To: Reedick, Andrew
> Cc: python-list@python.org
> Subject: Re: dictionary/hash and '1' versus 1
>
>
>
> Well one important thing to learn while learning Python is that while the  
> language is dynamically typed-- it is also /strongly/ typed. Every piece
> of data has an explicit type and it doesn't change unless you change it.

Meh, mixing dynamic and strong typing is a mixed blessing.  You don't 
find out that you screwed up the data types until the code block is actually 
executed.  Reminds me of Nostradamus.  He may have predicted the future[1], but 
the predictions are so vague/convoluted that you can only figure out the 
predictions in hindsight.


> It relies on duck typing a lot, and doesn't care if you mix and match 
> (even partially) compatible types as long as the operations are there,
> but one type will always be distinct and remain that type until you
> explicitly convert it.
>
> A single integer is distinctly different from a sequence of characters in
> some encoding that may just happen to contain representations of a
> number so they'll hash differently :)

Depends on the context.  The machine encoding may be different, but in 
human terms they "should" be the same.  Perl managed to achieve an impressive 
blend of presenting data as human friendly or as machine bits when it made 
sense to do so.  So much so, that Perl is probably the only language I've used 
that will do what you mean instead of what you say.  Nice, but frightening in 
some ways.


> One type will basically never implicitly convert into another type.
>
> To me, this sounds like the function should have converted the type 
> explicitly on return. Or maybe you need to convert it explicitly on
> receipt.

Type casting is easy, IFF you remember to do so.  The problem was that 
I missed the fact that one (important) function was returning a string instead 
of an int, and since Python supports heterogenous data structures, the human 
has to remember to keep the key's data type homongenous.
That and Perl does so much automatic type conversion in such a sensible 
way, that I stopped worrying about mixing data types, which is making the 
Python transition a tad more error prone.  Because of Perl, I almost consider 
automatic type casting to be the next "you don't have to manage your own 
memory" that people loved about Java.  =O


> But if you are in a use-case where you really don't care and only 
> want to hash strings, you can create a dict subclass easily that
> overrides __setitem__ to always str() the input. Check out the
> UserDict class.

UserDict looks like it could be useful.  Thanks for the info.


> A similar method lets you make 'case-insensitive' dicts, for example.
>
> Were such a thing to happen automagically, you could get some 
> weird situations, such as "assert (key in dict) == (key in dict.keys())" 
> failing.

I'm assuming that you would just need to overload the 'in' operator and 
.keys() method to be case insensitive also.




[1]  No, he didn't.


*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA625


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


RE: dictionary/hash and '1' versus 1

2008-01-07 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Steven D'Aprano
> Sent: Saturday, January 05, 2008 7:01 PM
> To: python-list@python.org
> Subject: Re: dictionary/hash and '1' versus 1
> 
> The problem with automatic conversions between strings and integers is
> that it isn't clear what the user wants when they do something like
> this:
> 
> >>> x = '1' + 1
> 
> Should x be the string '11' or the int 2? Please justify your answer.
> 
> 
> On the other hand, if the language includes separate operators for
> addition and concatenation (say, + and &) then that sort of auto-
> conversion is no longer ambiguous:
> 
> >>> '2' + 3
> 5
> >>> '2' & 3
> '23'


Bingo.  Perl has specific operators to establish intent:
> Perl -e "'1' + 1"
> 2
> Perl -e "'1' . 1"
> 11
'+' is the operator for addition
'.' is the operator for string concatenation

int and string comparisons also have specific operators:
$a == $b  # compare as integers:  ==,  >,  <, <=, >=
$a eq $b  # compare as strings:   eq, gt, lt, le, ge


Which now morphs the conversation into the issue of how too much
operator overloading creates confusion and/or ambiguity.



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


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


RE: dictionary/hash and '1' versus 1

2008-01-07 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Paddy
> Sent: Monday, January 07, 2008 12:52 PM
> To: python-list@python.org
> Subject: Re: dictionary/hash and '1' versus 1
> 
> Or how using different operators for similar operations on different
> types causes confusion.
> i.e. == versus eq; > versus gt
> If Perl had, for example, a complex number 'base' type would that need
> yet another set of operators?

The real question is: what's the simplest way to implement complex
numbers without sacrificing understanding, accuracy, and convenience?  I
would say, no new operators.  Imaginary numbers are numbers and should
use numeric operations which means overloaded match operators. 

As background:  In order to keep things simple, Perl's string operators
are string-like.  Math operators are math.
'2' * 5 = 10
'2' x 5 = '2'  ('x' is a char, so think strings)
==, >, >=, <, <=
eq, gt, ge, lt, le (string abbreviations for equal, greater
than, etc.)
'1' + 1 = 2
'1' . 1 = 11(Think period at the end of a sentence, which
implies stringing strings together.) 


> Well enough Perl vs Python. The thing is, that when writing in another
> programming language you have to use its idioms or you end up fighting
> the language in attempt to make it work like another language you are
> more familiar with. In Python strings won't ever automatically change
> to numbers.

Agreed.  However looking towards the future (new versions of
Perl/Python, new languages, new paradigms) is it worth asking whether
it's better/clearer/easier/more_accurate to 
a) type cast the data: a + b  (a and b must be of the same type)

a.1)  explicitly type cast the data:  str(a) + str(b)
(if a and b are different types)
b) type cast by operator: '1' + 1 = 2; '1' . 1 = '11' 
c) go really old school with: concat('1', 1); add('1', 1)

IMO, since Python is strongly but dynamically typed, a) is the 'worst'
solution.  If you forget to type cast, you're boned, since you probably
won't find the problem until the code block is actually executed and an
exception is thrown.  You could defensively type cast everything, but
that can clutter the code, and cluttered code is harder to understand
and keep bug free.  With b) or c), the compiler will type cast as you
intended.  Again, just my opinion.

Anyway, it's little things like '1' + 1 that will probably prevent
programming syntax from ever being similar to naturally spoken language.


*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: 'Borg' and multiple threads.

2008-01-09 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Tobiah
> Sent: Monday, January 07, 2008 5:24 PM
> To: python-list@python.org
> Subject: 'Borg' and multiple threads.
> 
> I have a class that I call Borg that starts like this:
> 
> class Borg(dict):
> 
> static_state = {}
> def __init__(self):
> self.__dict__ = self.static_state
> 
> 
> 
> My question is why this seems to work.  I had the idea that
> there was a class object that is created when the file containing
> the definition is read, which actually contains the static
> information that is later accessed by instances.  Isn't this
> done when the cherrypy app first loads, rather than each time
> a browser hits the app?  Otherwise, where is the individual data
> stored for each of two simultaneous hits of the web page?
> 


I had a similar question except mine was from a bug.  (Thinking in c++
lead me to inadvertently create static class vars.)  

You can "print self" and use the id() function to get the memory
addresses of the variables and see what's going on.  In the code below,
mem4 is equivalent to your static_state.

count = 1

class Foo:

mem4 = {}
mem5 = {}

def __init__(self):
self.mem = {}

global count
count += 1
self.mem2 = count

self.mem3 = "%x" % (id(self))

self.mem5 = {}

print 'init count =', count


def me(self):
print "object:  ", self
print "\tid(self.mem)  %x" % (id(self.mem)), " self.mem
=", self.mem
print "\tid(self.mem2) %x" % (id(self.mem2)), "
self.mem2 =", self.mem2
print "\tid(self.mem3) %x" % (id(self.mem3)), "
self.mem3 =", self.mem3
print "\tid(self.mem4) %x" % (id(self.mem4)), "
self.mem4 =", self.mem4
print "\tid(self.mem5) %x" % (id(self.mem5)), "
self.mem5 =", self.mem5
global count
count += 1
print '\tcount =', count
self.mem4[count] = count
print "\tid(self.mem4) %x" % (id(self.mem4)), "
self.mem4 =", self.mem4
#self.mem += count
#print "\tid(self.mem)  %x" % (id(self.mem)), " self.mem
=", self.mem
print


a = Foo()
b = Foo()
c = Foo()

a.me()
b.me()
c.me()
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: printing dots in simple program while waiting

2008-01-09 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Martin Marcher
> Sent: Wednesday, January 09, 2008 11:57 AM
> To: python-list@python.org
> Subject: Re: printing dots in simple program while waiting
> 
> John wrote:
> 
> > import time
> > s = '.'
> > print 'working', # Note the "," at the end of the line
> > while True:
> > print s
> > time.sleep(1)
> 
> see my comment in the code above...
> 
> if that's what you mean
> 


Bah.  The trailing command may prevent the newline, but it appends a
space whether you want it or not.[1]  Use sys.stdout.write('.') instead.

import sys

print "wussy nanny state, tax 'n spend my spaces, liberal comma:"
for i in range(1, 10):
print '.',
print
print "manly neo-con I know what's Right so keep your government out of
my strings! print:"
for i in range(1, 10):
sys.stdout.write('.')

[1] Which has to be _the_ most annoying feature of Python.  *grrr*

*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA625


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


RE: problem of converting a list to dict

2008-01-09 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Fredrik Lundh
> Sent: Wednesday, January 09, 2008 2:39 PM
> To: python-list@python.org
> Subject: Re: problem of converting a list to dict
> 
> [EMAIL PROTECTED] wrote:
> 
> >> to see what's going on on your machine, try printing "a" after the
> >> split, but before you use it to populate the dictionary.
> >
> > 'print a' works
> 
> so what does it tell you?
> 

A bigger hint:
a=i.split('=')
print "'%s' splits into " % (i), a
assert len(a) == 2
mydict[a[0]]=a[1]


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


RE: problem of converting a list to dict

2008-01-09 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of John Machin
> Sent: Wednesday, January 09, 2008 3:02 PM
> To: python-list@python.org
> Subject: Re: problem of converting a list to dict
> 
> On Jan 10, 6:52 am, "Reedick, Andrew" <[EMAIL PROTECTED]> wrote:
> >
> > A bigger hint:
> > a=i.split('=')
> > print "'%s' splits into " % (i), a
> 
> consider:
> (1) using %r instead of '%s'

Eh, personal preference depending on how sure you are of the
data's type. 

> (2) omitting the redundant space after 'into'

Some of us coming in from other languages and still aren't used
to the comma adding an unwanted space after everything.  I've been
tempted to root around in Python's source code to fix the problem.

> (3) losing the redundant () around i

For me, the () is there for readability.  Python's sprintf
syntax is odd to begin with, and something like 
print "'%s' splits into " % i, a, b, c
means either
1) you really do want to append b and c after the
sprintf, or
print "'%s' splits into " % (a), b, c
2) that the formatting string is missing a few things 
print "'%s' splits into " % (a, b, c)  ## Ooops!
forgot to change it to "%s %5.2d %6.3f"


*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA622


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


RE: Newbie question on Classes

2008-01-10 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Adrian Wood
> Sent: Thursday, January 10, 2008 4:47 PM
> To: python-list@python.org
> Subject: Newbie question on Classes
> 
> 
> I can call man.state() and then woman.state() or Person.state(man) and
> Person.state(woman) to print the status of each. This takes time and
> space however, and becomes unmanageable if we start talking about a
> large number of objects, and unworkable if there is an unknown number.
> What I'm after is a way to call the status of every instance of Man,
> without knowing their exact names or number.
> 



How about searching the garbage collector?

import gc
from random import random

class Person:
def __init__(self):
self.data= random() * 1000 + 1

def WhoAmI(self):
return self.data


a = Person()
b = Person()

for i in gc.get_objects():
try:
# classes have __class__ and __dict__ defined according to the
docs
if i.__class__ and i.__dict__ :
print i.__class__
if str(i.__class__) == '__main__.Person':
print "\tI am", i.WhoAmI()
except:
pass



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA622


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


RE: python recursive function

2008-01-11 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Tom_chicollegeboy
> Sent: Friday, January 11, 2008 3:30 AM
> To: python-list@python.org
> Subject: python recursive function
> 
> Now, you are to write a program that, if I give you n bears, returns
> true if it is at all possible for you to win the game. Your program
> must use recursion to check all possible ways in which you can apply
> the rules.
> 

> if n==42:
> return True

> return False

You have to check for all possible paths.  Returning True/False is
futile since the recursive chains will be returning a mix of true and
false.  Use a global variable to indicate if a solution is found.  (Or
pass the flag in using a list, since lists are passed by reference (if n
== 42: found_it[0] = True; return.)

There's also another teaching exercise in here.  Do you follow the
literal directions ('check all possible ways') and generate all possible
paths?  Or do you 'interpret' that to mean try all possible paths until
you find a solution?  (i.e. do you short circuit the recursion once you
have a solution?)

One of the most difficult things about programming is conveying the
requirements from Human A to Human Programmer B.  This is especially
difficult since business people and techies speak different languages
and, more importantly, think differently (different assumptions,
different paradigms, different levels of hand-waving away of details,
etc..)  And don't get me started about the people in marketing...



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


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


RE: reading a specific column from file

2008-01-11 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Ivan Novick
> Sent: Friday, January 11, 2008 12:46 PM
> To: python-list@python.org
> Subject: Re: reading a specific column from file
> 
> 
> You say you would like to "read" a specific column.  I wonder if you
> meant read all the data and then just seperate out the 3rd column or
> if you really mean only do disk IO for the 3rd column of data and
> thereby making your read faster.  The second seems more interesting
> but much harder and I wonder if any one has any ideas.  

Do what databases do.  If the columns are stored with a fixed size on
disk, then you can simply compute the offset and seek to it.  If the
columns are of variable size, then you need to store (and maintain) the
offsets in some kind of index.



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


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


RE: split parameter line with quotes

2008-01-11 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of teddyber
> Sent: Friday, January 11, 2008 1:51 PM
> To: python-list@python.org
> Subject: split parameter line with quotes
> 
> Hello,
> 
> first i'm a newbie to python (but i searched the Internet i swear).
> i'm looking for some way to split up a string into a list of pairs
> 'key=value'. This code should be able to handle this particular
> example string :
> 
> qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des,
> 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess
> 
> i know i can do that with some regexp (i'm currently trying to learn
> that) but if there's some other way...
> 

import re
s='''qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des,3des",m
axbuf=1024,charset=utf-8,algorithm=md5-sess'''
print s

all = re.findall(r'(.*?)=(".*?"|[^"]*?)(,|$)', s)
print all

for i in all:
print i[0], "=", i[1].strip('"')


Output:
qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des,3des",maxbuf
=1024,charset=utf-8,algorithm=md5-sess

[
('qop', '"auth,auth-int,auth-conf"', ','), 
('cipher', '"rc4-40,rc4-56,rc4,des,3des"', ','), 
('maxbuf', '1024', ','), 
('charset', 'utf-8', ','), 
('algorithm', 'md5-sess', '')
]

qop = auth,auth-int,auth-conf
cipher = rc4-40,rc4-56,rc4,des,3des
maxbuf = 1024
charset = utf-8
algorithm = md5-sess




*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: Newbie question on Classes

2008-01-11 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of John Machin
> Sent: Friday, January 11, 2008 4:08 PM
> To: python-list@python.org
> Subject: Re: Newbie question on Classes
> 
> On Jan 11, 9:27 am, "Reedick, Andrew" <[EMAIL PROTECTED]> wrote:
> > > -Original Message-
> > > From: [EMAIL PROTECTED]
[mailto:python-
> > > [EMAIL PROTECTED] On Behalf Of Adrian Wood
> > > Sent: Thursday, January 10, 2008 4:47 PM
> > > To: [EMAIL PROTECTED]
> > > Subject: Newbie question on Classes
> >
> >
> > How about searching the garbage collector?
> 
> Not a good idea, because gc is an implementation artifact and in fact
> is specific to the C Python implementation; you won't find it in e.g.
> Iron Python or Jython.
> 

a) I forgot the ';-)' and/or  tag.

b) It was junk code.  A cleaner loop would be (which I figured out 5
minutes after posting =P ):
for i in gc.get_objects():
if isinstance(i, Person):
print i.__class__, "%x" % id(i), i.SomeMethod()

c) It's good to know about GC being CPython only.

d) You forgot to mention the problem that some of the objects could be
'deleted' but not garbage collected yet.

e) Most importantly, anyone who is using the garbage collector as their
object manager isn't into proper coding practices in the first place.


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


RE: alternating string replace

2008-01-11 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of cesco
> Sent: Wednesday, January 09, 2008 5:34 AM
> To: python-list@python.org
> Subject: alternating string replace
> 
> Hi,
> 
> say I have a string like the following:
> s1 = 'hi_cat_bye_dog'
> and I want to replace the even '_' with ':' and the odd '_' with ','
> so that I get a new string like the following:
> s2 = 'hi:cat,bye:dog'
> Is there a common recipe to accomplish that? I can't come up with any
> solution...
> 


For those of us who still think in Perl, here's an easy to read, lazy
solution:

s = 'hi_cat_bye_dog'
print s
s = re.sub(r'_(.*?(_|$))', r':\1', s)   ## every odd '_' to ':'
print s
s = re.sub(r'_', r',', s)   ## every even '_' to ','
print s

> hi_cat_bye_dog
> hi:cat_bye:dog
> hi:cat,bye:dog


The equivalent Perl code:
my $s = 'hi_cat_bye_dog';

print $s, "\n";
$s =~ s/_(.*?(_|$))/:$1/g;
print $s, "\n";
$s =~ s/_/,/g;
print $s, "\n";


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


RE: encrypting python modules

2008-01-14 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Paul Sijben
> Sent: Friday, January 11, 2008 4:45 AM
> To: python-list@python.org
> Subject: encrypting python modules
> 
> 
> The problem: I have a client-server app written in python. I want to
> make sure that the client is not:
> 1) destabilized by users accidentally or on purpose dropping python
> files in the path (after which calling the helpdesk will not be
useful)
> 2) extended with "new features" without me knowing about it (again
> resulting in calls to my helpdesk...)

Would the site module help with that?  It looks like site will
let you put your modules first in sys.path.  Or what about just updating
sys.path as the first action in your program?  

Or what about pulling clean copies of the files from a
tar/zip/archive before execution?  A shell script creates a temp dir and
extracts the files to the temp dir to run.  Not sure it would do any
good to pull from an encrypted tar/zip/archive.

Or what about pulling the client files from the server instead
of a tar/zip/archive...?



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA625


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


RE: __init__ explanation please

2008-01-14 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Hrvoje Niksic
> Sent: Monday, January 14, 2008 11:29 AM
> To: python-list@python.org
> Subject: Re: __init__ explanation please
> 
> Mel <[EMAIL PROTECTED]> writes:
> 
> >> I don't understand the purpose of this "correction".  After all,
> >> __init__ *is* the closest equivalent to what other languages would
> >> call a constructor.
> >
> > Nevertheless, __init__ doesn't construct anything.
> 
> Only if by "construct" you mean "allocate".  __init__ starts out with
> an empty object and brings it to a valid state, therefore
> "constructing" the object you end up with.  That operation is exactly
> what other languages call a constructor.


Nah.  Most other languages combine the constructor and an init function.
Normally with c++ I'll have the constructor call an Init() function so I
can re-initialize the object as needed.  Python has explicitly split the
two.


Besides, the Python docs say that __new__ is the constructor and
__init__ may or may not be called after the instance is created:

__new__( cls[, ...]) 

Called to create a new instance of class cls. __new__() is a
static method (special-cased so you need not declare it as such) that
takes the class of which an instance was requested as its first
argument. The remaining arguments are those passed to the object
constructor expression (the call to the class). The return value of
__new__() should be the new object instance (usually an instance of
cls).

...
If __new__() returns an instance of cls, then the new instance's
__init__() method will be invoked
...
If __new__() does not return an instance of cls, then the new
instance's __init__() method will not be invoked. 


__init__( self[, ...]) 

Called when the instance is created.
...
As a special constraint on constructors, no value may be
returned;



Also, how can a constructor require 'self' as an argument...?
__init__(self, ...)


If the __init__ function is called by the constructor it cannot return a
value.  However if called as a normal function, it can return a value.
__init__ is just a function that gets called by the constructor, which
is __new__.


count = 0
class AClass (object):
def __init__ (self):
self.a = 4

global count
if count > 0:
return 'hello world'

count += 1


a = AClass()

print a.a
print a.__init__()


c:\foo\a.py>
4
hello world



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA622


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


RE: __init__ explanation please

2008-01-15 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Lie
> Sent: Tuesday, January 15, 2008 5:03 PM
> To: python-list@python.org
> Subject: Re: __init__ explanation please
> 
> I've been in this Python mailing list for a few days, and I've noticed
> several things here: There are too many fundamentalist!
> 
> Don't play stupid and all, don't be a fundamentalist. It might be true
> that __init__ isn't a constructor and __new__ might be the constructor
> (some people even claimed __new__ is also not a constructor).
 

Purist is a better term.  Fundamentalist is three syllables closer to
Holy War.


> >From the base definition of a constructor: constructor is the creator
> of an object. In this case, __new__ is technically the constructor
> while __init__ is an initializer.
> 
> However, it is also to be noted that __init__ is what makes an object
> meaningful, and that makes it a constructor in a sense (while still
> technically a constructor). Without initialization, an object is
> meaningless, even if the definition of the initializer is to leave it
> as it is.


You don't need to have an __init__ defined.  A subclass has to
explicitly call the parent's __init__ or the parent's __init__ is never
run.  If the __init__ makes the object meaningful, then how meaningful
is an object without an __init__?  I'm pretty sure that an object
without an __init__ is still a viable, working object.


> If you can't be convinced with this argument, then I'd give you
> another that's a bit more Pythonic:
> DUCK TYPING: If it looks like a duck, walks like a duck, and quacks
> like a duck, it is a duck!


But you don't need __init__ to be a duck!


> >From the class programmer's point of view, __init__ acts like an
> object constructor in other languages, there is no significant
> difference between __init__ and constructor in other languages. 


How many times can you call an object's constructor in other languages?
__init__ can be called repeatedly.


__init__ is the last straw that breaks the camel's back.  Or rather, the
last method we see in the object creation process, and thus must be
'guilty' of being a constructor.  Only a fundamentalist would blame the
victim instead of the real criminal, __new__.


We're splitting hairs.  And I'm pretty sure that, aside from being a
spiffy thought experiment, no one cares as long as it works and makes
sense.   =)


Repeated for clarity:  smiley -->  =)  <-- smiley



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA625


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


RE: Creating unique combinations from lists

2008-01-16 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of breal
> Sent: Wednesday, January 16, 2008 2:15 PM
> To: python-list@python.org
> Subject: Creating unique combinations from lists
> 
> I have three lists... for instance
> 
> a = ['big', 'small', 'medium'];
> b = ['old', 'new'];
> c = ['blue', 'green'];
> 
> I want to take those and end up with all of the combinations they
> create like the following lists
> ['big', 'old', 'blue']
> ['small', 'old', 'blue']
> ['medium', 'old', 'blue']
> ['big', 'old', 'green']
> ['small', 'old', 'green']
> ['medium', 'small', 'green']
> ['big', 'new', 'blue']
> ['small', 'new', 'blue']
> ['medium', 'new', 'blue']
> ['big', 'new', 'green']
> ['small', 'new', 'green']
> ['medium', 'new', 'green' ]
> 
> I could do nested for ... in loops, but was looking for a Pythonic way
> to do this.  Ideas?


http://www.python.org/dev/peps/pep-0202/

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


RE: Creating unique combinations from lists

2008-01-17 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Tim Chase
> Sent: Wednesday, January 16, 2008 3:40 PM
> To: breal
> Cc: python-list@python.org
> Subject: Re: Creating unique combinations from lists
> 
> You can use a recursive generator:
> 
>def iterall(*iterables):
>  if iterables:
>for head in iterables[0]:
>  for remainder in iterall(*iterables[1:]):
>yield [head] + remainder
>  else:
>yield []
> 
>for thing in iterall(
>['big', 'medium', 'small'],
>['old', 'new'],
>['blue', 'green'],
>):
>  print thing
 

Recursion definitely makes for an elegant solution.  However you do take
a bit of a performance hit.  If performance matters (and comprehensions
are supposed to be optimized/fast) and you want a "works for N nested
loops solution," then you could build a N deep comprehension on the fly
and eval() it:


def gen(lists):
out =  '[' + ','.join(["v%s" % i for i in range(len(lists))]) +
']'
comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in
range(len(lists))])
return eval('[ ' + out + comp + ' ]')

gen([a, b, c])


So for a three item list, it would build and execute the following
comprehension:
[ [v0,v1,v2] for v0 in lists[0] for v1 in lists[1] for v2 in
lists[2] ]
Seven item list:
[ [v0,v1,v2,v3,v4,v5,v6] for v0 in lists[0] for v1 in lists[1]
for v2 in lists[2] for v3 in lists[3] for v4 in lists[4] for v5 in
lists[5] for v6 in lists[6] ]


Some rough performance numbers in seconds for 1,000 iterations over a
three item list:
list comprehension:  0.74
nested for loop   :  0.97  31% slower
recursion :  3.91 428% slower  =P
eval  :  1.11  50% slower





from timeit import Timer

s = "a = [ i for i in range(10) ]; b = a; c = a"

t = Timer( "l = [ [i, j, k] for i in a for j in b for k in c]", s)

iterations = 1000

print "list comprehension:  %4.2f" % t.timeit(iterations)


t = Timer('''
l = [] 
for i in a:
for j in b: 
for k in c:
l.append([i, j, k])
''', s)

print "nested for loop   :  %4.2f" % t.timeit(iterations)


t = Timer('''
def iterall(*iterables):
if iterables:
for head in iterables[0]:
for remainder in iterall(*iterables[1:]):
yield [head] + remainder
else:
yield []

for thing in iterall(a, b, c):
pass #print thing
''', s)

print "recursion :  %4.2f" % t.timeit(iterations)


t = Timer('''
def gen(lists):
out =  '[' + ','.join(["v%s" % i for i in range(len(lists))]) +
']'
comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in
range(len(lists))])
return eval('[ ' + out + comp + ' ]')
gen([a, b, c])
''', s)

print "eval  :  %4.2f" % t.timeit(iterations)



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: Creating unique combinations from lists

2008-01-17 Thread Reedick, Andrew
> -Original Message-
> From: Tim Chase [mailto:[EMAIL PROTECTED]
> Sent: Thursday, January 17, 2008 10:30 AM
> To: Reedick, Andrew
> Cc: breal; python-list@python.org; [EMAIL PROTECTED]
> Subject: Re: Creating unique combinations from lists
> 
> Yick...a nice demo of the power of eval, but definitely filed
> under the "Hack" heading :)

You hurt my feeling.  *sniffle*  Given how late python
compiles/evaluates code blocks, I'm thinking that eval() is less hack
and more paradigm ..err.. pythonic.  ;-)

> 
> I think Martin's solution/recommendation[1] is better
> (readability-wise, and "less apt to shoot yourself in the foot
> with some bogus generated code"-wise) if you don't mind building
> the whole result set in memory which your eval() solution does as
> well.  I'm curious to see the timing results from adding that
> recipe to your test-suite.


Cookbook is relatively decent.  5 deep, 100 iterations:
list comprehension:  11.02
nested for loop   :  13.16   +19%
cookbook  :  18.85   +71%
recursion :  69.00  +526%
eval  :  13.30   +20%

> 
> The advantage to the recursive-generator solution is that it
> should really only keep your initial input and the current result
> in memory as the generated item, so you can reasonably iterate
> over millions of rows without having gigs of RAM.  I don't
> believe the recursion will go deeper than the number of lists
> you're iterating over, so the stack shouldn't explode.


Excellent point about memory usage.  However, since we're dealing with
exponential algorithms, will you run out of time or memory first?



Here's the test code if anyone wants to play with it.  It will let you
specify the levels of nested loops and display the generated code.


Usage: foo.py num_nested_loops num_iterations


import sys
from timeit import Timer

def CreateComprehension(lists):
out =  '[' + ','.join(["v%s" % i for i in range(len(lists))]) +
']'
comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in
range(len(lists))])
return '[ ' + out + comp + ' ]'


num_loops = int(sys.argv[1])
iterations = int(sys.argv[2])

results = []

lists = '''lists = []
for i in range(%d):
lists.append(range(i, i+10))
''' % (num_loops)

print ""
print lists
print

print ""
code = 'r = ' + CreateComprehension(range(num_loops))
t = Timer(code, lists)
results.append("list comprehension:  %4.2f" % t.timeit(iterations))
print results[-1:][0]
print code
print


print ""
code = 'r = []\n'
for i in range(num_loops):
code += "  " * i
code += "for v%d in lists[%d]:\n" % (i, i)
code += '  ' * num_loops
code += 'r.append(['
code += ','.join( ['v%d' % i for i in range(num_loops)])
code += '])'

t = Timer(code, lists)
results.append("nested for loop   :  %4.2f" % t.timeit(iterations))
print results[-1:][0]
print code
print


print ""
code = '''r=[[]]
for x in lists:
  t = []
  for y in x:
for i in r:
  t.append(i+[y])
  r = t
'''
t = Timer(code, lists)
results.append("cookbook  :  %4.2f" % t.timeit(iterations))
print results[-1:][0]
print code
print


print ""
code = '''
r = []
def iterall(*iterables):
  if iterables:
for head in iterables[0]:
  for remainder in iterall(*iterables[1:]):
yield [head] + remainder
  else:
yield []

for thing in iterall(%s):
r.append(thing)
''' % ( ','.join([ 'lists[%d]' % i for i in range(num_loops) ]) )

t = Timer(code, lists)
results.append("recursion :  %4.2f" % t.timeit(iterations))
print results[-1:][0]
print code
print


print ""
code = '''
def gen(lists):
  out =  '[' + ','.join(["v%s" % i for i in range(len(lists))]) + ']'
  comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in
range(len(lists))])
  return eval('[ ' + out + comp + ' ]')
gen(lists)
'''
t = Timer(code, lists)
results.append("eval  :  %4.2f" % t.timeit(iterations))
print results[-1:][0]
print code
print

print '\n'.join(results)




*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA622


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


RE: How to use only a sub shell to execute many commands in python

2008-01-18 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of raocheng
> Sent: Friday, January 18, 2008 6:31 AM
> To: python-list@python.org
> Subject: How to use only a sub shell to execute many commands in
python
> 
> Please see the following code.
> Suppose I have many shell commands to be executed. And I don't want to
> fork a sub shell for each command(eg: status,output =
> commands.getstatusoutput(cmd)) because it is too expensive. I want to
> use only one sub shell to execute all these commands and want to get
> each command's output. How can I accomplish this task ? Thanks in
> advance.
> 
> ===
> #!/usr/bin/env python
> import os
> fi, fo = os.popen2(
> '''
> while read line
> do
>   eval $line
> done
> ''',   't')
> 
> #Suppose I have many commands to execute, but I don't want to fork a
> sub shell for each command
> cmds = ['date','uptime','pwd','ls -rltF','who']
> 
> for cmd in cmds:
> #pseudocode
> fi.executeCmd(cmd)
> output = fo.readResult()
> 
> print output


Have each command write to a unique temp file.  
Create temp files in python
cmd = 'date > /tmp/date_temp 2>&1 ; uptime > /tmp/uptime_temp
2>&1; ...'
execute cmd
for file in tempfiles:
...

You can also get the return value of each command
cmd = 'date > /tmp/date_temp 2>&1; echo $? >> /tmp/date_temp;
uptime > /tmp/uptime_temp 2>&1; echo $? >> ...'




*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA622


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


RE: how to resolve Windows pathnames into cygwin ones

2008-01-18 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of
[EMAIL PROTECTED]
> Sent: Friday, January 18, 2008 11:11 AM
> To: python-list@python.org
> Subject: how to resolve Windows pathnames into cygwin ones
> 
> I am looking for a function to resolve 'F:/foo/bar' into '/cygdrive/f/
> foo/bar'. I get the original dirpath from tkFileDialog.askdirectory in
> a Windows form and none of os.path.* functions seem to resolve it to a
> cygwin form. Rather they _append_ it to the current directory,
> resulting at best in a monster '/cygdrive/c/whatever/f/foo/bar'.
> It's all being developed under cygwin currently (so it is a kind of
> mixed environment), but I would like the fix to work correctly in any
> environment.
> 

Firstly, '/cygdrive' is overrated.  Cygwin will accept:  'ls c:\\foo'
and 'ls c:/foo'


s= 'f:\\foo\\bar'

print re.sub(r'\\', '/', s)

m = re.match('^(.):(.*)$', s)
print '/cygdrive/' + m.group(1) + re.sub(r'\\', '/', m.group(2))

*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: Filtering two files with uncommon column

2008-01-18 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Madhur
> Sent: Friday, January 18, 2008 4:23 AM
> To: python-list@python.org
> Subject: Filtering two files with uncommon column
> 
> 
> Basically I want to compare the two files based on second column. If
> the second
> column matches on both the files do not print anything, else if there
> is no matc
> h in for the second column for first file in second file then print it
> under Fil
> e1 header, else if there is no match for the second column for second
> file in fi
> rst file print it under File2 header.
> 


I often do this to compare property files between environments.  The
follow algorithm works for any number of files by creating a dictionary
of lists (or hash of arrays in Perl-ese.)

Create a dictionary
Index = -1
For file in files
Index++
For line in file
col = match/split/regex the column
If col not in dictionary
Dictionary[col] = []

extend dictionary[col] to length of index
dictionary[col][index] = col

for col in sort(dictionary.keys()):
extend dictionary[col] to length of index
print dictionary[col]   




*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA622


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


RE: Stripping whitespace

2008-01-23 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of ryan k
> Sent: Wednesday, January 23, 2008 3:24 PM
> To: python-list@python.org
> Subject: Re: Stripping whitespace
> 
> On Jan 23, 3:02 pm, John Machin <[EMAIL PROTECTED]> wrote:
> > On Jan 24, 6:57 am, ryan k <[EMAIL PROTECTED]> wrote:
> >
> > > So yea i will just have to count dashes.
> >
> > Read my lips: *you* counting dashes is dumb. Writing your code so
> that
> > *code* is counting dashes each time it opens the file is smart.
> 
> Okay it's almost working ...
> 

Why is it that so many Python people are regex adverse?  Use the dashed
line as a regex.  Convert the dashes to dots.  Wrap the dots in
parentheses.  Convert the whitespace chars to '\s'.  Presto!  Simpler,
cleaner code.

import re

state = 0
header_line = ''
pattern = ''
f = open('a.txt', 'r')
for line in f:
if line[-1:] == '\n':
line = line[:-1]

if state == 0:
header_line = line
state += 1
elif state == 1:
pattern = re.sub(r'-', r'.', line)
pattern = re.sub(r'\s', r'\\s', pattern)
pattern = re.sub(r'([.]+)', r'(\1)', pattern)
print pattern
state += 1

headers = re.match(pattern, header_line)
if headers:
print headers.groups()
else:
state = 2
m = re.match(pattern, line)
if m:
print m.groups()


f.close()



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA625


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


RE: Stripping whitespace

2008-01-24 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of John Machin
> Sent: Wednesday, January 23, 2008 5:48 PM
> To: python-list@python.org
> Subject: Re: Stripping whitespace
> 
> On Jan 24, 7:57 am, "Reedick, Andrew" <[EMAIL PROTECTED]> wrote:
> >
> > Why is it that so many Python people are regex adverse?  Use the
> dashed
> > line as a regex.  Convert the dashes to dots.  Wrap the dots in
> > parentheses.  Convert the whitespace chars to '\s'.  Presto!
> Simpler,
> > cleaner code.
> 
> > pattern = re.sub(r'-', r'.', line)
> > pattern = re.sub(r'\s', r'\\s', pattern)
> > pattern = re.sub(r'([.]+)', r'(\1)', pattern)
> 
> Consider this:
> pattern = ' '.join('(.{%d})' % len(x) for x in line.split())
> 

Good.  But the main drawback to using split+join is that it works if
there is only one whitespace char acting as a column separator
(split+join will compress multiple whitespace characters down to one
char.)  Normally, it's safe to assume a one character separator between
columns, however since the input is supposed to be tab delimited (but
wasn't) and tabs tend to get randomly converted to spaces depending on
which butterfly is flapping its wings at any given instant, keeping the
original whitespace column separators is probably a good idea.



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA622


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


RE: piping into a python script

2008-01-24 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Donn
> Sent: Thursday, January 24, 2008 12:03 PM
> To: Michał Bentkowski
> Cc: python-list@python.org
> Subject: Re: piping into a python script
> 
> I have tested getopt and it strips the lone '-' out. I can get it from

Try 'foo.py -- -'.  The '--' normally tells the parser to stop parsing args.  
Ex: date > -foo.txt; rm -foo.txt; rm -- -foo.txt


I think this will tell you if stdin is being piped in or not:
import sys
import os
print os.isatty(sys.stdin.fileno())

D:\>type a.txt | python a.py
False

D:\>python a.py
True


Also if you're lazy, look at the StringIO class:

if options.filelist is None and len(args) < 1:  # read from stdin
f = sys.stdin
elif options.filelist is not None and len(args) < 1:  # read filenames 
from file
f = open(options.filelist, 'r')
elif options.filelist is None and len(args) > 0:  # filenames on 
command line
f = StringIO.StringIO('\n'.join(args))
else:  ## Thanks for playing.
parser.print_help()
exit(1)

if f:
for filename in f:



> -- Segio Aragones (Groo the Wanderer Number 99)

Ah yes, Groo.  Ever wonder who would win if Groo and Forrest Gump fought each 
other?



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


RE: Python noob SOS (any [former?] Perlheads out there?)

2008-01-29 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of kj
> Sent: Tuesday, January 29, 2008 11:39 AM
> To: python-list@python.org
> Subject: Python noob SOS (any [former?] Perlheads out there?)
> 
> 
> 
> For many months now I've been trying to learn Python, but I guess
> I'm too old a dog trying to learn new tricks...  For better or
> worse, I'm so used to Perl when it comes to scripting, that I'm
> just having a very hard time getting a hang of "The Python Way."
> 
> It's not the Python syntax that I'm having problems with, but rather
> with larger scale issues such as the structuring of packages,
> techniques for code reuse, test suites, the structure of
> distributions,...  Python and Perl seem to come from different
> galaxies altogether...


It sound like less of a "How to do Things the Python Way" problem, a
more of a "How to do Object Oriented Programming" problem.
 
Coming from a C++/Perl background, I found the O'Reilly 'Learning
Python' book to be useful.  It has a section on OOP, which covers basic
OO theory that you may find useful.  I can't think of a decent OO book
to recommend though.  


> Be that as it may, the activation barrier to using Python for my
> scripting remains too high.
> 
> I'd written a Perl module to facilitate the writing of scripts.
> It contained all my boilerplate code for parsing and validating
> command-line options, generating of accessor functions for these
> options, printing of the help message and of the full documentation,
> testing, etc.

Bleh.  Perl and Python have really good libraries.  Why waste time
rolling your own when you can use Python's getopt or optparse, or Perl's
Getopt and Getopt::Long?


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


RE: Using Regular Expressions to Parse SQL

2008-02-05 Thread Reedick, Andrew

> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of [EMAIL PROTECTED]
> Sent: Tuesday, February 05, 2008 9:31 AM
> To: python-list@python.org
> Subject: Using Regular Expressions to Parse SQL
> 
> 
> My pattern does not even come close.
> 
> Any help would be greatly appreciated.  My goal is to analyse a large
> number of SQL querys to try to identify the join field and see where
> indexing might make sense.
> 
> While I am mostly interested in understanding regular expressions, I
> would also be interested in knowing about any Python SQL parsers out
> there.


Python's regexes are a tad odd compared to Perl (or Perl's regexes are
odd.  Relativity.)  You need re.DOTALL to handle newlines in the sql:
DOTALL
Make the "." special character match any character at all,
including a newline; without this flag, "." will match anything except a
newline.
 


import re

s= ''' FROM ((qry_Scores_Lookup1 INNER JOIN CSS_Rpt1 ON
(qry_Scores_Lookup1.desc = CSS_Rpt1.desc) AND
(qry_Scores_Lookup1.lastcdu = CSS_Rpt1.lastcdu))'''

pat =
r"(^|\s+)FROM\s.+\s(?:INNER|LEFT|RIGHT)\s+JOIN\s.+\sON\s+((\s*(?:\S+)\s*
=\s*(?:\S+))(?:\s+|\s+AND\s+|$))+"
m = re.compile(pat, re.DOTALL).match(s)
if m:
print m


('(qry_Scores_Lookup1.desc = CSS_Rpt1.desc) ', '(qry_Scores_Lookup1.desc
= CSS_Rpt1.desc)')


You should be able to tweak the regex to get the exact matches you want.

An alternative to writing a lengthy regex might be to just grab
everything after the ON and then string split on "AND".



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


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


RE: Why not a Python compiler?

2008-02-06 Thread Reedick, Andrew

> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Luis M. González
> Sent: Tuesday, February 05, 2008 6:44 PM
> To: python-list@python.org
> Subject: Re: Why not a Python compiler?
> 
> 
> Pypy is a very ambitious project and it aims, amongst many other
> goals, to provide a fast just-in-time python implementation.
> They even say that the "secret goal is being faster than c, which is
> nonsense, isn´t it?" (I still didn´t get the joke though...).
>

'c' is also the speed of light.  And since nothing can travel faster than 
light...

One demerit has been marked against your geek card for missing an obvious 
science pun.  Additionally, your membership to the Star Trek Lifestyle 
Adventure Club has been put on probationary status for the next twelve parsecs.



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: Why not a Python compiler?

2008-02-06 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Grant Edwards
> Sent: Wednesday, February 06, 2008 10:35 AM
> To: python-list@python.org
> Subject: Re: Why not a Python compiler?
> 
> On 2008-02-06, Reedick, Andrew <[EMAIL PROTECTED]> wrote:
> 
> >> Pypy is a very ambitious project and it aims, amongst many
> >> other goals, to provide a fast just-in-time python
> >> implementation. They even say that the "secret goal is being
> >> faster than c, which is nonsense, isn´t it?" (I still didn´t
> >> get the joke though...).
> >
> > 'c' is also the speed of light.
> 
> 'c' is the speed of light _in_a_vacuum_.

True.

 
> > And since nothing can travel faster than light...
> 
> Nothing can travel faster than the speed of light
> _in_a_vacuum_.  There are situtaitons where things can (and
> regularly do) travel faster than light:
> http://en.wikipedia.org/wiki/Cherenkov_radiation


Nope.  It propagates, not travels, faster than light.  Go ask a physicist to 
explain it.  It's odd...


> 
> > One demerit has been marked against your geek card for missing
> > an obvious science pun.  Additionally, your membership to the
> > Star Trek Lifestyle Adventure Club has been put on
> > probationary status for the next twelve parsecs.
> 
> Ouch. Two demerits for using the distance unit "parsec" in a
> context where a quantity of time was required.


Ten demerits for not catching the Star Wars Kessel Run reference.


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


RE: Why not a Python compiler?

2008-02-07 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Torsten Bronger
> Sent: Thursday, February 07, 2008 3:32 PM
> To: python-list@python.org
> Subject: Re: Why not a Python compiler?
> 
> >
> > I wonder if George Lucas intended it as a joke or if he thought
> > a parsec was a unit of time.
> 
> The latter because it was corrected in the novelization.
> 

Errr... didn't one of the novels explain it away by describing the
kessel run as a region of space warped by black holes or other objects?
Bragging rights for crossing such a field thus centered on shortest
distance instead of time.



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


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


RE: keyword 'in' not returning a bool?

2008-02-08 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of c james
> Sent: Friday, February 08, 2008 12:10 PM
> To: python-list@python.org
> Subject: keyword 'in' not returning a bool?
> 
> Try this
> 
> >>> sample = {'t':True, 'f':False}
> >>> 't' in sample
> True
> >>> type('t' in sample)
> 
> >>> 't' in sample == True
> False
> 
> Why is this?  Now try
> >>> bool('t' in sample) == True
> True
> 
> Can someone explain what is going on?
> 

>>> ('t' in sample) == True
True

It's operator precedence. 'in' has lower precedence than '=='. Therefore
't' in sample == True
evaluates as
't' in (sample == True)

The real question is why does
't' in (sample == True)
cause an error:  
TypeError: argument of type 'bool' is not iterable
while 
't' in sample == True
does not?



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


RE: Why not a Python compiler?

2008-02-08 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Grant Edwards
> Sent: Friday, February 08, 2008 12:46 PM
> To: python-list@python.org
> Subject: Re: Why not a Python compiler?
> 
> On 2008-02-08, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
> 
> >> the compiler could do little else except translate it to something
> >> like:
> >>
> >> (python:add a b)
> > [snip more interesting considerations about compiling python]
> >
> > Please get back on topic.  This discussion is about parsecs and
> > wookies now.
> 
> What's a "wookie" a unit of?
> 

How many ewoks are there to a wookie?  (Yes, I know the metric system is
archaic, but I really don't care for them new fangled 'standard units'.)


*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: CSV Reader

2008-02-11 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Mike P
> Sent: Monday, February 11, 2008 11:42 AM
> To: python-list@python.org
> Subject: Re: CSV Reader
> 
> Cheers for the help, the second way looked to be the best in the end,
> and thanks for the boolean idea
> 
> Mike
> 
> 
> 
> working_CSV =  "//filer/common/technical/Research/E2C/Template_CSV/
> DFAExposureToConversionQueryTool.csv"
> 
> save_file = open("//filer/common/technical/Research/E2C/Template_CSV/
> CSV_Data2.csv","w")
> 
> CSV_Data = open(working_CSV)
> data = CSV_Data.readlines()
> flag=False
> for record in data:
> if record.startswith('"Transaction ID"'):
> flag=True
> if flag:
> save_file.write(record)
> save_file.close()


Don't be a pansy.

Use the csv module, or add a check for
record.startswith('TransactionID').  There's no guarantee that csv
columns will be double-quoted.  (Leading whitespace may or may not be
acceptable, too.)  Look at the first piece of sample code in the
documentation for the csv module.  (Section 9.1.5 in python 2.5)  You're
99% of the way to using csv.reader() properly.


Nitpick:  If the boolean check is expensive, then
if not flag and record.startswith(...):
flag = true

Nitpick:  flag is a weak name.  Use something like bPrint, okay2print,
or print_now or anything that's more descriptive.  In larger and/or more
complex programs, meaningful variable names are a must.



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA622


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


RE: CSV Reader

2008-02-11 Thread Reedick, Andrew

> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Mike P
> Sent: Monday, February 11, 2008 11:10 AM
> To: python-list@python.org
> Subject: Re: CSV Reader
> 
> Hi Larry,
> 
> i'm still getting to grips with python, but rest assured i thinkn it's
> better for me to write hte code for learnign purposes
> 
> My basic file is here, it comes up with a syntax error on the
> startswith line, is this because it is potentially a list?
> My idea was to get the lines number where i can see Transaction ID and
> then write out everything from this point into a new datafile.
> 
> 


>From the docs for reader:  "All data read are returned as strings. No
automatic data type conversion is performed."
Just use print or repr() to see what the row data looks.  Then the
method to check for 'transaction id' should be abundantly clear.

for data in reader:
print data
print repr(data)


> Would a better solution be just to use readlines and search for the
> string with a counter and then write out a file from there?

Yes you could, but the danger is that you get an insanely large file
that blows out your memory or causes the process to swap to disk space
(disk is slow.)
Just loop through the lines and use a boolean flag to determine when to
start printing.


*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: CSV Reader

2008-02-12 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Mike P
> Sent: Tuesday, February 12, 2008 5:37 AM
> To: python-list@python.org
> Subject: Re: CSV Reader
> 
> just saw i needed to change record.startswith to row.startswith
> but i get hte following traceback error
> 
> Traceback (most recent call last):
>   File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework
> \scriptutils.py", line 310, in RunScript
> exec codeObject in __main__.__dict__
>   File "Y:\technical\Research\E2C\Template_CSV\import CSV test.py",
> line 10, in 
> if not start_line and row.startswith('Transaction ID'):
> AttributeError: 'list' object has no attribute 'startswith'
> --
> http://mail.python.org/mailman/listinfo/python-list


Algorithms + Data Structures = Programs

You need to understand what kind of data structure a "list" is.  You're
foundering a bit because you don't have a good understanding of your
tools (the list data structure in this case.)  Try going through the
O'Reilly Learning Python book.  Even better would be to take/audit a
college/university class on data structures and algorithms.  



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


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


RE: Word document accessing using python

2008-02-13 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Hari
> Sent: Wednesday, February 13, 2008 8:40 AM
> To: python-list@python.org
> Subject: Word document accessing using python
> 
> Hello,
> I want to fetch some data from the work document and to fill it inside
> excel sheet. For this I want to perform opening word documents and do
> some string manipulations for extracting data and to fill it inside
> excel sheet.
> Can any one help in this by saying how to do this or by giving some
> link where I can find some hints.
> 


Google for sample scripts.  Check the python documentation about
"Quick-Starts to Python and COM' and makepy.py.


Word Object Model Reference:
http://msdn2.microsoft.com/en-us/library/bb244515.aspx

import win32com.client
word = win32com.client.Dispatch("Word.Application")
word.Visible = True 
word.Documents.Open('c:\\some\\where\\foo.doc')

doc = word.Documents(1)
tables = doc.Tables
for table in tables:
for row in table.Rows:
for cell in row.Cells:
...


Excel reference:  http://msdn2.microsoft.com/en-us/library/bb149081.aspx

import win32com.client
import os
excel = win32com.client.Dispatch("Excel.Application", "Quit")
excel.Visible = 1

dir = os.getcwd()
book = excel.Workbooks.Open(dir + "/test.xls")
sheet = book.Worksheets(1)

for i in sheet.Range("A8:B9"):
print i
print("active chart = " + str(excel.ActiveChart))
print("active sheet= " + str(excel.ActiveSheet))
print("\t" + str(excel.ActiveSheet.Name))
print("active workbook = " + str(excel.ActiveWorkbook))
print("\t" + str(excel.ActiveWorkbook.Name))


new_sheet = excel.Sheets.Add(None, None, None,
win32com.client.constants.xlWorksheet)
new_sheet.Name = "foo"

## import from a csv file
query_results = new_sheet.QueryTables.Add("TEXT;" + dir + "\\data.csv",
new_sheet.Cells(1,1))
query_results.TextFileParseType = win32com.client.constants.xlDelimited;
query_results.TextFileCommaDelimiter = 1;
query_results.Refresh();



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


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


RE: Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb)

2008-02-13 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of [EMAIL PROTECTED]
> Sent: Wednesday, February 13, 2008 1:41 PM
> To: python-list@python.org
> Subject: Re: Regular Expression for Prime Numbers (or How I came to
> fail at them, and love the bomb)
> 
> On Feb 13, 9:48 am, Carsten Haese <[EMAIL PROTECTED]> wrote:
> > On Wed, 2008-02-13 at 07:31 -0800, [EMAIL PROTECTED] wrote:
> > >     return re.match("^1?$|^(11+?)\1+$", convert)
> >
> > That needs to be either
> >
> > return re.match(r"^1?$|^(11+?)\1+$", convert)
> >
> > or
> >
> > return re.match("^1?$|^(11+?)\\1+$", convert)
> >
> > in order to prevent "\1" from being read as "\x01".
> 
> But why doesn't it work when you make that change?


It does work.  Read the referenced website.

If there is a match then 
the number isn't prime
else # no match
the number is prime.



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA622


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


RE: Word document accessing using python

2008-02-13 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Juan_Pablo
> Sent: Wednesday, February 13, 2008 1:07 PM
> To: python-list@python.org
> Subject: Re: Word document accessing using python
> 
> 
> > import win32com.client
> 
>  but, window32com.client is only functional in  windows


Correct.  Microsoft tries very hard to make sure that its applications
and their saved data are only readable/usable/automate-able using
MS-Office and MS-Windows (and preferably the current versions of each.)
If you can't create a quality product that people will willingly pay
money for, then use lock-in to squeeze money out of them.  =/

As suggested by castironpi, you could save the word docs in a neutral
format such as text or xml.  Another idea is to find a module or
commercial product that will read word files.  In theory, from what I've
heard, Open Office can read some (most?) word formats, and since OO has
a scriptable api (does it?), you could use OO to read the word doc and
use OO's api to get the relevant data.  You would need to test it out.



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: Solve a Debate

2008-02-15 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of nexes
> Sent: Friday, February 15, 2008 11:25 AM
> To: python-list@python.org
> Subject: Solve a Debate
> 
> Alright so me and my friend are having argument.
> 
> Ok the problem we had been asked a while back, to do a programming
> 
> He declared an array and assigned the number of days in a month to its
> own element in an array. Now
> I realise that in this example it would not make a difference in terms
> of efficiency, but it is my belief that if
> there is more data that needed to be assigned(i.e. a couple megs of
> data) it would be simpler (and more efficient) to
> do a compare rather then assigning all that data to an array, since
> you are only going to be using 1 value and the rest
> of the data in the array is useless.
> 
> What are everyone else's thoughts on this?


Efficient how?  

Looking up the data in a array would probably be faster (look-up tables
normally are.)  

You could make the array efficient by using pointers, gaining both space
and time efficiency.  Mon[1] and mon[3] ... would point to 31.

The array can also just be collection of pointers to the multi-megabyte
objects on disk.  Most languages have modules letting you maintain an
index in memory that points to data on disk.

If the array is static or otherwise only loaded once into memory at
startup, and you have plenty of memory and patience, then who cares if
it is inefficient?  Simple solutions are normally faster to implement.
It's not often that you need to spend three days to save three seconds.

Then there's debug and change efficiency.  An array lookup is simple to
understand and thus less prone to bugs.  It can also be easier to change
a single array element than to change a complicated formula or a cluster
of nested if-then-else statements.



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA625


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


RE: Looking for a Python Program/Tool That Will Add Line Numbers to atxt File

2008-02-18 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of William Pursell
> Sent: Monday, February 18, 2008 8:37 AM
> To: python-list@python.org
> Subject: Re: Looking for a Python Program/Tool That Will Add Line
> Numbers to atxt File
> 
> On Feb 14, 6:54 am, "W. Watson" <[EMAIL PROTECTED]> wrote:
> > See Subject. It's a simple txt file, each line is a Python stmt, but
> I need
> > up to four digits added to each line with a space between the number
> field
> > and the text. Perhaps someone has already done this or there's a
> source on
> > the web for it. I'm not yet into files with Python. A sudden need
has
> burst
> > upon me. I'm using Win XP.
> 
> Not sure if "Python program/tool" means "a tool or a program
> in Python", but if awk is okay, that's the tool I would use:
> 
> awk '{printf( "%4d %s\n", NR % 1, $0 )}'


On a related note, since it's probably easier to install Perl instead of
awk on a windows box:

type foo.java | perl -ne "$counter++; print sprintf(qq(%4d ), $counter),
$_;"


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


RE: Article of interest: Python pros/cons for the enterprise

2008-02-21 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Tim Chase
> Sent: Wednesday, February 20, 2008 8:58 AM
> To: estherschindler
> Cc: python-list@python.org
> Subject: Re: Article of interest: Python pros/cons for the enterprise
> 
> 
> Oh noes!  You might need competent programmers that actually
> understand what they're doing!
> 
> (they might even have to write testing code to make sure their
> code works as intended...it's a good thing that Python includes
> unittest and doctest modules in the stock install)
> 
> Sigh.  Any programmer that can overcome the hurdles of learning
> Java or C# can quickly/easily pick up Python as long as they're
> willing to unlearn some bad habits.
> 

> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Carl Banks
> Sent: Wednesday, February 20, 2008 8:39 PM
> To: python-list@python.org
> Subject: Re: Article of interest: Python pros/cons for the enterprise

> C++ is a compile-time, type-checked language, which means it is
> totally safer for newbies than Python.  Yep, your big company is
> totally safe with newbie C++ programmers.



Eh, don't laugh too hard.  Since Python code isn't type-checked until
the actual code block is executed, you have to go through the extra step
of testing/running _every_ line of code before you'll find an error.
Then there's the problem of how mutable Python objects are.  So even if
you execute every line of code, you might not have executed the code
with every possible type of object combination.

Compared to a statically typed language, it can get very expensive to
write comprehensive test cases for python scripts.  So I wouldn't be
quick to dismiss the notion that Java/C#/C++ are more newbie-safe than
Python. =/

An amusing case in point was where I had a type-cast error in an
exception's catch block's print statement.  This simple error caused the
program to stop with an unhandled exception.  Something that basic would
have been caught in a statically typed language very early in the dev
cycle when it's cheaper to fix the problem.  And the idea of
running/testing exceptions or simple print statements isn't always
foremost in people's minds.  =P




*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA625


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


RE: Last 4 Letters of String

2008-02-21 Thread Reedick, Andrew
How would you get the last 4 items of a list?

 

 

From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of
Robert Rawlins - Think Blue
Sent: Thursday, February 21, 2008 11:36 AM
To: python-list@python.org
Subject: Last 4 Letters of String

 

Hello Guys,

 

I'm looking for a function which will give me the last 4 characters of a
given string. I'm sure it's a very simple task but I couldn't find
anything of it.

 

Any ideas?

 

Rob

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

RE: Last 4 Letters of String

2008-02-25 Thread Reedick, Andrew


> -Original Message-
> From: Tim Chase [mailto:[EMAIL PROTECTED]
> Sent: Monday, February 25, 2008 8:34 AM
> To: Reedick, Andrew
> Cc: Robert Rawlins - Think Blue; python-list@python.org
> Subject: Re: Last 4 Letters of String
> 
> > How would you get the last 4 items of a list?
> 
> Did you try the same "get the last 4 items" solution that worked
> for a string?
> 
>lst[-4:]


The idea was to ask a question that would help the original poster to
answer their own question.  =)



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: List Combinations

2008-03-12 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Shane Geiger
> Sent: Wednesday, March 12, 2008 10:33 AM
> To: Michael Wieher
> Cc: python-list@python.org
> Subject: Re: List Combinations
> 
> >
> 
> 
> def gen(lists):
> out =  '[' + ','.join(["v%s" % i for i in range(len(lists))]) +
']'
> comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in
> range(len(lists))])
> return eval('[ ' + out + comp + ' ]')
> 
> a,b,c = [1,2,3],[4,5,6],[7,8,9]
> 
> print gen([a, b, c])
> 
> 
> 
> 
> 
> --
> Shane Geiger
> IT Director
> National Council on Economic Education
> [EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net
> 


It helps to quote your source...
http://www.mail-archive.com/python-list@python.org/msg178457.html


Start here

http://www.mail-archive.com/python-list@python.org/msg178356.html
and go through the thread.  There are several ways to solve the problem
and we evaluated the performance and 'pythonicity' of each.  




*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA625


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


RE: Joseph Weizenbaum

2008-03-14 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Aahz
> Sent: Friday, March 14, 2008 2:05 PM
> To: python-list@python.org
> Subject: RIP: Joseph Weizenbaum
> 
> Creator of Eliza:
> 
> http://www-tech.mit.edu/V128/N12/weizenbaum.html
> --

How do you feel about creator of Eliza?



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: What Programming Languages Should You Learn Next?

2008-03-20 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Donn Cave
> Sent: Thursday, March 20, 2008 3:39 PM
> To: python-list@python.org
> Subject: Re: What Programming Languages Should You Learn Next?
> 
> 
> Worth repeating.
> 
> One of the perhaps surprising consequences, Haskell code can
> be very easy to modify.  I've been fooling around with computer
> programs for a couple decades, and I'm just getting used to the
> idea that I can casually rewrite Haskell code and get the compiler
> to find what I missed.  I have come to feel that the indiscipline
> of dynamic typing in languages like Python leads to an intuitively
> surprising rigidity.  Ten years ago I would cheerfully accept this,
> given the meager and clumsy support for static typing in languages
> like C++, but today, it makes me appreciate Haskell's potential
> for complex projects.
> 


Haskell does look interesting (especially in light of that one summer
job way back when doing a _lot_ of Lotus-123 spreadsheet programming.)
There's a Haskell wiki: http://www.haskell.org/


Quicksort in Haskell versus C is amazing:
http://www.haskell.org/haskellwiki/Introduction#What.27s_good_about_func
tional_programming.3F

Quicksort in Python inspired by Haskell's quicksort:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66473



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


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


RE: Haskell vs ??

2008-03-20 Thread Reedick, Andrew
> From: [EMAIL PROTECTED] 
> [mailto:[EMAIL PROTECTED] On Behalf Of 
> Michael Wieher
> Sent: Thursday, March 20, 2008 4:36 PM
> To: python-list@python.org
> Subject: Haskell vs ??
> 
> Just to help clear up my own understanding of this discussion, this 
> is basically a language that obfuscates details and makes low-level 
> decisions in a "average-best" way, and thus allows for lazy people 
> to write kind of decent code quickly?


Change "obfuscates details" to focuses on the right level of detail.
C's details are too low.  Python ignores details to the point that you
don't find dumb type-casting mistakes until the code is actually being
executed.


"makes low-level decisions in a "average-best" way,"  Yes, just like how
CPython is considered slow because of it's silly garbage collecting, too
dynamically typed to be optimized, paradigm.


> allows for lazy people to write kind of decent code quickly?
No, it's not at all like a usenet group or mailing list where people are
too lazy to post kind of thought out comments.  ;-)

The whole point of coding is to implement a requirement.  A requirement
is tied back to a business case, and a business case is an idea on how
to get people to give you money in return for your service or product.
Any code that doesn't directly implement the business case is 'overhead'
(such as memory management, having to execute every single line of your
Python code in order to catch type mismatches instead of having a
compiler find such things early in development, having to write
verbose|obfuscated syntax that requires more debugging since it's so
verbose|obfuscated, responding to trolls, etc.)

In theory, it follows the "less is more" strategy but without crossing
the line into anarchy or the Wild West (i.e., no type checking,) while
not being so syntactically brief as to look like hieroglyphics.



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


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


RE: Element Tree Help

2008-03-24 Thread Reedick, Andrew
Robert Rawlins wrote:
> I have little to no experiance with element tree and I'm struggling to 
> find a way to parse the details from the XML document (attached) into 
> my application. Essentialy I'm looking to take the following document 
> and turn it into a dict of tuples, each dict element defines a 
> datasource with the key to the element being the 'name' which is 
> defined in the XML and then the value of the pair is a tuple which 
> contains the details of the datasource, like the host and port etc.


Here's another way to walk an ElementTree.  This one creates a hash of hashes 
which are normally more useful than tuples for property lookups.

import xml.etree.ElementTree as ET

tree = ET.ElementTree(file = "foo.xml")
d = {}
for ds in tree.findall("datasource"):

name = ds.find('name').text
d[name] = {}
print 'datasource =', name

for i in ds.findall('*'):
#for i in ds.getiterator():  # also works

if i.tag in ('datasource', 'name'):
continue

print '',i.tag, "=", i.text
d[name][i.tag] = i.text

print

print d

*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: Guido's new method definition idea

2008-12-08 Thread Reedick, Andrew

> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Aaron Brady
> Sent: Monday, December 08, 2008 3:27 PM
> To: python-list@python.org
> Subject: Re: Guido's new method definition idea
> 
> On Dec 7, 4:23 pm, Philip Slate <[EMAIL PROTECTED]> wrote:
> > On Dec 7, 1:13 pm, Bruno Desthuilliers
> >
> > <[EMAIL PROTECTED]> wrote:
> > > > and friendlier to newbies.
> >
> > > I'd rather say "more acceptable to java-brainwashed developpers".
> >
> > And I'd rather say you're trolling, but that's ok since you're
> > preaching to the converted. You conveniently forgot to mention the
> C++/
> > Eiffel/Smalltalk/pretty-much-every-OO-lang "brainwashed" developers
> > too. In reality Python, with its kludgy OO and objects being
> > essentially glorified dicts, is the odd one out, not the other way
> > around.
> 
> That's true.  But what would a Python-brainwashed developer be?


Anyone who believes that writing beautiful, unencumbered code is efficient, 
while still believing that discovering type casting errors at runtime isn't 
grossly inefficient.


Or given whitespace delimited code, Python developers believe that nothing is 
important.

;-)



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


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


RE: Array of dict or lists or ....?

2008-10-07 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Pat
> Sent: Tuesday, October 07, 2008 10:16 PM
> To: python-list@python.org
> Subject: Re: Array of dict or lists or ?
> 

> 
> The Perl routine works fine and I'd like to emulate that behavior but
> since I've just starting learning Python I don't know the syntax for
> designing the data structure.  I would really appreciate it if someone
> could point me in the right direction.




states = {}

if 'georgia' not in states:
states['georgia'] = {}

states['georgia']['fulton'] = {}
states['georgia']['fulton']['ps101'] = {}
states['georgia']['fulton']['ps101']['math'] = {}
states['georgia']['fulton']['ps101']['math']['max'] = 100
states['georgia']['fulton']['ps101']['math']['current'] = 33 


states['georgia']['dekalb'] = {}
states['georgia']['dekalb']['ps202'] = {}
states['georgia']['dekalb']['ps202']['english'] = {}
states['georgia']['dekalb']['ps202']['english']['max'] = 500
states['georgia']['dekalb']['ps202']['english']['current'] = 44 

print states


*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: parsing MS word docs -- tutorial request

2008-10-29 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of
> [EMAIL PROTECTED]
> Sent: Tuesday, October 28, 2008 10:26 AM
> To: python-list@python.org
> Subject: parsing MS word docs -- tutorial request
> 
> All,
> 
> I am trying to write a script that will parse and extract data from a
> MS Word document.  Can / would anyone refer me to a tutorial on how to
> do that?  (perhaps from tables).  I am aware of, and have downloaded
> the pywin32 extensions, but am unsure of how to proceed -- I'm not
> familiar with the COM API for word, so help for that would also be
> welcome.
> 
> Any help would be appreciated.  Thanks for your attention and
> patience.
> 
> ::bp::
> --
> http://mail.python.org/mailman/listinfo/python-list


Word Object Model:
http://msdn.microsoft.com/en-us/library/bb244515.aspx

Google for sample code to get you started.


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


RE: exists=false, but no complaint when i open it!?

2008-05-15 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Reedick, Andrew
> Sent: Thursday, May 15, 2008 12:11 PM
> To: globalrev; python-list@python.org
> Subject: RE: exists=false, but no complaint when i open it!?
> 
> >
> > print os.path.exists('C:\Users\saftarn\Desktop\NetFlixDataSet
> > \trainingsetunzipped\training_set\mv_001.txt')
> >
> 
> 
> You're falling victim to string interpolation because of the
> backslashes.  (\n == newline, \N == N).
> 
> Try using a raw string r'filename', instead of 'filename':
>   print
>
os.path.exists(r'C:\Users\saftarn\Desktop\NetFlixDataSet\trainingsetunz
> i
> pped\training_set\mv_001.txt')
> 
> 

Specificially, the \t in '\trainingsetunzipped' and in '\training_set'
were being treated as tab characters.  Ignore my comment about '\N ==
N'.
--
http://mail.python.org/mailman/listinfo/python-list


RE: exists=false, but no complaint when i open it!?

2008-05-15 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of globalrev
> Sent: Thursday, May 15, 2008 12:04 PM
> To: python-list@python.org
> Subject: exists=false, but no complaint when i open it!?
> 
> print os.path.exists('C:\Users\saftarn\Desktop\NetFlixDataSet
> \trainingsetunzipped\training_set\mv_001.txt')
> 
> d=open('C:/Python25/myPrograms/mapexperiments/maps/provinces-of-
> sweden.gif')
> d.close()
> 
> exists returns false but when i open it doesnt complain. how come?
> 
> another file that exists returned false for complained when i tried to
> open it.
> --


You're falling victim to string interpolation because of the
backslashes.  (\n == newline, \N == N).

Try using a raw string r'filename', instead of 'filename':
print
os.path.exists(r'C:\Users\saftarn\Desktop\NetFlixDataSet\trainingsetunzi
pped\training_set\mv_001.txt')


*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: webspider, regexp not working, why?

2008-05-23 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of
> [EMAIL PROTECTED]
> Sent: Friday, May 23, 2008 12:43 PM
> To: python-list@python.org
> Subject: webspider, regexp not working, why?
> 
> url = re.compile(r"^((ht|f)tp(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]
> 
> search and match yields the same results.
> 
> but when you put something like href= in front of it it doesnt work.


a)  '^' matches at the beginning of a line.  So if 'href=' is at the
beginning of the line...

b)  Regexes are hard enough to read as is.  (http|ftp|https) is more
readable than ((ht|f)tp(s?).

c)  If you're going to parse html/xml then bite the bullet and learn one
of the libraries specifically designed to parse html/xml.  Many other
regex gurus have learned this lesson.  Myself included.  =)



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: regex help

2008-06-03 Thread Reedick, Andrew
> From: [EMAIL PROTECTED] 
> [mailto:[EMAIL PROTECTED] 
> On Behalf Of Support Desk
> Sent: Tuesday, June 03, 2008 9:32 AM
> To: python-list@python.org
> Subject: regex help
>
> I am trying to put together a regular expression that will 
> rename users address books on our server due to a recent 
> change we made.  Users with address books user.abook need 
> to be changed to [EMAIL PROTECTED] I'm having trouble 
> with the regex. Any help would be appreciated.


import re

emails = ('foo.abook', 'abook.foo', 'bob.abook.com', 'john.doe.abook')

for email in emails:
print email, '-->', 
print re.sub(r'\.abook$', '@domain.com.abook', email)



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


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


RE: New variable?

2008-06-03 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of tmallen
> Sent: Tuesday, June 03, 2008 2:41 PM
> To: python-list@python.org
> Subject: New variable?
> 
> What's the proper way to instantiate a new variable? x = ""?

I've always used
X = None
in those cases where I need to pre-declare a variable to set scope.


*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


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


RE: Iterate creating variables?

2008-06-13 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Diez B. Roggisch
> Sent: Friday, June 13, 2008 11:21 AM
> To: python-list@python.org
> Subject: Re: Iterate creating variables?
> 
> [EMAIL PROTECTED] schrieb:
> > I have twenty-five checkboxes I need to create (don't ask):
> >
> > self.checkbox1 = ...
> > self.checkbox2 = ...
> > .
> > .
> > .
> > self.checkbox25 = ...
> >
> > Right now, my code has 25 lines in it, one for each checkbox, since
> > these are all variables.
> >
> > Is there a way to write a loop so that I can have fewer lines of
code
> > but still keep the variables?
> >

> 
> Keep either a list or dictionary around. Like this:
> 
> checkboxes = []
> 
> for o in xrange(25):
>  checkboxes.append(create a checkbox...)
> 
> self.checkboxes = checkboxes
> 


And if you're too lazy to go back and convert the 25 checkboxes to an
array/list/dictionary, this will create a list from the existing
variable names:

s1 = 'one'
s2 = 'two'
s3 = 'three'
s4 = 'four'

s_list = []
s_list.append(None)  # since there is no s0, let's use 1 based list

for i in range(1, 5):
code = "s%d" % i
s_list.append(eval(code))


print s_list





*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: Iterate creating variables?

2008-06-13 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of [EMAIL PROTECTED]
> Sent: Friday, June 13, 2008 11:11 AM
> To: python-list@python.org
> Subject: Iterate creating variables?
> 
> I have twenty-five checkboxes I need to create (don't ask):
> 
> self.checkbox1 = ...
> self.checkbox2 = ...
> .
> .
> .
> self.checkbox25 = ...
> 
> Right now, my code has 25 lines in it, one for each checkbox, since
> these are all variables.
> 
> Is there a way to write a loop so that I can have fewer lines of code
> but still keep the variables?
> 
> I've tried:
> 
> for o in xrange(25):
> self.checkbox[o] = ...
> 
> which didn't work, and
> 
> for o in xrange(25):
> self.checkbox[''%d'%(o)] = ...
> 
> which also didn't work.
> 
> Both give the error message: "Attribute error: Main.App has no
> attribute "checkbox"", which clearly indicates that I'm not keeping
> the "variability" aspect I want.
> 
> Is there a way?
> 
> I appreciate any and all answers!


Either store the checkboxes in an array or hash/dictionary.  If that's
not practical, then
You can use strings to build the code and use eval to execute the string
as code.  Ex:

for i in range(10):
code = "%d + %d" % (i, i)
print eval(code)



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


RE: Freeze problem with Regular Expression

2008-06-25 Thread Reedick, Andrew

> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Kirk
> Sent: Wednesday, June 25, 2008 11:20 AM
> To: python-list@python.org
> Subject: Freeze problem with Regular Expression
> 
> Hi All,
> the following regular expression matching seems to enter in a infinite
> loop:
> 
> 
> import re
> text = ' MSX INTERNATIONAL HOLDINGS ITALIA srl (di seguito MSX ITALIA)
> una '
> re.findall('[^A-Z|0-9]*((?:[0-9]*[A-Z]+[0-9|a-z|\-]*)+\s*[a-
> z]*\s*(?:[0-9]
> *[A-Z]+[0-9|a-z|\-]*\s*)*)([^A-Z]*)$', text)
> #
> 
> No problem with perl with the same expression:
> 
> #
> $s = ' MSX INTERNATIONAL HOLDINGS ITALIA srl (di seguito MSX ITALIA)
> una
> ';
> $s =~ /[^A-Z|0-9]*((?:[0-9]*[A-Z]+[0-9|a-z|\-]*)+\s*[a-z]*\s*(?:[0-
> 9]*[A-
> Z]+[0-9|a-z|\-]*\s*)*)([^A-Z]*)$/;
> print $1;
> #
> 
> I've python 2.5.2 on Ubuntu 8.04.
> any idea?
> Thanks!
> 


It locks up on 2.5.2 on windows also.  Probably too much recursion going
on.


What's with the |'s in [0-9|a-z|\-]?  The '|' is a character not an 'or'
operator.  I think you meant to say either '[0-9a-z\-]' or '[0-9a-z\-|]'



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: How make regex that means "contains regex#1 but NOT regex#2" ??

2008-07-01 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of
> [EMAIL PROTECTED]
> Sent: Tuesday, July 01, 2008 2:29 AM
> To: python-list@python.org
> Subject: How make regex that means "contains regex#1 but NOT regex#2"
> ??
> 
> I'm looking over the docs for the re module and can't find how to
> "NOT" an entire regex.
> 
> For example.
> 
> How make regex that means "contains regex#1 but NOT regex#2" ?
> 

Match 'foo.*bar', except when 'not' appears between foo and bar.


import re

s = 'fooAAABBBbar'
print "Should match:", s
m = re.match(r'(foo(.(?!not))*bar)', s);
if m:
print m.groups()

print

s = 'fooAAAnotBBBbar'
print "Should not match:", s
m = re.match(r'(foo(.(?!not))*bar)', s);
if m:
print m.groups()


== Output ==
Should match: fooAAABBBbar
('fooAAABBBbar', 'B')

Should not match: fooAAAnotBBBbar



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: How make regex that means "contains regex#1 but NOT regex#2" ??

2008-07-01 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Reedick, Andrew
> Sent: Tuesday, July 01, 2008 10:07 AM
> To: [EMAIL PROTECTED]; python-list@python.org
> Subject: RE: How make regex that means "contains regex#1 but NOT
> regex#2" ??
>  
> Match 'foo.*bar', except when 'not' appears between foo and bar.
> 
> 
> import re
> 
> s = 'fooAAABBBbar'
> print "Should match:", s
> m = re.match(r'(foo(.(?!not))*bar)', s);
> if m:
>   print m.groups()
> 
> print
> 
> s = 'fooAAAnotBBBbar'
> print "Should not match:", s
> m = re.match(r'(foo(.(?!not))*bar)', s);
> if m:
>   print m.groups()
> 
> 
> == Output ==
> Should match: fooAAABBBbar
> ('fooAAABBBbar', 'B')
> 
> Should not match: fooAAAnotBBBbar
> 


Fixed a bug with 'foonotbar'.  Conceptually it breaks down into:

First_half_of_Regex#1(not
Regex#2)(any_char_Not_followed_by_Regex#2)*Second_half_of_Regex#1

However, if possible, I would make it a two pass regex.  Match on
Regex#1, throw away any matches that then match on Regex#2.  A two pass
is faster and easier to code and understand.  Easy to understand == less
chance of a bug.  If you're worried about performance, then a) a
complicated regex may or may not be faster than two simple regexes, and
b) if you're passing that much data through a regex, you're probably I/O
bound anyway.


import re

ss = ('foobar', 'fooAAABBBbar', 'fooAAAnotBBBbar', 'fooAAAnotbar',
'foonotBBBbar', 'foonotbar')

for s in ss:
print s,
m = re.match(r'(foo(?!not)(?:.(?!not))*bar)', s);
if m:
print m.groups()
else:
print


== output ==
foobar ('foobar',)
fooAAABBBbar ('fooAAABBBbar',)
fooAAAnotBBBbar
fooAAAnotbar
foonotBBBbar
foonotbar

*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: 'if name is not None:' v. 'if name:'

2008-07-15 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Victor Noagbodji
> Sent: Tuesday, July 15, 2008 3:44 PM
> To: python-list@python.org
> Subject: Re: 'if name is not None:' v. 'if name:'
> 
> >>what's the difference between these two statement?
> >one checks if the given object is not None, the other checks if it's
a
> true value:
> >http://docs.python.org/ref/Booleans.html#Booleans
> >>And which one should one use?
> >depends on what you want to test for, of course.
> >
> >
> 
> Well that's exactly why I'm asking. Since None returns False in if
> statements. Why do people use if name is not None: instead of simply
> writing if not name?
> 


If name is None:
Then name is NULL, nothing, nada, no object, no memory allocated, a
NULL pointer

If name is not None:
Then name is an object.  It's a pointer to some kind of allocated
structure in memory.  No idea if it contains a false or true value.

If name:
Then either
a) name is an object, and that object does not have a 'false'
value, such as False, zero, or empty.
  or
b) name is NULL/None.  No object.


Try this:

d = dict()
if not d:
d['a'] = 1
print d

d = None
if not d:
d['c'] = 3
print d





*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA622


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


RE: 'if name is not None:' v. 'if name:'

2008-07-15 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Reedick, Andrew
> Sent: Tuesday, July 15, 2008 4:13 PM
> To: Victor Noagbodji; python-list@python.org
> Subject: RE: 'if name is not None:' v. 'if name:'
> 


> If name:
> Then either
> a) name is an object, and that object does not have a 'false'
> value, such as False, zero, or empty.
>   or
> b) name is NULL/None.  No object.
 


Change that to: 

If not name:
Then either
a) name is an object, and that object does not have a 'false'
value, such as False, zero, or empty.
  or
b) name is NULL/None.  No object.



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


RE: properly delete item during "for item in..."

2008-07-17 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Ratko
> Sent: Thursday, July 17, 2008 12:27 PM
> To: python-list@python.org
> Subject: properly delete item during "for item in..."
> 
> Say you have something like this:
> 
> for item in myList:
>del item
> 
> Would this actually delete the item from the list or just decrement
> the reference counter because the item in myList is not associated
> with name "item" anymore (but still is with myList[itemIndex])? In
> other words, is "item" a temporary reference to myList[itemIndex] or
> is it actually that reference that myList has stored?
> 
> I am not sure if this question even makes any sense anymore. I've been
> using python for years and never had any problems (and I don't now
> either) but now that I had to revisit c++/STL, I had to deal about
> these issues and was wondering how python does it.
> 


Walk the list backwards when deleting.



master = ['a', 'b', 'c', 'd', 'e', 'f', 'g']


print "Deletes nothing"
a = master[:]
print a
for i in a:
del i
print a

print
print

print "Deletes safely from end"
a = master[:]
print a
for i in range(len(a)-1, -1, -1):
print i
if i % 2 == 0:
print "removing ", master[i]
del a[i]
print "", a,
if master[i] in a:
print "Ooops, deleted wrong thing...",
print
print a

print
print

print "Delete from front.  Deletes wrong things and throws an
exception..."
a = master[:]
print a
#for i in range(len(a)-1, -1, -1):
for i in range(len(a)):
print i
if i % 2 == 0:
print "removing ", master[i]
del a[i]
print "", a,
if master[i] in a:
print "Ooops, deleted wrong thing...",
print
print a


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


RE: New to Python, familiar with Perl - Seeking info sources

2008-07-24 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Brett Ritter
> Sent: Thursday, July 24, 2008 9:54 AM
> To: python-list@python.org
> Subject: New to Python, familiar with Perl - Seeking info sources
> 
> After many years happily coding Perl, I'm looking to expand my
> horizons. [no flames please, I'm pretty aware of Perl's strengths and
> weaknesses and I'm just here to learn more, not to enter religious
> debates].
> 

> 
> Any recommendations?  Thanks in advance.
> 

I have a Perl background and have found the O'Reilly books to be useful.
The Learning Python book (or whatever it's called) is good because it
covers the paradigm shifts and potential gotchas that you won't even
consider thinking about otherwise.  Only downside is wading through the
novice 'how to program' parts.  The Cookbook is also good for getting
'standard' apps up and running quickly (meaning you know how to do it in
Perl, and just need the equivalent Python syntax/paradigm.)

The Python help can be very hit or miss.  You're going to have _fun_
with the Python regex module.  *twitch*winch*sputter*  Generally
speaking, there's a Python module to do just about everything you could
do in Perl.  The only gap I've found is in the win32com with a class in
a .tlb file (works fine in Perl, fails in Python.)  But someone on the
python-win32 list posted a potential workaround which I need to test.

The really spiffy part is that when I converted a few Perl scripts to
Python, the Python scripts were a bit smaller.  =O  Python does less
compile time type checking than Perl.  And finally, this mailing list
does produce useful, polite answers about syntax to theory, despite some
noise.


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


RE: Monitor and compare two log files in real time

2008-08-06 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of m
> Sent: Wednesday, August 06, 2008 1:25 PM
> To: python-list@python.org
> Subject: Monitor and compare two log files in real time
> 
> I have a script I would like to write but I am not sure of where to
> start / approach. Perhaps someone could help direct me in the right
> direction. Any advice is appreciated.
> 
> I would like to write a python script that monitors two log files.
> If a certain string, lets say string1 shows up in logfile-A, I want to
> check if that same string shows up in log file-B within 8 minutes. If
> it does not show up within 8 minutes, send an email ( using sendmail
> or postfix).
> 
> Do you have any suggestions?
> --

Google on "python tail" to get a python implementation of the unix tail
command.  The rest should be easy. 

http://code.activestate.com/recipes/157035/



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA622


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


RE: Is this a good time to start learning python?

2008-03-31 Thread Reedick, Andrew

> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Rui Maciel
> Sent: Monday, March 31, 2008 12:41 PM
> To: python-list@python.org
> Subject: Is this a good time to start learning python?
> 
> Recently I woke up inclined to take up the task of learning another
> programming language. I've already dipped my toes in Perl (I've read
> online
> tutorials and wrote a couple of irrelevant pet projects) but, as the
> computers at my workplace only sport the python interpreter, it
> probably
> means that learning python will end up serving me better, at least in
> the
> short run. Plus, you know how Perl goes.
> 
> So far the decision seems to be a no brainer. Yet, Python 3000 will
> arrive
> in a few months. As it isn't backwards compatible with today's Python,
> there is the risk that no matter what I learn until then, I will end
up
> having to re-learn at least a considerable part of the language. To
put
> it
> in other words, I fear that I will be wasting my time.
> 
> At least that is what a clueless newbie believes. As this group is
> frequented by people who have more insight into all things
pythonesque,
> what are your thoughts on this?
> 

Meh.  That's like asking if you should learn to use a fork or a spoon.

If you're learning how to program, go with Python.  (Learning as in
algorithms and data structures.)
If you need to use OO, go with Python.  Perl's OO syntax is just
horrific. 
If you're using a lot of regexes, need a bit of speed, or need something
a bit more robust than dynamically typed objects randomly breaking your
code, then go with Perl.  ;-)
Libraries can also affect your choice.  (I had to switch to Perl when
Python's win32com failed.) 

Perl's learning curve is "unreadable" syntax, whereas Python's curve
requires knowing about side effects and dealing with strong, dynamic
typing.

Overall, Python is more high level and cleaner looking/readable.
However, Python's dynamically typed objects require additional
effort/expense to debug, and it's regex module is pretty quirky/painful
to use.  Perl has a very large library, is fast, is mostly statically
compiled, and doesn't get in the way (automatic type conversions,
several ways to do something, etc..)

Python is probably faster to learn (clearer syntax and OO,) but slower
to master (side effects, strongly but dynamically typed.)  With Perl,
once you get the core syntax down, you don't need to master Perl.
Instead you just look up the module/feature you want to use and just use
it.  Finally, I find that Perl's documentation is much better than
Python's.


All IMO, IME.


*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


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


RE: Is this a good time to start learning python?

2008-04-01 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Ant
> Sent: Monday, March 31, 2008 5:58 PM
> To: python-list@python.org
> Subject: Re: Is this a good time to start learning python?
> 
> On Mar 31, 5:40 pm, Rui Maciel <[EMAIL PROTECTED]> wrote:
> 
> BTW. I have to disagree with Andrew's comment: "With Perl,
> once you get the core syntax down, you don't need to master Perl.
> Instead you just look up the module/feature you want to use and just
> use
> it.". This may be true for knocking up Perl scripts, but for reading
> *other peoples* code in any language you need to have a good mastery
> of the core language. In Perl this is a quagmire of strange syntax,
> special cases, multiple ways to do the same thing and esoterica/magic,
> whereas Python's design to make whitespace significant and its "One
> (obvious) way to do things" philosophy makes reading other peoples
> code much easier. (Of course other peoples code always sucks, but
> hey ;-)


Eh... reading other people's Python code can be pretty hit or miss too.
Between undeclared variables (did you mean to reuse that variable name?)
and dynamic typing, Python can be really tough to follow.  Add in side
effects, over-use of lambdas, and the really hit or miss quality of
Python's documentation, and Python can be just as difficult to follow as
Perl.

The things that make code readable are good comments, good design
(Python emphasizes OO which helps,) and well-structured code (i.e. don't
combine 3-4 operations in a single line.)  This holds true for any
language, so I wouldn't go out of my to ding Perl.  IME.


> its "One (obvious) way to do things" philosophy

Given some of the solutions people have proposed to code questions in
the past, I'm going to pretend you didn't say that.  ;-)



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


RE: Stripping scripts from HTML with regular expressions

2008-04-09 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Michel Bouwmans
> Sent: Wednesday, April 09, 2008 3:38 PM
> To: python-list@python.org
> Subject: Stripping scripts from HTML with regular expressions
> 
> Hey everyone,
> 
> I'm trying to strip all script-blocks from a HTML-file using regex.
> 
> I tried the following in Python:
> 
> testfile = open('testfile')
> testhtml = testfile.read()
> regex = re.compile(']*>(.*?)', re.DOTALL)


Aha! \b is being interpolated as a backspace character:
  \b ASCII Backspace (BS)

Always use a raw string with regexes:
regex = re.compile(r']*>(.*?)', re.DOTALL)

Your regex should now work.



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA622


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


RE: Stripping scripts from HTML with regular expressions

2008-04-09 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Michel Bouwmans
> Sent: Wednesday, April 09, 2008 3:38 PM
> To: python-list@python.org
> Subject: Stripping scripts from HTML with regular expressions
> 
> Hey everyone,
> 
> I'm trying to strip all script-blocks from a HTML-file using regex.
> 
> I tried the following in Python:
> 
> testfile = open('testfile')
> testhtml = testfile.read()
> regex = re.compile(']*>(.*?)', re.DOTALL)
> result = regex.sub('', blaat)
> print result
> 
> This strips far more away then just the script-blocks. Am I missing
> something from the regex-implementation from Python or am I doing
> something
> else wrong?
> 

[Insert obligatory comment about using a html specific parser
(HTMLParser) instead of regexes.]

Actually your regex didn't appear to strip anything.  You probably saw
stuff disappear because blaat != testhtml:
testhtml = testfile.read()
result = regex.sub('', blaat)


Try this:

import re

testfile = open('a.html')
testhtml = testfile.read()
regex = re.compile('(.*?)', re.DOTALL)
result = regex.sub('',testhtml)

print result




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


RE: basic python question about for loop

2008-04-09 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of jmDesktop
> Sent: Wednesday, April 09, 2008 4:51 PM
> To: python-list@python.org
> Subject: basic python question about for loop
> 
> >From the Python.org tutorial:
> 
> >>> for n in range(2, 10):
> ... for x in range(2, n):
> ... if n % x == 0:
> ... print n, 'equals', x, '*', n/x
> ... break
> ... else:
> ... # loop fell through without finding a factor
> ... print n, 'is a prime number'
> ...
> 2 is a prime number
> 3 is a prime number
> 4 equals 2 * 2
> 5 is a prime number
> 6 equals 2 * 3
> 7 is a prime number
> 8 equals 2 * 4
> 9 equals 3 * 3
> 
> 
> 
> first time 2 mod 2, 2/2, no remainder == 0, what am I doing wrong?
> Why did it fall through?
> 

a) 2 is prime, so nothing is wrong.

b) Range isn't doing what you think it's doing:

>>> print range(2,2)
[]
>>> print range(2,3)
[2]
>>> print range(2,4)
[2, 3]
>>> print range(2,5)
[2, 3, 4]

>>> print range(1,1)
[]
>>> print range(1,2)
[1]
>>> print range(1,3)
[1, 2]
>>>



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA622


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


RE: basic python question about for loop

2008-04-09 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of jmDesktop
> Sent: Wednesday, April 09, 2008 5:04 PM
> To: python-list@python.org
> Subject: Re: basic python question about for loop
> 
> >
> > > >>> for n in range(2, 10):
> > > ...     for x in range(2, n):
> > > ...         if n % x == 0:
> > > ...             print n, 'equals', x, '*', n/x
> > > ...             break
> > > ...     else:
> > > ...         # loop fell through without finding a factor
> > > ...         print n, 'is a prime number'
> > > ...
> >
> > > first time 2 mod 2, 2/2, no remainder == 0, what am I doing wrong?
> > > Why did it fall through?
> >

> 
> So what is n and x in the first iteration?  Sorry.  I'm trying.


You're never getting to n and x in the first iteration, because the 'for x in 
range(2, n)' loop isn't looping.

This:  
for x in range(2, n)
is equivalent in C/Perl/etc. to:
for(x=2; xhttp://mail.python.org/mailman/listinfo/python-list


RE: How can I use quotes without escaping them using CSV?

2008-04-09 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of jeffself
> Sent: Wednesday, April 09, 2008 5:11 PM
> To: python-list@python.org
> Subject: How can I use quotes without escaping them using CSV?
> 
> 
> If I put an escape character in, it works.  For example, if I use ~ as
> my escape character, my output looks like this:
> 0001[tab]Michael L. ~"Mick~" Jones[tab]189
> 
> I don't want that. If I don't include an escape character, it doesn't
> work.
> 
> 
> Here's my code:
> import sys
> import csv
> from readexcel import *
> 
> f = open("results.txt", 'wb')
> book = sys.argv[1]
> sheet = sys.argv[2]
> 
> xl = readexcel(book)
> sheetnames = xl.worksheets()
> 
> for s in sheetnames:
> if s == sheet:
> writer = csv.writer(f, delimiter='\t', quoting=csv.QUOTE_NONE)
> for row in xl.getiter(s):
> 
>
writer.writerow((row['Precinct'],row['Candidate'],unicode(int(row['Vote
> s']
> f.close()
> 


The documentation is pretty, uhm, obtuse, but you also need to set
quotechar.

import sys
import csv

names = ['Michael L. "Mick" Jones', 'Vickie A. Meyers', 'John "Jack"
Smith']

writer = csv.writer(sys.stdout, delimiter='\t', quotechar='',
quoting=csv.QUOTE_NONE)
for i in names:
writer.writerow(['a', i, 'b'])

output:
a   Michael L. "Mick" Jones b
a   Vickie A. Meyersb
a   John "Jack" Smith   b



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: Stripping scripts from HTML with regular expressions

2008-04-10 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Michel Bouwmans
> Sent: Wednesday, April 09, 2008 5:44 PM
> To: python-list@python.org
> Subject: RE: Stripping scripts from HTML with regular expressions
> 
> 
> Thanks! That did the trick. :) I was trying to use HTMLParser but that
> choked on the script-blocks that didn't contain comment-indicators.
> Guess I
> can now move on with this script, thank you.
> 


S you asked for help with a regex workaround, but didn't ask for
help with the original problem, namely HTMLParser?  ;-)



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA625


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


RE: vary number of loops

2008-04-16 Thread Reedick, Andrew

> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Tim Chase
> Sent: Wednesday, April 16, 2008 9:53 AM
> To: [EMAIL PROTECTED]
> Cc: python-list@python.org
> Subject: Re: vary number of loops
> 
> >
> > If n=3, I want to have 3 sets of elements and mix them up using 3
for
> > loops.
> 
> You might be ineterested in this thread:
> 
> http://mail.python.org/pipermail/python-list/2008-January/473650.html
> 
> where various solutions were proposed and their various merits
> evaluated.
> 

I second that.  The thread compared building loops on the fly, building
comprehensions nested to arbitrarily levels, recursion (slw!), a
slick cookbook recipe using iterators, etc. and provided timings for
each method.  Definitely worth bookmarking.



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA625


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


RE: Python Success stories

2008-04-23 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of azrael
> Sent: Tuesday, April 22, 2008 6:26 AM
> To: python-list@python.org
> Subject: Python Success stories
> 
> Hy guys,
> A friend of mine i a proud PERL developer which always keeps making
> jokes on python's cost.
> 
> Please give me any arguments to cut him down about his commnets
> like :"keep programing i python. maybe, one day, you will be able to
> program in VisualBasic"
> 
> This hurts. Please give me informations about realy famous
> aplications.


IIRC, Python is used in games like Eve Online (SciFi MMO) and Vampire:
Bloodlines (RPG.)  Years later, a dedicated fan is still fixing/updating
the Bloodlines python scripts that control the dialogue and scripted
events.

OTOH, I use Perl over Python when it comes to Windows COM scripts due to
finding a typelib that Python just refused to load.  *shrug*

Perl, Python, and your friend are tools.  Use them appropriately for the
given situation.

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


RE: How to modify meaning of builtin function "not" to "!"?

2008-05-09 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of grbgooglefan
> Sent: Friday, May 09, 2008 9:41 AM
> To: python-list@python.org
> Subject: How to modify meaning of builtin function "not" to "!"?
> 
> I am creating functions, the return result of which I am using to make
> decisions in combined expressions.
> In some expressions, I would like to inverse the return result of
> function.
> 
> E.g. function contains(source,search) will return true if "search"
> string is found in source string.
> I want to make reverse of this by putting it as:
> if ( ! contains(s1,s2) ):
>  return 1
> 
> I found that "!" is not accepted by Python & compile fails with
> "invalid syntax".
> Corresponding to this Boolean Operator we've "not" in Python.
> 
> How can I make "not" as "!"?


Serious question:  Why would you want to?  'not' is easier to read (and type) 
than '!'.  Mentally, when you  see '!' you think 'not'.  It's also harder to 
overlook 'not', especially when compared to '!contains()'.  Finally, I imagine 
that Spanish speaking coders suffer enormous mental anguish when they see a 
right-side up '!' at the beginning of a sentence.

if ( ! contains(s1,s2) ):
 return 1

if ( !contains(s1,s2) ):
 return 1

if ( not contains(s1,s2) ):
 return 1

if ( ¡contains(s1,s2)):
 return 1




*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA625


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


RE: Good python equivalent to C goto

2008-08-18 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Kurien Mathew
> Sent: Saturday, August 16, 2008 5:21 PM
> To: python-list@python.org
> Subject: Good python equivalent to C goto
> 
> Hello,
> 
> Any suggestions on a good python equivalent for the following C code:
> 
> while (loopCondition)
> {
>   if (condition1)
>   goto next;
>   if (condition2)
>   goto next;
>   if (condition3)
>   goto next;
>   stmt1;
>   stmt2;
> next:
>   stmt3;
>   stmt4;
>   }
> 


===
Use a flag and a one loop for loop


while loopCondition:
flag = False
for i in range(1):
if condition1:
break
if condition2:
break
if condition3:
break
stmt1
stmt2
flag = True
if not flag:
stmt3
stmt4


===
Or just a straight flag

while ( loopCondition ):
flag = False

if (condition1)
flag = True  # goto next;
if (not flag and condition2)
flag = True  # goto next;
if (not flag and condition3)
flag = True  # goto next;

if not flag:
stmt1
stmt2
else
stmt3
stmt4



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA622


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


RE: how many nested for can we utilize?

2008-08-18 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Lie
> Sent: Monday, August 18, 2008 11:04 AM
> To: python-list@python.org
> Subject: Re: how many nested for can we utilize?
> 
> On Aug 17, 4:23 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> > Patrol Sun wrote:
> > > when I use 20 for ,"SystemError: too many statically nested blocks"
> > > When I use 100 for ,"IndentationError: too many levels of
> indentation"
> > > How to handle these errors?
> >
> > so why exactly are you trying to nest 20 or 100 for-in loops?
> >
> > 
> 
> I think most (all?) algorithm that might use 20+ levels of for-in
> loops could almost always be replaced with a recursive function. Or at
> least they could be broken into smaller functions.


Recursion is slow.  There was a thread on permutations and I ran some timings 
on various methods of nesting loops.  Also, I do remember hitting nested for 
limits very quickly.  I think list comprehensions allowed for deeper nesting 
than straight for loops.  Anyway, the thread contains various code and 
solutions that should help the OP.

http://mail.python.org/pipermail/python-list/2008-January/473787.html

Cookbook is relatively decent.  5 deep, 100 iterations:
list comprehension:  11.02
nested for loop   :  13.16   +19%
cookbook  :  18.85   +71%
recursion :  69.00  +526%
eval  :  13.30   +20%


Start of thread:  
http://mail.python.org/pipermail/python-list/2008-January/473650.html



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


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


RE: How to use win32com to convert a MS WORD doc to HTML ?

2008-08-19 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Lave
> Sent: Tuesday, August 19, 2008 10:06 AM
> To: python-list@python.org
> Subject: How to use win32com to convert a MS WORD doc to HTML ?
> 
> Hi, all !
> 
> I'm a totally newbie huh:)
> 
> I want to convert MS WORD docs to HTML, I found python windows
> extension win32com can make this. But I can't find the method, and I
> can't find any document helpful.
> 

Word Object Model:  
http://msdn.microsoft.com/en-us/library/bb244515.aspx

Specifically look at Document's SaveAs method.

*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


RE: Renaming Excel Spreadsheets

2008-08-26 Thread Reedick, Andrew
Excel object model:  

http://msdn.microsoft.com/en-us/library/bb149081.aspx

I think the Sheets object is where you add more sheets to a workbook.

 

You can google for code examples on how to use COM with Excel.  You
don't have to limit  yourself to Python code examples since COM is
"generic".

 

 

From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of Greg
Lindstrom
Sent: Tuesday, August 26, 2008 2:54 PM
To: python-list@python.org
Subject: Renaming Excel Spreadsheets

 

Hello,

I am working with Python to create Excel spreadsheets and have run into
a couple of problems I hope you can help me with.

First...are there any bindings/libraries into Open Office?

Now, back to Excel.  

--> Does anyone know a way to create N worksheets?  By default, 3 are
created, but I would like more.

--> Is it possible to rename a worksheet inside of the workbook (change
"Sheet1" to "July 08", for example).

I've been working with Mark Hammond's book on Windows programming with
Python, but these have me stumped.

Better yet, an Open Source reporting system (ala Crystal Reports) would
keep me from having to write this.  I've looked at Jasper and
DataVision;

Thanks,
--greg

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

RE: decent interactive python shell on MS Windows?

2008-10-01 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of
> [EMAIL PROTECTED]
> Sent: Wednesday, October 01, 2008 12:54 PM
> To: python-list@python.org
> Subject: decent interactive python shell on MS Windows?
 

 
> Is there an interactive Python shell on Windows that supports:
> 
> - easy copy-pasting to/from an editor? (as opposed to the cumbersome
> "mark", "copy" and then "paste" sequence that any terminal on Windows
> seems forced to adopt)

Just turn QuickEdit on.  Create shortcut to CMD.exe (or python.exe.)
Right click the short cut, Properties -> Options.  Check QuickEdit and
InsertMode.  When you save, choose Apply to all...  You can paste by
right clicking.  To copy just highlight and hit return.

 
> - readline-like command history (up/down for previous/next command,
> Ctr-R for searching, etc) ?

CMD has doskey for command history.  To search the history, type a few
leading characters of the command you want to recall and press F8.  Type
"help doskey" for more info.




*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


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