Blogmaker 0.5 - blog app for Django

2007-12-12 Thread Kent Johnson
PreFab Software has released Blogmaker (tm) 0.5, a full-featured, 
production-quality blogging application for Django. It supports 
trackbacks, ping and comments with moderation and honeypot spam 
prevention. Blogmaker is free, open-source software licensed under a BSD 
license.

Blogmaker powers the blogs at http://blog.blogcosm.com/ and 
http://prefabcosm.com/blog/.

Full announcement:
http://blog.blogcosm.com/2007/12/06/

Release page with the full feature list and (limited) documentation:
http://blogcosm.com/media/blog/release/README.html

Blogmaker is hosted at Google code:
http://code.google.com/p/blogmaker/

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

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


Re: [csv module] duplication of end of line character in output file generated

2005-01-11 Thread Kent Johnson
simon.alexandre wrote:
Hi all,
I use csv module included in python 2.3. I use the writer and encouter the
following problem: in my output file (.csv) there is a duplication of the
end of line character, so when I open the csv file in Ms-Excel a blank line
is inserted between each data line.
From the docs for csv.writer():
writer(  	csvfile[, dialect='excel'[, fmtparam]])
...If csvfile is a file object, it must be opened with the 'b' flag on platforms where that 
makes a difference.

Windows is a platform where that makes a difference. So try
  self.writer = csv.writer(file(Test.csv, wb))
Kent
OS: W2k
Someone has an idea ?
thanks in advance
the source code is the following:
--
import csv
class CsvDumper:
   def __init__(self):
   self.object =
[['la','mb','mc','md'],['ma','mb','mc','md'],['ma','mb','mc','md']]
   self.writer = csv.writer(file(Test.csv, w))
   def DumpCsvFile(self):
  for row in self.object:
  self.writer.writerow(row)
c = CsvDumper()
c.DumpCsvFile()

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


Re: Python unicode

2005-01-11 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
Kent:
I don't think so. You have hacked an attribute with latin-1
characters in it, but you
haven't actually created an identifier.

No, I really created an identifier. For instance
I can create a global name in this way:

globals()[è]=1
globals()[è]
1
Maybe I'm splitting hairs but to me an identifier is a syntactical element that can be used in 
specific ways. For example the syntax defines
attributeref ::=
 primary . identifier
so if identifiers can contain latin-1 characters you should be able to say
C.è=1

Kent

According to the language reference, identifiers can only contain
letters a-z and A-Z,
digits 0-9 and underscore.
http://docs.python.org/ref/identifiers.html

The parser has this restriction, so it gets confused if it finds è.
But the underlying
implementation just works for generic identifiers.
Michele Simionato
--
http://mail.python.org/mailman/listinfo/python-list


Re: xml parsing escape characters

2005-01-20 Thread Kent Johnson
Luis P. Mendes wrote:
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1
this is the xml document:
?xml version=1.0 encoding=utf-8?
string xmlns=http://www..;lt;DataSetgt;
~   lt;Ordergt;
~ lt;Customergt;439lt;/Customergt;
(... others ...)
~   lt;/Ordergt;
lt;/DataSetgt;/string
This is an XML document containing a single tag, string, whose content is text containing 
entity-escaped XML.

This is *not* an XML document containing tags DataSet, Order, Customer, 
etc.
All the behaviour you are seeing is a consequence of this. You need to unescape the contents of the 
string tag to be able to treat it as structured XML.

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


Re: xml parsing escape characters

2005-01-20 Thread Kent Johnson
Irmen de Jong wrote:
Kent Johnson wrote:
[...]
This is an XML document containing a single tag, string, whose 
content is text containing entity-escaped XML.

This is *not* an XML document containing tags DataSet, Order, 
Customer, etc.

All the behaviour you are seeing is a consequence of this. You need to 
unescape the contents of the string tag to be able to treat it as 
structured XML.

The unescaping is usually done for you by the xml parser that you use.
Yes, so if your XML contains for example
stufflt;not a taggt;/stuff
and you parse this and ask for the *text* content of the stuff tag, you will 
get the string
not a tag
but it's still *not* a tag. If you try to get child elements of the stuff 
element there will be none.
This is exactly the confusion the OP has.
--Irmen
--
http://mail.python.org/mailman/listinfo/python-list


Re: Overloading ctor doesn't work?

2005-01-20 Thread Kent Johnson
Martin Häcker wrote:
Hi there,
I just tried to run this code and failed miserably - though I dunno 
why. Could any of you please enlighten me why this doesn't work?
Here is a simpler test case. I'm mystified too:
from datetime import datetime
class time (datetime):
  def __init__(self, hours=0, minutes=0, seconds=0, microseconds=0):
datetime.__init__(self, 2001, 10, 31, hours, minutes, seconds, microseconds)
print time(1,2,3,4) # = 0001-02-03 04:00:00
print time()# = TypeError: function takes at least 3 arguments (0 
given)
What happens to the default arguments to time.__init__? What happens to the 2001, 10, 31 arguments 
to datetime.__init__?

I would expect the output to be
2001-10-31 01:02:03.04
2001-10-31 00:00:00.00
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Overloading ctor doesn't work?

2005-01-20 Thread Kent Johnson
Paul McGuire wrote:
Kent Johnson [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
Martin Häcker wrote:

Hi there,
I just tried to run this code and failed miserably - though I dunno
why. Could any of you please enlighten me why this doesn't work?
Here is a simpler test case. I'm mystified too:
from datetime import datetime
class time (datetime):
  def __init__(self, hours=0, minutes=0, seconds=0, microseconds=0):
datetime.__init__(self, 2001, 10, 31, hours, minutes, seconds,
microseconds)
print time(1,2,3,4) # = 0001-02-03 04:00:00
print time()# = TypeError: function takes at least 3 arguments (0
given)
What happens to the default arguments to time.__init__? What happens to
the 2001, 10, 31 arguments
to datetime.__init__?
I would expect the output to be
2001-10-31 01:02:03.04
2001-10-31 00:00:00.00
Kent

I can't explain this behavior, but this version does work (uses
datetime.combine instead of ctor)
-- Paul
from datetime import datetime, date as dt_date, time as dt_time
class time_d (datetime):
def __new__(cls, *args):
# default to no microseconds
if len(args)==3:
args = args + (0,)
if len(args)==4:
tmpdate = datetime.today()
h, mi, s, ms = args
return datetime.combine(tmpdate, dt_time(h,mi,s,ms))
elif len(args)==7:
y,m,d,h,mi,s,ms = args
return datetime.combine(dt_date(y,m,d), dt_time(h,mi,s,ms))
else:
raise TypeError, wrong number of args
print time_d(2001,10,31,1,2,3,4)
print time_d(1,2,3,4)
print time_d(1,2,3)

Ah, right. The light turns on...
datetime is immutable so overriding the constructor doesn't change the constructed object. You have 
to override __new__ instead.
http://www.python.org/2.2.1/descrintro.html#__new__

This works:
from datetime import datetime
class time (datetime):
def __new__(cls, hours=0, minutes=0, seconds=0, microseconds=0):
return datetime.__new__(cls, 2001, 10, 31, hours, minutes, seconds, 
microseconds)
print time(1,2,3,4) # = 2001-10-31 01:02:03.04
print time()# = 2001-10-31 00:00:00
Kent


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


Re: Overloading ctor doesn't work?

2005-01-21 Thread Kent Johnson
Nick Craig-Wood wrote:
Martin Häcker [EMAIL PROTECTED] wrote:
Now I thought, just overide the ctor of datetime so that year, month and 
  day are static and everything should work as far as I need it.

That is, it could work - though I seem to be unable to overide the ctor. :(
Its a bug!
  
http://sourceforge.net/tracker/index.php?func=detailaid=720908group_id=5470atid=105470
However its been fixed in a recent Python 2.3.
My example was developed in Python 2.4. The problem was the immutability of 
datetime.
Kent
(I was bitten by the same thing which used to fail but now works after
an upgrade of python 2.3!)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help with saving and restoring program state

2005-01-25 Thread Kent Johnson
Jacob H wrote:
Hello list...
I'm developing an adventure game in Python (which of course is lots of
fun). One of the features is the ability to save games and restore the
saves later. I'm using the pickle module to implement this. Capturing
current program state and neatly replacing it later is proving to be
trickier than I first imagined, so I'm here to ask for a little
direction from wiser minds than mine!
When my program initializes, each game object is stored in two places
-- the defining module, and in a list in another module. The following
example is not from my actual code, but what happens is the same.
(code contained in globalstate module)
all_fruit = []
(code contained in world module)
class Apple(object): # the class hierarchy goes back to object, anyway
def __init__(self):
self.foo = 23
self.bar = something
globalstate.all_fruit.append(self)  
apple = Apple()
I enjoy the convenience of being able to refer to the same apple
instance through world.apple or globalstate.all_fruit, the latter
coming into play when I write for loops and so on. When I update the
instance attributes in one place, the changes are reflected in the
other place. But now comes the save and restore game functions, which
again are simplified from my real code:
My understanding of pickle is that it will correctly handle shared references in the saved data. So 
if you pack all your global dicts into one list and pickle that list, you will get what you want. 
See code changes below:

(code contained in saveload module)
import pickle
import world
  import globalstate
def savegame(path_to_name):
world_data = {}
for attr, value in world.__dict__.items():
	# actual code is selective about which attributes 
	# from world it takes -- I'm just keeping this 
	# example simple
	world_data[attr] = value
  the_whole_shebang = [ world_data, globalstate.all_fruit, globalstate.all_items ]
fp = open(path_to_name, w)
  pickle.dump(the_whole_shebang, fp)
fp.close()

def loadgame(path_to_name):
fp = open(path_to_name, r)
  the_whole_shebang = pickle.load(fp)
  world_data, globalstate.all_fruit, globalstate.all_items = 
the_whole_shebang
for attr, value in world_data.items():
setattr(world, attr, value)
fp.close()
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: fast list lookup

2005-01-26 Thread Kent Johnson
Klaus Neuner wrote:
Hello,
what is the fastest way to determine whether list l (with
len(l)3) contains a certain element?
If you can use a set or dict instead of a list this test will be much 
faster.
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: re.search - just skip it

2005-01-26 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
Input is this:
SET1_S_W CHAR(1) NOT NULL,
SET2_S_W CHAR(1) NOT NULL,
SET3_S_W CHAR(1) NOT NULL,
SET4_S_W CHAR(1) NOT NULL,
;
.py says:
import re, string, sys
s_ora = re.compile('.*S_W.*')
lines = open(y.sql).readlines()
for i in range(len(lines)):
try:
if s_ora.search(lines[i]): del lines[i]
When you delete for example lines[0], the indices of the following lines change. So the former 
lines[1] is now lines[0] and will not be checked.

The simplest way to do this is with a list comprehension:
lines = [ line for line in lines if not s_ora.search(line) ]
Even better, there is no need to make the intermediate list of all lines, you 
can say
lines = [ line for line in open(y.sql) if not s_ora.search(line) ]
In Python 2.4 you don't have to make a list at all, you can just say
open(z.sql,w).writelines(line for line in open(y.sql) if not 
s_ora.search(line))
;)
Kent
except IndexError:
open(z.sql,w).writelines(lines)
but output is:
SET2_S_W CHAR(1) NOT NULL,
SET4_S_W CHAR(1) NOT NULL,
;
It should delete every, not every other!
thx,
RasDJ
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help With Python

2005-01-26 Thread Kent Johnson
Thomas Guettler wrote:
# No comma at the end:
mylist=[]
for i in range(511):
mylist.append(Spam)
or just
mylist = [Spam] * 511
Kent
print , .join(mylist)
 Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Startying with Python, need some pointers with manipulating strings

2005-01-27 Thread Kent Johnson
Benji99 wrote:
I've managed to load the html source I want into an object 
called htmlsource using:


import urllib
sock = urllib.urlopen(URL Link)
htmlSource = sock.read()
sock.close()

I'm assuming that htmlSource is a string with \n at the end of 
each line.
NOTE: I've become very accustomed with the TStringList class in 
Delphi so forgive me if I'm trying to work in that way with 
Python...

Basically, I want to search through the whole string( 
htmlSource), for a specific keyword, when it's found, I want to 
know which line it's on so that I can retrieve that line and 
then I should be able to parse/extract what I need using Regular 
Expressions (which I'm getting quite confortable with). So how 
can this be accomplished?
The Pythonic way to do this is to iterate through the lines of htmlSource and process them one at a 
time.
htmlSource = htmlSource.split('\n')  # Split on newline, making a list of lines
for line in htmlSource:
  # Do something with line - check to see if it has the text of interest

You might want to look at Beautiful Soup. If you can find the links of interest by the tags around 
them it might do what you want:
http://www.crummy.com/software/BeautifulSoup/

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


Re: Possible additions to the standard library? (WAS: About standardlibrary improvement)

2005-02-04 Thread Kent Johnson
Daniel Bickett wrote:
|def reverse( self ):
|
|Return a reversed copy of string.
|
|string = [ x for x in self.__str__() ]
|string.reverse()
|return ''.join( string )
def reverse(self):
return self[::-1]
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: changing local namespace of a function

2005-02-05 Thread Kent Johnson
Bo Peng wrote:
Dear list,
I have many dictionaries with the same set of keys and I would like to 
write a function to calculate something based on these values. For 
example, I have

a = {'x':1, 'y':2}
b = {'x':3, 'y':3}
def fun(dict):
  dict['z'] = dict['x'] + dict['y']
fun(a) and fun(b) will set z in each dictionary as the sum of x and y.
My function and dictionaries are a lot more complicated than these so I 
would like to set dict as the default namespace of fun. Is this 
possible? The ideal code would be:

def fun(dict):
  # set dict as local namespace
  # locals() = dict?
  z = x + y
You can part way there using keyword arguments. You just have to use dictionary syntax for changing 
values in the dictionary:

  def f(d, x=None, y=None):
 ...   d['z'] = x + y
 ...
  a = {'x':1, 'y':2}
  b = {'x':3, 'y':3}
 
  f(a, **a)
  a
{'y': 2, 'x': 1, 'z': 3}
  f(b, **b)
  b
{'y': 3, 'x': 3, 'z': 6}
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: changing local namespace of a function

2005-02-05 Thread Kent Johnson
Bo Peng wrote:
Yes. I thought of using exec or eval. If there are a dozen statements,
def fun(d):
  exec 'z = x + y' in globals(), d
seems to be more readable than
def fun(d):
  d['z'] = d['x'] + d['y']
But how severe will the performance penalty be?
You can precompile the string using compile(), you only have to do this 
once.
  def makeFunction(funcStr, name):
 ...   code = compile(funcStr, name, 'exec')
 ...   def f(d):
 ... exec code in d
 ... del d['__builtins__'] # clean up extra entry in d
 ...   return f
 ...
  f = makeFunction('z = x + y', 'f')
  a = {'x':1, 'y':2}
  b = {'x':3, 'y':3}
  f(a)
  a
{'y': 2, 'x': 1, 'z': 3}
  f(b)
  b
{'y': 3, 'x': 3, 'z': 6}
--
http://mail.python.org/mailman/listinfo/python-list


Re: changing local namespace of a function

2005-02-05 Thread Kent Johnson
Bo Peng wrote:
Exec is slow since compiling the string and calls to globals() use a 
lot of time.  The last one is most elegant but __getattr__ and 
__setattr__ are costly. The 'evil hack' solution is good since 
accessing x and y takes no additional time.

Previous comparison was not completely fair since I could pre-compile 
fun2 and I used indirect __setattr__. Here is the new one:
  # solution two: use exec
... def makeFunction(funcStr, name):
...   code = compile(funcStr, name, 'exec')
...   def f(d):
... exec code in d
...   return f
...
  def fun2(d):
...   myfun = makeFunction('z = x + y', 'myfun')
...   for i in xrange(0,N):
... myfun(d)
...   del d['__builtins__']
You are still including the compile overhead in fun2. If you want to see how fast the compiled code 
is you should take the definition of myfun out of fun2:

myfun = makeFunction('z = x + y', 'myfun')
def fun2(d):
  for i in xrange(0,N):
myfun(d)
  del d['__builtins__']
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: changing local namespace of a function

2005-02-06 Thread Kent Johnson
Bo Peng wrote:
Kent Johnson wrote:
You are still including the compile overhead in fun2. If you want to 
see how fast the compiled code is you should take the definition of 
myfun out of fun2:
I assumed that most of the time will be spent on N times execution of 
myfunc.
Doh! Right.
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Subclassing cElementTree.Element

2005-02-07 Thread Kent Johnson
Is it possible to subclass cElementTree.Element? I tried
  import cElementTree as et
  class Elt(et.Element):
 ...   pass
 ...
Traceback (most recent call last):
  File stdin, line 1, in ?
TypeError: Error when calling the metaclass bases
cannot create 'builtin_function_or_method' instances
I want to create a tree where I can navigate from a node to its parent. The 
standard Element class
doesn't seem to support this so I am trying to make a subclass that does. The 
XML files in question
are large so the speed of cElementTree is very helpful.
Thanks,
Kent
(apologies if this is a duplicate post)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Big development in the GUI realm

2005-02-08 Thread Kent Johnson
Fredrik Lundh wrote:
Robert Kern wrote:

Fair enough. The only time I've seen it in dead-tree print was in Heinlein's _Time Enough For 
Love_, unattributed to anyone else.
Amazon.com search inside the book finds no hits for malice in this book.
http://www.amazon.com/gp/reader/0441810764/102-7636110-6481700?v=search-insidekeywords=malice

if that's true, it would seem that it predates the Hanlon reference by a
couple of years:
http://www.statusq.org/archives/2001/12/04
on the other hand, Google tells me that Time Enough For Love con-
tains a couple of other famous stupidity quotes, including:
Never underestimate the power of human stupidity
Search inside the book finds this *twice* in Time Enough For Love.
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Name of type of object

2005-02-10 Thread Kent Johnson
Jive Dadson wrote:
I don't think I've quite got it.
The application I'm writing has some similarities to an interactive
shell.  Like an interactive shell, it executes arbitrary code that it
receives from an input stream.  When it gets an exception, it should
create an informative message, regardless of the type of exception.  The
traceback routine does that, somehow, some way, but I've tried to read
that code and figure out how and I don't get it.
The best I have so far is,
class Exec_thread(BG_thread):
 Execute a line of code in the global namespace. 
def _process(s):
 Process one instruction 
try:
exec s.product in globals()
except (Exception), e:
handle_error( typename(e)+ :  + str(e) )
Have you looked at the traceback module? If you want to print the same kind of trace you get from 
Python, just use traceback.print_exc().

import traceback
try:
  # whatever
except:
  traceback.print_exc()
Kent

But that works only if the exception happens to be derived from
Exception.  How do I handle the
general case?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is this a bug? BOM decoded with UTF8

2005-02-11 Thread Kent Johnson
Diez B. Roggisch wrote:
I know its easy (string.replace()) but why does UTF-16 do
it on its own then? Is that according to Unicode standard or just
Python convention?

BOM is microsoft-proprietary crap. 
Uh, no. BOM is part of the Unicode standard. The intent is to allow consumers of Unicode text files 
to disambiguate UTF-8, big-endian UTF-16 and little-endian UTF-16.
See http://www.unicode.org/faq/utf_bom.html#BOM

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


Re: changing __call__ on demand

2005-02-13 Thread Kent Johnson
Stefan Behnel wrote:
Hi!
This somewhat puzzles me:
Python 2.4 (#1, Feb  3 2005, 16:47:05)
[GCC 3.3.4 (pre 3.3.5 20040809)] on linux2
Type help, copyright, credits or license for more information.
. class test(object):
...   def __init__(self):
... self.__call__ = self.__call1
...   def __call1(self):
... print 1
...   def __call__(self):
... print 2
...
. t = test()
. t()
2
It works the way you want if test is an old-style class:
  class test:
 ...  def __init__(self):
 ...self.__call__ = self.__call1
 ...  def __call1(self):
 ...print 1
 ...  def __call__(self):
 ...print 2
 ...
  t=test()
  t()
1
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Second posting - Howto connect to MsSQL

2005-02-13 Thread Kent Johnson
John Fabiani wrote:
Hi,
Since this is (sort of) my second request it must not be an easy solution. 
Are there others using Python to connect MsSQL?  At the moment I'd accept
even a windows solution - although, I'm looking for a Linux solution.
On Windows, you can use http://sourceforge.net/projects/adodbapi
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can't subclass datetime.datetime?

2005-02-14 Thread Kent Johnson
Grant Edwards wrote:
Is it true that a datetime object can convert itself into a
string, but not the other way around?  IOW, there's no simple
way to take the output from str(d) and turn it back into d?
According to this thread, a patch has been checked in that adds strptime() to datetime. So there is 
something to look forward to...
http://tinyurl.com/4fbkb

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


Re: Newbie help

2005-02-14 Thread Kent Johnson
Chad Everett wrote:
Nope,  I am trying to learn it on my own.  I am using the book by Michael 
Dawson.
You might be interested in the Python tutor mailing list which is 
specifically intended for beginners.
http://mail.python.org/mailman/listinfo/tutor
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie help

2005-02-14 Thread Kent Johnson
Kent Johnson wrote:
You might be interested in the Python tutor mailing list which is 
specifically intended for beginners.
http://mail.python.org/mailman/listinfo/tutor
Ah, I don't mean to imply that this list is unfriendly to beginners, or that you are not welcome 
here! Just pointing out another resource.

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


Re: more os.walk() issues... probably user error

2005-02-16 Thread Kent Johnson
rbt wrote:
rbt wrote:
This function is intended to remove unwanted files and dirs from 
os.walk(). It will return correctly *IF* I leave the 'for fs in 
fs_objects' statement out (basically leave out the entire purpose of 
the function).

It's odd, when the program goes into that statment... even when only a 
'pass', and nothing else is present, nothing is returned. Why is that? 
I'm testing Python 2.4 on Linux x86 and WinXP. Results are the same on 
either platform.

def build_clean_list(self, path):
file_skip_list = ['search_results.txt']
dir_skip_list = ['dev', 'proc', 'Temporary Internet Files']
fs_objects = os.walk(path, topdown=True)
fs_objects is a generator, not a list. This loop is exhausting fs_objects, so when you return 
fs_objects is at the end of iteration, there is nothing left.

##  for fs in fs_objects:
##
##for f in fs[2]:
##if f in file_skip_list:
##print f
##fs[2].remove(f)
##
##for d in fs[1]:
##if d in dir_skip_list:
##print d
##fs[1].remove(d)
Add this here:
 yield fs
and take out the return. This turns build_clean_list() into a generator function and you will be 
able to iterate the result.

Kent
return fs_objects

Just to clarify, it's wrong of me to say that 'nothing is returned'... 
in either case, this is what is returned:

Here's what was returned and its type:

generator object at 0x407dbe4c
type 'generator'

But, I can't iterate over the returned object when I descend into the 
for statement I mentioned above.

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


Re: more os.walk() issues... probably user error

2005-02-16 Thread Kent Johnson
rbt wrote:
##  for fs in fs_objects:
##
##for f in fs[2]:
##if f in file_skip_list:
##print f
##fs[2].remove(f)
##
##for d in fs[1]:
##if d in dir_skip_list:
##print d
##fs[1].remove(d)
Will the changes I made (file and dir removals from os.walk()) be 
reflected in the generator object? Is it safe to remove objects this way 
and pass the results in a generator on to another function? Sorry for 
all the questions, I just like to fully understand something before I 
start doing it with confidence.
Yes. The docs for os.walk() explicitly state, When topdown is true, the caller can modify the 
dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into 
the subdirectories whose names remain in dirnames.

So changes to the dir list affect the iteration; changes to the file list directly affect the value 
you return to the caller.

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


Re: Alternative to standard C for

2005-02-17 Thread Kent Johnson
James Stroud wrote:
It seems I need constructs like this all of the time
i = 0
while i  len(somelist):
  if oughta_pop_it(somelist[i]):
somelist.pop(i)
  else:
i += 1
There has to be a better way...
somelist[:] = [ item for item in somelist if not oughta_pop_it(item) ]
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: need some advice on x y plot

2005-10-20 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
 how ?
 i have tried to use unix timestamps, and i have also tried with
 DateTime objects
 do i need to use a scale that isn't linear (default in most) ?
 how do i putt this off ?

Here is some code that works for me. It plots multiple datasets against time. 
The input data looks like this:
2005-04-04 16:00:00 141.154.195.129 - W3SVC1 SP6018ASP2 208.254.37.191 443 GET 
/rkadqsr/newskills/newskills.cfm selectedTab=1 200 0 53440 599 1594 HTTP/1.1 
adqsr.skillport.com Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.1) 
CookiesEnabled=1;+ASPSESSIONIDACTSSRAT=MCNLNLGADPOFGFKAHJHLDDKG;+CFID=785030;+CFTOKEN=27203160
 https://adqsr.skillport.com/rkadqsr/login/login.cfm
2005-04-04 16:00:00 208.254.38.216 - W3SVC1 SP6018ASP2 208.254.37.191 443 POST 
/_rkadqsrBackend_od_cgi/aiccisapi.dll - 200 0 372 274 4547 HTTP/1.0 
adqsr.skillport.com aiccisapi - -
2005-04-04 16:00:00 208.254.38.240 - W3SVC1 SP6018ASP2 208.254.37.191 443 POST 
/_rkadqsrBackend_od_cgi/aiccisapi.dll - 200 0 372 3019 250 HTTP/1.0 
adqsr.skillport.com aiccisapi - -

import datetime, time
import Gnuplot

dataPath = 'ex05040416.log'

datasets = {}
startTime = None

f = open(dataPath)

for line in f:
try:
dat, tim, c_ip, cs_username, s_sitename, s_computername, s_ip, s_port, \
cs_method, cs_uri_stem, cs_uri_query, sc_status, sc_win32_status, 
sc_bytes, \
cs_bytes, time_taken, cs_version, cs_host, cs_User_Agent, 
cs_Cookie, cs_Referer = line.split()
except ValueError:
print Can't parse, line
continue

tim = time.mktime(time.strptime(dat+' '+tim, %Y-%m-%d %H:%M:%S))
delay = int(time_taken)

if startTime is None:
startTime = tim

tim -= startTime

#print tim, delay
datasets.setdefault(sc_status, []).append([tim, delay])

g = Gnuplot.Gnuplot(debug=1)

plotter = g.plot
for key, values in datasets.items():
plotter(values)
plotter = g.replot

raw_input('Please press return to continue...\n')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sort problem

2005-10-20 Thread Kent Johnson
Michele Petrazzo wrote:
 Lasse Vågsæther Karlsen wrote:
 
 How about:

 list.sort(key=lambda x: x[3])

Better to use key=operator.itemgetter(3)

 Yes, on my linux-test-box it work, but I my developer pc I don't have
 the 2.4 yet. I think that this is a good reason for update :)

or learn about decorate-sort-undecorate:

lst = [ ...whatever ]
lst = [ x[3], i, x for i, x in enumerate(lst) ]
lst.sort()
lst = [ x for _, _, x in lst ]

Kent

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


Re: Question on re.IGNORECASE

2005-10-20 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
 Hi,
 
 I'm having some problems with basic RE in python. I was wondering
 whether
 somebody could provide a hint on what's going wrong with the following
 script. Comments are included.
 
 TIA.
 -myself
 
 
python2.3
 
 Python 2.3.4 (#1, Nov 18 2004, 13:39:30)
 [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-39)] on linux2
 Type help, copyright, credits or license for more information.
 
import re
pattern = re.compile('.*HTTP/(\d\.\d) *(\d*) *(.*)$')
pattern.search(GGHTTP/1.1 200 OK\r\n, re.IGNORECASE)
 
 _sre.SRE_Match object at 0xb75c6ed0
 
pattern.search(GHTTP/1.1 200 OK\r\n, re.IGNORECASE)
 
 # this makes no sense to me. Why is the previous line matched

Because the second argument to pattern.search() is the position where the 
search starts, not a flag. re.IGNORECASE == 2 so your search is skipping the 
first two chars.

Try giving the flags as a second argument to re.compile():
  import re
  re.IGNORECASE
2
  pattern = re.compile('.*HTTP/(\d\.\d) *(\d*) *(.*)$', re.IGNORECASE)
  pattern.search(GGHTTP/1.1 200 OK\r\n)
_sre.SRE_Match object at 0x00965980
  pattern.search(GHTTP/1.1 200 OK\r\n)
_sre.SRE_Match object at 0x009659D0
  pattern.search(Ghttp/1.1 200 OK\r\n)
_sre.SRE_Match object at 0x009651B0

Kent


 # and this not?
 
pattern.search(GHTTP/1.1 200 OK\r\n)
 
 _sre.SRE_Match object at 0xb758d020
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Beginning Python (Practical Python 2.0)

2005-10-21 Thread Kent Johnson
Magnus Lie Hetland wrote:
 I guess it has actually been out for a while -- I just haven't
 received my copies yet... Anyways: My book, Beginning Python: From
 Novice to Professional (Apress, 2005) is now out.

Apress is offering a $10 rebate if you purchase the book before October 30. See 
for example
http://www.bookpool.com/sm/159059519X

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


Re: Binding a variable?

2005-10-21 Thread Kent Johnson
Paul Dale wrote:
 
 Hi everyone,
 
 Is it possible to bind a list member or variable to a variable such that

No, Python variables don't work that way.
 
 temp = 5

The name 'temp' is now bound to the integer 5. Think of temp as a pointer to an 
integer object with value 5.
 
 list = [ temp ]

the name 'list' is bound to a list whose only member is a reference to the 
integer 5
 
 temp == 6

Ok now temp is bound to a new integer, but the list hasn't changed - it's 
member is still a reference to 5
 
 list
 
 would show
 
 list = [ 6 ]

You have to put a mutable object into the list - something whose state you can 
change. For example this works, because temp and lst[0] are references to the 
same mutable (changeable) list:
  temp = [6]
  lst = [temp]
  lst
[[6]]
  temp[0] = 5
  lst
[[5]]

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


Re: need some advice on x y plot

2005-10-21 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
 i am running a query on a database and making a list of time, value
 pairs
 kinda like this
 plot_points = ([time, value], [time, value], [time, value])
 gnuplot complains that it needs a float for one of the values.
 i can plot just the value, and it shows up ( no x value found)
 
 how should i proceed?

Convert one of the values to a float? What are your time and value numbers?

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


Re: Redirect os.system output

2005-10-21 Thread Kent Johnson
jas wrote:
 I would like to redirect the output from os.system to a variable, but
 am having trouble.  I tried using os.popen(..).read() ...but that
 doesn't give me exactly what i want.

Here is an example using subprocess:
http://groups.google.com/group/comp.lang.python/msg/9fa3a3c287e8e2a3?hl=en;

Kent

 
 ..this is windows by the way.
 
 For example:
 tmp = os.popen(hostname).read()
 
 ...works as expected.
 
 however,
 
 tmp = os.popen(cmd).read()
 ...i would like to have access to the cmd process...i.e. enter commands
 like a normal command line. os.system() allows this, but i dont want
 output to the screen..i wanna store it to a variable.  then send
 content of variable elsewhere,  receive more input and submit it.
 almost emulate the windows command prompt.
 
 any ideas?
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python vs Ruby

2005-10-21 Thread Kent Johnson
Casey Hawthorne wrote:
 I have heard, but have not been able to verify that if a program is
 about
 10,000 lines in C++
 it is about
 5,000 lines in Java
 and it is about
 3,000 lines in Python (Ruby to?)

My experience is that Java:Python is roughly 2:1, the highest I have seen (on 
small bits of code) is 3:1.

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


Re: coloring a complex number

2005-10-21 Thread Kent Johnson
Arthur wrote:
 Spending the morning avoiding responsibilities, and seeing what it would
 take to color some complex numbers.
 
 class color_complex(complex):
 def  __init__(self,*args,**kws):
 complex.__init__(*args)
 self.color=kws.get('color', 'BLUE')

In general when you subclass an immutable type you have to override __new__ 
rather than __init__. There is some explanation and example here:
http://www.python.org/2.2.3/descrintro.html#__new__

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


Re: Python vs Ruby

2005-10-21 Thread Kent Johnson
Bryan wrote:
 i would not say sion's ratio of 5:1 is dubious.  for what it's worth, 
 i've written i pretty complex program in jython over the last year.  
 jython compiles to java source code and the number of generated java 
 lines to the jython lines is 4:1.

Ugh. The code generated by jythonc is *nothing like* the code you would write 
by hand to do the same thing. This is a meaningless comparison.

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


Re: Module Importing Question

2005-10-22 Thread Kent Johnson
James Stroud wrote:
 Hello All,
 
 I have two modules that I use interchangably depending on the circumstances. 
 These modules are imported by yet another module. I want the importation of 
 these two alternatives to be mutually exclusive and dependent on the state of 
 the outermost module
 
 A diagram:
 
 mainApp ==imports== aModule ==imports== [oneMod | orTheOtherMod]
 
 I want the importing of oneMod or orTheOtherMod to depend on the state of the 
 mainApp. aModule is frozen, as are oneMod and orTheOtherMod. How might I 
 accomplish this?

I don't know what you mean by frozen, so maybe this is no good, but I would 
avoid having aModule look back at the state of mainApp. Instead use another 
module to communicate state. This could be a simple as

# in mainApp
import helper
if something:
  import oneMod as theMod
else:
  import orTheOtherMod as theMod
helper.theMod = theMod

import aModule

# in aModule
import helper.theMod as theMod
theMod.someFunction()

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


Re: Question about inheritance...

2005-10-22 Thread Kent Johnson
KraftDiner wrote:
 This is what I've got so far:
 class Rect(Shape):
   def __init__(self):
   super(self.__class__, self).__init__()

Should be 
  super(Rect, self).__init__()

   def render(self):
   super(self.__class__, self).render()

ditto

In this example it doesn't make any difference but with a deeper inheritance 
hierachy it does. See
http://www.python.org/2.2.3/descrintro.html#cooperation

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


Re: Tricky Areas in Python

2005-10-24 Thread Kent Johnson
Steven D'Aprano wrote:
 Alex Martelli wrote:

 Those two are easy. However, and this is where I show my hard-won 
 ignorance, and admit that I don't see the problem with the property 
 examples:
 
 class Base(object)
 def getFoo(self): ...
 def setFoo(self): ...
 foo = property(getFoo, setFoo)

 class Derived(Base):
 def getFoo(self): 
 
 
 Unless the answer is Why are you using setters and getters anyway? This 
 isn't Java you know.
 
 Oh wait! Yes I do... the setter doesn't actually take an argument to set 
 the property too. Is that it, or have a missed a cunningly hidden deeper 
 problem?

Derived.getFoo() will not override the use of Base.getFoo() to access the 
attribute foo.

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


Re: High Order Messages in Python

2005-10-24 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
 counting that out(regardless whether it is (dis)advantage or not), what
 else a block can do but not a named function ?

My limited understanding is that the advantage is
- simpler syntax
- high level of integration into the standard library (*many* methods that take 
closure arguments). Blocks are used not just for iteration but for the kinds of 
things shown in the examples to PEP 343 http://www.python.org/peps/pep-0343.html

For example to open a file and read from it uses two closures, one to wrap a 
block with the file open/close, one to iterate lines (from the pickaxe book):

File.open(testfile) do |file|
  file.each_line { |line| puts line }
end

Kent

 
 Alex Martelli wrote:
 
[EMAIL PROTECTED] [EMAIL PROTECTED] wrote:


could someone enlighten me what is the advantage of block over named
function ?

One thing that I can see a difference may be lexical scope ?

Yes, but -- according to the latest Ruby book, the mixed lexical
scope of blocks is a highly controversial notion in the Ruby community;
so I wouldn't necessarily count it as an _advantage_ of Ruby blocks...


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


Re: output from external commands

2005-10-24 Thread Kent Johnson
darren kirby wrote:
 quoth the James Colannino:
So, for example, in Perl I could do something like:

@files = `ls`;

So I guess I'm looking for something similiar to the backticks in Perl.
Forgive me if I've asked something that's a bit basic for this list.
Any help would be greatly appreciated :)  Thanks very much in advance.
 
 
 If all you want is filenames this will work:
 
import glob
files = [%s % f for f in glob.glob(*)]

or
import os
files = os.listdir('.')

Python has built-in support for many file manipulations, see the os, os.path 
and shutil modules.

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


Re: Redirect os.system output

2005-10-24 Thread Kent Johnson
jas wrote:
 Any other ideas? or examples of using subprocess to do what I was
 asking?

Actually I thought I was giving an example of what you were asking:
- on windows
- send a series of commands to a command process
- capture the result to a variable

The example I referenced sends a series of HELP commands to cmd.exe, captures 
the output of the commands and saves it to a file.

What did I miss?

Kent

 
 
 Kent Johnson wrote:
 
jas wrote:

I would like to redirect the output from os.system to a variable, but
am having trouble.  I tried using os.popen(..).read() ...but that
doesn't give me exactly what i want.

Here is an example using subprocess:
http://groups.google.com/group/comp.lang.python/msg/9fa3a3c287e8e2a3?hl=en;

Kent


..this is windows by the way.

For example:
tmp = os.popen(hostname).read()

...works as expected.

however,

tmp = os.popen(cmd).read()
...i would like to have access to the cmd process...i.e. enter commands
like a normal command line. os.system() allows this, but i dont want
output to the screen..i wanna store it to a variable.  then send
content of variable elsewhere,  receive more input and submit it.
almost emulate the windows command prompt.

any ideas?

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


Re: Redirect os.system output

2005-10-24 Thread Kent Johnson
jas wrote:
 Ok, I tried this...
 
 C:\python
 Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]
 on win32
 Type help, copyright, credits or license for more information.
 
import subprocess as sp
p = sp.Popen(cmd, stdout=sp.PIPE)

result = p.communicate(ipconfig)
 
 'result' is not recognized as an internal or external command,
 operable program or batch file.
 
 
 
 basically I was opening to send the ipconfig command to cmd.exe and
 store the result in the result variable.  But you can see there was
 an error with result.

This works for me:
import subprocess as sp
p = sp.Popen(ipconfig, stdout=sp.PIPE)
result = p.communicate()[0]
print result

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


Re: XML Tree Discovery (script, tool, __?)

2005-10-26 Thread Kent Johnson
Istvan Albert wrote:
 All I can add to this is:
 
 - don't use SAX unless your document is huge
 - don't use DOM unless someone is putting a gun to your head

+1 QOTW
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scanning a file

2005-10-28 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
 I want to scan a file byte for byte for occurences of the the four byte
 pattern 0x0100. 

data = sys.stdin.read()
print data.count('\x00\x00\x01\x00')

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


Re: OEM character set issue

2005-10-28 Thread Kent Johnson
Dennis Lee Bieber wrote:
 On Fri, 28 Oct 2005 15:55:56 +0200, Ladvánszky Károly [EMAIL PROTECTED]
 declaimed the following in comp.lang.python:
 
 
On my hungarian Win2k, some of the accented characters of the file names
appear incorrectly when Python is driven from the command line. However,
they
 
 
   The MS-DOS command window tends to use a different character
 encoding than full Windows widgets.

You can chaneg the encoding used by the command window with the chcp command.

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


Re: extracting numbers from a file, excluding fixed words

2005-10-29 Thread Kent Johnson
dawenliu wrote:
 Hi, I have a file with this content:
 xxx xx x xxx
 1
 0
 0
 0
 1
 1
 0
 (many more 1's and 0's to follow)
 y yy yyy yy y yyy
 
 The x's and y's are FIXED and known words which I will ignore, such as
 This is the start of the file and This is the end of the file.  The
 digits 1 and 0 have UNKNOWN length.  I want to extract the digits and
 store them in a file.  Any suggestions will be appreciated.
 

Off the top of my head (not tested):

inf = open('input.txt')
out = open('output.txt', 'w')

skips = [
  'xxx xx x xxx',
  'y yy yyy yy y yyy',
]

for line in inf:
  for skip in skips:
if skip in line:
  continue
  out.write(line)

inf.close()
out.close()

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


Re: Function returns none

2005-10-31 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
 I'm trying to write a website updating script, but when I run the
 script, my function to search the DOM tree returns None instead of what
 it should.

When you call findelement() recursively you have to return the value from the 
recursive call to the next caller up. See example below.

Kent

 
 I have this program:
 
 import sys
 from xml.dom.minidom import parse
 
 
 # search the tree for an element with a particular class
 
 def findelement(current, classtofind, topnode = None):
 if topnode == None: topnode = current
 
 
 
 # if it's an xml element...
 if current.nodeType == 1:
 print current.nodeName, ':', current.getAttribute('class')
 if current.getAttribute('class') == classtofind:
 print 'Returning node:', current
 return current
 elif current.hasChildNodes():
 findelement(current.firstChild, classtofind, topnode)

Should be
  return findelement(current.firstChild, classtofind, topnode)
and similarly wherever you call findelement().

 elif current.nextSibling:
 findelement(current.nextSibling, classtofind, topnode)
 
 elif (current.parentNode != topnode) \
 
  and (current.parentNode.nextSibling != None):
 
 findelement(current.parentNode.nextSibling, classtofind,
 topnode)
 else:
 
 print 'Returning None...'
 
 return None
 
 # others (text, comment, etc)
 
 else:
 
 if current.nextSibling:
 
 findelement(current.nextSibling, classtofind, topnode)
 
 elif (current.parentNode != topnode) \
 
  and (current.parentNode.nextSibling != None):
 
 findelement(current.parentNode.nextSibling, classtofind,
 topnode)
 else:
 
 print 'Returning None...'
 
 return None
 
 
 
 # parse the document
 
 blog = parse('/home/noah/dev/blog/template.html')
 
 
 
 # find a post
 
 postexample = findelement(blog.documentElement, 'post')
 
 
 
 print 'Got node:   ', postexample
 
 -
 
 My output is this:
 
 -
 html :
 head :
 title :
 body :
 h1 :
 ul :
 li :
 h2 :
 ol :
 li : post
 Returning node: DOM Element: li at -0x48599c74
 Got node:None
 -
 
 The function finds the right element fine, and says it will return DOM
 Element: li at -0x48599c74, but the program gets None instead.  What's
 happening here?  Any suggestions?
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: frozenset/subclassing/keyword args

2005-10-31 Thread Kent Johnson
Mark E. Fenner wrote:
 Speaking of which, in the docs at the bottom of the description of the
 builtin set/frozenset, there is a link to a page describing differences
 between the builtin sets and the sets module sets.  This link is broken
 locally and on the python.org docs.
 Locally, it reads:
 file:///usr/share/doc/python-docs-2.4.2/html/lib/module-comparison-to-builtin-set.html
 
 While it should read:
 file:///usr/share/doc/python-docs-2.4.2/html/lib/comparison-to-builtin-set.html

A little further down the page it says See About this document... for 
information on suggesting changes. If you click the link there it will tell 
you how to submit a doc bug which is the best way to get this fixed.

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


Re: Flat file, Python accessible database?

2005-11-01 Thread Kent Johnson
Karlo Lozovina wrote:
 I've been Googling around for _small_, flat file (no server processes), 
 SQL-like database which can be easily access from Python. Speed and 
 perforamnce are of no issue, most important is that all data is contained 
 within single file and no server binary has to run in order to use the 
 dbase. Oh, and I'm using Python under Cygwin.

Depending on what you mean by SQL-like you might like KirbyBase
http://www.netpromi.com/kirbybase.html

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


Re: Object-Relational Mapping API for Python

2005-11-02 Thread Kent Johnson
Aquarius wrote:
 I explored Java's Hibernate a bit and I was intrigued by how you can
 map entity objects to database tables, preserving all the relations and
 constraits. I am interested if there is something like this for Python
 - I noticed some APIs in the Cheeseshop, but most of them were alpha,
 better, or seemed to be forsaken a long time ago. Can you recommend me
 anything?
 

SQLObject, PyDO, Durus and Django's database API.

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


Re: Learning multiple languages (question for general discussion)

2005-11-03 Thread Kent Johnson
John Salerno wrote:
 I thought it might be interesting to get some opinions on when you know 
 when you're done learning a language. I've been learning C# for a few 
 months (albeit not intensively) and I feel I have a good grasp of the 
 language in general. 

Never? When you move on? You can become proficient in a couple of months but 
that is different from expert which is different from knows everything there 
is to know. I have been using Python for several years and I still learn from 
the old hands in this news group.

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


Re: How can I do this in Python?

2005-11-05 Thread Kent Johnson
Lad wrote:
 Can you please explain in more details (1) choice?

If you are using CGI you might be interested in the VoidSpace logintools which 
seems to handle much of this process. See
http://www.voidspace.org.uk/python/logintools.html#no-login-no-access

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


Re: Calling Class' Child Methods

2005-11-05 Thread Kent Johnson
Steve Holden wrote:
 Andrea Gavana wrote:
 The class Custom has a lot of methods (functions), but the user 
 won't call
 directly this class, he/she will call the MainClass class to construct 
 the
 GUI app. However, all the methods that the user can call refer to the
 Custom class, not the MainClass class. That is, the methods that the 
 user
 call should propagate to the Custom class. However, I know I can do:

 # Inside MainClass
 def SomeMethod(self, param):
 self.customwidget.SomeMethod(param)

 It seems that what you need is a generic delegation.
 
 This pattern (in Python, anyway) makes use of the fact that if the 
 interpreter can't find a method or other attribute for an object it will 
 call the object's __getattr__() method.

Another alternative is to delegate specific method by creating new attributes 
in MainClass. In MainClass.__init__() you can write
  self.SomeMethod = self.customwidget.SomeMethod
to automatically delegate SomeMethod. You can do this from a list of method 
names:
  for method in [ 'SomeMethod', 'SomeOtherMethod' ]:
setattr(self, method, getattr(self.customwidget, method))

This gives you more control over which methods are delegated - if there are 
some Custom methods that you do *not* want to expose in MainClass this might be 
a better approach.

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


Re: re sub help

2005-11-05 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
 hi
 
 i have a string :
 a =
 this\nis\na\nsentence[startdelim]this\nis\nanother[enddelim]this\nis\n
 
 inside the string, there are \n. I don't want to substitute the '\n'
 in between
 the [startdelim] and [enddelim] to ''. I only want to get rid of the
 '\n' everywhere else.

Here is a solution using re.sub and a class that maintains state. It works when 
the input text contains multiple startdelim/enddelim pairs.

import re

a = this\nis\na\nsentence[startdelim]this\nis\nanother[enddelim]this\nis\n * 2

class subber(object):
def __init__(self):
self.delimiterSeen = False

def __call__(self, m):
text = m.group()
if text == 'startdelim':
self.delimiterSeen = True
return text

if text == 'enddelim':
self.delimiterSeen = False
return text

if self.delimiterSeen:
return text

return ''

delimRe = re.compile('\n|startdelim|enddelim')

newText = delimRe.sub(subber(), a)
print repr(newText)


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


Re: modifying source at runtime - jython case

2005-11-05 Thread Kent Johnson
Jan Gregor wrote:
 Hello folks
 
  I want to apply changes in my source code without stopping jython
  and JVM. Preferable are modifications directly to instances of
  classes. My application is a desktop app using swing library.

Can you be more specific? Python and Jython allow classes to be modified at 
runtime without changing the source code or compiling new code. For example you 
can add and remove methods and attributes from a class and change the base 
classes of a class. You can also modify individual instances of a class to 
change their attributes and behaviour independently of other instances of the 
class. What are you trying to do? For example see
http://groups.google.com/group/comp.lang.python/browse_frm/thread/8f7d87975eab0ca4/18215f7ce8f5d609?rnum=15#18215f7ce8f5d609
http://groups.google.com/group/comp.lang.python/browse_frm/thread/a0b19b37ac48deaa/e599041de4b8feb0?rnum=22#e599041de4b8feb0

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


Re: modifying source at runtime - jython case

2005-11-06 Thread Kent Johnson
Jan Gregor wrote:
 my typical scenario is that my swing application is running, and i see
 some error or chance for improvement - modify sources of app, stop and run
 application again.
 so task is to reload class defitions (from source files) and modify also
 existing instances (their methods).

Ok, I think my first reply completely missed the mark. IIUC what you want is 
hard. This recipe might help:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164

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


Re: Pylab and pyserial plot in real time

2005-11-06 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
 Hiya,
 
 I've got a PIC microcontroller reading me humidity data via rs232, this
 is in ASCII format. I can view this data easily using hyperterminal or
 pyserial and convert it to its value (relative humidty with ord(input))
 
 But what im trying to do is plot the data in real time, ideally with
 pylab - as it looks simple to use and simple is the way i want to go!
 
 My code is below, it doesnt show a graph, I was wondering whether
 someone could suggest whats wrong?

You have to call pylab.show() for the graph to be drawn. I don't know if it 
will work incrementally if you call show() in the loop.

Kent

 
 thank you in advance
 
 David
 
 
 
 import serial
 from pylab import *
 
 ser = serial.Serial(0)
 t = arange(0.0, 1.0+0.01, 0.01)
 
 xlabel('time')
 ylabel('RH %')
 title(' RH sensor data sampled at 1 sec intervals ')
 #grid(true)
 
 x = 0
 
 while 1:
   s = ser.read()
   b = ord(s)
   h = []
   h.append(b)
   x = x + 1
   plot(t,h)
 
 ser.close
 
 
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: need help extracting data from a text file

2005-11-07 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
 Hey there,
 i have a text file with a bunch of values scattered throughout it.
 i am needing to pull out a value that is in parenthesis right after a
 certain word,
 like the first time the word 'foo' is found, retrieve the values in the
 next set of parenthesis (bar) and it would return 'bar'
 
 i think i can use re to do this, but is there some easier way?

It's pretty easy with an re:

  import re
  fooRe = re.compile(r'foo.*?\((.*?)\)')
  fooRe.search('foo(bar)').group(1)
'bar'
  fooRe.search('This is a foo bar baz blah blah (bar)').group(1)
'bar'

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


Re: Regular expression question -- exclude substring

2005-11-07 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
 Hi,
 
 I'm having trouble extracting substrings using regular expression. Here
 is my problem:
 
 Want to find the substring that is immediately before a given
 substring. For example: from
 00 noise1 01 noise2 00 target 01 target_mark,
 want to get
 00 target 01
 which is before
 target_mark.
 My regular expression
 (00.*?01) target_mark
 will extract
 00 noise1 01 noise2 00 target 01.

If there is a character that can't appear in the bit between the numbers then 
use everything-but-that instead of . - for example if spaces can only appear as 
you show them, use
(00 [^ ]* 01) target_mark or
(00 \S* 01) target_mark

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


Re: Regular expression question -- exclude substring

2005-11-07 Thread Kent Johnson
James Stroud wrote:
 On Monday 07 November 2005 16:18, [EMAIL PROTECTED] wrote:
 
Ya, for some reason your non-greedy ? doesn't seem to be taking.
This works:

re.sub('(.*)(00.*?01) target_mark', r'\2', your_string)
 
 
 The non-greedy is actually acting as expected. This is because non-greedy 
 operators are forward looking, not backward looking. So the non-greedy 
 finds the start of the first start-of-the-match it comes accross and then 
 finds the first occurrence of '01' that makes the complete match, otherwise 
 the greedy operator would match .* as much as it could, gobbling up all '01's 
 before the last because these match '.*'. For example:
 
 py rgx = re.compile(r(00.*01) target_mark)
 py rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01')
 ['00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01']
 py rgx = re.compile(r(00.*?01) target_mark)
 py rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01')
 ['00 noise1 01 noise2 00 target 01', '00 dowhat 01']

??? not in my Python:
  rgx = re.compile(r(00.*01) target_mark)
  rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01')
['00 noise1 01 noise2 00 target 01']
  rgx = re.compile(r(00.*?01) target_mark)
  rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01')
['00 noise1 01 noise2 00 target 01']

Since target_mark only occurs once in the string the greedy and non-greedy 
match is the same in this case.

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


Confusion about __call__ and attribute lookup

2005-11-10 Thread Kent Johnson
I am learning about metaclasses and there is something that confuses me.

I understand that if I define a __call__ method for a class, then instances of 
the class become callable using function syntax:

  class Foo(object):
 ...   def __call__(self):
 ... print 'Called Foo'
 ...
  f=Foo()
  f()
Called Foo

To create a class instance, you call the class. This made me think that the 
class' class must define __call__, and indeed it does, and calling it as an 
unbound method also creates a class instance:

  dir(type)
[..., '__call__', ...]
  f=type.__call__(Foo)
  f
__main__.Foo object at 0x00A35EB0

But why doesn't Foo.__call__ shadow type.__call__? Normally an instance 
attribute takes precedence over a class attribute. Is it something special 
about how function call syntax is handled internally, or do all special methods 
work this way, or is there something else going on?

PS Is there any place in the standard Python docs where the details of 
attribute lookup are spelled out?

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


Re: Confusion about __call__ and attribute lookup

2005-11-10 Thread Kent Johnson
Leif K-Brooks wrote:
 New-style classes look up special methods on the class, not on the instance:

For my future reference, is this documented somewhere in the standard docs?

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


Re: Confusion about __call__ and attribute lookup

2005-11-13 Thread Kent Johnson
John J. Lee wrote:
 Kent Johnson [EMAIL PROTECTED] writes:
 
Leif K-Brooks wrote:

New-style classes look up special methods on the class, not on the instance:

For my future reference, is this documented somewhere in the standard docs?
 
 Maybe somewhere in here :-(
 
 http://www.python.org/doc/newstyle.html

I have never found it there. I think something like the writeup Serge 
referenced should be in the language reference. I just sent the suggestion to 
[EMAIL PROTECTED]

Thanks to both of you,
Kent
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Book

2005-11-13 Thread Kent Johnson
David Rasmussen wrote:
 What is the best book for Python newbies (seasoned programmer in other 
 languages)?

I like Learning Python. Python in a Nutshell is good if you want something 
brief.

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


Re: generate HTML

2005-11-15 Thread Kent Johnson
Jim wrote:
 Perhaps you are trying to do this:
   'text to go here: %s' % ('text',)
 ?  For that you need a double-quoted string:
   text to go here: %s % ('text',)

Uh, no, not in Python:
  'text to go here: %s' % ('text',)
'text to go here: text'
  text to go here: %s % ('text',)
'text to go here: text'

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


Re: Need advice on subclassing code

2005-11-15 Thread Kent Johnson
Rusty Shackleford wrote:
 Hi --
 
 We have some code that returns an object of a different class, depending
 on some parameters.  For example:
 
 if param x is 1 and y is 1, we make an object of class C_1_1.
 if param x is 1 and y is 2, we make an object of class C_1_2.
 
 C_1_1 and C_1_2 share a common C ancestor, and in practice may be
 identical, but theoretically, could have the same function name with two
 different implementations underneath.
 
 We have a file where all the C_X_Y classes are defined.  
 Is this the best solution?  Is there some way of doing a default vs.
 non-default deal, without having to manually hardcode all the different
 possible subclasses?

How are you instantiating the correct class? You should be able to provide a 
default behaviour. For example if the classes are all defined in module C you 
could have a factory like this:

import C
def makeC(x, y):
  subtype = 'C_%d_%d' % (x, y)
  cls = getattr(C, subtype, C.C)
  return cls(x, y)

Then in module C just define the subtypes you need to specialize; all other 
values of x and y will get the base class C.C.

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


Re: searching for files on Windows with Python

2005-11-17 Thread Kent Johnson
Shane wrote:
 I've been giving Google a good workout with no luck. I would like to
 be able to search a Windows filesystem for filenames, returning a
 list off absolute paths to the found files, something like: 
 def findFiles(filename, pathToSearch):
  ...
  ...
  return foundFileNames
 
 Is the os module where I should start?

I always use Jason Orendorff's path module for this kind of stuff. It's way 
easier to use than os.whatever:

import path
files = path.path(pathToSearch).walkfiles(filename)

will give a list of path.path objects in pathToSearch whose names match 
filename (which is a glob so wildcards are recognized).

path.path is a subclass of str so the results can be used wherever you want the 
full path.

http://www.jorendorff.com/articles/python/path/index.html

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


Re: searching for files on Windows with Python

2005-11-19 Thread Kent Johnson
Peter Hansen wrote:
 Kent Johnson wrote:
 import path
 files = path.path(pathToSearch).walkfiles(filename)
 
 A minor enhancement (IMHO) (though I certainly agree with Kent's 
 recommendation here): since there is nothing else of interest in the 
 path module, it seems to be a fairly common idiom to do from path 
 import path and skip the doubled path.path bit.

Certainly it's your choice. I find most programs using path only reference 
path.path once, to create a starting path; other paths are created from that 
using files() or / etc. In this case it is less typing to say

import path
basePath = path.path(...)

instead of

from path import path
basePath = path(...)

from path import path only wins on number of chars if you reference path 
*three* times.

YMMV :-)

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


Re: Web-based client code execution

2005-11-20 Thread Kent Johnson
Stephen Kellett wrote:
 In message [EMAIL PROTECTED], Steve 
 [EMAIL PROTECTED] writes
 
 AJAX works because browsers can execute javascript.  I don't know of a
 browser that can execute python.  Basically your stuck with java or
 javascript because everything else really isn't cross platform.
 
 
 ActiveState do a version of Python that can run in a script tag like 
 JavaScript and VBScript. This requires Windows Scripting Host. They also 
 do a similar thing for Perl, not sure about TCL.

See
http://groups.google.com/group/comp.lang.python/msg/2d34acee66b40830

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


Re: Is there a way to create a button in either pygame or livewires?

2005-11-20 Thread Kent Johnson
Nathan Pinno wrote:
 Hey all,
 
 Is there a way to create a button in either pygame or livewires, that is 
 able to be clicked and when clicked sends a command to restart the program?

Maybe something here:
http://www.pygame.org/wiki/gui

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


Re: Web-based client code execution

2005-11-20 Thread Kent Johnson
Paul Watson wrote:
 Kent Johnson wrote:
 Stephen Kellett wrote:
 ActiveState do a version of Python that can run in a script tag like 
 JavaScript and VBScript. This requires Windows Scripting Host. They 
 also do a similar thing for Perl, not sure about TCL.

 See
 http://groups.google.com/group/comp.lang.python/msg/2d34acee66b40830
 
 Please correct my misunderstanding if I am wrong, but I thought that 
 this runs server-side only and requires Microsoft IIS as the httpd 
 server.  Is that correct?

I haven't tried it but the referenced article seems to be about including 
Python in a web page to be run in-browser by IE.

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


Re: Web-based client code execution

2005-11-21 Thread Kent Johnson
Paul Watson wrote:
 My desire to have the code distributed through a web page is just to 
 ensure that the user is running the correct version and has not hacked 
 it in any way.  I suppose I can checksum the local client application 
 and compare it with what is on the server.  Then, make a way to 
 update... ARGH!

I have used Java Web Start to distribute Jython applications from a web page. 
There are a few glitches getting it set up but then it works well. Solves 
'ensure that the user is running the correct version' nicely. Not sure if it 
protects against hacking.

My Jython and Web Start recipe is here:
http://personalpages.tds.net/~kent37/Python/JythonWebStart.html

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


Persist a class (not an instance)

2005-11-25 Thread Kent Johnson
Is there a way to persist a class definition (not a class instance, the actual 
class) so it can be restored later? A naive approach using pickle doesn't work:

  import pickle
  class Foo(object):
 ...   def show(self):
 ... print I'm a Foo
 ...
  p = pickle.dumps(Foo)
  p
'c__main__\nFoo\np0\n.'

Hmm, doesn't look too promising. In a new interpreter:

  import pickle
  p='c__main__\nFoo\np0\n.'
  Foo = pickle.loads(p)
Traceback (most recent call last):
  File stdin, line 1, in ?
  File C:\Python24\lib\pickle.py, line 1394, in loads
return Unpickler(file).load()
  File C:\Python24\lib\pickle.py, line 872, in load
dispatch[key](self)
  File C:\Python24\lib\pickle.py, line 1104, in load_global
klass = self.find_class(module, name)
  File C:\Python24\lib\pickle.py, line 1140, in find_class
klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'Foo'

The idea is to persist classes that are created and modified at runtime.

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


Re: Python book for a non-programmer

2005-11-25 Thread Kent Johnson
Simon Brunning wrote:
 I have a non-programming friend who wants to learn Python. It's been
 so long since I've been in her shoes that I don't feel qualified to
 judge the books aimed at people in her situation. 

Python Programming for the absolute beginner
http://premierpressbooks.com/ptr_detail.cfm?group=Programmingisbn=1%2D59200%2D073%2D8

Python Programming: An Introduction to Computer Science
http://www.fbeedle.com/99-6.html

And the Introductory Books page in the wiki lists many:
http://wiki.python.org/moin/IntroductoryBooks

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


Re: Persist a class (not an instance)

2005-11-25 Thread Kent Johnson
Sybren Stuvel wrote:
 Kent Johnson enlightened us with:
 
Is there a way to persist a class definition (not a class instance,
the actual class) so it can be restored later?
 
 
 From the docs:
 
 Similarly, classes are pickled by named reference, so the same
 restrictions in the unpickling environment apply. Note that none of
 the class's code or data is pickled [...]

OK that confirms that pickle won't work. Is there another approach that will?

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


Re: Looking for good beginner's tutorial

2005-11-29 Thread Kent Johnson
Roy Smith wrote:
 My wife wants to learn Python.  Can anybody suggest a good tutorial
 for her to read?  She's a PhD molecular biologist who is a pretty
 advanced Unix user.  She mucks about with Perl scripts doing things
 like text processing and even some simple CGI scripts, but has no
 formal programming training.

http://wiki.python.org/moin/BeginnersGuide/NonProgrammers
Kent
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string slicing

2004-12-05 Thread Kent Johnson
Ishwor wrote:
s = 'hello'
m = s[:]
m is s
True
 I discussed the *is* operator with some of the pythoners before as
well but it is somewhat different than what i intended it to do. The
LP2E by Mark  David says -
 m gets a *full top-level copy* of a sequence object- an object with
the same value but distinct piece of memory. but when i test them
with *is* operator then the result is True. Why is this happening??
This behaviour is due to the way strings are handled. In some cases strings are 'interned' which 
lets the interpreter keep only a single copy of a string. If you try it with a list you get a 
different result:

 s=list('hello')
 s
['h', 'e', 'l', 'l', 'o']
 m=s[:]
 m
['h', 'e', 'l', 'l', 'o']
 m is s
False
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: string slicing

2004-12-05 Thread Kent Johnson
Ishwor wrote:
On Sun, 05 Dec 2004 09:44:13 -0500, Kent Johnson [EMAIL PROTECTED] wrote:
This behaviour is due to the way strings are handled. In some cases strings are 
'interned' which
lets the interpreter keep only a single copy of a string. If you try it with a 
list you get a
different result

Thanx Kent.  so for lists Python doesn't keep the same object in the
cache??? 
Right, AFAIK lists are not cached in this way.
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Import a module without executing it?

2004-12-07 Thread Kent Johnson
Jay O'Connor wrote:
The real question, I suppose, is what is a good technique to find what 
modules and classes implement or refer to particular names
You might like to try ctags. I have had a good experience with it. It's not as automatic as I would 
like - you have to build a cross-reference table before you can use it - and it only finds 
implementors, not referrers. It integrates with lots of editors, I have used it with TextPad.
http://ctags.sourceforge.net/

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


Re: Import a module without executing it?

2004-12-08 Thread Kent Johnson
Andy, this is a nice example. It prompted me to look at the docs for compiler.visitor. The docs are, 
um, pretty bad. I'm going to attempt to clean them up a little. Would you mind if I include this 
example?

Thanks,
Kent
Andy Gross wrote:
Here's a quick example that will pull out all functions defined in the 
top-level of a module:

---
#/usr/bin/env python
from compiler import parse, walk
from compiler.visitor import ASTVisitor
testdata = r'''
def aFunction(anArg):
return anArg + 1
'''
class SimpleVisitor(ASTVisitor):
def visitFunction(self, parsedFunc):
print Function %(name)s at %(lineno)s takes %(argnames)s  \
   with code %(code)s % parsedFunc.__dict__
if __name__ == __main__:
ast = parse(testdata)
walk(ast, SimpleVisitor(), verbose=True)
---
[EMAIL PROTECTED]:~$ ./test.py
Function aFunction at 2 takes ['anArg']  with code 
Stmt([Return(Add((Name('anArg'), Const(1])

HTH,
/arg
On Dec 7, 2004, at 11:14 PM, Caleb Hattingh wrote:
Andy
thx for that.  I had a file called 'tktest.py' lying around, and I did:
' a = compiler.parseFile('tktest.py')
And a looks something like this:
***
Stmt([Import([('Tkinter', None)]), Function(None, 'add_rows', ['w', 
'titles', 'rows'], [], 0, None, 
Stmt([Discard(CallFunc(Getattr(Name('w'), 'configure'), 
[Keyword('state', Const('normal'))], None, None)), For(AssName('r', 
'OP_ASSIGN'), Name('rows'), Stmt([For(AssTuple([AssName('t', 
'OP_ASSIGN'), AssName('v', 'OP_ASSIGN')]), CallFunc(Name('zip'), 
[Name('titles'), Name('r')], None, None), 
Stmt([Discard(CallFunc(Getattr(Name('w'), 'insert'), [Const('end'), 
Mod((Const('%s:\t%s\n'), Tuple([Name('t'), Name('v')])))], None, 
None))]), None), Discard(CallFunc(Getattr(Name('w'), 'insert'), 
[Const('end'), Const('\n')], None, None))]), None), 
Discard(CallFunc(Getattr(Name('w'), 'configure'), [Keyword('state', 
Const('disabled'))], None, None))])), Assign([AssName('app', 
'OP_ASSIGN')], CallFunc(Getattr(Name('Tkinter'), 'Tk'), [], None, 
None)), Assign([AssName('t', 'OP_ASSIGN')], 
CallFunc(Getattr(Name('Tkinter'), 'Text'), [Name('app'), 
Keyword('state', Const('disabled'))], None, None)), 
Discard(CallFunc(Getattr(Name('t'), 'pack'), [], None, None)), 
Assign([AssName('info', 'OP_ASSIGN')], List([List([Const('Ali'), 
Const(18)]), List([Const('Zainab'), Const(16)]), 
List([Const('Khalid'), Const(18)])])), 
Discard(CallFunc(Name('add_rows'), [Name('t'), List([Const('Name'), 
Const('Age')]), Name('info')], None, None)), 
Discard(CallFunc(Getattr(Name('app'), 'mainloop'), [], None, None))])
***

Pretty impressive :)
Do you know of more batteries that can process this stuff further, for 
interest sake (and maybe the OP)?

thx again
Caleb
On Tue, 7 Dec 2004 15:57:16 -0500, Andy Gross [EMAIL PROTECTED] wrote:
You'll want to use the compiler package.  compiler.parseFile will 
return an AST that you can inspect (which is not really 'reflection', 
btw).

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

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


Re: converting html escape sequences to unicode characters

2004-12-09 Thread Kent Johnson
harrelson wrote:
I have a list of about 2500 html escape sequences (decimal) that I need
to convert to utf-8.  Stuff like:
#48708;
#54665;
#44592;
#47196;
#48372;
#45244;
#44144;
#50640;
#50836;
#45236;
#47732;
#44552;
#51060;
#50620;
#47560;
#51648;
#51104;
Anyone know what the decimal is representing?  It doesn't seem to
equate to a unicode codepoint...
In well-formed HTML (!) these should be the decimal values of Unicode 
characters. See
http://www.w3.org/TR/html4/charset.html#h-5.3.1
These characters appear to be Hangul Syllables:
http://www.unicode.org/charts/PDF/UAC00.pdf
import unicodedata
nums = [
48708,
54665,
44592,
47196,
48372,
45244,
44144,
50640,
50836,
45236,
47732,
44552,
51060,
50620,
47560,
51648,
51104,
]
for num in nums:
print num, unicodedata.name(unichr(num), 'Unknown')
=
48708 HANGUL SYLLABLE BI
54665 HANGUL SYLLABLE HAENG
44592 HANGUL SYLLABLE GI
47196 HANGUL SYLLABLE RO
48372 HANGUL SYLLABLE BO
45244 HANGUL SYLLABLE NAEL
44144 HANGUL SYLLABLE GEO
50640 HANGUL SYLLABLE E
50836 HANGUL SYLLABLE YO
45236 HANGUL SYLLABLE NAE
47732 HANGUL SYLLABLE MYEON
44552 HANGUL SYLLABLE GEUM
51060 HANGUL SYLLABLE I
50620 HANGUL SYLLABLE EOL
47560 HANGUL SYLLABLE MA
51648 HANGUL SYLLABLE JI
51104 HANGUL SYLLABLE JAM
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: gather information from various files efficiently

2004-12-13 Thread Kent Johnson
Keith Dart wrote:
try:
dict[a].append(b)
except KeyError:
dict[a] = [b]
or my favorite Python shortcut:
dict.setdefault(a, []).append(b)
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: getopt: Make argument mandatory

2004-12-16 Thread Kent Johnson
Frans Englich wrote:
On Wednesday 15 December 2004 14:07, Diez B. Roggisch wrote:
In my use of getopt.getopt, I would like to make a certain parameter
mandatory. I know how to specify such that a parameter must have a value
if it's specified, but I also want to make the parameter itself
mandatory(combined with a mandatory value, the result is that the user
must specify a value).
Use optparse - in the examples section you'll find what you need.

I'm slow here, do you mean in of the callback examples in 6.21.4?
http://docs.python.org/lib/module-optparse.html
No, try here - this section seems to have been deleted from the Python 2.4 
docs!
http://www.python.org/doc/2.3.4/lib/optparse-extending-examples.html
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Wrapper objects

2004-12-10 Thread Kent Johnson
Nick Coghlan wrote:
Simon Brunning wrote:
This work - 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52295?

Only for old-style classes, though. If you inherit from object or 
another builtin, that recipe fails.
Could you explain, please? I thought __getattr__ worked the same with new- 
and old-style classes?
Thanks,
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I convert characters into integers?

2004-12-14 Thread Kent Johnson
Markus Zeindl wrote:
I have got a string from the user, for example Hi!.
Now I get every character with a loop:
code
buffer = 
for i in range(len(message)):
  ch = message[i-1:i]
for ch in message:
...
is simpler and more idiomatic.
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Jython performance

2004-12-23 Thread Kent Johnson
Sean Blakey wrote:
On Wed, 22 Dec 2004 17:03:55 -0200, Gabriel Cosentino de Barros
[EMAIL PROTECTED] wrote:
On the Best GUI for small-scale accounting app? tread some people
mentioned jython. I went to read about it, but i was wondering if anyone has
any real project done with it and can give real world comments about
performance. 
I've been very happy with it's performance, after the one-time
interpreter startup.
That matches my experience as well. I have written a medium-sized GUI app using Jython and Swing and 
I am very happy with the performance. Most of the heavy lifting is done in Java libraries anyway - 
primarily Swing, dom4j and Velocity in my case.

The initial import of a module is relatively slow and I often defer importing a module until it is 
needed. Other than that I have been pleased with the performance.

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


Re: mathmatical expressions evaluation

2004-12-23 Thread Kent Johnson
Tonino wrote:
thanks all for the info - and yes - speed is not really an issue and no
- it is not an implementation of a complete financial system - but
rather a small subset of a investment portfolio management system
developed by another company ...
What I am trying to achieve is to parse a formula(s) and generate a
result ...
Why do you need to parse the formulas at runtime? It sounds like they are known in advance and you 
could just write functions to implement the calculations.

Kent
I will look into the pyparsing suggested and maybe even leave out
numarrays for now - as it seems a bit overkill ...
The formula are a bit complex and maybe even difficult to write out
Thanks all - I will post my progress ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-23 Thread Kent Johnson
Robin Becker wrote:
Alex Martelli wrote:
.
By the way, if that's very important to you, you might enjoy Mozart
(http://www.mozart-oz.org/)
.very interesting, but it wants to make me install emacs. :(
Apparently you can also use oz with a compiler and runtime engine...see
http://www.mozart-oz.org/documentation/apptut/index.html
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Jython IronPython Under Active Development?

2004-12-27 Thread Kent Johnson
Steve Holden wrote:
Just a little further background. The Python Software Foundation 
recently awarded a grant to help to bring Jython into line with the 
current CPython release.
Is information publicly available about this and other PSF grants? I don't see any announcement on 
the PSF web site or in the grants-discuss mail list.

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


Re: The Industry choice

2005-01-04 Thread Kent Johnson
Alex Martelli wrote:
Roy Smith [EMAIL PROTECTED] wrote:

Stefan Axelsson [EMAIL PROTECTED] wrote:
Yes, ignoring most of the debate about static vs. dynamic typing, I've
also longed for 'use strict'.
You can use __slots__ to get the effect you're after.  Well, sort of; it
only works for instance variables, not locals.  And the gurus will argue
that __slots__ wasn't intended for that, so you shouldn't do it.

There's a simple, excellent recipe by Michele Simionato, on both the
online and forthcoming 2nd edition printed Cookbook, showing how to do
that the right way -- with __setattr__ -- rather than with __slots__ .
The recipe is here (it took me a few minutes to find it, I found the title 
misleading):
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter: passing parameters to menu commands

2005-01-07 Thread Kent Johnson
Philippe C. Martin wrote:
I have many menu items and would like them all to call the same method
-However, I need the method called to react differently depending on the
menu item selected. Since the menu command functions do not seem to
receive any type of event style object, is there some type of Tkinter
call that would let my method know the menu id selected ?
Much as it seems to be out of favor, IMO this is a place where a lambda expression is very handy. 
You can make a callback for each menu item that binds an extra parameter to the handler:

# Based on an example by Fredrik Lundh
from Tkinter import *
def callback(code):
print called the callback with code, code
root = Tk()
# create a menu
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label=File, menu=filemenu)
filemenu.add_command(label=New, command=lambda: callback('New'))
filemenu.add_command(label=Open..., command=lambda: callback('Open'))
filemenu.add_separator()
filemenu.add_command(label=Exit, command=lambda: callback('Exit'))
mainloop()
Of course you could do this with named forwarding functions if you prefer.
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter: passing parameters to menu commands

2005-01-08 Thread Kent Johnson
Philippe C. Martin wrote:
menu.add_cascade(label=File, menu=filemenu)
filemenu.add_command(label=New, command=lambda: callback('New'))
filemenu.add_command(label=Open..., command=lambda:

Of course you could do this with named forwarding functions if you
prefer
I'm not sure what 'named forwarding functions' 
Bad choice of terminology, I just mean you can explicitly define
def handleNew:
  callback('New')
etc.
are but I'm actually in a
class and when applying your suggestion in the following manner,
everything works (THANKS!)

def __Dec(self,p_string):
  for i in p_string:
self.__Insert(i)
.
.
.
#menu creation
l_dec.add_command(label = 'ATR', command=lambda: self.__Dec('ATR'))
l_dec.add_command(label = 'IN', command=lambda:self.__Dec('IN'))
.
.
.

Yet I have a question:
If I replace the menu creation code as below, and since __Insert appends
the string p_string into a text widget that is created _after_ the menu
creation; the method __Dec seems to be called at the menu creation and
I get an error in __Insert because the test widget is equal to None.
My reflexes of C programmer tell me that command=self.__Dec just
passes a method pointer (sorry I said it) to add_command - yet it does
not seem to be so.

 What is actually going on ?


 #menu creation
 l_dec.add_command(label = 'ATR', command=self.__Dec('ATR'))
 l_dec.add_command(label = 'IN', command=self.__Dec('IN'))
self.__Dec is a reference to the function. It is similar to a method pointer so you don't need to 
apologize ;) The name of a function without the () is a reference. When you append () it becomes a 
call to the referenced function.

The command parameter for the menu must be a reference to a function. The function is called with no 
arguments when the menu is invoked.

So, you need a function of no arguments to handle the command. For example,
def handleMenu():
  print 'Handled'
filemenu.add_command(label=New, command=handleMenu)
Note there is no () after handleMenu. 'command' is bound to the function object; the function is not 
called until later.

OK, now suppose you want to pass a parameter to handleMenu?
def handleMenu(menuName):
  print 'Handled', menuName
Now what do you put in the command parameter? This won't work because you are *calling* handleMenu 
and assigning the result of the call (in this case the value None) to 'command':

filemenu.add_command(label=New, command=handleMenu('New')) # WRONG
You need a new function of zero arguments to bind to 'command'. Here is one way 
to do it:
def handleNew():
  handleMenu('New')
filemenu.add_command(label=New, command=handleNew) # OK
Note, again, no () after handleNew. 'command' is bound to the function object 
again.
OK, what about lambda? lambda is a way to create a simple anonymous function. One simple use of 
lambda is to make a new function that binds a parameter to another function.

lambda: handleMenu('New')
defines a function that does the same thing as handleNew. The value of the lambda expression is the 
function object. So

filemenu.add_command(label=New, command=lambda: handleMenu('New')) # OK
is another way to get the result you want.
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Speed revisited

2005-01-09 Thread Kent Johnson
Andrea Griffini wrote:
I've to admit that I also found strange that deleting the
first element from a list is not O(1) in python. My wild
guess was that the extra addition and normalization required
to have insertion in amortized O(1) and deletion in O(1) at
both ends of a random access sequence was going to have
basically a negligible cost for normal access (given the
overhead that is already present in python).
This was added to Python 2.4 as collections.deque
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Please Contribute Python Documentation!

2005-01-09 Thread Kent Johnson
Aahz wrote:
In article [EMAIL PROTECTED],
Tony Meyer [EMAIL PROTECTED] wrote:
I don't think I've seen such a statement before - the stuff I've seen
all indicates that one should be submitting proper LaTeX docs/patches.
If plain-text contributions are welcome, could this be added to the doc
about contributing to the docs?  (I suppose I could submit a patch, but
that seems overkill wink).

It *is* in the docs now -- see the top of
http://www.python.org/doc/2.4/doc/doc.html
It's also spelled out pretty clearly in the About this document document you get by clicking on 
the link at the bottom of every page.

Kent
(This has been the official policy for some time, but you're right that
it wasn't earlier documented.  So I filed a bug report. ;-)  If you
think this still isn't enough, file another.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to list currently defined classes, methods etc

2005-12-02 Thread Kent Johnson
Deep wrote:
 I have been looking a bit and am stuck at this point.
 
 Given a string, how do i find what is the string bound to.
 Let me give an example.
 
 def deep():
  print Hello
 
 now inspect.ismethod(deep) returns true. (As it should).
 But if I am trying to make a list of all bound methods), i use
 dir(), which is a list of strings. I get the string deep from this
 list.

Look it up in the globals() dict:
  def deep():
 ...   print 'Hello'
 ...
  globals()['deep']
function deep at 0x008ECF70

 How do I obtain the reference to the method it is bound to.
 The same problem can be extended to attributes and classes.

Use getattr() to inspect classes and instances:
  class deeper:
 ...   def deepest(self):
 ... print 'goodbye'
 ...
  getattr(deeper, 'deepest')
unbound method deeper.deepest
  d=deeper()
  getattr(d, 'deepest')
bound method deeper.deepest of __main__.deeper instance at 0x00A41350

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


  1   2   3   4   5   6   7   >