[Tutor] Subclassing list

2009-06-18 Thread Luis N
I get an error "TypeError: 'rounding' is an invalid keyword argument
for this function" on my list subclass.

How might I subclass list without this error?

This is the code:

class SeriesList(list):
def __new__(cls, *args, **kwargs):
series_list = list.__new__(cls, *args)
series_list.rounding = kwargs.get('rounding', None)
return series_list

def moving_average(self, function, period=10):
index = 0
window = []
ma = []
for i in self.__iter__():
i = float(i)
if is_not_nan(i):
window.insert(0, i)
if len(window) == period:
ma.append(function(window))
window.pop()
else:
ma.append(float('nan'))
return round(ma, self.rounding)
---
Regards,

Luis
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Subclassing list

2009-06-18 Thread Luis N
On Fri, Jun 19, 2009 at 12:56 AM, bob gailer  wrote:
>
> Luis N wrote:
>>
>> I get an error "TypeError: 'rounding' is an invalid keyword argument
>> for this function" on my list subclass.
>>
>> How might I subclass list without this error?
>>
>> This is the code:
>>
>> class SeriesList(list):
>>    def __new__(cls, *args, **kwargs):
>>        series_list = list.__new__(cls, *args)
>>        series_list.rounding = kwargs.get('rounding', None)
>>        return series_list
>>
>>    def moving_average(self, function, period=10):
>>        index = 0
>>        window = []
>>        ma = []
>>        for i in self.__iter__():
>>            i = float(i)
>>            if is_not_nan(i):
>>                window.insert(0, i)
>>                if len(window) == period:
>>                    ma.append(function(window))
>>                    window.pop()
>>            else:
>>                ma.append(float('nan'))
>>        return round(ma, self.rounding)
>> ---
>>
>
> I copied and ran the above. It gives me no errors.
>
> Of course all it is is a class definition.
>
> Is there more to the code?
>
> And please post the traceback so we have more information!
>
> --
> Bob Gailer
> Chapel Hill NC
> 919-636-4239

This is the traceback. I want to let SeriesList know how to round
moving average series derived from itself.

In [121]: s = SeriesList(rounding=1)
---
TypeError Traceback (most recent call last)

/Users/Luis/Documents/Programming/speculation/ in ()

TypeError: 'rounding' is an invalid keyword argument for this function


Thank you for your help,

Luis
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Comments appreciated

2004-12-21 Thread Luis N
This is the most meaningful thing this newbie has ever done. Comments
are appreciated:

#!/usr/local/bin/python

trashcan = "/home/anewby/.trashcan"

import os, sys, shutil

junk = []
for arg in sys.argv:
junk.append(arg)

junk = junk[1:]

empty = False

if "-e" in junk:
empty = True
junk.remove("-e")

if not os.path.exists(trashcan):
os.mkdir(trashcan)

def trash(junk):  
for i in junk:
toss = trashcan + "/" + i
if os.path.exists(toss):
if os.path.isdir(toss):
shutil.rmtree(toss)
if os.path.isfile(toss):
os.remove(toss)
os.rename(i, toss)

def can():
for j in os.listdir(trashcan):
if os.path.isdir(j):
shutil.rmtree(j)
if os.path.isfile(j):
os.remove(j)

if len(junk) is 0 and empty == False:
sys.exit()
else:
if len(junk) > 0:
trash(junk)
if empty == True:
can()
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Comments appreciated

2004-12-26 Thread Luis N
Hi, 

Jeff Shanon, thanks for your help. I was wondering if there was a
function to automatically get the user on a *nix system, and had tried
the if __name__ == __main__ but didn't really get it until your
example. The only thing I'm not clear about is how 'trashcan' can be a
local variable inside main() when it's required by both trash() and
can()

The only thing that's missing is that this script can't handle paths
like ~/dir/junkthis

Would a regular expression be the best way of finding the last /
followed by some text to be able to chdir to junk files from another
location?

#!/usr/local/bin/python

import os.path
from os import mkdir, remove
from sys import argv
from shutil import rmtree

trashcan = os.path.expanduser("~/.trashcan")

def main(junk):
empty = False
if "-e" in junk:
empty = True
junk.remove("-e")

if not os.path.exists(trashcan):
os.mkdir(trashcan)

if len(junk) > 0:
trash(junk)

if empty:
can()

def trash(junk):
for i in junk:
toss = trashcan + "/" + i
if os.path.exists(toss):
if os.path.isdir(toss):
rmtree(toss)
if os.path.isfile(toss):
os.remove(toss)
os.rename(i, toss)

def can():
for j in os.listdir(trashcan):
toss = trashcan + "/" + j
if os.path.isdir(toss):
rmtree(toss)
if os.path.isfile(toss):
os.remove(toss)

if __name__ == '__main__':
main(argv[1:])
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Comments appreciated

2004-12-29 Thread Luis N
> [Jeff]
> > Also, even though this is intended to be a quick shell script, it's
> > not a bad idea to make everything except function defs into a little
> > main() function, and call it in a script-only section.
> 
> 
> [Luis]
> 
> > The only thing I'm not clear about is how 'trashcan' can be a
> > local variable inside main() when it's required by both trash() and
> > can()
> 
> 
> What Jeff is trying to say is that it's possible to pass 'trashcan' around
> as yet another parameter to both trash() and can().  That is, we can avoid
> global variables altogether, and just work with parameter passing.
> 

Lovely, thank you. I started a project that is for learning spanish
on-line, of currently 300 lines or so, that is proceeding rapidly
thanks to these lessons learned. Thank you Python Tutors, and thank
you Python!

Cheers,

Luis
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] cgi.FieldStorage and dictionary.get(' ')

2004-12-30 Thread Luis N
Hi,

I've passed this through the interperter line-by-line, yet still can't
get it to work right.

The first time the cgi driver script initiates it runs the login
function which renders a zpt. Upon submission of their vitals,  the
user is authenticated via sqlobject, and if they pass the chapters
function should run. However, what I get is zip, zilch, nada. Just a
blank page, with the query string appended to the url.

def main(form):
   if form.has_key('author') and form.has_key('password'):
  q = Users.select(AND(Users.q.author==form.get('author'),
  Users.q.password==form.get('password')))
  if len(list(q))>0:
 chapters(author=form.get('author'))
  else:
 login(failure=True)
   else:
  login(failure=False)

Out of curiosity I wrote a simple test cgi.

#!/usr/local/bin/python

print 'Content-type: text/plain\n\n'

import cgi

form = cgi.FieldStorage()
if form.has_key('author') and form.has_key('password'):
print form.keys()
print form.get('author')
print form.get('password')

Strangely, the calls to print form.get('author') and
form.get('password') don't appear in the output. Only the form.keys()
appears.

Additionally, why doesn't def main(form=cgi.FieldStorage()) work, I
tried to do it as so, thinking it more graceful, and it floundered.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] *args, **kwargs

2005-01-01 Thread Luis N
Hi,

I gave this a quick read: http://aspn.activestate.com/ASPN/Mail/Message/573292

I'm wondering how I can turn a variable number of keyword arguments
passed to a class into variables for use in said class:

#This so doesn't work

class SomethingLikeThis:
def __init__(self, **kwargs):
self.kwargs = kwargs

def show(self):
for k in self.kwargs.keys():
v = selfkwargs.get(k)
print v

I'm probably misunderstanding the purpose of *args and **kwargs totally.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] CGI and cookies.

2005-01-05 Thread Luis N
When the script begins with main(f), it gets a KeyError and goes to
the login page, but when the form data is submitted it returns a 404.
Am I not setting/getting the cookie properly? Absolutely nothing is
printed until zptIO is called.

import os
import Cookie
from spanishlabs.conf import *
from spanishlabs.zpt import *
from spanishlabs.sql import *

def main(f):
   try:
  c = os.environ["HTTP_COOKIE"]
   except KeyError:
  login(f, fail=False)
   else:
  fetchCookie(f)

def login(f, fail):
   if f:
  authenticate(f)
   zpt = 'login.zpt'
   context = {'here':Render(fail)}
   zptIO(zpt, context)

def authenticate(f):
   if f.has_key('author') and f.has_key('password'):
  author = f.['author'].value
  password = f.['password'].value
  q = Users.select(AND(Users.q.author==author,
   Users.q.password==password))
  if len(list(q))>0:
 setCookie(f, author)
   else:
  login(f, fail=True)

def chapters(f, author):
   if f.has_key('event') and f.has_key('chapter'):
  event = f['event'].value
  chapter = f['chapter'].value
  q = Chapters.select(Chapters.q.chapter==chapter)

  if event == 'create' and len(list(q))>0:
 exists = True
  else:
 create = chapter

  if event == 'edit' and len(list(q))>0:
 edit = chapter

   zpt = 'chapters.zpt'
   context = {'here':Render(exists=None, create=None, edit=None)}
   zptIO(zpt, context)

def setCookie(f, author):
   c1 = Cookie.SimpleCookie()
   c1['author'] = author
   c1['author']['max-age'] = 7200
   c1['author']['expires'] = 7200
   c1['author']['version'] = 1
   print c1
   chapters(f, author)

def fetchCookie(f):
   c2 = Cookie.SimpleCookie()
   c2.load(os.environ["HTTP_COOKIE"])
   author = c2['author'].value
   chapters(f, author)

def zptIO(zpt, context):
   pt = PageTemplate()
   template = open(os.path.join(templates, zpt))
   pt.write(template.read())
   template.close()
   print 'Content-type: text/html\n\n'
   print pt(context=context)

A previous message I sent to the list about **kwds mostly makes sense
to me now. The missing dot was a typo.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] ascii encoding

2005-01-24 Thread Luis N
How would I best turn this string:

'2005-01-24 00:00:00.0'

into this string:

'2005%2D01%2D24%2000%3A00%3A00%2E0'

In order to call a URL.

I've hunted through the standard library, but nothing seemed to jump out.

Thank You.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ascii encoding

2005-01-25 Thread Luis N
Ok, urllib.quote worked just fine, and of course so did urllib.pathname2url.

I should have run a dir() on urllib. Those functions don't appear in
http://docs.python.org/lib/module-urllib.html

Now, how might one go about calculating the New York time off-set from
GMT? The server is in the U.S. but time.localtime() is giving me GMT.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ascii encoding

2005-01-25 Thread Luis N
In other words I have to do some arithmetic:

>>> import time
>>> time.timezone
0

The server is located in Dallas, Texas.


On Wed, 26 Jan 2005 15:44:48 +1300, Tony Meyer <[EMAIL PROTECTED]> wrote:
> > time.timezone gives you, I think, the offset between
> > your current timezone and GMT. However, being myself in the GMT zone,
> > I don't know exactly if the returned offset is positive or negative
> > (it returns 0 here, which makes sense :D ).
> 
> Whether or not it's positive or negative depends on which side of GMT/UTC
> you are, of course :)  Note that the result in is seconds, too:
> 
> >>> import time
> >>> time.timezone
> -43200
> >>> time.timezone/60/60
> -12
> 
> (I'm in NZ, 12 hours ahead of GMT/UTC).
> 
> =Tony.Meyer
> 
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] elementtree, lists, and dictionaries

2005-02-11 Thread Luis N
Hi,

This code works, but I don't like it much:

def authenticateAuthor(author, password):
authorxml = 'author.xml'
path = os.path.join(xml, authorxml)
try: if not os.path.exists(path):
authorfile = False
else:
authorfile = True
tree = E.ElementTree(file=path)
u = tree.getiterator('user')
p = tree.getiterator('password')
ul = []
pl = []
for unode in u:
ul.append(unode.text)
for pnode in p:
pl.append(pnode.text)
d = {}
for i in range(len(ul)):
d[ul[i]] = pl[i]
if d.has_key(author):
if d.get(author) == password:
auth = True
else:
auth = False
return auth, authorfile

It assumes a great deal, such as that there is no chance that there
will be more users then there are passwords, etc. given an xml
document format such as:



authorname
authorpassword



I don't like how I'm making two lists and then turning them into a
dictionary. It seems unpythonic.

Suggestions are appreciated.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] elementtree, lists, and dictionaries

2005-02-17 Thread Luis N
Thanks that's much nicer.

On Fri, 11 Feb 2005 22:28:55 -0500, Kent Johnson <[EMAIL PROTECTED]> wrote:
> If you iterate over the author nodes you can check the user name and password 
> of each in turn.
> 
> Not tested code!
> 
> def authenticateAuthor(author, password):
> authorxml = 'author.xml'
> path = os.path.join(xml, authorxml)
> if not os.path.exists(path):
> return False, False
> else:
> tree = E.ElementTree(file=path)
> for authorNode in tree.getiterator('author'):
> user = authorNode.find('user').text
> pass = authorNode.find('password').text
> 
> if author == user:
> if password == pass:
> return True, True
> else:
> return False, True
> 
> return False, True
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Class in a class

2005-02-17 Thread Luis N
Does it make sense to do this:

In [2]: class AB:
   ...: pass
   ...:
In [3]: a = AB()

In [4]: a
Out[4]: <__main__.AB instance at 0x8428bec>

In [5]: class BC:
   ...: def __init__(self, foo):
   ...: self.foo = foo

In [6]: b = BC(a)

In [7]: b.foo
Out[7]: <__main__.AB instance at 0x8428bec>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] slow html generation code

2005-03-02 Thread Luis N
This code seems a little slow, is there anything in particular that
jumps out as being not quite right.

The idea is that a file is opened that contains path names to other
files, that are appended and outputed into a directory of choice.

I plan to move this off the filesystem into a database when the
concept is worked out, maybe that will help.

#!/usr/local/bin/python

import sys
import os
from string import Template
from textile import textile

def main(files):
if len(files) < 1:
print 'Feed me with XHTML, String Templates, and Textile'
else:
path = os.path.expanduser('~/')
publish = os.path.join(path, 'publish')
pages = os.path.join(publish, 'pages')
write = os.path.join(path, 'public_html/write')
try:
for i in files:
page = os.path.join(write, i)
f = open(os.path.join(pages, i), 'r')
tmp = ""
for line in f.readlines():
line = line.rstrip()
structure = open(os.path.join(publish, line))
clean = structure.read()
tmp = tmp + clean.rstrip()
txt = textile(tmp) + ''
t = Template(txt)
s = t.safe_substitute(title='Web-siter: %s' % i[:-5])
output = open(page, 'w')
output.write('')
output.write(s)
except:
pass

if __name__ == '__main__':
main(sys.argv[1:])
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] xmlrpc server

2005-03-23 Thread Luis N
Hi,

I've been exploring xmlrpc implementations, and am somewhat confused
as to what I should use. I've spent the most time poking at Twisted,
which took me a while to figure out the basics of, and have spent a
moment or two exploring py-xmlrpc as well as SimpleXMLRPCServer in the
standard library. My observations are that:

Twisted fully loaded with xmlrpc, database access using adbapi, and
virtual hosts to proxy behind apache runs at almost 20mb of memory.
This seems a lot, but Twisted also offers a great deal more such as
web-templating with Nevow, if necessary.

py-xmlrpc uses a scant 4mb of memory, does only one thing, and does it
well, serve xmlrpc requests. It appears significantly faster than
Twisted.

SimpleXMLRPCServer, as a CGI solution, appears acceptable, given that
it be run from FastCGI or mod_python to give it that extra boost.

What would you suggest?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to setup gnu.py

2005-04-01 Thread Luis N
I grabbed this from the docs:

Gnuplot.py uses Python distutils and can be installed by untarring the
package, changing into the top-level directory, and typing "python
setup.py install". The Gnuplot.py package is pure Python--no
compilation is necessary.


On Mar 30, 2005 11:13 PM, jrlen balane <[EMAIL PROTECTED]> wrote:
> hi! i don't know if this is the proper forum but i'll ask anyway...
> 
> how am i going to setup gnu.py(or gnuplot.py) gnuplot with python???
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] slicing nested lists/dicts/tuples

2005-06-28 Thread Luis N
Hi,

>>> l
[{'last': 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'},
{'last': 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}]


This is how I imagine it: 

for i in l:
    for j in l[i]:
        for k in l[i][j]:
            print k.get('first')
    print k.get('last')

Is there a short and sweet way of doing this (that actually works). 

Luis.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slicing nested lists/dicts/tuples

2005-07-02 Thread Luis N
Hi,


Yes, sorry I haven't posted to the list in a while. I should have been
more specific. I'm writing a simple contact database, using metakit as
the backend. Thank you for pointing out that what I was trying to do
was easier than I believed.

Here's some code. 

db = metakit.storage('c:/addy.mk',1)
vw = db.getas('contacts[first:S,last:S,phone:S,email:S,notes:S]')

desc = ('first', 'last', 'phone', 'email', 'notes')

def listItems():
    l= []
    d = {}
    for r in range(len(vw)): 
    d = {'first':vw[r].first,
'last':vw[r].last, 'phone':vw[r].phone, 'email':vw[r].email,
'notes':vw[r].notes} 
    l.append(d)
    return l

At the moment I would like to generate the listItems dynamically, from
the desc variable, so new databases can be added without changing the
code.

I thought that if:

def listItems():
    l= []
    d = {}
    lt = len(desc)
    for r in range(len(vw)):
    for x in range(len(lt)):
    d[desc[x]] = exec("""'vw'+[r]+'.'+desc[x]""")
    l.append(d)
    return l

Whereby the vw metakit object behaves like a dictionary, and the exec statement isn't usable in the way I would wish for.

Luis N.

On 6/28/05, Brian van den Broek <[EMAIL PROTECTED]
> wrote:Luis N said unto the world upon 28/06/2005 15:25:> Hi,>

>>>>>l>> [{'last': 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}, {'last':> 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}]>>> This is how I imagine it:
>> for i in l:> for j in l[i]:> for k in l[i][j]:> print k.get('first')> print k.get('last')>> Is there a short and sweet way of doing this (that actually works).


>> Luis.Hi Luis,I'm not certain I see what you are wanting from your description.(You've got more nesting in your loops than in l.) But does this dowhat is wanted? >>> a_list = [ {'last': 'Bar', 'first': 'Foo'},
{'last': 'Bar', 'first': 'Foo'},{'last': 'Bar', 'first': 'Foo'},{'last':
'Bar', 'first': 'Foo'} ] >>> for a_dict in a_list: print a_dict['first'] print a_dict['last']FooBarFooBarFooBarFooBar >>>


If it does, why are you doing this? Is it to figure out how tomanipulate data structures with Python? If so, good. If you are tryingto do real work this way, there is surely a better way. Maybe if yousaid what you are trying to accomplish, someone could help you find a
good way to do it.Best,Brian vdB



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slicing nested lists/dicts/tuples

2005-07-02 Thread Luis N
On 7/2/05, Luis N <[EMAIL PROTECTED]> wrote:

Umm, sorry, I meant:
d[desc[x]] = exec("""'vw[%s].desc[%s]'""" % (r,x )) 




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Iterating over nested lists part2

2005-07-02 Thread Luis N
Okay,

This works great now:

def listItems():
    l= []
    d = {}
    for r in range(len(vw)): 
    for x in range(lt):
    ed = desc[x] 
    exec("d['%s']=vw[%d].%s" % (ed,r,ed))
    l.append(d)
    print l

But, it multiplies all of the records from vw by 5. How can I have:

for each record in the database:
    for each column in the record:
    do stuff.

Without multiplying the result i.e len(vw) * lt

Thanks.

Luis N.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Iterating over nested lists part2

2005-07-03 Thread Luis N
On 7/2/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
Luis N wrote:> def listItems():> l= []> d = {}> for r in range(len(vw)):> for x in range(lt):> ed = desc[x]> exec("d['%s']=vw[%d].%s" % (ed,r,ed))
> l.append(d)> print lIf
I understand correctly, you want to take all the rows of the view and
turn them into dicts, and build a list of all the dicts. If so, the
code above is way too complex.First, you can iterate over a list such as vw directly, you don't have to iterate the indices. Instead offor r in range(len(vw)):  do something with vw[r]you just say
for vwitem in vw:  do something with vwNext,
instead of exec you should use getattr(). To put the value into d you
don't need either; you can assign to d[ed] directly. To get the 'ed'
attribute from vwitem, use getattr(vwitem, ed).I also moved the assignment to d inside the loop so you start each row with a fresh dictionary. Here is the result:def listItems():l= []for vwitem in vw:
d = {}for ed in desc:d[ed] = getattr(vwitem, ed)l.append(d)print lKent

That's beautiful. I'm really grokking getattr, and I notice that it has
some close relations in the family of built-in functions.

Luis N.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] OT, Tcl & Python

2005-07-16 Thread Luis N
Hi,

I was wondering if someone knowledgeable of both Tcl and Python could
suggest whether it would be a good or a bad idea to write a Python/Tk
application, with the motive to rewrite the application in Tcl/Tk once
completed. My reason for considering this route is that I have never
written a single line of Tcl code nor coded a Tk application in the
past. My motivation is the greater ease of deployment across systems
that Tcl seems to offer, with Starkits and Starpacks,
http://www.equi4.com/starkit.html Tcl also appears useful to learn, for
writing scripts in tclsh, etc.  

I've experimented with py2exe in the past, which seems fine for
Windows, although I have never tried py2app, and this approach seems
cumbersome. A typical GUI app is approximately 5 MB in python,
distributed as a collection of files in a folder, whereas a Tcl
Starpack is a compact 1 MB, distributed as a single file executable. 

Sincerely,


Luis 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT, Tcl & Python

2005-07-19 Thread Luis N
On 7/16/05, Alan G <[EMAIL PROTECTED]> wrote:
>
I was wondering if someone knowledgeable of both Tcl and Python could
suggest whether it would   > be a good or a bad idea to
write a Python/Tk application, with the motive to rewrite the
application in > Tcl/TkOooh that's a tough one, it would depend on the program.Python is a very different language to Tcl and you would needto write the code in a Tcl style - don't use an OOP style for
the GUI for example. In fact I'd avoid OOP all together sinceTcl OOP is significantly different to Python OOP and not evenpart of standard Tcl.
 ...
You might like to take a quick run through the basics of my oldPython tutor which used Tcl as a comparison to Python. Its far
from comprehensive but would give a fairly good Python viewof Tcl.http://www.freenetpages.co.uk/hp/alan.gauld/oldtutor/index.htm
HTH,Alan GAuthor of the Learn to Program web tutorhttp://www.freenetpages.co.uk/hp/alan.gauld
Thanks, this is a really good point. I've been examining incr Tcl with
interest, but to learn Tcl/Tk by porting code from Python, its probably
best to avoid incr Tcl/incr Widgets at first.



Your tutor is really great, I've skimmed through it a bit, and will give it a more thorough read shortly.



Thanks!



Luis N 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] globals and map()

2005-07-19 Thread Luis N
I'd appreciate some comments on my use of globals and the map function.
The idea here is that (simple) Metakit database definitions can be
loaded dynamically from another Metakit database detifintion. (Yes this
would likely be easier with a SQL database, don't ask!) Nasty code
ahead: 

import metakit
import marshal

db = metakit.storage('addy.mk',1)
dbs = db.getas('dbs[db:S,marshal:B]')

def li(i):
    i = i[:-2]
    return i

def selectDB(f):
    if f.has_key('db'):
    d = []
    d['db'] = f.get('db').value
    id = dbs.find(d)
    if id != -1:
    global desc, vw, primaryKey
    desc
=
marshal.loads(dbs[id].marshal)  

    vw = db.getas('%s%s' % (dbs[id].db,desc))
    desc = map(li,desc) 
   
primaryKey =
desc[0]

   
return desc, vw, primaryKey   
    else:
   
error(-1)   

    else:
    error(select=None)  
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] globals and map()

2005-07-19 Thread Luis N
On 7/19/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
Luis N wrote:> I'd appreciate some comments on my use of globals and the map function.>> import metakit> import marshal>> db = metakit.storage('addy.mk
 <http://addy.mk>',1)> dbs = db.getas('dbs[db:S,marshal:B]')>> def li(i):> i = i[:-2]> return i>> def selectDB(f):> if 
f.has_key('db'):> d = []> d['db'] = f.get('db').valueThe above line is not valid Python; list indices must be integers
> id = dbs.find(d)
> if id != -1:> global desc, vw, primaryKey> desc = 
marshal.loads(dbs[id].marshal)> vw = db.getas('%s%s' % (dbs[id].db,desc))> desc = map(li,desc)This
use of map seems fine to me. You could also write it as a list
comprehension which is more mainstream Python idiom and maybe more
readable in this case as it is self-contained:  desc = [ i[:-2] for i in desc ]> primaryKey = desc[0]> return desc, vw, primaryKeyI
don't see the need for the global declaration; desc, vw, primaryKey are
all assigned within this function and returned to the caller.Kent



My blooper, should be d={} 

In this case consider desc, vw, and primaryKey to be of the same
importance as dbs, other functions must access them in a way that
renders their being local impossible, unless the logic where to be
encapsulated in a class, which didn't seem necessary.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] hello

2005-07-21 Thread Luis N
On 7/21/05, dina lenning <[EMAIL PROTECTED]> wrote:

YES...heres my problem  I am a university student..will be a teacher in 2 years hopefully..andhave taken a first year computing course that said it required NO PRIORknowledge, but i am having great difficulty. The students (71 of them)
are all complaining, including myself , as we all find it too hard.Anyway..i am having a heck of a time, but can not fail becasue i am onstudent loans. I am looking for help for this assignment:

http://www.cs.sfu.ca/CC/165/popowich/assign-1/assign4
Damn school, making things to hard for students! As a fellow SFU student, I can sympathize. 

But geez, I wish I'd known this course existed, it would have been an
easy A. Graduating this fall though, and what does a business major
really need to use a computer for anyway ;-)

Luis.
  
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] String slicing from tuple list

2005-07-21 Thread Luis N
On 21 Jul 2005 20:39:36 +0100, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
Hi,I have a list of tuples like this:[(1423, 2637),(6457, 8345),(9086, 10100),(12304, 15666)]
Each tuple references coordinates of a big long string and they are in the'right' order, i.e. earliest coordinate first within each tuple, andeearliest tuple first in the list. What I want to do is use this list of
coordinates to retrieve the parts of the string *between* each tuple. So inmy example I would want the slices [2367:6457], [8345:9086] and[10100:12304]. Hope this is clear.I'm coming up short of ideas of how to achieve this. I guess a for loop,
but I'm not sure how I can index *the next item* in the list, if that makessense, or perhaps there is another way.Any help, as ever, appreciated.Chris
Not sure if I follow you, seems like computational biology or something to me, but my quick (and dirty) solution:

   l = [(1423, 2637),(6457, 8345),(9086, 10100),(12304, 15666)]
for x in range(len(l)-1):

    l[x][1], l[x+1][0]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How do I go about this?

2005-07-27 Thread Luis N
On 7/27/05, Nathan Pinno <[EMAIL PROTECTED]> wrote:







Hi all,
 
How do I go about the following: I want to write a program that will print 
two lists one after another, then show all the available possibilities for 
matches e.g a0 and x0.
 
Here is what I have so far:
 
lista = [x0, x1, x2, x3]listb = [a0, a1, a2, a3]print 
listaprint listb
Thanks for the help,
Nathan Pinno

Hi,

Could you give some additional information as to what you intend to do?
If you are strictly matching, by position within the lists, such that
you would print the list elements only if: 

for x in range(min(len(lista),len(listb))):
    a = lista[x]
    b = listb[x]
    if a == b:
    print a, b

that is easy, however, if you want to match more complex patterns, or
wish to match list elements not in the same position then the
complexity of the task increases.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How do I go about this?

2005-07-27 Thread Luis N
On 7/27/05, Luis N <[EMAIL PROTECTED]> wrote:
On 7/27/05, Nathan Pinno <[EMAIL PROTECTED]
> wrote:








Hi all,
 
How do I go about the following: I want to write a program that will print 
two lists one after another, then show all the available possibilities for 
matches e.g a0 and x0.
 
Here is what I have so far:
 
lista = [x0, x1, x2, x3]listb = [a0, a1, a2, a3]print 
listaprint listb
Thanks for the help,
Nathan Pinno

Hi,

Could you give some additional information as to what you intend to do?
If you are strictly matching, by position within the lists, such that
you would print the list elements only if: 

for x in range(min(len(lista),len(listb))):
    a = lista[x]
    b = listb[x]
    if a[1] == b[1]:
    print a, b

that is easy, however, if you want to match more complex patterns, or
wish to match list elements not in the same position then the
complexity of the task increases.


Woops, I forgot the a[1], b[1]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] single executable

2005-07-31 Thread Luis N
On 7/31/05, Jorge Louis de Castro <[EMAIL PROTECTED]> wrote:
Hi,Thanks for your reply. I have been googling this issue and found thisarticle:http://starship.python.net/crew/theller/moin.cgi/SingleFileExecutable
that seems to indicate what I want is possible and it is available. 
Hi,

I looked at this, and took the time to try out the approach some time ago, you should be aware:

 The startup time of a wxPython app with lzma compression becomes very
long (1+ minute) on a machinne with 64MB RAM and a Pentium 200MHz, but
it's usable on faster machines that are common today ;-) 

The startup time is rather long, and this sould be considered as a serious drawback of this approach. 

Luis.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Web Browser in Python

2005-08-03 Thread Luis N
On 8/3/05, Shitiz Bansal <[EMAIL PROTECTED]> wrote:
> Hi, 
> I need to program a web browser in python.I dont have any idea of how to
> start, what i do have is time and willingness to learn.Could anyone direct
> me to some suitable reference? 
> Shitiz
> 

How about Grail http://grail.sourceforge.net/ ?

Luis.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Zope/Python web devel

2005-08-03 Thread Luis N
On 8/3/05, Jay Loden <[EMAIL PROTECTED]> wrote:
> I've been considering some web projects recently, but I have some concerns
> about selecting the tools I plan to use. I like Python, and I was immediately
> thinking of using Zope to build on.
> 
> However, I am concerned about performance, resource usage, and scalability.
> Does anyone here have any experience with Zope or any other application
> frameworks like CherryPy used in a large/enterprise environment? Is Zope
> overly memory hungry or slow? If performance is a key point, am I better off
> growing my own solution from the ground up?
> 
> Second, and more specific to Python itself - does anyone here have first hand
> knowledge of how Python compares with other solutions for server side web
> development? I'm specifically interested in comparisons to PHP, but Ruby,
> Perl, Java, C/C++ and Lisp, etc. observations would be welcome. Basically,
> I'm trying to get a feel for what kind of performance and resource usage I'd
> see out of Python versus other options. I realize this is heavily dependent
> on what exactly I end up doing, but just as a general observation, I'd like
> to know what others have experienced. I know that some large web applications
> are built on Python (Yahoo Mail, Google), but there's certainly less being
> done in Python on the web than in Perl or PHP. I just want to make sure this
> isn't because of Python disadvantages as opposed to simple market share.
> 
> All responses are welcome. If anyone has links to some benchmarking studies
> comparing the two for web development I'd be grateful for those as well.
> 
> -Jay

I don't have any particular experience with the various web
frameworks, but have experimented with most of them. Benchmarks are
more or less useless in this arena (it depends on what you are doing,
and how you intend to do it), and as they say there exists three kinds
of lies: lies, damn lies, and statistics!

Zope2.x is a bit of a bear IMO, but has a great number of packages to
use. The most compelling reasons to use Zope2 might be Plone or Silva.
I didn't pay much attention to CPU usage (usually 0 anyway, unless a
request is firing), but ram for Zope2 from my VPS on a FreeBSD box,
basic functionality, no additional packages, was approximately 24mb;
with Silva, 30mb; and with Plone+Psyco, 50mb. This is just the
beginning of course.

If you want a community site, use Plone, if you want to grok Zope use
Silva. Zope scales http://www.enfoldsystems.com/About/News/oxfam

Zope3 is interesting, but is fairly fresh. Ram usage tends towards
30mb with no additional packages.

Twisted is an excellent framework, with the downside that your code
becomes somewhat tied to Twisted (although this is true with any
framework), and single thread methodology. Nevow+Livepage looks
interesting, but I've never really experimented. Livepage seems to
fail if Twisted is proxied by another server, such as Apache. Ram
usage begins at 10mb, with a fully loaded site, including database
access via an adapter such as pgasync, requiring about 20mb. The most
compelling feature of Twisted is its breadth of protocols i.e. http
server, with xmlrpc and soap, in almost 0 lines of code (provided you
understand the libraries :^)

CherryPy2 is the most interesting in my opinion, the builtin server
tends towards 16mb of ram out of the box. Your code is pure python,
without requiring you to learn many cherrpyism's, which also means
your code will be more portable, say if you wished to create a tk/wx
gui front, in addition to the web. I beleive that the builtin cherry
server is to be depracated in some future release, in favor of WSGI.

I have been writing a rather long CGI, and am intending to port the
code to cherrypy. Not certain about cherrypy's enterprise
applicability, and starting/stopping the server when your code changes
can be annoying, however, it seems to work...

As to the rest of your question, coffee's waiting, and my fingers are tired...

You may get a greater response on the comp.lang.python newsgroup.

Luis.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [Metakit] Mk4py

2005-08-04 Thread Luis N
On 8/4/05, Brian Kelley <[EMAIL PROTECTED]> wrote:
> Yeah the spaces kill me as well sometimes, and then I think that the
> spaces are okay sometimes.
> 
> The real issue is that a metakit column name can include any printable
> character except a comma ",".
> 
> So, now you know :)
> 
> Here is another gotcha for you.  Never, ever delete a column and then
> add a column with the same name and a different type.  This will drive
> you bananas, I guarantee.
> 
> To safely do this, delete the column, write out the db to a new file.
> delete the database, repoen it and then add the new column.
> 
> At some point I had an enhanced python metakit tutorial, but I just
> noticed that it was gone.  I'll dig it up and repost it on my new web
> site.
> 
> Brian


Thanks for the warning, I had downloaded your tutorial in
http://www.equi4.com/pipermail/metakit/2003-March/001091.html , which
helped me get started, and is still relevant as I better understand
metakit.

Luis.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a qucker method than the following?

2005-08-05 Thread Luis N
On 8/5/05, Nathan Pinno <[EMAIL PROTECTED]> wrote:
>  
> Hi all, 
>   
> Is there a quicker method than the following? 
>   
> import random
> numbers = [0,1,2,3,4,5,6,7,8,9,10,11,12]
> cards =
> ["Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"]
> hand = {numbers:cards} 
>   

hand is invalid syntax, list objects are unhashable. deal() is also
invalid syntax, and will throw a type error. Fixing these might show
you a way to do things quicker. List comprehensions might be useful to
you in this context.

Luis.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Assistance!

2005-08-07 Thread Luis N
On 8/7/05, gordnjen <[EMAIL PROTECTED]> wrote:
> 
> I am now stuck again. I am at my wit's end. The course I am taking is a
> supposed "beginners" course. It is a distance education class, and our
> textbook does NOT contain the information required to do all of the
> assignments (perhaps it was designed for people with more experience and/or
> knowledge?). Anyways, our latest assignment is that we have to create a
> working chequebook (view here:
> http://cmpt165.cs.sfu.ca/~ggbaker/examples/chequebook.html)
> 
> This is what I have so far (see attached).
> 
> I am so completely lost.
> 
> Our textbook does not tell us how to implement a password security system on
> a website, or how to store data.
> 
> The project is already over a week late, and I feel absolutely hopeless
> about it.
> 
> Could you possibly give me some pointers on this? Please, please please?
> 
> Thank you in advance,
> 
> Jennine Gates
> 

Hi Jennine,

To complete this assignment you will be writing a CGI. From the
website it appears that you have not had to write one before that used
form data. To use form data with python, you should use the cgi
module. You can examine the documentation for this module by pressing
F1 while within IDLE, and entering the module list.

Here's a simple example:

#!/usr/LOCAL/bin/python

print "Content-type: text/html\n\n"

import cgi

def main(form):
if form.has_key("Name"):
print "Name: %s" % form["Name"].value
else:
print """http://cgi.sfu.ca/~rbnewby/cgi-bin/example.cgi"; method="get">
 
 
 """

if __name__ == "__main__":
main(cgi.FieldStorage())


A working example is viewable at: 

http://cgi.sfu.ca/~rbnewby/cgi-bin/example.cgi


Depending upon the requirements of the assignment you may be able to
password protect the script with htauth, details here:

http://www.sfu.ca/acs/sfuwebhelp/htaccess.htm

Cheers,

Luis
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with modulus.

2007-11-27 Thread Luis N
I'd like the below to be a single line if possible.

hours = metrics.totaltime/360
minutes = (metrics.totaltime - 360*hours)/6
seconds = (metrics.totaltime - 360*hours - 6*minutes)/1000

Would it be possible to simplify this with a generator expression e.g.

total_time = tuple((...))
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Still Can't Find Timed While Loops

2007-12-07 Thread Luis N
I can't recall what your initial project was. I think it was a text
adventure. I imagine that you have bigger ideas regarding timers then
your current code suggests. Maybe you should investigate a time aware
long-running process. Twisted Python is such a beast.

While I can't recommend it's use as it's probably over your head and
certainly over mine, there is some code out there for a text adventure
using Twisted Python. I think the codebase is called Twisted Reality
now.

Luis
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Versions

2007-12-12 Thread Luis N
On Dec 13, 2007 3:38 PM, earlylight publishing
<[EMAIL PROTECTED]> wrote:
> Do people really write whole applications just using the shell?
>
The shell isn't intended for writing whole applications. However, it's
invaluable for testing. For writing whole applications I'd recommend
The One True Editor with the external python-mode.

I use Aquamacs on a Macintosh. If you are on windows than consider Gnu Emacs.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Introspect function or class' required arguments

2007-12-13 Thread Luis N
Is there a way to introspect a function or class' required arguments,
particularly keyword arguments?

I can easily use a dictionary since it is my own function that I wish
to introspect. I haven't tested the below code yet, but e.g.

obj = getattr(self, 'obj')()
preprocessors = {'Card':[{'obj_attr':'mastery',
  'call':mastery,
  'args_dict':['front', 'back']}
 ]
 }
obj_preprocessors = preprocessors.get(obj.__name__, None)
if obj_preprocessors:
for preprocessor in obj_preprocessors:
function_name = preprocessor['call'].__name__
args_dict = {}
for arg in preprocessor['args_dict']:
if self.query_dict.has_key(arg):
args_dict[preprocessor[arg]] = self.query_dict.get(arg)
else:
self.error = 'Required argument %s omitted for
function %s' % (arg, function_name)
break
if not hasattr(self, error):
try:
setattr(obj, preprocessor['obj_attr'],
preprocessor['call'](args_dict))
except:
self.error = 'Preprocessor %s failed.' % function_name
else:
break
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Introspect function or class' required arguments

2007-12-13 Thread Luis N
On Dec 14, 2007 12:08 PM, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Luis N wrote:
> > Is there a way to introspect a function or class' required arguments,
> > particularly keyword arguments?
>
> See inspect.getargspec() and formatargspec().
> Look at the source if you want details of where the info is stored.

Thanks that's exactly what I was looking for :-)

> > I can easily use a dictionary since it is my own function that I wish
> > to introspect. I haven't tested the below code yet, but e.g.
>
> I don't understand what you are trying to do here.

The code I posted before is to be part of a dispatcher for a django
application. Objects are routed to 'add', 'edit', or 'delete' methods.
Data for some of the fields/attributes of my django models objects
needs to be preprocessed.

However, as the add/edit/delete methods are used for multiple objects
I need to determine dynamically if a particular preprocessor needs to
be called.

> Kent
>

Thanks again,


Luis
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Nested, line by line, file reading

2007-12-16 Thread Luis N
On Dec 16, 2007 10:17 PM, jon vs. python <[EMAIL PROTECTED]> wrote:
> Hi everyone,
> I have a file with this content:
>
> "1
> 1
> 1
> 1
> 1
> 1
> 1
> 2
> 1
> 1"
>
> I wanted a little script that would print the line containing "2" and every
> line containing "1" after it. I've tried this:
>
> >>> def p():
> f = file("prueba.txt",'r')
> for startline in f.read():
> if startline.find("2") != -1:
> print startline
> for endline in f.read():
> if endline.find("1") != -1:
> print endline
> break
> f.close()
>
>
> >>> p()
> 2
>
> I found a way for doing it.
>
> But still I don't really understand why I don't get two "1" lines printed.
> It seems that every line is read in "for startline f.read()" so "for endline
> in f.read()" will start reading but find no data, am I right?
>
> Thanks, Jon.
>


Try something like:

show_ones = False

for line in f.read():
if line.find(2) != -1 or show_ones == True:
   print line
   show_ones = True
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python and xml

2005-08-13 Thread Luis N
On 8/13/05, David Holland <[EMAIL PROTECTED]> wrote:
> What is a good way of using xml and python ?

ElementTree? http://effbot.org/zone/element-index.htm

or, lxml http://codespeak.net/lxml/

Luis.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] web gallery

2005-08-15 Thread Luis N
On 8/15/05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hi All,
>
> I'd like to write some web gallery software from scratch for my girlfriend. 
> I've looked at the > PIL (python imaging library) and I'm using it to 
> generate thumbnails from given images.
> Something else i'd like to get done now though, is building an index of 
> images.
>
> Are there any libs suited for this? basically I want an text index of images, 
> which 
> contains the main image name, the thumbnail name, and a description. a new 
> image can > be added to the index either by adding it via ftp, or through an 
> html upload form with the  > comment in the form.
> 
> So basically, i'm after advice on indexes.
> 
> thanks for reading,
> Paul
> 

You may find this useful: http://freshmeat.net/projects/python-exif/

I think you need to write a script, cgi or otherwise, which will read
a particular directory to create your index, including:

imagedir = 'path'

import os 
for item in os.listdir(imagedir):
#grab some info about the image.


Luis.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python hosting again

2005-08-15 Thread Luis N
On 8/11/05, Jorge Louis De Castro <[EMAIL PROTECTED]> wrote:
> Hello, 
>   
> I'm interested in writing with my own Python implementation of a Jabber IM
> server and client. 
> Anyone knows where I could host my Python Jabber IM server for a reasonable
> monlthy fee? It doesn't need to be a top-notch place since my goal is to
> test something else, not the scalability of the application. 
>   
> chrs 
> j. 

I think you will find http://hub.org to be an excellent host. You get
a VPS for about $12/month They are the host of the
http://postgresql.org project

Luis.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Replacement for 'Find' Module

2005-08-15 Thread Luis N
On 8/15/05, Simon Gerber <[EMAIL PROTECTED]> wrote:
> You could probably do something like this... (Note: This example is
> for Linux - but you can adapt it fairly easily to Windows.)
> 
> 
> # E.g. Find every .inf file on a CD-ROM.
> path = '/cdrom'
> # 'E:\\' or whatever for Windows
> inf_list = []
> for root, dirs, files in os.walk(path):
> for current_file in files:
> if '.inf' in current_file:

if current_file.endswith('.inf'): #or current_file[:-4] might be more
appropriate, just my 2c

I wrote this in a script for limited globbing:

if cd:
toss = os.path.join(trashcan, os.path.split(i)[1])
pwd = os.getcwd()
else:
toss = os.path.join(trashcan, i)

if toss[-1] == '*': 
crumple = []
if cd:
l = os.listdir(cd)
for i in l:
crumple.append(os.path.join(cd, i))
else:
crumple = os.listdir('.')
for i in crumple:
if i.startswith(toss[:-1]):
junk.append(i)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] LiveWires problems

2005-08-16 Thread Luis N
On 8/15/05, ZIYAD A. M. AL-BATLY <[EMAIL PROTECTED]> wrote:
> On Mon, 2005-08-15 at 11:52 -0400, Michael Murphy wrote:
> > Hi all
> >
> > I'm having problems with installing LiveWire for python for Linux
> > (Linspire 5.0 to be exact) and I'm having trouble compiling setup.py.
> > Heres the results:
> >
> > running install
> > running build
> > running build_py
> > running install_lib
> > creating /usr/lib/python2.3/site-packages/livewires
> > error: could not create '/usr/lib/python2.3/site-packages/livewires':
> > Permission denied
> >
> > I'm new at this but I'm sure this is an easy fix but I can't figure it
> > out, any help is appreciated.

Consider typing:

python setup.py install home=$HOME 

instead of,

python setup.py install

You will then install into ~/lib/python2.3/livewires if this location
is acceptable to livewires.

Luis.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Remove a number from a string

2005-08-23 Thread Luis N
On 8/23/05, Shitiz Bansal <[EMAIL PROTECTED]> wrote:
> Hi, 
> Suppose i have a string '347 liverpool street'. 
> I want to remove all the numbers coming at the starting of the string. 
> I can think of a few ways but whats the cleanest way to do it? 
>   
> Shitiz
> 

I believe this question to be rather variable in its answer. If all
your strings are of the form "### word word", then you could safetly
use 'split', as in:

>>> s = '347 liverpool street'

def splitter(s):
l = s.split()
try:
i = int(l[0])
return i
except ValueError:
print "String segment not a number"

>>> splitter(s)
347

But, if your string is also of the form "347-10 liverpool street",
then your problem is more complex.

Luis.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Counting help

2005-08-23 Thread Luis N
On 8/23/05, Scott Oertel <[EMAIL PROTECTED]> wrote:
> I have extracted a list of names, i.e.
> 
> "Joe Smith"
> "Joe Smith"
> "Jack Smith"
> "Sam Love"
> "Joe Smith"
> 
> I need to be able to count the occurances of these names and I really
> don't have any idea where to begin.
> 
> Any ideas?  excuse me this is my first post to this list, I hope I
> included enough information.
> 
> 
> -Scott Oertel

Ideally, you would put your names into a list or dictionary to make
working with them easier. If all you're trying to do is count them
(and your list of names is long), you might consider a dictionary
which you would use like so:

#This is just the first thing I considered.

l = ['a list of names']

d = {}

for name in namelist:
if d.has_key(name):
x = d.get(name)
d[name] = x + 1
else:
d[name] = 1  

Luis
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Website Retrieval Program

2005-08-24 Thread Luis N
On 8/24/05, Daniel Watkins <[EMAIL PROTECTED]> wrote:
> I'm currently trying to write a script that will get all the files
> necessary for a webpage to display correctly, followed by all the
> intra-site pages and such forth, in order to try and retrieve one of the
> many sites I have got jumbled up on my webspace. After starting the
> writing, someone introduced me to wget, but I'm continuing this because
> it seems like fun (and that statement is the first step on a slippery
> slope :P).
> 
> My script thus far reads:
> """
> import re
> import urllib
> 
> source = urllib.urlopen("http://www.aehof.org.uk/real_index2.html";)
> next = re.findall('src=".*html"',source.read())
> print next
> """
> 
> This returns the following:
> "['src="nothing_left.html"', 'src="testindex.html"',
> 'src="nothing_right.html"']"
> 
> This is a good start (and it took me long enough! :P), but, ideally, the
> re would strip out the 'src=' as well. Does anybody with more re-fu than
> me know how I could do that?
> 
> Incidentally, feel free to use that page as an example. In addition, I
> am aware that this will need to be adjusted and expanded later on, but
> it's a start.
> 
> Thanks in advance,
> Dan
> 

You may wish to have a look at the Beautiful Soup module,
http://www.crummy.com/software/BeautifulSoup/

Luis.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python2.3.4, PySqlite2 and Solaris

2005-09-01 Thread Luis N
Hi,

After fighting with installing pysqlite2, (although you require the
.tar.gz for a *Nix build, the header file required, sqlite3.h, was
actually in the source .zip supplied for windows users sans a unix
build environment)

Anyway, I have pysqlite2, but:

Python 2.3.4 (#1, Aug 23 2004, 13:59:34)
[GCC 3.2.3] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> from pysqlite2 import dbapi2 as sqlite
Traceback (most recent call last):
  File "", line 1, in ?
  File "/home/rbnewby/lib/python/pysqlite2/dbapi2.py", line 32, in ?
from pysqlite2._sqlite import *
ImportError: ld.so.1: python: fatal: relocation error: file
/home/NaN/lib/python/pysqlite2/_sqlite.so: symbol sqlite3_libversion:
referenced symbol not found

However,

bash-2.05$ ldd -s _sqlite.so

   find object=libsqlite.so.0; required by ./_sqlite.so
search path=/usr/openwin/lib  (LD_LIBRARY_PATH)
trying path=/usr/openwin/lib/libsqlite.so.0
search path=/home/NaN/lib  (RPATH from file ./_sqlite.so)
trying path=/home/NaN/lib/libsqlite.so.0
libsqlite.so.0 =>/home/NaN/lib/libsqlite.so.0

I'm a little confused why a python process wouldn't also be able to
find the required library.

Any insights about what's happening would be appreciated.

Luis
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python2.3.4, PySqlite2 and Solaris

2005-09-02 Thread Luis N
On 9/1/05, Luis N <[EMAIL PROTECTED]> wrote:
> Hi,
> 
> After fighting with installing pysqlite2

Apologizes, I started over. It went much better the second time.

bash-2.05$ test-pysqlite
..
--
Ran 142 tests in 0.672s

> 
> Luis
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Boa-Constructor

2005-09-13 Thread Luis N
On 9/12/05, Terry Kemmerer <[EMAIL PROTECTED]> wrote:
>  Hey Guys,
>  
>  I am trying to pick an IDE, and it seems to me that Boa-Constructor has 
> great potential.


Did you check Boa out of CVS? It tends not to have an intermittent
schedule of releases.

Luis
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Venom / Python23.dll missing

2005-09-13 Thread Luis N
On 9/11/05, Damien Gouteux <[EMAIL PROTECTED]> wrote:
> Hi all.
> I try to run Venom, a Python binding for the Irrlicht engine. But I need 
> python23.dll. 

Download a game from pygame.org

Luis.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Boa-Constructor

2005-09-15 Thread Luis N
 >  Luis,
>  
>  I was actually asking how usable Boa-Constructor is right now for project
> purposes, since I had "heard" it was kind of unstable and crashes a lot. Is
> that your experience with Boa-Constructor? Or was the information I found
> misleading?
>  
>  Thanks,
>  Terry 

I found Boa-constructor interesting/useful. Since this was sometime
ago, and wxPython has since gained a few version numbers, I can't
comment on its current stability. It was fine when I tried it, little
bloated though.

I'm a committed emacs user now.

Luis
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Any good Glade and python tutorials?

2005-10-18 Thread Luis N
You might want to search for how it fits together with twisted's reactor

http://www.google.com/search?q=twisted+glade+reactor

Luis.

On 10/15/05, Adam <[EMAIL PROTECTED]> wrote:
> I'm making a Twisted app that needs a client side GUI and GTK seems like the
> best way to go about this. Can anybody point me in the direction of any
> decent tutorials on how to use Glade with python and pyGTK.
>  Thanks.
>  Adam.
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor