Re: MySQLdb syntax issues - HELP

2007-12-16 Thread wes
test script i made that does everything the same
> except substituting the strings within my query. Ive been stuck on this all
> week and have read numerous tutorials, the DB-API specification sheet, the
> MySQL manual, the MySQLdb documentation, and a few books... none of which
> seem to adress my problem since they are all only assigning variables to
> the table name OR the values of the query, not both. Please help me figure
> this out.

Luke,
It would be most helpful if you assigned the sql to
a string, printed the string, executed the string, and
posted the error message.

sql = "INSERT INTO %s (name, gender, job, level, str, dex, intel, cha, luc) 
VALUES \
  (%s, %s, %s, %s, %s, %s, %s, %s, %s) \
  " % (CharAccount, CharName, CharGender, CharJob, CharLevel, Strength,\
   Dexterity, Inteligence, Charm, Luck)

print "sql=",sql
cursor.execute(sql)

-then show the error message here

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


Re: problem with global var

2008-01-03 Thread wes
Bruno Ferreira wrote:
> Hi,
> 
> I wrote a very simple python program to generate a sorted list of
> lines from a squid access log file.
> 
> Here is a simplified version:
> 
> ##
> 1  logfile = open ("squid_access.log", "r")
> 2  topsquid = [["0", "0", "0", "0", "0", "0", "0"]]
> 3
> 4  def add_sorted (list):
 global topsquid
> 5 for i in range(50):
> 6  if int(list[4]) > int(topsquid[i][4]):
> 7  topsquid.insert(i,list)
> 8  break
> 8  # Max len = 50
> 10 if len(topsquid) > 50:
> 11 topsquid = topsquid[0:50]
> 12
> 13 while True:
> 14 logline = logfile.readline()
> 15 linefields = logline.split()
> 16
> 17 if logline != "":
> 18 add_sorted (linefields)
> 19 else:
> 20 break
> 21
> 22 for i in range (len(topsquid)):
> 23 print topsquid[i][4]
> 
> 
> When I execute the program _without_ the lines 10 and 11:
> 
> 10 if len(topsquid) > 50:
> 11 topsquid = topsquid[0:50]
> 
> it runs perfectly.
> 
> But if I execute the program _with_ those lines, this exception is thrown:
> 
> [EMAIL PROTECTED]:~$ python topsquid.py
> Traceback (most recent call last):
>   File "topsquid.py", line 20, in 
> add_sorted (linefields)
>   File "topsquid.py", line 6, in add_sorted
> if int(list[4]) > int(topsquid[i][4]):
> UnboundLocalError: local variable 'topsquid' referenced before assignment
> 
> 
> Note that now the error shown is not related with the lines 10 and 11,
> but wiht a line prior to them.
> 
> Any hints?
> 

Try line 4 add.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Genetic Algorithm

2008-01-28 Thread wes
Max,

 def GeneticNextGen(self):
 numsets   = len(self.WtSets)
 numwts= len(self.WtSets[0].Lis)

 self.WtSets.sort(CompByCurrentFitness)
 index_lis = []
 K = 100.0

 N= float(numwts)

 #if RISE(slope) is too high, concentration occurs too fast and
 #you lose many quickly

 RISE = -0.01*K
 RUN  = N - 1.0
 m= RISE/RUN
 for i in range( numsets ):
 x = float(i)
 numin = int(m * x + K)
 for k in range(numin):
 index_lis.append( i )

 new_wtset_list = WtSetListClass()

 while len(new_wtset_list.WtSets) < numsets:
 #split in a number of placeses
 splitPoints = []#empty list of 
places where dna's are crossed
 numSplitPoints = random.randint( 2, 4 ) #number of places 
to cross at(not to hot & not to cold)
 while len(splitPoints) < numSplitPoints:#get required num 
of points at random
 split_pt = random.randint( 0, numwts - 1 )
 if split_pt not in splitPoints:
 splitPoints.append(split_pt)

 i1 = random.choice( index_lis ) #get two old 
weight sets at random from a biased list
 while( 1 ):
 i2 = random.choice( index_lis )
 if i2 <> i1:
 break
 wts1 = self.WtSets[ i1 ]
 wts2 = self.WtSets[ i2 ]

 list1 = wts1.Lis[0:]#just size new 
weight sets
 list2 = wts1.Lis[0:]

 flip  = False   #copy into new 
weight sets from old alternating the
 for k in range(len(wts1.Lis)):  #  the source on 2 
to 4 flip points
 if k in splitPoints:
 flip = not flip

 if flip:
 list1[k] = wts2.Lis[k]
 list2[k] = wts1.Lis[k]
 else:
 list1[k] = wts1.Lis[k]
 list2[k] = wts2.Lis[k]

 split_pt1 = random.choice(splitPoints)  #capture a place 
to mutate at low probabilty

 x = random.randint( 0, 1000 ) #.1 % of time mutate at boundry
 if x == 5:
 list1[ split_pt1 ] = RandomFloat(LOWWT,HIGHWT)
 list2[ split_pt1 ] = RandomFloat(LOWWT,HIGHWT)

 wt = WtSetClass( list1 )
 wt.FoldParentFitnesses( wts1,wts2 )
 new_wtset_list.WtSets.append( wt )
 if len(new_wtset_list.WtSets) < numsets:
 wt = WtSetClass( list2 )
 wt.FoldParentFitnesses( wts1,wts2 )
 new_wtset_list.WtSets.append( wt )
 x = random.randint(0,1)
 if x == 5:
 new_wtset_list.RandomizeRandomWt() #0.01% of time made an entire 
new random wt
 self.WtSets = new_wtset_list.WtSets
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where can I find sample "beginner" programs to study?

2005-01-28 Thread wes weston
Todd_Calhoun wrote:
I'm trying to learn Python (and programming), and I'm wondering if there are 
any places where I can find small, simple programs to study.

Thanks. 


Todd,
   Have you been here:
http://www.python.org/doc/
and tried the tutorial or beginners guide?
The tutorial has all the pieces you use most
often.
wes
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where are list methods documented?

2005-02-01 Thread wes weston
Grant Edwards wrote:
I'm trying to figure out how to sort a list, and I've run into
a problem that that I have tripped over constantly for years:
where are the methods of basic types documented?  The only
thing I can find on a list's sort() method is in the tutorial
where it states:
   sort()
   Sort the items of the list, in place. 

Doesn't the list method would accept a callable to be used as a
comparison function?  Where is that sort of thing in the
documentation?  I've looking in the library reference, the
language reference, the global module index.
I have figured out I can do 


list.sort.__doc__
'L.sort(cmpfunc=None) -- stable sort *IN PLACE*; cmpfunc(x, y) -> -1, 0, 1'
Grant,
   For a quick, short doc string list: >>> help(list)
wes
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do you do arrays

2005-02-01 Thread wes weston
Thomas Bunce wrote:
I am new at Pyton and I am learning from book not classes
so please forgive my being slow
The below does not work I get an Error of  File 
"Matrix[index] = k
NameError: name 'iMatrix' is not defined"

while  index < majorlop1:
   index = index + 1
   k = random.choice(listvalues) + 1
   iMatrix[index] = k
The book statement of 
 array(typecode, initializer) does not make sence
to me how it henerates ore relaes to the org name 
for the array.

Thank You
 Tom
Thomas,
   You can do
>>> m = [4]
>>> m
[4]
wes
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do you do arrays

2005-02-01 Thread wes weston
Thomas,
   If you were allowed to do what you're doing, the
list first element would be getting skipped as "index"
is always > 0. The thing is, you don't want the "index"
var at all for adding to the list; just do jMatrix.append(k).
   You can iterate over the list with
for x in jMatrix:
   print x
   Is it basic that indexes from 1 vs. 0? 'just about
completely forgotten basic.
wes
Thomas Bunce wrote:
Tryed it and this is what I got (I did go to the web sight)
tom(h=500)$ /tmp/501/Cleanup\ At\ Startup/ptesting-128981347.87.py.command; exit
Input the maximu number of tvalue: 114
Traceback (most recent call last):
  File "/Users/tom/Desktop/ptesting.py", line 20, in ?
iMatrix[index] = k
IndexError: list assignment index out of range
logout
[Process completed]
The complete listing:
#!/usr/bin/python
import random
import sys
import array
#
### generates a list of numbers between 1 and target
### and uses 23 % of these values.
#
iMatrix = []
tvalue = input('Input the maximu number of tvalue: ')
majorlop1 = int tvalue * .23)
listvalues = range(tvalue)
sep = '- '
index = 0
while index < majorlop1:
   index = index + 1
   k = random.choice(listvalues) + 1
   iMatrix[index] = k
   
while index < majorlop1:
   print '- %s %s' % (iMatrix[index], sep)
#
###
#
I would like to set the size of the List/array independent 
of having to intialialize it prior to use. 
If it help I will say the bad works I am using OSX

   Thanks Tom
In article <[EMAIL PROTECTED]>,
"Kartic" <[EMAIL PROTECTED]> wrote:

Tom,
Before you use iMatrix[index], you have to tell python to use iMatrix
as an array. You will do that using iMatrix = [] *outside* the loop.
iMatrix = []
while index < majorlop1: # rest of the loop statements
Since you are new, please take a look at the Python tutorial to get you
started.
http://docs.python.org/tut/tut.html
Thanks,
-Kartic
--
http://mail.python.org/mailman/listinfo/python-list


Re: broke tkinter

2005-02-08 Thread wes weston
Philippe C. Martin wrote:
Hi,
I decided to clean my system and rebuild python from scratch.
I downloaded tk8.4.9, tcl8.4.9 and Python2-4.tar.bz2.
I installed tcl then tk using './configure --prefix=/usr'
tkcvs is now working OK
trying to compile python (configure = './configure --prefix=/usr', I get
this:
In file included
from /home/philippe/downloaded/Python-2.4/Modules/_tkinter.c:67:
/usr/include/tk.h:337: error: syntax error before "CONST84"
In file included from /usr/include/tk.h:1576,
from /home/philippe/downloaded/Python-2.4/Modules/_tkinter.c:67:
Any clue!
Regards,
Philippe

Phillipp,
   Might you be getting the wrong header file/tk version?
http://wiki.tcl.tk/3669  talks about it.
wes
--
http://mail.python.org/mailman/listinfo/python-list


Re: namespace collisions

2005-02-17 Thread wes weston
Will McGugan wrote:
Hi,
I'm accumulating a number of small functions, which I have sensibly put 
in a single file called 'util.py'. But it occurs to me that with such a 
generic name it could cause problems with other modules not written by 
myself. Whats the best way of handling this? If I put it in a common 
location in my Python path, should I call it willsutil.py?

TIA,
Will McGugan
Will,
  See  
http://www.boost.org/libs/python/doc/tutorial/doc/html/python/techniques.html
'about page 30 of google search. It gives an example
that should help.
wes
--
http://mail.python.org/mailman/listinfo/python-list


Re: String Replace Problem...

2005-02-28 Thread wes weston
[EMAIL PROTECTED] wrote:
Hello NG,
  probably this is a basic question, but I'm going crazy... I am unable
to find an answer. Suppose that I have a file (that I called "Errors.txt")
which contains these lines:
MULTIPLY
  'PERMX'  @PERMX1  1 34  1  20  1 6 /
  'PERMX'  @PERMX2  1 34  21 41  1 6 /
  'PERMX'  @PERMX3  1 34  1  20  7 14/
  'PERMX'  @PERMX4  1 34  21 41  7 14/
  'PERMX'  @PERMX5  1 34  1  20 15 26/
  'PERMX'  @PERMX6  1 34  21 41 15 26/
  'PERMX'  @PERMX7  1 34  1  20 27 28/
  'PERMX'  @PERMX8  1 34  21 41 27 28/
  'PERMX'  @PERMX9  1 34  1  20 29 34/
  'PERMX'  @PERMX10  1 34  21 41 29 34/
  'PERMX'  @PERMX11  1 34  1  20 35 42/
  'PERMX'  @PERMX12  1 34  21 41 35 42/
  'PERMX'  @PERMX13  1 34  1  20 43 53/
  'PERMX'  @PERMX14  1 34  21 41 43 53/
  'PERMX'  @PERMX15  1 34  1  20 54 61/
  'PERMX'  @PERMX16  1 34  21 41 54 61/
/
I would like to replace all the occurrencies of the "keywords" (beginning
with the @ (AT) symbol) with some floating point value. As an example, this
is what I do:
#  --- CODE BEGIN
import re
import string
# Set Some Dummy Parameter Values
parametervalues = range(1, 17)
# Open And Read The File With Keywords
fid = open("Errors.txt","rt")
onread = fid.read()
fid.close()
# Find All Keywords Starting with @ (AT)
regex = re.compile("[EMAIL PROTECTED]", re.IGNORECASE)
keywords = regex.findall(onread)
counter = 0
# Try To Replace The With Floats
for keys in keywords:
pars = parametervalues[counter]
onread = string.replace(onread, keys, str(float(pars)))
counter = counter + 1
# Write A New File With Replaced Values
fid = open("Errors_2.txt","wt")
fid.write(onread)
fid.close()
#  --- CODE END
Now, I you try to run this little script, you will see that for keywords
starting from "@PERMX10", the replaced values are WRONG. I don't know why,
Python replace only the "@PERMX1" leaving out the last char of the keyword
(that are 0, 1, 2, 3, 4, 5, 6 ). These values are left in the file and I
don't get the expected result.
Does anyone have an explanation? What am I doing wrong?
Thanks to you all for your help.
Andrea.
--
 Message for the recipient only, if received in error, please notify the
sender and read http://www.eni.it/disclaimer/

andrea,
   If you put in "keywords.reverse()" after getting
keywords, things may work better. Though not a good
fix, it illustrates part of the problem. If you replace
"@PERMX1" you also replace part of "@PERMX10".
   Wouldn't it be better to read the file as lines
instead of strings?
wes
--
http://mail.python.org/mailman/listinfo/python-list


Re: What's the cost of using hundreds of threads?

2005-03-01 Thread wes weston
Przemysław Różycki wrote:
Hello,
I have written some code, which creates many threads for each connection 
('main connection'). The purpose of this code is to balance the load 
between several connections ('pipes'). The number of spawned threads 
depends on how many pipes I create (= 2*n+2, where n is the number of 
pipes).

For good results I'll presumably share main connection's load between 10 
pipes - therefore 22 threads will be spawned. Now if about 50 
connections are forwarded the number of threads rises to thousand of 
threads (or several thousands if even more connections are established).

My questions are:
- What is the cost (in memory / CPU usage) of creating such amounts of 
threads?
- Is there any 'upper boundary' that limits the number of threads? (is 
it python / OS related)
- Is that the sign of 'clumsy programming' - i.e. Is creating so many 
threads a bad habit? (I must say that it simplified the solution of my 
problem very much).

Limiting the number of threads is possible, but would affect the 
independence of data flows. (ok I admit - creating tricky algorithm 
could perhaps gurantee concurrency without spawning so many threads - 
but it's the simplest solution to this problem :) ).
PR,
   I notice there's a resource module with a
getrusage(who) that looks like it would support
a test to get what you need.
wes
--
http://mail.python.org/mailman/listinfo/python-list


Re: MySQL problem

2005-03-17 Thread wes weston
Lad wrote:
I have the following
program( only insert a record)

import MySQLdb
conn = MySQLdb.connect (host = "localhost",user = "", passwd =
"",db="dilynamobily")
cursor = conn.cursor ()
cursor.execute("""CREATE TABLE produkt1 (
  id int(10) unsigned NOT NULL auto_increment,
  MyNumber varchar(30) NOT NULL default '',
  PRIMARY KEY  (id))
  """)
#MyValue=111
cursor.execute ("""INSERT INTO produkt1
(MyNumber)
VALUES(111)
""")
#
It works. But If I change the program like the following ( only use a
variable MyValue in INSERT statement it does not work.
##THIS DOES NOT WORK
import MySQLdb,re,string
conn = MySQLdb.connect (host = "localhost",user = "", passwd =
"",db="dilynamobily")
cursor = conn.cursor ()
cursor.execute("""CREATE TABLE produkt1 (
  id int(10) unsigned NOT NULL auto_increment,
  MyNumber varchar(30) NOT NULL default '',
  PRIMARY KEY  (id))
  """)
MyValue=111
cursor.execute ("""INSERT INTO produkt1
(MyNumber)
VALUES(MyValue)
""")
#
Program says
OperationalError: (1054, "Unknown column 'MyValue' in 'field list'")
Where is a problem. Thanks for help
Lad.
Lad,
  Try
str = "INSERT INTO produkt1 (MyNumber) VALUES(%d)" % (MyNumber)
cursor.execute(str)
wes
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple account program

2005-03-17 Thread wes weston
Igorati wrote:
Hello all, I am still needing some help on this code, I have gone a bit
further on it. Thank you for the help. I am trying to understand how to
make the file searchable and how I am to make the deposit and withdrawl
interact with the transaction class. 
I need to just search the file only for the deposits and withdrawls and
the amount in the account with a time stamp. Thank you for your
assistance.

class Account:
def __init__(self, initial):
 self.balance = initial
def deposit(self, amt):
 self.balance = self.balance + amt
def withdraw(self, amt):
 self.balance = self.balance - amt
def getbalance(self):
 return self.balance 

class Transactoin:
def transaction(self,

   
self.transaction = 
import time
time.asctime()
raw_input("Is this a deposit or withdrawl?")
if withdrawl:
elif 
raw_input("Please enter amount here.")
   
class Deposit(Transaction):
def deposit(self, amt):
self.balance = self.balance + amt
def getbalance(self):
return self.balance

class Withdrawl(Trasaction):
def withdrawl(self, amt):
self.balance = self.balance - amt
def getbalance(self):
return self.balance
import pickle
pickle.dump ((withdrawl), file ('account.pickle', 'w'))
pickle.dump ((deposit), file ('account.pickle', 'w'))

print "Your current account total is.", self.balance
Igorati,
   Suggestion. Write out what you want to do in
words such that all the things you want to do are
there as unambiguously clear as you can get it.
It will help your thinking on the problem, the
design, and the code; and help anyone trying to
help you.
   Why have transactions not associated with accounts?
All transactions are related to an account; have
a self.TransActList in Account.
   You have "amount" in both Withdrawl and Deposit
both derived from Transaction. If Transactions always
have an amount, why not put amount in the transactions
class? But we don't know.
wes
--
http://mail.python.org/mailman/listinfo/python-list


Re: MySQL problem

2005-03-18 Thread wes weston
Dennis Lee Bieber wrote:
On Thu, 17 Mar 2005 16:45:57 GMT, wes weston <[EMAIL PROTECTED]> declaimed
the following in comp.lang.python:

str = "INSERT INTO produkt1 (MyNumber) VALUES(%d)" % (MyNumber)
cursor.execute(str)
Think you meant "MyValue" for the second item... However...
Try neither, the recommended method is to let the execute() do
the formatting... That way /it/ can apply the needed quoting of
arguments based upon the type of the data.
cursor.execute("insert into produkt1 (MyNumber) values (%d)", (MyValue))
Dennis,
   Do you know if this has some efficiency advantage
or is it just an agreed upon custom.
wes
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question on sorting

2004-11-29 Thread wes weston
Lad wrote:
Hi,
I have a file of records of 4 fields each.
Each field is separated by a semicolon. That is
Filed1;Ffield2;Field3;Field4
But there may be also empty records such as

(only semicolons).
For sorting I used
#
lines = file('Config.txt').readlines()# a file I want to sort
lines.sort()
ff=open('ConfigSorted.txt','w')# sorted file
ff.writelines(lines)
ff.close()
###
It was sorted but empty records were first. I need them to be last(at
the end of the file). How can I do that?
Thanks for help
Lad
Lad,
   The sort call can have a function name as an arg. You
could do:
def mycompare(s1,s2):
#return -1 to put s1's at front; 1 to put s1's at back; 0 for a tie
#if s1=="" and s2<>"": return 1
lines.sort(mycompare)
wes
--
http://mail.python.org/mailman/listinfo/python-list


Re: Find index of item in list

2004-12-07 Thread wes weston
Sean Berry wrote:
Given
myList = ['cat', 'dog', 'mouse' ... 'bear']
what is the easiest way to find out what index 'dog' is at?

Sean,
>>> myList = ['cat', 'dog', 'mouse','bear']
>>> myList.index('dog')
1
>>>
wes
--
http://mail.python.org/mailman/listinfo/python-list


Re: A completely silly question

2004-12-17 Thread wes weston
Amir Dekel wrote:
Harlin Seritt wrote:
Simple, Simple, Simple:
Var = raw_input("Some prompting text here: ")
Frans Englich wrote:
 >
 > See sys.stdin
 >
What I need from the program is to wait for a single character input, 
something like while(getchar()) in C. All those Python modules don't 
make much sence to me...

Amir
Amir,
>>> import tkSimpleDialog
>>> ch = tkSimpleDialog.askstring("","ch?")
wes
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rotating arbitrary sets of elements within a list

2005-04-08 Thread wes weston
[EMAIL PROTECTED] wrote:
I'm trying to come up with a good algorithm to do the following:
Given a list 'A' to be operated on, and a list 'I' of indices into 'A',
rotate the i'th elements of 'A' left or right by one position.
Here's are some examples:
A = [a, b, c, d, e, f]
I = [0, 3, 4]
rotate(A, I, 'left') --> [b, c, d, e, f, a]
rotate(A, I, 'right') --> [b, a, c, f, d, e]
I = [1, 3, 4]
rotate(A, I, 'left') --> [b, a, d, e, c, f]
rotate(A, I, 'right') --> [a, c, b, f, d, e]
Any ideas?
phil,
   Could you do a circlular buffer where the front
starts at 'a' (0) and rotate left increments front.
The i'th element is gotten as mod 6 (front+i) where
6 would be the length of the list.
wes
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rotating arbitrary sets of elements within a list

2005-04-08 Thread wes weston
[EMAIL PROTECTED] wrote:
I'm trying to come up with a good algorithm to do the following:
Given a list 'A' to be operated on, and a list 'I' of indices into 'A',
rotate the i'th elements of 'A' left or right by one position.
Here's are some examples:
A = [a, b, c, d, e, f]
I = [0, 3, 4]
rotate(A, I, 'left') --> [b, c, d, e, f, a]
rotate(A, I, 'right') --> [b, a, c, f, d, e]
I = [1, 3, 4]
rotate(A, I, 'left') --> [b, a, d, e, c, f]
rotate(A, I, 'right') --> [a, c, b, f, d, e]
Any ideas?

class CBuf:
def __init__(self,list=[]):
self.List = list
self.Front = 0
def ActualIndexGet(self,index):
return (self.Front + index) % len(self.List)
def ValueGet(self,index):
return self.List[self.ActualIndexGet(index)]
def Rotate(self,dir):
if dir == 'L':
self.Front += 1
else:
self.Front -= 1
self.Front = self.Front % len(self.List)
def Show(self):
i = self.Front
while 1:
print self.List[i]," ",
i = (i+1) % len(self.List)
if i == self.Front:
break
print
b = CBuf(['a','b','c','d','e','f'])
b.Show()
b.Rotate('L')
b.Show()
b.Rotate('L')
b.Show()
>>>  RESTART 

>>>
a   b   c   d   e   f
b   c   d   e   f   a
c   d   e   f   a   b
>>>
--
http://mail.python.org/mailman/listinfo/python-list


Re: python under earthlink hosting?

2006-08-01 Thread wes weston
No, but before I signed up with them I asked if it was available
and they said yes.
wes


mbstevens wrote:
> I keep chatting with the tech support people at Earthlink, asking where
> the location of the Python interpreter is.  They don't seem to know where
> it is.  They don't know if Python is running on my server, either.  I know
> Perl is at /usr/local/bin/perl ...but when I use a similar address for
> Python I get a 500 internal server error.
> 
> Has anyone succeeded in getting Python CGI scripts running on an earthlink
> hosted site?
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing HTML--looking for info/comparison of HTMLParser vs. htmllib modules.

2006-07-07 Thread wes weston
from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
 def __init__(self):
 HTMLParser.__init__(self)
 self.TokenList = []
 def handle_data( self,data):
 data = data.strip()
 if data and len(data) > 0:
 self.TokenList.append(data)
 #print data
 def GetTokenList(self):
 return self.TokenList


try:
 url = "http://your url here.."
 f = urllib.urlopen(url)
 res = f.read()
 f.close()
except:
 print "bad read"
 return

h = MyHTMLParser()
h.feed(res)
tokensList = h.GetTokenList()


Kenneth McDonald wrote:
> I'm writing a program that will parse HTML and (mostly) convert it to 
> MediaWiki format. The two Python modules I'm aware of to do this are 
> HTMLParser and htmllib. However, I'm currently experiencing either real 
> or conceptual difficulty with both, and was wondering if I could get 
> some advice.
> 
> The problem I'm having with HTMLParser is simple; I don't seem to be 
> getting the actual text in the HTML document. I've implemented the 
> do_data method of HTMLParser.HTMLParser in my HTMLParser subclass, but 
> it never seems to receive any data. Is there another way to access the 
> text chunks as they come along?
> 
> HTMLParser would probably be the way to go if I can figure this out. It 
> seems much simpler than htmllib, and satisfies my requirements.
> 
> htmllib will write out the text data (using the AbstractFormatter and 
> AbstractWriter), but my problem here is conceptual. I simply don't 
> understand why all of these different "levels" of abstractness are 
> necessary, nor how to use them. As an example, the html text 
> should be converted to ''text'' (double single-quotes at each end) in my 
> mediawiki markup output. This would obviously be easy to achieve if I 
> simply had an html parse that called a method for each start tag, text 
> chunk, and end tag. But htmllib calls the tag functions in HTMLParser, 
> and then does more things with both a formatter and a writer. To me, 
> both seem unnecessarily complex (though I suppose I can see the benefits 
> of a writer before generators gave the opportunity to simply yield 
> chunks of output to be processed by external code.) In any case, I don't 
> really have a good idea of what I should do with htmllib to get my 
> converted tags, and then content, and then closing converted tags, 
> written out.
> 
> Please feel free to point to examples, code, etc. Probably the simplest 
> solution would be a way to process text content in HTMLParser.HTMLParser.
> 
> Thanks,
> Ken
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Basic coin flipper program - logical error help

2006-02-21 Thread wes weston
DannyB wrote:
> I'm just learning Python.  I've created a simple coin flipper program -
> here is the code:
> 
> [source]
> #Coin flipper
> import random
> 
> heads = 0
> tails = 0
> counter = 0
> 
> coin = random.randrange(2)
> 
> while (counter < 100):
> if (coin == 0):
> heads += 1
> counter += 1
> else:
> tails += 1
> counter += 1
> 
> coin = random.randrange(2)
> 
> 
> print "\nThe coin landed on heads", heads, "times."
> print "\nThe coin landed on tails", tails, "times."
> [/source]
> 
> << anyway.>>>
> 
> The program runs - however - it will give me 100 heads OR 100 tails.
> Can someone spot the logic error?  
> 
> Thanks
> 
> ~Dan
> 

Dan,
Looping is easier with:
for x in range(100):
if random.randint(0,1) == 0:
   heads += 1
else:
   tails += 1

Inside the loop you need to "flip" on each pass.
You're "flipping" once before the start of the loop now.
wes
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Walking through a mysql db

2005-06-04 Thread wes weston
Jeff Elkins wrote:
> I'm writing a small wxpython app to display and update a dataset. So far, I 
> get the first record for display:
> 
>  try:
>   cursor = conn.cursor ()
>   cursor.execute ("SELECT * FROM dataset")
>   item = cursor.fetchone ()
> 
> Now, how do I step through the dataset one row at a time?  My form has  
> 'next' 
> and 'back' buttons, and I'd like them to step forward or back, fetching the 
> appropriate row in the table. I've tried setting cursor.rownumber by 
> incrementing it prior to the fetchone() w/o effect.
> 
> Thanks for any pointers.
> 
> Jeff Elkins
> 
> 
> 
> 
> 
> 
Jeff,
You just check for a fetchone return of None. "list" is a list
of tuples here.
 ...
 cursor.execute( sql )
 list = []
 while 1:
 row = cursor.fetchone()
 if not row:
 break
 list.append(row)
 ...
wes
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary help

2007-11-01 Thread wes weston
Steve wrote:
> I'm currently working on a little database type program is which I'm 
> using a dictionary to store the information. The key is a component a and 
> the definition is a list of parts that make up the component. My problem 
> is I need to list out several components, but not all, and there 
> associated parts to a printer. Not having any luck. I can list them to 
> the screen but not the printer. Any help/ideas would be appreciated.
> 
> Steve

You can do os.system("") after
putting your stuf in a file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class probkem - getting msg that self not defined

2006-05-22 Thread wes weston
Andrew Robert wrote:
> Hi Everyone,
> 
> I am having a problem with a class and hope you can help.
> 
> When I try to use the class listed below, I get the statement that self
> is not defined.
>   
> test=TriggerMessage(data)

self is not known here; only inside the class.

> var = test.decode(self.qname)
> 
> I would have thought that self would have carried forward when I grabbed
> an instance of TriggerMessage.
> 
> Any ideas on this?
> 
> 
> 
> The class in question is:
> 
> 
> class TriggerMessage(object):
>   
>   def __init__(self,data):
>   """
>   Unpacks the passed binary data based on the MQTCM2 format 
> dictated in
>   the MQ Application Programming Reference
>   """
> 
>   self.data=data
>   self.structid=None
>   self.version=None
> self.qname=None
>   self.procname=None
>   self.trigdata=None
>   self.appltype=None
>   self.applid=None
>   self.envdata=None
>   self.userdata=None
>   self.qmgr=None
> 
> 
>   def decode(self):
>   import struct
>   format='4s 4s 48s 48s 64s 4s 256s 128s 128s 48s'
>   size=struct.calcsize(format)
>   self.data=data  
>   self.structid, self.version, self.qname, self.processname,  
>  \
>   self.triggerdata, self.appltype, self.applid,   
>  \
>   self.envdata, self.userdata, self.qmgr  
>  \
>   = struct.unpack(format,self.data)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class probkem - getting msg that self not defined

2006-05-22 Thread wes weston
Andrew Robert wrote:
> wes weston wrote:
>> Andrew Robert wrote:
>>> Hi Everyone,
>>>
>>> I am having a problem with a class and hope you can help.
>>>
>>> When I try to use the class listed below, I get the statement that self
>>> is not defined.
>>>
>>> test=TriggerMessage(data)
>> self is not known here; only inside the class.
>>
>>> var = test.decode(self.qname)
>>>
> 
> 
> I guess I was barking up the wrong tree on that one.
> 
> How would I go about getting the required values out of the class?
> 
> Return self?

You can refer to the variables inside the class as test.version;
for example - as they are not protected. Or, you could add access
methods in the class like def GetVersion(self): return self.version
If you want to protect version, call it self.__version which mangles
the name from outside.
wes
-- 
http://mail.python.org/mailman/listinfo/python-list


parsing text from a file

2009-01-29 Thread Wes James
If I read a windows registry file with a line like this:

"{C15039B5-C47C-47BD-A698-A462F4148F52}"="v2.0|Action=Allow|Active=TRUE|Dir=In|Protocol=6|Profile=Public|App=C:\\Program
Files\\LANDesk\\LDClient\\tmcsvc.exe|Name=LANDesk Targeted
Multicast|Edge=FALSE|"

with this code:

f=open('fwrules.reg2.txt')

for s in f:
  if s.find('LANDesk') <0:
print s,


LANDesk is not found.

Also this does not work:

for s in f:
  try:
i=s.index('L')
print s[i:i+7]
 except:
   pass

all it prints is "LAND"

how do I find LANDesk in a string like this.  is the "\\" messing things up?

thx,

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


how to conditionally add a dict in-line

2009-02-23 Thread Wes James
I have this line:

navs.append(A(' '+str(i+1)+'
',_href=self.action(args=request.args,vars={'_page':i,'_query':request.vars._query
or ''})))

How do I do something like this:

vars={'_page':i, if request.vars._query not None then insert this
key/value pair ('_query':request.vars._query) else insert nothing }

thx,

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


Re: how to conditionally add a dict in-line

2009-02-23 Thread Wes James
On Mon, Feb 23, 2009 at 9:35 PM, Wes James  wrote:
> I have this line:
>
> navs.append(A(' '+str(i+1)+'
> ',_href=self.action(args=request.args,vars={'_page':i,'_query':request.vars._query
> or ''})))
>
> How do I do something like this:
>
> vars={'_page':i, if request.vars._query not None then insert this
> key/value pair ('_query':request.vars._query) else insert nothing }


Nevermind, this seems to work:

navs.append(A(' '+str(i+1)+'
',_href=self.action(args=request.args,vars={'_page':i,'_query':request.vars._query}
if request.vars._query else {'_page':i})))

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


Re: how to conditionally add a dict in-line

2009-02-23 Thread Wes James
Steven. Thx

(see my question below...)

On Mon, Feb 23, 2009 at 9:47 PM, Steven D'Aprano
 wrote:
> On Mon, 23 Feb 2009 21:35:38 -0700, Wes James wrote:
>
>> I have this line:
>>
>> navs.append(A(' '+str(i+1)+'
>> ',_href=self.action(args=request.args,vars=
> {'_page':i,'_query':request.vars._query
>> or ''})))
>
> What a mess. How can you read it?
>
>
>> How do I do something like this:
>>
>> vars={'_page':i, if request.vars._query not None then insert this
>> key/value pair ('_query':request.vars._query) else insert nothing }
>
> vars = {'_page': i}
> if request.vars._query is not None:
>    vars['_query'] = request.vars._query

Could this be:

vars = {'_page': i}
 if request.vars._query:
vars['_query'] = request.vars._query



>
> See how simple and clear things are when you give up the insistence on
> making everything a one-liner?



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


Re: Upgrade Python on a Mac

2009-03-02 Thread Wes James
On Mon, Mar 2, 2009 at 2:53 PM, Rey Bango  wrote:
> Hi,
>
> I'd like to upgrade the installed version of Python that came standard
> on OS X (Leopard) with either 2.6.1 or 3.0.1. Before I stick my foot
> in it, I just wanted to get a better understanding of the process.

I'd recommend you put your new versions in to /usr/local

Leave the OS X one alone.

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


Re: file open fails.

2009-03-24 Thread Wes James
On Tue, Mar 24, 2009 at 4:04 PM, Scott David Daniels
 wrote:
> Atul. wrote:



> In your case, '\r' is a return (a single character), not two
> characters long. I think its sad that 'C:\Thesis' doesn't cause
> an error because there is no such character as '\T', but I am
> probably excessively pedantic.

\T might mean the same thing as \t (tab), but I thought it would be different...

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


Re: file open fails.

2009-03-24 Thread Wes James
On Tue, Mar 24, 2009 at 4:32 PM, Wes James  wrote:
> On Tue, Mar 24, 2009 at 4:04 PM, Scott David Daniels
>  wrote:
>> Atul. wrote:
>
> 
>
>> In your case, '\r' is a return (a single character), not two
>> characters long. I think its sad that 'C:\Thesis' doesn't cause
>> an error because there is no such character as '\T', but I am
>> probably excessively pedantic.
>
> \T might mean the same thing as \t (tab), but I thought it would be 
> different...


I guess not:

http://docs.python.org/reference/lexical_analysis.html#string-literals

Wonder why when I do print "test\Ttest" vs print "test\ttest"  \T just
get printed?

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


python twitter

2009-04-15 Thread Wes James
Anyone know if there is a twit for python?  I did
http://twitter.com/python, but nope on that  I was looking for
twit py announcements, etc...

thx,

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


Re: Best Python Web Framework ?

2009-04-21 Thread Wes James
On Tue, Apr 21, 2009 at 12:46 PM, SKYLAB  wrote:
> Greetings..
>
> First , my english is not good .
>
> I heard that was written in python ( Youtube Programming Language :
> PYTHON :S ) Correct ?
>
> That's not correct ? Then youtube is PHP application ?
>
> That's correct ; Which python web framework in friendfeed ? Web.py ?
> Django ? web2py ?
>


You'll need to do some homework to see what fits.

Here's a starter point:

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

Try some or all.

I used perl for a long time, went looking for a framework, tried
django for a few days then found web2py and web2py fits for me.

good luck

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


string to list when the contents is a list

2010-02-17 Thread Wes James
I have been trying to create a list form a string.  The string will be
a list (this is the contents will look like a list).  i.e. "[]" or
"['a','b']"

The "[]" is simple since I can just check if value == "[]" then return []

But with "['a','b']" I have tried and get:

a="['a','b']"

b=a[1:-1].split(',')

returns

[ " 'a' "," 'b' " ]

when I want it to return ['a','b'].

How can I do this?

thx,

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


error trying to join #python on irc.freenode.net

2010-02-17 Thread Wes James
When I try to join #python on irc.freenode.net it keeps saying:

You need to identify with network services to join the room "#python"
on "irc.freenode.net".

Server Details:
Cannot join channel (+r) - you need to be identified with services

What does this mean?

thx,

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


Re: error trying to join #python on irc.freenode.net

2010-02-17 Thread Wes James
On Wed, Feb 17, 2010 at 4:53 PM, Wes James  wrote:
> When I try to join #python on irc.freenode.net it keeps saying:
>
> You need to identify with network services to join the room "#python"
> on "irc.freenode.net".
>
> Server Details:
> Cannot join channel (+r) - you need to be identified with services
>
> What does this mean?


Nevermind, I think it means I need to register with the service and
supply real username/password.

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


Re: string to list when the contents is a list

2010-02-18 Thread Wes James
On Thu, Feb 18, 2010 at 8:18 AM, Tim Chase
 wrote:
> Wes James wrote:


>
> Just to add to the list of solutions I've seen, letting the built-in csv
> module do the heavy lifting:
>
>  >>> s = "['a','b']"
>  >>> import csv
>  >>> no_brackets = s[1:-1] # s.strip(' \t[]')
>  >>> c = csv.reader([no_brackets], quotechar="'")
>  >>> c.next()
>  ['a', 'b']
>
> This also gives you a bit of control regarding how escaping is done, and
> other knobs & dials to twiddle if you need. Additionally, if you have more
> than one string to process coming from an iterable source (such as a file),
> you can just pass that iterator to csv.reader() instead of concocting a
> one-element list.

Thx,  I think this will work for what I want.

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


Re: string to list when the contents is a list

2010-02-18 Thread Wes James
On Thu, Feb 18, 2010 at 12:32 PM, Wes James  wrote:
> On Thu, Feb 18, 2010 at 8:18 AM, Tim Chase
>  wrote:
>> Wes James wrote:
> 
>
>>
>> Just to add to the list of solutions I've seen, letting the built-in csv
>> module do the heavy lifting:
>>
>>  >>> s = "['a','b']"
>>  >>> import csv
>>  >>> no_brackets = s[1:-1] # s.strip(' \t[]')
>>  >>> c = csv.reader([no_brackets], quotechar="'")
>>  >>> c.next()
>>  ['a', 'b']


Hmm.  When I put csv.reader in a class:

import csv

class IS_LIST():
def __init__(self, format='', error_message='must be a list!'):
self.format = format
self.error_message = error_message
def __call__(self, value):
try:
if value=='[]' or value=='':
value=[]
else:
no_brackets = value[1:-1] # s.strip(' \t[]')
c = csv.reader([no_brackets], quotechar="'")
value=c.next()
return (value, None)
except:
return (value, self.error_message)
def formatter(self, value):
return value

I get an error (when I take the "try" out):

AttributeError: 'function' object has no attribute 'reader'

Why?

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


Re: python dowload

2010-02-23 Thread Wes James


>
>
> NEW QUESTION if y'all are still reading:
>
> Is there an integer increment operation in Python? I tried
> using i++ but had to revert to 'i = i + 1'

i+=1


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


Re: WANTED: Regular expressions for breaking TeX/LaTeX document into tokens

2010-02-24 Thread Wes James
On Wed, Feb 24, 2010 at 5:03 AM, Jonathan Fine  wrote:
> Hi
>
> Does anyone know of a collection of regular expressions that will break a
> TeX/LaTeX document into tokens?  Assume that there is no verbatim or other
> category code changes.

I'm not sure how this does it, but it might help:

http://plastex.sourceforge.net/plastex/sect0025.html

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


Structure accessible by attribute name or index

2010-03-17 Thread Wes Santee
I am very new to Python, and trying to figure out how to create an
object that has values that are accessible either by attribute name,
or by index.  For example, the way os.stat() returns a stat_result or
pwd.getpwnam() returns a struct_passwd.

In trying to figure it out, I've only come across C implementations of
the above types.  Nothing specifically in Python.  What is the Python
native way to create this kind of object?

I apologize if this has been widely covered already.  In searching for
an answer, I must be missing some fundamental concept that is
excluding me from finding an answer.

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


Re: Structure accessible by attribute name or index

2010-03-17 Thread Wes Santee
On Mar 17, 11:14 am, Christian Heimes  wrote:
> Wes Santee wrote:
> > I am very new to Python, and trying to figure out how to create an
> > object that has values that are accessible either by attribute name,
> > or by index.  For example, the way os.stat() returns a stat_result or
> > pwd.getpwnam() returns a struct_passwd.
>
> > In trying to figure it out, I've only come across C implementations of
> > the above types.  Nothing specifically in Python.  What is the Python
> > native way to create this kind of object?
>
> > I apologize if this has been widely covered already.  In searching for
> > an answer, I must be missing some fundamental concept that is
> > excluding me from finding an answer.
>
> You can't use the same implementation as the result object of os.stat()
> and others. However Python 2.6 has a new factory that creates a similar
> datatype called named 
> tuple:http://docs.python.org/library/collections.html#namedtuple-factory-fu...

Thanks for the pointer.  At least I know there is a reason why I
wasn't finding a solution. :)

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


Re: Structure accessible by attribute name or index

2010-03-17 Thread Wes Santee
On Mar 17, 11:34 am, Bruno Desthuilliers  wrote:
> Wes Santee a écrit :
>
> > I am very new to Python, and trying to figure out how to create an
> > object that has values that are accessible either by attribute name,
> > or by index.  For example, the way os.stat() returns a stat_result or
> > pwd.getpwnam() returns a struct_passwd.
>
> > In trying to figure it out, I've only come across C implementations of
> > the above types.  Nothing specifically in Python.  What is the Python
> > native way to create this kind of object?
>
> Using the appropriate __magicmethods__ for indexed access and computed
> attributes for the attribute access might be a good solution:

This is as good an excuse as any to get familiar with the rest of the
__magicmethods__. :)

>
> # warning : Q&D implementation, would require some sanity checks.
>
> class IndexedValueDescriptor(object):
>      def __init__(self, index):
>          self._index = index
>      def __get__(self, instance, cls):
>          if instance is None:
>              return self
>          return instance[self._index]
>      def __set__(self, instance, value):
>          instance[self._index] = value
>
> class Structure(object):
>      def __init__(self, value1, value2, value3):
>          self._values = [value1, value2, value3]
>      def __setitem__(self, index, value):
>          self._values[index] = value
>      def __getitem__(self, index):
>          return self._values[index]
>      value1 = IndexedValueDescriptor(0)
>      value2 = IndexedValueDescriptor(1)
>      value3 = IndexedValueDescriptor(2)
>
> Note that there are probably other solutions... Don't know how
> os.stat_result is implemented, might be worth looking at the source
> code. But anyway : the above should get you started.
>
> > I apologize if this has been widely covered already.   In searching for
> > an answer, I must be missing some fundamental concept that is
> > excluding me from finding an answer.
>
> Well, that's not really a FAQ AFAICT !-)

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


socket.MSG_WAITALL flag broken on Windows XP in Python 2.5.4?

2009-09-15 Thread Wes McKinney
I noticed the flag socket.MSG_WAITALL seems to have crept its way into
Python 2.5 on Windows (it's in 2.5.4, but not in 2.5.1, not sure about
intermediate releases). I do not think Windows supports it. It seems
to cause some problems in some libraries (like Pyro) that use it if
it's available in the socket module.

Does anyone know more about this?

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


Re: socket.MSG_WAITALL flag broken on Windows XP in Python 2.5.4?

2009-09-16 Thread Wes McKinney
On Sep 16, 3:53 pm, Irmen de Jong  wrote:
> Tim Roberts wrote:
> > Wes McKinney  wrote:
> >> I noticed the flag socket.MSG_WAITALL seems to have crept its way into
> >> Python 2.5 on Windows (it's in 2.5.4, but not in 2.5.1, not sure about
> >> intermediate releases). I do not think Windows supports it. It seems
> >> to cause some problems in some libraries (like Pyro) that use it if
> >> it's available in the socket module.
>
> >> Does anyone know more about this?
>
> > MSG_WAITALL is supported, starting with Windows Server 2003.
>
> > It's a tough situation.  Ideally, you'd want socket to remove that symbol
> > on the systems where it's not supported, but that's asking a lot.
>
> My installation doesn't have _socket.MSG_WAITALL, Wes, I wonder where yours 
> is coming from?
> (Python 2.5.4 and 2.5.2, on Windows XP.  On my Mac (OS X) it does have the 
> flag, and
> it's working fine there.).
>
> --irmen

I am running what is apparently a custom Python 2.5.4 (part of the
Enthought Python Distribution) which should be identical to the one on
python.org, but is not. I contacted Enthought about the issue-- it can
be worked around in the Pyro configuration for the time being.

Thanks a lot for the debugging help,
Wes
-- 
http://mail.python.org/mailman/listinfo/python-list