Re: [Tutor] Python 2.4 IDLE Windows 2000

2004-12-02 Thread Liam Clarke
>Yowza; that's some bug.  Danny, do you happen to know the bug number?  I
>can't find it on sourceforge.

It's been like that since 2.3 as far as I know. It generates a
connection to localhost to run code in a separate environment.



On Thu, 02 Dec 2004 07:20:19 -0700, Mike Hansen <[EMAIL PROTECTED]> wrote:
> I'm pretty sure that there isn't any firewall software running on the
> workstation.
> 
> I do get a blank window when I run the commands below, so Tkinter seems
> to be working.
> 
> This is strange since IDLE in Python 2.3.4 was working fine.
> 
> Thanks for the help. I welcome any other ideas.
> 
> Mike
> 
> 
> 
> Danny Yoo wrote:
> 
> >
> >
> >>Also, If you can start up the console version of Python, try executing the
> >>following:
> >>
> >>###
> >>
> >>
> >import Tkinter
> >root = Tkinter.root()
> >
> >
> >>###
> >>
> >>
> >
> >Doh.  Sorry, I should have tested that.  The commands should actually be:
> >
> >###
> >
> >
> import Tkinter
> root = Tkinter.Tk()
> 
> 
> >###
> >
> >You should see a small, blank window pop up if Tkinter is working
> >properly.
> >
> >
> >
> >
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Strange Appending

2004-12-02 Thread Liam Clarke
What's t supposed to be, what are you initialising self.a as, where is
t generated, what is your expected output? What else is happening to
self.a?

Looks like an indentation error to me.

This kind of output 
[[1, 237, 543], [1, 237, 543], [1, 237, 543], [1, 237, 543]]

would only come from 

a loop iterating over the command that appends [1,237,543] several times.

I'd check your logic, logical errors are the hardest.
I use that kind of thing often - 

i.e. 

x=[]
a="Hello 123, How is 456?"
for item in a:
   try:
 w=(int(item))/1
   except TypeError:
continue
x.append(item)

print x

['1','2','3','4','5','6']


But yeah, post up all the relevant code please, just not the bit
that's not breaking. I can't see your loop that's writing the wrong
values, or perhaps self.a is getting reinitialized wrong? If you get
my point.


Regards,

Liam Clarke

On Thu, 2 Dec 2004 14:41:03 -0800 (PST), Marilyn Davis
<[EMAIL PROTECTED]> wrote:
> On Thu, 2 Dec 2004, mdcooper wrote:
> 
> 
> 
> > Hello,
> >
> > I am trying to append a list to another list, but everytime I do, the new
> > parent list has a new child list, but all the other lists have become the 
> > same
> > as the new child list.
> >
> > Code:
> >
> >
> > self._f.write(str(self.residue.atoms[int(t[0])-1].element) + ' ')
> > for m in t:
> > self._f.write(str(m)+' ')
> > self._f.write('\n')
> >
> > self.a.append(t) # WHY DOES THIS NOT WORK?
> 
> Hi,
> 
> I'm not sure that I understand your question because I don't see all
> the code and I don't know what you hope will happen.  But ...
> 
> append appends the object as a single element.
> 
> Try self.a.extend(t)
> 
> extend attaches the t list to the end of the list.
> 
> Does this give you what you expect?
> 
> Marilyn Davis
> 
> 
> 
> > print self.a
> >
> > Output:
> >
> > [[1, 234, 543]]
> > [[1, 234, 548], [1, 234, 548]]
> > [[1, 234, 59], [1, 234, 59], [1, 234, 59]]
> > [[1, 237, 543], [1, 237, 543], [1, 237, 543], [1, 237, 543]]
> >
> >
> > Can anyone help?
> >
> > thanks,
> >
> > Matthew (mdcooper at uvic dot ca)
> >
> >
> > ___
> > Tutor maillist  -  [EMAIL PROTECTED]
> > http://mail.python.org/mailman/listinfo/tutor
> >
> 
> --
> 
> 
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] programming newbie question

2004-12-02 Thread Liam Clarke
IMAP / POP3 /SMTP connections/sessions as objects are very useful, as
you can pass them from function to function.




On Thu, 2 Dec 2004 21:50:20 -0500, Jacob S. <[EMAIL PROTECTED]> wrote:
> > I am fairly new to programming and I have started to learn programming
> > then stopped out of frustration several times in the past.  I guess my
> > frustration stems from not being able to understand when to use certain
> > aspects of programming such as functions or classes.
> 
> Use functions when you will execute a certain code block many, many times
> during a script. Or if you want to make a code block simpler and more
> generic. For example...
> 
> def rfill(stri,length,sep=" "):  # stri is short for string, and sep
> (seperator) is defaulted to a space
> stri = str(stri) # This is to help make sure that what the user gives us
> is a string
> if stri < length:
> stri = stri + sep*(length-len(stri)) # This fills the string to the
> length with seperators
> return stri # This returns the string so we can assign it, print it etc.
> 
> Usage is as follows:
> 
> a = 'The'
> b = 'Many'
> c = 'Two'
> e = 'Forty'
> f = [a,b,c,e]
> for i in range(4):
> print "%s%d" % (rfill(f[i],15),i)
> 
> yields
> 
> The0
> Many   1
> Two2
> Forty  3
> 
> This is just one example. You can use functions over and over from anywhere
> in your script.
> Classes are just like defining new types. You have the usual types like
> dictionary, list, tuple, integer, float, etc.  but with classes you can
> define your own. Methods are just attributes of classes, or so I understand.
> For example...
> 
> class MyClass:
> def __init__(self,pos=[0,1,0]):
> self.pos = pos
> def printpos(self):
> print self.pos
> 
> Which in turn can be used like this.
> 
> >>> a = MyClass()  ## pos defaults to [0,1,0] so I don't have to specify
> explicitly
> >>> print a.pos
> [1,0,1]
> >>> a.pos = [1,2,1]
> >>> a.printpos()
> [1,2,1]
> >>>
> 
> The most interesting use of classes that I have seen is the VPython package
> where they define new classes (again I think of them as types) as shapes
> with attributes (or methods - like L.append() which refers to appending to
> lists) like position, color, radius, axis, etc.
> But I digress.
> 
> HTH,
> Jacob Schmidt
> 
> 
> 
> > I have read enough
> > books and tutorials to know the syntax of python and I understand most
> > everything related to the concepts of programming, but I have never been
> > able to put it all together and learn how and when to use specific
> > features.  Can anyone suggest a method or some reading to help out with
> > this?  I also struggle with finding projects to work on does anyone know
> > of projects that a novice could contribute to?
> >
> >
> > ___
> > Tutor maillist  -  [EMAIL PROTECTED]
> > http://mail.python.org/mailman/listinfo/tutor
> >
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] backup failed - gzip

2004-12-02 Thread Liam Clarke
As the below quote from the manual shows - 

On Windows, the return value is that returned by the system shell
after running command, given by the Windows environment variable
COMSPEC: on command.com systems (Windows 95, 98 and ME) this is always
0; on cmd.exe systems (Windows NT, 2000 and XP) this is the exit
status of the command run; on systems using a non-native shell,
consult your shell documentation.

Your return value is OS specific. What OS are you using? Did you check
to see if your zip files were created? It may just be a funky return
code.

On Fri, 3 Dec 2004 12:08:25 +0600, Ramkumar Parimal Alagan
<[EMAIL PROTECTED]> wrote:
> This is what i intend to do:
> 
> 1. The files and directories to be backed up are given in a list.
> 2. The backup must be stored in a main backup directory.
> 3. The files are backed up into a zip file.
> 4. The name of the zip archive is the current date and time.
> 
> the coding:
> 
> __
> 
> import os
> import time
> 
> source = ['D:\\down', 'D:\\Pics']
> 
> target_dir = 'D:\\backup'
> 
> target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
> 
> zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
> 
> if os.system(zip_command) == 0:
> print 'Successful backup to', target
> else:
> print 'Backup FAILED'
> 
> _
> 
> result : Backup FAILED
> 
> whats wrong ?
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] backup failed - gzip

2004-12-03 Thread Liam Clarke
Hi Rankumar - 

That's your problem then - 

if os.system(zip_command) == 0:
> > > print 'Successful backup to', target

So, os.system() returns 0 for Win 95,98, ME.
For XP, it returns whatever the exit code your programme returns .

So whatever zip returns, is what os.system() returns, which may or may not be 0.

Try rewriting your code to find out like so - 

import os
import os.path
import time

source = ['D:\\down', 'D:\\Pics']
target_dir = 'D:\\backup'
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))

returnCode=os.system(zip_command)

if os.path.isfile(target):
  print "Back-up succeeded!"
  print returnCode, " is a successful return code."
else:
 print "Back-up failed."
 print returnCode, " is an unsuccessful return code."

 #if os.system(zip_command) == 0:
 #print 'Successful backup to', target
 #else:
#print 'Backup FAILED'

os.path.isfile(path) checks if there is a regular existing file there - i.e.

target="c:/windows/win.ini"

if not os.path.isfile(target):
print "I'm in serious trouble here."


Check it out, hope it helps.

Regards,

Liam Clarke

On Fri, 3 Dec 2004 13:01:44 +0600, Ramkumar Parimal Alagan
<[EMAIL PROTECTED]> wrote:
> Thanks for your reply Liam, I am using Windows Xp
> 
> 
> 
> 
> On Fri, 3 Dec 2004 19:46:14 +1300, Liam Clarke <[EMAIL PROTECTED]> wrote:
> > As the below quote from the manual shows -
> >
> > On Windows, the return value is that returned by the system shell
> > after running command, given by the Windows environment variable
> > COMSPEC: on command.com systems (Windows 95, 98 and ME) this is always
> > 0; on cmd.exe systems (Windows NT, 2000 and XP) this is the exit
> > status of the command run; on systems using a non-native shell,
> > consult your shell documentation.
> >
> > Your return value is OS specific. What OS are you using? Did you check
> > to see if your zip files were created? It may just be a funky return
> > code.
> >
> >
> >
> > On Fri, 3 Dec 2004 12:08:25 +0600, Ramkumar Parimal Alagan
> > <[EMAIL PROTECTED]> wrote:
> > > This is what i intend to do:
> > >
> > > 1. The files and directories to be backed up are given in a list.
> > > 2. The backup must be stored in a main backup directory.
> > > 3. The files are backed up into a zip file.
> > > 4. The name of the zip archive is the current date and time.
> > >
> > > the coding:
> > >
> > > __
> > >
> > > import os
> > > import time
> > >
> > > source = ['D:\\down', 'D:\\Pics']
> > >
> > > target_dir = 'D:\\backup'
> > >
> > > target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
> > >
> > > zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
> > >
> > > if os.system(zip_command) == 0:
> > > print 'Successful backup to', target
> > > else:
> > > print 'Backup FAILED'
> > >
> > > _
> > >
> > > result : Backup FAILED
> > >
> > > whats wrong ?
> > > ___
> > > Tutor maillist  -  [EMAIL PROTECTED]
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> >
> >
> > --
> > 'There is only one basic human right, and that is to do as you damn well 
> > please.
> > And with it comes the only basic human duty, to take the consequences.
> >
> 
> 
> --
> 
>  <<  The end depends upon the beginning. >>
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] gzip (fwd)

2004-12-03 Thread Liam Clarke
>target_dir = 'D:\\backup'
>target = target_dir +"Zipnametoreplacestrftimeformatstring"+ '.zip'

Just noticed this - 

target_dir("D:\\backup") + "Zipnametoreplacestrftimeformatstring"+ '.zip'

= D:\\backupZipnametoreplacestrftimeformatstring.zip

No wonder it doesn't work.

Try 

target=target_dir+'\\'+time.strftime('%Y%m%d%H%M%S') + '.zip'

Regards,

Liam Clarke

PS Yes, do use reply to all




On Fri, 3 Dec 2004 15:16:27 +0600, Ramkumar Parimal Alagan
<[EMAIL PROTECTED]> wrote:
> I have only 2 word documents in both the directories, i tried removing
> '-qr' too, but no change, no zip files formed. i'm using windows XP.
> 
> On Thu, 2 Dec 2004 23:54:11 -0800 (PST), Danny Yoo
> 
> 
> <[EMAIL PROTECTED]> wrote:
> > Hi Ramkumar,
> >
> > I'm forwarding your message to Python-tutor; in your replies, please make
> > sure that you are using the "reply-to-all" feature in your email client.
> > This will allow your response to reach the others on the tutor list.
> > Don't rely on me alone: give the community the chance to help you.
> >
> > I don't have enough information to pinpoint what the problem is yet.  I'll
> > have to ask more questions, and others on the Tutor list will probably
> > also ask a few questions.  Please try to answer them, because that will
> > help us give a better idea of what the problem is.
> >
> > It looks like you are trying to zip up whole directories.  Does the
> > program work if you zip up single files?
> >
> > It also appears that you're using the '-q' and '-r' options of the 'zip'
> > command line utility.  '-q' stands for 'quiet' mode, and although that's
> > nice when the command is working properly, it's not helpful when you're
> > debugging a situation.  Try turning quiet mode off, so that you have a
> > better chance of getting good error output from the zip command.  Even
> > better, try enabling verbose mode, so you can see better what 'zip' is
> > attempting to do.
> >
> > Do you see anything else when you execute the program?  Does anything else
> > come out of standard error?
> >
> > Good luck to you.
> >
> > -- Forwarded message --
> > Date: Fri, 3 Dec 2004 10:24:15 +0600
> > From: Ramkumar Parimal Alagan <[EMAIL PROTECTED]>
> > To: Danny Yoo <[EMAIL PROTECTED]>
> > Subject: Re: [Tutor] gzip
> >
> > This is what i intend to do:
> >
> > 1. The files and directories to be backed up are given in a list.
> > 2. The backup must be stored in a main backup directory.
> > 3. The files are backed up into a zip file.
> > 4. The name of the zip archive is the current date and time.
> >
> > the coding:
> >
> > __
> >
> > import os
> > import time
> >
> > source = ['D:\\down', 'D:\\Pics']
> >
> > target_dir = 'D:\\backup'
> >
> > target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
> >
> > zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
> >
> > if os.system(zip_command) == 0:
> > print 'Successful backup to', target
> > else:
> > print 'Backup FAILED'
> >
> > _
> >
> > result : Backup FAILED
> >
> > whats wrong ?
> >
> >
> 
> 
> --
> 
>  <<  The end depends upon the beginning. >>
> 
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple RPN calculator

2004-12-04 Thread Liam Clarke
RPN calculator, with operators and operands separate? Sounds
counter-intuitive to me.
What's the advantage I'm missing?

P.S.

Nice Shodan quote Max ;)


On Sat, 4 Dec 2004 23:45:18 +, Max Noel <[EMAIL PROTECTED]> wrote:
> 
> 
> 
> On Dec 4, 2004, at 23:30, Alan Gauld wrote:
> 
> >> to make it request for input(s) of say a simple math like  "1 2 3 4
> > 5 + - * /".
> >
> > Look at raw_input()
> >
> > But if you are that much of a beginner you need to take several
> > steps back and try one of the tutorials, they all cover raw_input
> > fairly early on...
> >
> > And finally doesn't RPN put the operators first? Or is it me thats
> > getting confused fromtoo much Lisping recently?...
> 
> Nope, RPN calculators (such as the HP48GX, IMHO the best calculator
> ever made) require you to input the operands first, then the operators.
> It's both easier to implement and more intuitive (not to mention way
> faster to both input and compute) once you've gotten the hang of it.
> You can probably do a very basic RPN calculator in less than a hundred
> lines of code, using raw_input() and a stack (well, a list's append()
> and pop() methods).
> 
> -- Max
> maxnoel_fr at yahoo dot fr -- ICQ #85274019
> "Look at you hacker... A pathetic creature of meat and bone, panting
> and sweating as you run through my corridors... How can you challenge a
> perfect, immortal machine?"
> 
> 
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Real time reading

2004-12-05 Thread Liam Clarke
You could just get Python to see if the maillog has increased in size,
and if so then open it, or you could get the 'last modified date' and
so forth... os module will do this.

Or, all changes to the maillog could be passed through Python, which writes it?
http://www.python.org/doc/2.3/lib/module-StringIO.html

???

Good luck,

Liam Clarke


On Sun, 5 Dec 2004 11:31:32 +0100 (CET), Øyvind <[EMAIL PROTECTED]> wrote:
> I would like to analyze a maillog. The maillog is automatically generated
> and every mail sent is added to the log. I would like to check if someone
> send more than 5 mails pr minute (spams) and if so, get Python to send a
> warningmail to the mailmaster.
> 
> How would I in the best way read the log? To open the file and close it
> every second sounds like a bad idea? Is there some function to analyze the
> file, and automatically extract additions to the file?
> 
> Thanks in advance.
> 
> --
> This email has been scanned for viruses & spam by Decna as - www.decna.no
> Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple RPN calculator

2004-12-05 Thread Liam Clarke
My head boggles. This is like trying to understand game theory.

On Sun, 05 Dec 2004 11:40:38 -0500, Brian van den Broek
<[EMAIL PROTECTED]> wrote:
> Kent Johnson said unto the world upon 2004-12-05 06:55:
> > RPN reverses the order of operator and operand, it doesn't reverse the
> > whole string. So in Polish Notation 2 + 3 is +23 and (2 + 3) - 1 is
> > -+231; in RPN they become 23+ and 23+1-
> >
> > Kent
> 
> Hi all,
> 
> Thanks Kent, that is what I had assumed it would be by analogy to Polish
> notation in logic. Somewhere on the thread, I though it had been
> asserted that all opps and operands were separated. For a bit there, I
> thought I'd gone all goofy :-) So, thanks for clearing that up.
> 
> Thanks also for the other interesting posts on the thread.
> 
> Largely off-topic things follow:
> 
> One other advantage, at least from the logicians perspective is that
> standard "infix" notation is only able to comfortably deal with binary
> and unary operations (operations that have 2 or 1 arguments). For
> arithmetic, where you can do everything with zero, successor,
> multiplication, and addition, that isn't so important. But notice that
> general function notation, in Python and in math, is also Polish -- to
> write a 4 placed function that takes, say, the greatest common divisor
> of two numbers, and the least common multiple of two others, and tells
> you if the first divides the second, you've got to write:
>   f(a,b,c,d).
> 
> So, Polish notation makes manifest the conceptual similarity between the
> addition -- ADD(a,b) -- 2-placed function and arbitrary n-placed functions.
> 
> This also helps out a lot in some of the areas where formal logic and
> formal semantics for natural languages bleed into each other. At a cost
> of patience, all truth functions can be expressed in terms of the "not
> both" truth function, so polyadic truth-functions past binary don't
> really need Polish notation.
> 
> But, when you consider the quantifiers ('for everything . . .' and
> 'there is at least on thing . . . '), standard ones are one-placed (with
> a given universe of discourse set assumed). In the 1950's and 1960's
> mathematicians began exploring generalizations of the quantifier notion.
> There have, since the 1980's, been a sizable group of linguists who
> argue that natural language quantification is almost always 2 or higher
> placed. After two places, this too needs Polish notation (or heroic and
> ugly conventions).
> 
> 
> 
> Brian vdB
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Could I have used time or datetime modules here?

2004-12-05 Thread Liam Clarke
Hi Dick, 

import datetime

OK = 0
while not OK:
   wakeup=raw_input( "enter time in 24 hour format for alarm - in this
format HH:MM:SS")
   wakeup=wakeup.split(":")
if len(wakeup) == 3:
if -1 < int(wakeup[0]) < 24  and -1 < int(wakeup[1]) < 60 and
-1 <  int(wakeup[2]) < 60:
OK = 1

# Above loops until valid input is received.

secIncre = datetime.timedelta(seconds=1) 
workingObj = datetime.datetime.now() 
idealTimeObj=datetime.time(int(wakeup[0]),int(wakeup[1]),int(wakeup[2]))
#Inits datetime.time(hours, minutes, seconds)
seconds = 0

while workingObj.time() ! = idealTimeObj:
   workingObj += secIncre #Increase workingObj by one second
seconds += 1

print seconds


That should, in theory, give the number of seconds between the current
time, and the desired time.

Of course, if you used a datetime.datetime object, and asked your user
to set the desired date, you could use -

nowDateTime=datetime.datetime.now()
desiredDateTime = datetime.datetime(year, month, day, hours, minutes seconds)

difference = desiredDateTime - nowDateTime

print difference

x days, y hours, q minutes, r seconds.

totalSec = (x*86400)+(y*3600)+(q*60)+r

Of course, getting x, y, q, and r is a bit  finicky,

Or, for your purposes - 

curDateTime = datetime.datetime.now()
wakeup=raw_input( "enter time in 24 hour format for alarm - in this
format HH:MM:SS")
wakeup=wakeup.split(":")

#Going to assume that valid input was entered
timeinfo=[]
for element in wakeup:
  t = int(element)
  timeinfo.append(t)

desiredDateTime = curDateTime.replace(t[0], t[1], t[2]) #hours,
minutes, seconds

if curDateTime > = desiredDateTime: 
#As both times will be on same day, if desired time is previous to
current date, then make it #time for next day.
  dayIncre=datetime.timedelta(days=1)
   desiredDateTime += dayIncre

difference = desiredDateTime - curDateTime

#Now do some sort of split of difference, as difference will be in x
days, y hours, m minutes, #s seconds format. As I said, I have no
interpreter so I can't check this out.

So yeah, that's a couple of different ways I'd do it using datetime,
but someone else will no doubt do it better and simpler.

HTH

Liam Clarke
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] gzip (fwd)

2004-12-05 Thread Liam Clarke
Heh, I was just pointing out his missing separator was causing his
function to fail.

: )




On Sun, 5 Dec 2004 17:06:17 -0500, Jacob S. <[EMAIL PROTECTED]> wrote:
> Hello!
> 
> 
> 
> > >target_dir = 'D:\\backup'
> > >target = target_dir +"Zipnametoreplacestrftimeformatstring"+ '.zip'
> >
> > Just noticed this -
> >
> > target_dir("D:\\backup") + "Zipnametoreplacestrftimeformatstring"+ '.zip'
> >
> > = D:\\backupZipnametoreplacestrftimeformatstring.zip
> >
> > No wonder it doesn't work.
> >
> > Try
> >
> > target=target_dir+'\\'+time.strftime('%Y%m%d%H%M%S') + '.zip'
> 
> Instead of doing this, use os.path.join to make it more platform
> independent.
> 
> target = os.path.join(target_dir,time.strftime('%Y%m%d%H%M%S')+'.zip')
> 
> 
> 
> >
> > Regards,
> >
> > Liam Clarke
> >
> > PS Yes, do use reply to all
> >
> >
> >
> >
> > On Fri, 3 Dec 2004 15:16:27 +0600, Ramkumar Parimal Alagan
> > <[EMAIL PROTECTED]> wrote:
> > > I have only 2 word documents in both the directories, i tried removing
> > > '-qr' too, but no change, no zip files formed. i'm using windows XP.
> > >
> > > On Thu, 2 Dec 2004 23:54:11 -0800 (PST), Danny Yoo
> > >
> > >
> > > <[EMAIL PROTECTED]> wrote:
> > > > Hi Ramkumar,
> > > >
> > > > I'm forwarding your message to Python-tutor; in your replies, please
> make
> > > > sure that you are using the "reply-to-all" feature in your email
> client.
> > > > This will allow your response to reach the others on the tutor list.
> > > > Don't rely on me alone: give the community the chance to help you.
> > > >
> > > > I don't have enough information to pinpoint what the problem is yet.
> I'll
> > > > have to ask more questions, and others on the Tutor list will probably
> > > > also ask a few questions.  Please try to answer them, because that
> will
> > > > help us give a better idea of what the problem is.
> > > >
> > > > It looks like you are trying to zip up whole directories.  Does the
> > > > program work if you zip up single files?
> > > >
> > > > It also appears that you're using the '-q' and '-r' options of the
> 'zip'
> > > > command line utility.  '-q' stands for 'quiet' mode, and although
> that's
> > > > nice when the command is working properly, it's not helpful when
> you're
> > > > debugging a situation.  Try turning quiet mode off, so that you have a
> > > > better chance of getting good error output from the zip command.  Even
> > > > better, try enabling verbose mode, so you can see better what 'zip' is
> > > > attempting to do.
> > > >
> > > > Do you see anything else when you execute the program?  Does anything
> else
> > > > come out of standard error?
> > > >
> > > > Good luck to you.
> > > >
> > > > -- Forwarded message --
> > > > Date: Fri, 3 Dec 2004 10:24:15 +0600
> > > > From: Ramkumar Parimal Alagan <[EMAIL PROTECTED]>
> > > > To: Danny Yoo <[EMAIL PROTECTED]>
> > > > Subject: Re: [Tutor] gzip
> > > >
> > > > This is what i intend to do:
> > > >
> > > > 1. The files and directories to be backed up are given in a list.
> > > > 2. The backup must be stored in a main backup directory.
> > > > 3. The files are backed up into a zip file.
> > > > 4. The name of the zip archive is the current date and time.
> > > >
> > > > the coding:
> > > >
> > > > __
> > > >
> > > > import os
> > > > import time
> > > >
> > > > source = ['D:\\down', 'D:\\Pics']
> > > >
> > > > target_dir = 'D:\\backup'
> > > >
> > > > target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
> > > >
> > > > zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
> > > >
> > > > if os.system(zip_command) == 0:
> > > > print 'Successful backup to', target
> > > > else:
> > > > print 'Backup FAILED'
> > > >
> > > > _
> > > >
> > > > result : Backup FAILED
> > > >
> > > > whats wrong ?
> > > >
> > > >
> > >
> > >
> > > --
> > >
> > >  <<  The end depends upon the beginning. >>
> > >
> > >
> > > ___
> > > Tutor maillist  -  [EMAIL PROTECTED]
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> >
> >
> > --
> > 'There is only one basic human right, and that is to do as you damn well
> please.
> > And with it comes the only basic human duty, to take the consequences.
> > ___
> 
> 
> > Tutor maillist  -  [EMAIL PROTECTED]
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
> 
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] CGI Video collection application File I/O troubles

2004-12-05 Thread Liam Clarke
Try an intermediate step 
videodb={'title':title,'year':year,'director':director}

x=videodb['title'] #Sometimes this helps
print type(x)#Check x is a string
print x #see if it's got stuff

#save to database
try:
  f=open(filename,'w')
except TypeError:
  print "the error is occurring on opening the file, which would mean
that it's variable filename which is causing the problem."
try:
f.write(x)
except TypeError:
   print "The error is occurring on writing to the file, which means
the written values need to be checked."
f.close()

Good luck,

Liam Clarke






On Sun, 5 Dec 2004 17:46:39 -0500, Jacob S. <[EMAIL PROTECTED]> wrote:
> Your error message says that you are getting an empty string from your cgi
> variable. I IMHO would suggest printing videodb['title'] before writing it
> to a file to see what the variable contains. Or you might print out videodb
> to see what the dictionary looks like. My off the wall guess is that 1) Your
> cgi variables are not returning the value from the actual object that you
> want 2) The script is running and assigning values to title, etc. before the
> afore mentioned object is given a value. IOW, maybe you haven't assigned
> values to the form before you try to read them.
> Another suggestion. Comment out the file writing part and print everything
> to the screen to verify that the output is what you want. "When in doubt,
> print it out." - Jacob Schmidt
> 
> HTH,
> Jacob
> 
> 
> 
> > Quoting "Jacob S." <[EMAIL PROTECTED]>:
> >
> > > Hi!
> > >
> > > Can I ask a few questions? (Other than this one...)
> > > What output did you expect? A string, tuple, or what?
> >
> > A string output. When I create a dictionary variable from
> > the python shell like this:
> > videodb={'title':'Crash','year':'1996','director':'David Cronenberg'}
> >
> > and type in videodb['title'] afterwards python spits out the
> > value 'Crash'. That's fine I get a string as expected.
> > But when I try to write the value of videodb['title'] to
> > a file nothing gets written.
> > I hope I clarified the issue somewhat.
> >
> > > I'm not strong with
> > > cgi stuff.
> > > Also, you don't need the string module 1) because you don't use it 2)
> > > because you can use string methods.
> > >
> > > Jacob Schmidt
> >
> > ok. I'll remove it. thanx.
> >
> > [snip]
> >
> > --
> > The lady on the call box in Monkey Island 2
> > Guybrush: I'm lost in the Inky Island Jungle in Monkey 2
> > Lady: Just walk off the edge of the screen
> >
> >
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re:[Tutor] Address book sort of

2004-12-05 Thread Liam Clarke
Oops

I've got my own wee dictionary reader, writers. Very simple -

So, you have a user Dave, who has a dictionary of {'address':'21 jump
St', 'Number: 'One, the loneliest.'}

So, you create a dictionary of dictionaries -myDict = {'Dave' :
{'address':'21 jump St', 'Number: 'One, the loneliest.'}

And then you have -
def writeDict(file, diction):
inp=file(file, 'w')

for (key, item) in diction.items():
  inp.write(key+'\n')
  inp.write(item+'\n')
inp.close()

return 1

Courtesy of Danny Yoo, the very helpful pair generating function below
(it's indispensable this one, I use it so often)

def groupAdjacentElements(someSequence, n = 2):
"""A little helper utility to group up adjacent elements."""
nextGroup = []
for element in someSequence:
nextGroup.append(element)
if len(nextGroup) == n:
yield tuple(nextGroup)
nextGroup = []

Goes with -

def loadDict(filename):
   store2 = file(filename,'r')

   for (name, entry) in groupAdjacentElements(store2):
 name = name.strip()
 entry = entry.strip()
 book[name] = entry

   store2.close()
   return book

So - to save myDict to saveddic.dct -

writeDict('saveddic.dct', myDict)

and to open it -

myDictCopy=loadDict('saveddic.dct')

And it saves in the format -

dave
{'address':'21 Jump St', 'number':'One, the loneliest'}
key
value
key
value

Nice and plaintext.

HTH




On Sun, 5 Dec 2004 16:31:59 -0500, Jacob S. <[EMAIL PROTECTED]> wrote:
> I did something like this about three or four months ago...
> This is what I did. Notice the use of the built-in str() and eval()
> functions to write and receive data to and from Telephone.cfg...
>
> from __future__ import division
> tel = {}
> try:
> file = open('Telephone.cfg', 'r')
> except:
> file = open('Telephone.cfg','w')
> file.close()
> file = open('Telephone.cfg','r')
> try:
> tel = eval(file.read())
> a = 0
> except:
> a = 1
> print "No entries on file."
> pass
> print """\
> Commands are:
> add
> get
> save
> delete
> quit
> all is a wildcard
> """
>
> while 1:
> ask = raw_input('Tell me what you wish to do. ')
> if ask == "quit":
> break
> ask = ask.split(" ")
> command = ask[0]
> entity = ask[1:]
> entity = " ".join(entity)
> if entity == '':
> entity = raw_input("Who do you want to %s? " % command)
> if command == 'add':
> person = entity
> if tel.has_key(person):
> print "That person is already in there. If you wish to edit the
> file, please delete the record first."
> else:
> tel[person] = raw_input("What is their phone number? ")
> if command == 'get':
> if a == 1:
> print "Sorry, there are no entries available."
> else:
> person = entity
> if person == 'all':
> key = tel.keys()
> key.sort()
> print
> for x in key:
> print "%s\n%s\n" % (x,tel[x])
> elif tel.has_key(person):
> print "\n%s\n%s\n" % (person,tel[person])
> else:
> print "%s is not in your records." % person
> if command == 'save':
> file=open('Telephone.cfg', 'w')
> file.write(str(tel))
> file.close()
> print 'Saved in Telephone.cfg'
> if command == 'delete':
> if a == 1:
> print "Sorry, there are no entries available."
> else:
> person = entity
> if person == 'all':
> tel={}
> newfile=open('Telephone.cfg', 'w')
> newfile.close()
> else:
> if tel.has_key(person):
> del tel[person]
> else:
> print "%s is not in your records." % person
> file.close()
> file = open('Telephone.cfg', 'w')
> file.write(str(tel))
> file.close()
>
> As always, feel free to modify, use, and otherwise tear apart my code and
> give me suggests on how to improve it.
> Jacob Schmidt
>
>
>
> > Dear Tutor,
> >
> > I like to know what is the proper procedure (is algorithmn the right
> > term?) in creating data in a program, write it to file, close the app
> > then retrieve the data when run again. Basically, I'm trying to simulate
> > a simple address book (well not really for the datas are just names for
> > now) and so far have created the basic menu interface. It is console
> > base so forget gui. I ask user input and store it in a list. There are
> > menus to change, delete the data, and to save the data list in file. I
> > use cPickle for this and have verified the file is created by checking
> > in my $PWD. I want to retrieve that data when program is run again. What
> > to add in my code? I thought not to post the code but explain it as
> > above.
> >
> > What i want: when program is run again, the saved data is loaded when user
> > selects optio

Re: [Tutor] Could I have used time or datetime modules here?

2004-12-05 Thread Liam Clarke
Best thing in Python, I reckon, is an interpreter to check out your code.
I find it hard to answer queries in this list when I don't have
Pythonwin open to check what I'm suggesting works!



On Mon, 6 Dec 2004 18:27:49 +1300, Liam Clarke <[EMAIL PROTECTED]> wrote:
> Ah,  nope. : )
> 
> >>> x="1234"
> >>> y=x.split(":")
> >>> print y
> ['1234']
> 
> And I'm checking for y having 3 items exactly.
> 
> 
> 
> 
> On Sun, 05 Dec 2004 19:02:39 -0800, Dick Moores <[EMAIL PROTECTED]> wrote:
> > Brian van den Broek wrote at 16:53 12/5/2004:
> >
> >
> > >Dick Moores said unto the world upon 2004-12-05 15:03:
> > >>Thanks, Brian. I looked at your code a long time, and also read the
> > >>11/26 thread you started. I can see how I could use datetime() and your
> > >>t2 - t1 to get the seconds for time.sleep(), but  the resulting code I
> > >>have in mind is more convoluted than the heart of my timer3.py, which I
> > >>quote below.  (I don't need the alarm time to be more than 24 hours
> > >>from current time--therefore I want to ignore the year, month, and day.)
> > >>===
> > >>import time
> > >>alarm = raw_input("Enter alarm time as hhmm: ")
> > >>now = time.strftime("%X")  # produces current time in format  hh:mm:ss
> > >>nowSecond = int(now[6:])
> > >>nowMinute = int(now[3:5])
> > >>nowHour = int(now[0:2])
> > >>alarmMinute = int(alarm[2:4])
> > >>alarmHour = int(alarm[0:2])
> > >>hoursDiff = alarmHour - nowHour
> > >>minutesDiff = alarmMinute - nowMinute
> > >>if hoursDiff < 0 or (hoursDiff == 0 and minutesDiff <= 0):
> > >> hoursDiff = hoursDiff + 24 # add a day
> > >>sleepSeconds = hoursDiff*3600 + minutesDiff*60 - nowSecond
> > >>time.sleep(sleepSeconds)
> > >>
> > >>If I'm wrong, could someone please set me right?
> > >>Dick
> > >
> > >Hi Dick and all,
> > >
> > >sorry I was too lazy to follow your link before, Dick. Thanks for
> > >posting the relevant portions.
> > >
> > >I took another run, but my code is a lot longer as I put in some error
> > >checking on the input request -- hope you don't mind ;-) (I might have
> > >gone overboard -- I did it to learn how as much as anything else.)
> > >
> > >I suspect that my way is easier than yours. (I don't know about Liam's.
> > >His came in as I was writing mine, and I've not read his closely yet.)
> > >
> > >In mine, the key bit is that if you have two datetime objects, d1 and
> > >d2, d1 - d2 gives a timedelta object expressing the time difference
> > >between them in the form (days, seconds, microseconds). So, the datetime
> > >module seems to do the work you want -- just make the current time a
> > >datetime object, use the user input to get a datetime object in the
> > >future and then find their timedelta and ask it for its seconds
> > >attribute. This disregards any difference in days and gives only the
> > >hour + minute + seconds difference expressed in seconds.
> > >
> > >That logic is near the bottom, though, as first you've got to read
> > >through my error checking code ;-)
> > >
> > >I tested it pretty well, but as always, undetected errors entitle you to
> > >a full refund of purchase price. (Minus a reasonable handling fee, of
> > >course.)
> > >
> > >I hope this is of some use to you.
> > >
> > >Best to all,
> > >
> > >Brian vdB
> > >
> > >CODE:
> > >
> > >import datetime
> > >import time
> > >
> > >def get_alarm_time():
> > > '''Asks user for a time in the form 'hh:mm' and return tuple of ints.
> > >
> > > Includes error checking to make sure user input really is of form
> > > 'hh:mm' where the values of 'hh' and 'mm' are appropriate.
> > > '''
> > > while True:
> > > alarm_time = raw_input("Enter alarm time as hh:mm")
> > > er_msg = '''
> > > An alarm time must be entered in the format 'hh:mm' where 'hh'
> > > is a number between 0 and 23 inclusiv

Re: [Tutor] Address book sort of

2004-12-05 Thread Liam Clarke
[quote]
if select == '1' or select == 'v' or select == 'V':
if file_in_disk in os.listdir('/home/jerimed'): # change???
fhandle = open(file_in_disk, 'r')   # read mode
cPickle.load(fhandle)   # restore saved data
fhandle.close()
show_contacts()
elif len(data_holder) > 0:
show_contacts()
else:
is_empty()
[/quote]

if file_in_disk in os.listdir('/home/jerimed'):  - 

if os.path.exists('/home/jerimed/file_in_disk'):

Oh, and if it's in a subdir off the current dir - 

if os.path.exists('./home/jerimed/file_in_disk'):

"./' means current

or you could use - 
path = os.path.join(os.getcwd(), 'home','jerimed','filename')

[quote]How do i pretty print output of dictionary container? Sort of tabular
form or something, e.g.,

1. name1email address1
2. name2email address2[/quote]

try this - 

index = 0 
for (key, item) in myDict.items():
  index += 1
  print "%d. %s \t %s" % (index, key, item)

Although you may find that the length of key will vary, making it look messy. 

So, find the max length of the keys (names) first - 

highLength=0
for element in myDict.keys():
 if len(element) > highLength:
  highLength = len(element)

index = 0
minimumSpaces= 5
for (key, item) in myDict.items():
  index += 1
  spaceMult=(highLength+minimumSpaces)-len(key)
  outString=str(index)+". "+key+(spaceMult * " ") + item
  print outString


What this line spaceMult=(highLength+minimumSpaces)-len(key) does - 

So, say you have two names -

Bob
Bobalicious 

obviously one tab(which Python usually counts as four spaces)
separating will be

BobBob's email
BobaliciousBobalicious' email

spaceMult=(highLength+minimumSpaces)-len(key)

highLength is 11, the length of Bob. The minimum separation between
key and item is 5 spaces, so we're looking for the item to be 16 chars
away from the start of the line.

so spaceMult=(11+5)-len('bob') 
spaceMult = 13

So, the function will pad 13 spaces between 'bob' and 'bob's email'
whereas only the minimum 5 between Bobalicious and his email.

Which should equal nicely laid out.

Haven't tested this though...

Standard disclaimer - 

There's probably an easier way to do it, and a more elegant way. Which
someone will post shortly.

Cheers,

Liam Clarke




On Mon, 6 Dec 2004 07:55:11 +0300 (Arab Standard Time), Eri Mendz
<[EMAIL PROTECTED]> wrote:
> On Sun, 5 Dec 2004, Jacob S. wrote:
> 
> > I did something like this about three or four months ago...
> > This is what I did. Notice the use of the built-in str() and eval()
> > functions to write and receive data to and from Telephone.cfg...
> 
> Thanks a lot Jacob, and to all who replied. I'll go through the code
> definitely. I started building that address book last night and its
> pretty crude. I hit a snag though: i was able to save the name/email
> address pairs and write to disk. But i cant get it to load on startup. My
> location is several dirs down my home directory. Of course the pickled
> file is in same directory as the code. Its something like:
> 
>  if select == '1' or select == 'v' or select == 'V':
>  if file_in_disk in os.listdir('/home/jerimed'): # change???
>  fhandle = open(file_in_disk, 'r')   # read mode
>  cPickle.load(fhandle)   # restore saved data
>  fhandle.close()
>  show_contacts()
>  elif len(data_holder) > 0:
>  show_contacts()
>  else:
>  is_empty()
> 
> /home/jerimed should be changed and should be dynamic to match wherever
> the python script is. Can you guyz advise? And is that first
> if-statement right? I like to know if im doing the right thing.
> 
> How do i pretty print output of dictionary container? Sort of tabular
> form or something, e.g.,
> 
> 1. name1email address1
> 2. name2email address2
> 
> Just for my learning experience :-). Thanks!
> 
> --
> Regards,
> Eri Mendz
> 
> 
> 
> 
> >
> > from __future__ import division
> > tel = {}
> > try:
> >file = open('Telephone.cfg', 'r')
> > except:
> >file = open('Telephone.cfg','w')
> >file.close()
> >file = open('Telephone.cfg','r')
> > try:
> >tel = eval(file.read())
> >a = 0
> > except:
> >

Re: [Tutor] Address book sort of

2004-12-05 Thread Liam Clarke
Just tested the setout thing. It works. Prolly a hack, but it works.


On Mon, 6 Dec 2004 19:05:58 +1300, Liam Clarke <[EMAIL PROTECTED]> wrote:
> [quote]
> 
> 
> if select == '1' or select == 'v' or select == 'V':
> if file_in_disk in os.listdir('/home/jerimed'): # change???
> fhandle = open(file_in_disk, 'r')   # read mode
> cPickle.load(fhandle)   # restore saved data
> fhandle.close()
> show_contacts()
> elif len(data_holder) > 0:
> show_contacts()
> else:
> is_empty()
> [/quote]
> 
> if file_in_disk in os.listdir('/home/jerimed'):  -
> 
> if os.path.exists('/home/jerimed/file_in_disk'):
> 
> Oh, and if it's in a subdir off the current dir -
> 
> if os.path.exists('./home/jerimed/file_in_disk'):
> 
> "./' means current
> 
> or you could use -
> path = os.path.join(os.getcwd(), 'home','jerimed','filename')
> 
> [quote]How do i pretty print output of dictionary container? Sort of tabular
> form or something, e.g.,
> 
> 1. name1email address1
> 2. name2email address2[/quote]
> 
> try this -
> 
> index = 0
> for (key, item) in myDict.items():
>   index += 1
>   print "%d. %s \t %s" % (index, key, item)
> 
> Although you may find that the length of key will vary, making it look messy.
> 
> So, find the max length of the keys (names) first -
> 
> highLength=0
> for element in myDict.keys():
>  if len(element) > highLength:
>   highLength = len(element)
> 
> index = 0
> minimumSpaces= 5
> for (key, item) in myDict.items():
>   index += 1
>   spaceMult=(highLength+minimumSpaces)-len(key)
>   outString=str(index)+". "+key+(spaceMult * " ") + item
>   print outString
> 
> What this line spaceMult=(highLength+minimumSpaces)-len(key) does -
> 
> So, say you have two names -
> 
> Bob
> Bobalicious
> 
> obviously one tab(which Python usually counts as four spaces)
> separating will be
> 
> BobBob's email
> BobaliciousBobalicious' email
> 
> spaceMult=(highLength+minimumSpaces)-len(key)
> 
> highLength is 11, the length of Bob. The minimum separation between
> key and item is 5 spaces, so we're looking for the item to be 16 chars
> away from the start of the line.
> 
> so spaceMult=(11+5)-len('bob')
> spaceMult = 13
> 
> So, the function will pad 13 spaces between 'bob' and 'bob's email'
> whereas only the minimum 5 between Bobalicious and his email.
> 
> Which should equal nicely laid out.
> 
> Haven't tested this though...
> 
> Standard disclaimer -
> 
> There's probably an easier way to do it, and a more elegant way. Which
> someone will post shortly.
> 
> Cheers,
> 
> Liam Clarke
> 
> 
> 
> 
> On Mon, 6 Dec 2004 07:55:11 +0300 (Arab Standard Time), Eri Mendz
> <[EMAIL PROTECTED]> wrote:
> > On Sun, 5 Dec 2004, Jacob S. wrote:
> >
> > > I did something like this about three or four months ago...
> > > This is what I did. Notice the use of the built-in str() and eval()
> > > functions to write and receive data to and from Telephone.cfg...
> >
> > Thanks a lot Jacob, and to all who replied. I'll go through the code
> > definitely. I started building that address book last night and its
> > pretty crude. I hit a snag though: i was able to save the name/email
> > address pairs and write to disk. But i cant get it to load on startup. My
> > location is several dirs down my home directory. Of course the pickled
> > file is in same directory as the code. Its something like:
> >
> >  if select == '1' or select == 'v' or select == 'V':
> >  if file_in_disk in os.listdir('/home/jerimed'): # change???
> >  fhandle = open(file_in_disk, 'r')   # read mode
> >  cPickle.load(fhandle)   # restore saved 
> > data
> >  fhandle.close()
> >  show_contacts()
> >  elif len(data_holder) > 0:
> >  show_contacts()
> >  else:
> >  is_empty()
> >
> > /home/jerimed should be changed and should be dynamic to match wherever
> > the python script is. Can you guyz advise? And is that first
> > if-statement right? 

Re: [Tutor] psyco 1.3 is out, with support for Python 2.4

2004-12-06 Thread Liam Clarke
Have you used Pysco much Dick? Is it n00bie friendly?

Or, to put it another way, at what point in a programme's size/speed
does it become worthwhile to implement Pysco?

Regards,

Liam Clarke

On Sun, 05 Dec 2004 23:49:03 -0800, Dick Moores <[EMAIL PROTECTED]> wrote:
> <http://psyco.sourceforge.net/>
> 
> And "The Ultimate Psyco Guide" for 1.3 is at
> <http://psyco.sourceforge.net/psycoguide/index.html>
> 
> Dick Moores
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Could I have used time or datetime modules here?

2004-12-06 Thread Liam Clarke
Hey Dick, don't know if anyone actually answered your original question.

>IOW, is there an easier way to calculate the time difference between the
>time now, say 08:51 and say, tomorrow at 03:45, to take an example of the
>most difficult case?

So, you need two datetime.datetime objects.

>>>now = datetime.datetime(year, month, day, hours, minutes, seconds)
>>>now = datetime.datetime(2004, 12, 7*, 8*, 51, 00)
>>> later= datetime.datetime(2004, 12, 8*, 3*, 45, 00)

 *Can't start with zero. Must be 8 not 08

>>> difference = later - now
>>> print difference
18:54:00
>>> type(difference)

>>> timeList=str(difference).split(":")
>>> print timeList
['18', '54', '00']
>>> timeinSecs=(int(timeList[0])*3600)+(int(timeList[1])*60)+int(timeList[2])
>>> print timeinSecs
68040

Now, to check if that's right...

>>> timeChange=datetime.timedelta(seconds=68040)
>>> checkVal=now + timeChange
>>> print checkVal
2004-12-08 03:45:00

Looks good to me.

So, to summarise the code part -

now = datetime.datetime(2004, 12, 7, 8, 51, 00)
later= datetime.datetime(2004, 12, 8, 3, 45, 00)
difference = later - now
timeList=str(difference).split(":")
timeinSecs=(int(timeList[0])*3600)+(int(timeList[1])*60)+int(timeList[2])

And that's the easier way to find the difference between two times in seconds.

HTH

Liam Clarke

P.S. If you're interested, here's a 20 line alarm clock I wrote
because my one broke this morning.

http://www.rafb.net/paste/results/ctOH1T36.html




On Mon, 06 Dec 2004 02:15:55 -0800, Dick Moores <[EMAIL PROTECTED]> wrote:
> Hey, no problem. And thanks again for your help.
>
> Dick
>
> Liam Clarke wrote at 02:05 12/6/2004:
> >Whoops, sorry. 
>
>


--


'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Finding a part of an element in a list

2004-12-06 Thread Liam Clarke
Hey Kumar, 

nearly there - 

List1 =
['Tyres','windsheild','A\CUnit','Model=Toyota_Corolla']

In other list I have :
List2= ['Corolla','Accord','Camry']

for element1 in List1:
  for element2 in List2:
 if element2 in element1:
  #Do something here, usually a break or continue clause

(Incidentally,'for element in list' is an easier version of for i in
range(len(list)) when you don't need to use index numbers. It just
steps element by element.)

'if x in y' works for strings within strings as well.

Regards,

Liam Clarke



On Mon, 6 Dec 2004 09:57:11 -0800 (PST), kumar s <[EMAIL PROTECTED]> wrote:
> Dear Group,
> 
> I have a list that is:
> 
> List1 =
> ['Tyres','windsheild','A\CUnit','Model=Toyota_Corolla']
> 
> In other list I have :
> List2= ['Corolla','Accord','Camry']
> 
> I want to see if Corolla is there in list 1:
> 
> The code:
> for i in range(len(List1)):
>  if i in range(len(List2):
>   print i
> 
> If I have 'Corolla' as an element in both list then it
> is easy to find.  However, in List1 this element
> appears as 'Model=Toyota_Corolla'.
> 
> How can I ask python to match both elements:
> 'Model=Toyota_Corolla' and 'Corolla', where a part of
> element is matching.
> 
> please help.
> 
> thanks
> 
> 
> __
> Do you Yahoo!?
> All your favorites on one personal page â Try My Yahoo!
> http://my.yahoo.com
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 2.3.5 out in January??

2004-12-07 Thread Liam Clarke
Sometimes I suspect XP is the latest 3.11 beta. ;)


On Tue, 07 Dec 2004 01:41:05 -0800, Dick Moores <[EMAIL PROTECTED]> wrote:
> Just saw this on comp.lang.python.announce.
> 
> 
> I don't understand this. Why is a new version of 2.3 being worked on
> after 2.4 has been released?
> 
> I see Tim Peters has said this on python-list:
> ===begin Tim Peters' post===
> [Brett C]
>  >> Anthony Baxter, our ever-diligent release manager, mentioned this
> past week
>  >> that Python 2.3.5 will most likely come to fruition some time in January
>  >> (this is not guaranteed date).
> 
> [Roy Smith]
>  > Interesting.  Does that mean that 2.3 and 2.4 will be maintained in
>  > parallel for a while?  That would be awesome.
> 
> They'll be maintained in parallel through 2.3.5 in January, which is
> all Brett said.  If history is a guide, after 2.3.5 nobody will
> volunteer to work on a 2.3.6, and 2.3.5 will be the last release in
> the 2.3 line.  It's *possible* that volunteers for 2.3.6 will appear.
> That would be unprecedented, but not impossible ...
> end TP's post
> 
> I ask here because I'm sure it's a newbie question. It's got me wondering
> if Microsoft is still working on Windows 3.1..  ;-)
> 
> Thanks,
> 
> Dick Moores
> [EMAIL PROTECTED]
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] String matching?

2004-12-07 Thread Liam Clarke
Hi all, 

I have a large amount of HTML that a previous person has liberally
sprinkled a huge amount of applets through, instead of html links,
which kills my browser to open.

So, want to go through and replace all applets with nice simple links,
and want to use Python to find the applet, extract a name and an URL,
and create the link.

My problem is, somewhere in my copying and pasting into the text file
that the HTMl currently resides in, it got all messed up it would
seem, and there's a bunch of strange '=' all through it. (Someone said
that the code had been generated in Frontpage. Is that a good thing or
bad thing?)

So, I want to search for http://www.rafb.net/paste/results/WcKPCy64.html)

So, I want to be write a search that will match http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Could I have used time or datetime modules here?

2004-12-07 Thread Liam Clarke
Hi all,

>I like your alarm clock a lot,
><http://www.rafb.net/paste/results/ctOH1T36.html>. I first tried to run
>it with IDLE, then remembered that mscvrt won't catch keypresses if run
>with IDLE. Works fine in the console!

>Instead of your beeps in the second while loop, I think I'd need

>winsound.PlaySound('SystemAsterisk', winsound.SND_ALIAS)
>winsound.PlaySound('SystemHand', winsound.SND_ALIAS)

>and turn my speakers way up!


Heh, I use headphones,  but speakers would be better. I'm sure you
could play an mp3 also.

But, I actually made a mistake in my alarm clock in that 

desiredTime.datetime.time(6,00,00)
is now desiredTime=datetime.datetime(2004,12,8,6, 00, 00)

while nowTime.time < desiredTime:

is now

while nowTime < desiredTime:

because, I wrote the alarm clock after midnight! If I had run it
before 11:59pm my while condition would've been True immediately, so I
changed desiredTime to a datetime object.

Alternatively, I could have just changed

checkPeriod=5 #minutes
nowTime=datetime.datetime.now()
startTime=nowTime

while nowTime.time() < desiredTime or nowTime.time() > startTime.time():

But Occam's Razor works better.

>Brian, where did you learn about the ".seconds". And the .year, .month,
>.day of

What's funny, is that after I'd gone to bed that night, I suddenly
woke up and thought "Hang on, what about the attribute .seconds of a
datetime object? I better check that out."

Which I promptly forgot about until your last reply.

Heh.

Liam Clarke

On Tue, 07 Dec 2004 09:04:46 -0800, Dick Moores <[EMAIL PROTECTED]> wrote:
> Brian van den Broek wrote at 07:50 12/7/2004:
> 
> 
> >Dick Moores said unto the world upon 2004-12-07 07:04:
> >>To Liam and Brian,
> >
> >
> >
> >>Here's Brian's script in it's bare bones, without the input error
> >>checking and his extensive and helpful comments:
> >>===begin code
> >>import datetime
> >>import time
> >>alarm_time = raw_input("Enter alarm time as hh:mm ")
> >>alarm_time_list = alarm_time.split(':')
> >>alarm_hour, alarm_minute = (int(alarm_time_list[0]),
> >> int(alarm_time_list[1]))
> >>now = datetime.datetime.now()
> >>alarm_datetime = datetime.datetime(now.year+4, now.month, now.day,
> >>alarm_hour, alarm_minute)
> >>print alarm_datetime
> >>alarm_in_seconds = (alarm_datetime - now).seconds
> >>print "I should wake up in %d seconds" % alarm_in_seconds
> >>time.sleep(alarm_in_seconds)
> >>print "I'm awake!"
> >>end code=
> >
> >
> >
> >>Brian, where did you learn about the ".seconds". And the .year, .month,
> >>.day of
> >>"alarm_datetime = datetime.datetime(now.year + 4, now.month, now.day,
> >>alarm_hour, alarm_minute)"?
> >>Does this come from a general knowledge of OOP, or is it somewhere in
> >>the Python docs? The only thing I've seen, and it's not an explanation,
> >>is in note (1) on http://docs.python.org/lib/datetime-date.html
> >
> >Oh Sir, you flatter me! My general knowledge of OOP is about the same as
> >my general knowledge of the migration patterns of Siberian water-fowl. ;-)
> >
> >After Anna, Gonçalo, and Liam encouraged me to explore the datetime
> >module, I read (OK, skimmed) the docs. For my original purpose, I just
> >needed to test two times with '>', but I recalled something about
> >timedelta objects being returned by subtracting one datetime from
> >another. I hadn't used them before I wrote my script in reply to you. I
> >learned about the handy for your purposes .seconds attribute in the
> >Library Reference -- 6.10.2 timedelta Objects. (That's the section name
> >in the 2.4 installed docs; I'm typing off line so can't [OK, won't] get
> >a link.)
> >
> >>It seems I've missed out on something important
> >>BTW I'm not sure you need the +4 of "now.year + 4". I've run this
> >>without the +4 and it doesn't seem to be needed. And notes (1) and (4)
> >>on that page seem to say this, as far as I understand them.
> >
> >I'm not sure I do either :-)
> >
> >Here's why I did it:
> >
> >I discovered that in order to get the right "seconds until alarm" value
> >from the datetime for now and the alarm datetime

Re: [Tutor] Re: Could I have used time or datetime modules here?

2004-12-07 Thread Liam Clarke
False, I meant false. Ack, need coffee.

>while nowTime < desiredTime:

>because, I wrote the alarm clock after midnight! If I had run it
>before 11:59pm my while condition would've been True immediately, so I
>changed desiredTime to a datetime object.


On Wed, 8 Dec 2004 06:50:22 +1300, Liam Clarke <[EMAIL PROTECTED]> wrote:
> Hi all,
> 
> 
> 
> >I like your alarm clock a lot,
> ><http://www.rafb.net/paste/results/ctOH1T36.html>. I first tried to run
> >it with IDLE, then remembered that mscvrt won't catch keypresses if run
> >with IDLE. Works fine in the console!
> 
> >Instead of your beeps in the second while loop, I think I'd need
> 
> >winsound.PlaySound('SystemAsterisk', winsound.SND_ALIAS)
> >winsound.PlaySound('SystemHand', winsound.SND_ALIAS)
> 
> >and turn my speakers way up!
> 
> 
> Heh, I use headphones,  but speakers would be better. I'm sure you
> could play an mp3 also.
> 
> But, I actually made a mistake in my alarm clock in that
> 
> desiredTime.datetime.time(6,00,00)
> is now desiredTime=datetime.datetime(2004,12,8,6, 00, 00)
> 
> while nowTime.time < desiredTime:
> 
> is now
> 
> while nowTime < desiredTime:
> 
> because, I wrote the alarm clock after midnight! If I had run it
> before 11:59pm my while condition would've been True immediately, so I
> changed desiredTime to a datetime object.
> 
> Alternatively, I could have just changed
> 
> checkPeriod=5 #minutes
> nowTime=datetime.datetime.now()
> startTime=nowTime
> 
> while nowTime.time() < desiredTime or nowTime.time() > startTime.time():
> 
> But Occam's Razor works better.
> 
> >Brian, where did you learn about the ".seconds". And the .year, .month,
> >.day of
> 
> What's funny, is that after I'd gone to bed that night, I suddenly
> woke up and thought "Hang on, what about the attribute .seconds of a
> datetime object? I better check that out."
> 
> Which I promptly forgot about until your last reply.
> 
> Heh.
> 
> Liam Clarke
> 
> 
> 
> On Tue, 07 Dec 2004 09:04:46 -0800, Dick Moores <[EMAIL PROTECTED]> wrote:
> > Brian van den Broek wrote at 07:50 12/7/2004:
> >
> >
> > >Dick Moores said unto the world upon 2004-12-07 07:04:
> > >>To Liam and Brian,
> > >
> > >
> > >
> > >>Here's Brian's script in it's bare bones, without the input error
> > >>checking and his extensive and helpful comments:
> > >>===begin code
> > >>import datetime
> > >>import time
> > >>alarm_time = raw_input("Enter alarm time as hh:mm ")
> > >>alarm_time_list = alarm_time.split(':')
> > >>alarm_hour, alarm_minute = (int(alarm_time_list[0]),
> > >> int(alarm_time_list[1]))
> > >>now = datetime.datetime.now()
> > >>alarm_datetime = datetime.datetime(now.year+4, now.month, now.day,
> > >>alarm_hour, alarm_minute)
> > >>print alarm_datetime
> > >>alarm_in_seconds = (alarm_datetime - now).seconds
> > >>print "I should wake up in %d seconds" % alarm_in_seconds
> > >>time.sleep(alarm_in_seconds)
> > >>print "I'm awake!"
> > >>end code=
> > >
> > >
> > >
> > >>Brian, where did you learn about the ".seconds". And the .year, .month,
> > >>.day of
> > >>"alarm_datetime = datetime.datetime(now.year + 4, now.month, now.day,
> > >>alarm_hour, alarm_minute)"?
> > >>Does this come from a general knowledge of OOP, or is it somewhere in
> > >>the Python docs? The only thing I've seen, and it's not an explanation,
> > >>is in note (1) on http://docs.python.org/lib/datetime-date.html
> > >
> > >Oh Sir, you flatter me! My general knowledge of OOP is about the same as
> > >my general knowledge of the migration patterns of Siberian water-fowl. ;-)
> > >
> > >After Anna, Gonçalo, and Liam encouraged me to explore the datetime
> > >module, I read (OK, skimmed) the docs. For my original purpose, I just
> > >needed to test two times with '>', but I recalled something about
> > >timedelta objects being returned by subtracting one datetime from
> > >another. I hadn't used them before I wrote my script in reply to 

Re: [Tutor] String matching?

2004-12-07 Thread Liam Clarke
Hi all, 

It's a messy situation - basically, the HTML is from a tool used at
work, which was, ahem, 'maintained' by someone who loved the flashy
bits. Like animated gifs of the bad CG baby from Ally McBeal playing
soccer with itself. So, yeah, instead of using href links, he used
Java applets. 272 of them.

Which takes appx. 2- 5min to open in Mozilla on all the older work
boxes. So someone who knows HTML has taken over, and I'm helping out.
So, I have to email changes backwards and forth, because heaven forbid
they install Python. I mean, they've already got Perl, Java, and
Visual Basic sitting there. Luckily the 'hackers' are waiting for
Python.

So, all I want to do is rip the urls from the applet, and replace it. 

>test2 = test.replace('=\n', '')
>test2 = test2.replace('=3D"', '="')

Thanks, Kent, for some reason I totally missed that.

And thanks for the re, hopefully I won't have to use it, but it gives
me a starting point to poke the re module from.

Regards,

Liam Clarke
On Tue, 07 Dec 2004 09:03:45 -0500, orbitz <[EMAIL PROTECTED]> wrote:
> Instead of copying and pasting and then just doing a simple match, why
> not use urllib2 to download the html and then run through it with HTMLParse?
> 
> 
> 
> Liam Clarke wrote:
> 
> >Hi all,
> >
> >I have a large amount of HTML that a previous person has liberally
> >sprinkled a huge amount of applets through, instead of html links,
> >which kills my browser to open.
> >
> >So, want to go through and replace all applets with nice simple links,
> >and want to use Python to find the applet, extract a name and an URL,
> >and create the link.
> >
> >My problem is, somewhere in my copying and pasting into the text file
> >that the HTMl currently resides in, it got all messed up it would
> >seem, and there's a bunch of strange '=' all through it. (Someone said
> >that the code had been generated in Frontpage. Is that a good thing or
> >bad thing?)
> >
> >So, I want to search for  >
> > >let
> > code
> >
> >or  >code
> >
> >or  >plet
> >
> >etc. etc. (Full example of yuck here
> >http://www.rafb.net/paste/results/WcKPCy64.html)
> >
> >So, I want to be write a search that will match  > >
> >I was thinking the re module is for this sort of stuff? Truth is, I
> >wouldn't know where to begin with it, it seems somewhat powerful.
> >
> >Or, there's a much easier way, which I'm missing totally. If there is,
> >I'd be very grateful for pointers.
> >
> >Thanks for any help you can offer.
> >
> >Liam Clarke
> >
> >
> >
> 
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing two elements in a list

2004-12-07 Thread Liam Clarke
Hi Kumar, 

I've been studiously avoiding re, and I think you can too for this problem - 

>I want to remove Name=Xxxx_at identifiers.

>My List:
>['Name=32972_at',
>'Cell1=432\t118\tN\tcontrol\t32972_at\t0\t13\tA\tA\tA\t0\t75952\t-1\t-1\t99\t',
>'Cell2=432\t117\tN\tcontrol\t32972_at\t0\t13\tA\tT\tA\t0\t75312\t-1\t-1\t99\t',
>'Cell3=499\t632\tN\tcontrol\t32972_at\t1\t13\tC\tC\tC\t1\t404979\t-1\t-1\t99\t']


so - 
hasName=[]
for indexNum in range(len(myList):
   if "Name=" in myList[indexNum]:
hasName.append(indexNum)

hasName.reverse()

for element in hasName:
 del myList(element)

Might be able to do it 

hasName=[]
for indexNum in myList.index(): #???
   if "Name=" in indexNum:
hasName.append(indexNum)

hasName.reverse()

for element in hasName:
 del myList(element)

But, you need a list of the index numbers of the list members to be
deleted, and then you need to reverse it... why?

aList=['b','c','d']
indexes=[0,1,2]
for element in indexes:
del aList[element]

Watch what happens as it runs.

element=0
del aList[0]
aList=['c','d']

element = 1
del aList[1]
aList=['c']

element = 2
del aList[2]

IndexError - value out of range.

Whereas - 

aList=['b','c','d']
indexes=[0,1,2]
indexes.reverse()

for element in indexes:
del aList[element]

element=2
del aList[2]
aList=['b','c']

element = 1
del aList[1]
aList=['b']

element=0
del aList[0]
aList=[]


HTH

Liam Clarke
On Tue, 7 Dec 2004 14:09:32 -0800 (PST), kumar s <[EMAIL PROTECTED]> wrote:
> Hello group,
>  Thank you very much for your kind replies. In fact I
> survived to pull out what I needed by going with
> Kent's tip by enumerating on iterator.
> 
> The problem with me is suddenly I embarked on
> something big problem and I am surviving it in pieces
> by writing pieces of code.
> 
> I have another question:
> To be brief:
> 
> My list contains some elements that I do not want and
> I want to remove unwanted elements in my list:
> 
> My TEXT file looks like this:
> 
> Name=32972_at
> Cell1=xxx   xxx N   control 32972_at
> Cell1=xxx   xxx N   control 32972_at
> Cell1=xxx   xxx N   control 32972_at
> Cell1=xxx   xxx N   control 32972_at
> Name=3456_at
> Cell1=xxx   xxx N   control 3456_at
> Cell1=xxx   xxx N   control 3456_at
> Cell1=xxx   xxx N   control 3456_at
> Cell1=xxx   xxx N   control 3456_at
> .   ... x   xxx
> (34K lines)
> 
> I want to remove Name=Xxxx_at identifiers.
> 
> My List:
> ['Name=32972_at',
> 'Cell1=432\t118\tN\tcontrol\t32972_at\t0\t13\tA\tA\tA\t0\t75952\t-1\t-1\t99\t',
> 'Cell2=432\t117\tN\tcontrol\t32972_at\t0\t13\tA\tT\tA\t0\t75312\t-1\t-1\t99\t',
> 'Cell3=499\t632\tN\tcontrol\t32972_at\t1\t13\tC\tC\tC\t1\t404979\t-1\t-1\t99\t']
> 
> I tried to resolve in this way:
> 
> >>>pat = re.compile('Name')
> >>> for i in range(len(cord)):
> x = pat.search(cord[i])
> cord.remove(x)
> 
> I know I am wrong here because I do not know how to
> search and remove an element in a list. Can any one
> please help me.
> 
> on Page 98, chapter Lists and dictionaries of mark
> lutz's learning python. It is mentioned in table 6-1 :
> L2.append(4)  Methods: grow,sort,search,reverse etc.
> 
> Although not much is covered on this aspect in this
> book, I failed to do more operations on list.
> 
> Looking forward for help from tutors.
> 
> Thank you.
> Kumar.
> 
> 
> 
> 
> --- Kent Johnson <[EMAIL PROTECTED]> wrote:
> 
> > kumar,
> >
> > Looking at the quantity and structure of your data I
> > think the search you are doing is going to be
> > pretty slow - you will be doing 4504 * 398169 =
> > 1,793,353,176 string searches.
> >
> > Where does the seq data come from? Could you
> > consolidate the pairs of lines into a single record?
> > If
> > you do that and extract the '399:559' portion, you
> > could build a dict that maps '399:559' to the
> > full record. Looking up '399:559' in the dictionary
> > would be much, much faster than searching the
> > entire list.
> >
> > If you have multiple entries for '399:559' you could
> > have the dict map to a list.
> >
> > Kent
> >
> > kumar s wrote:
> > >
> > >>>>len(x)
> > >
> > > 4504
> > >
> > >>>

Re: [Tutor] Re: Could I have used time or datetime modules here?

2004-12-07 Thread Liam Clarke
 >alarm_datetime = datetime.datetime(now.year, now.month, now.day,
   alarm_hour, alarm_minute)

Now that's clever.

I too, have learnt a large amount from this thread.


On Tue, 07 Dec 2004 23:57:59 -0500, Brian van den Broek
<[EMAIL PROTECTED]> wrote:
> Dick Moores said unto the world upon 2004-12-07 12:04:
> 
> 
> > Brian van den Broek wrote at 07:50 12/7/2004:
> >
> >>> It seems I've missed out on something important
> >>> BTW I'm not sure you need the +4 of "now.year + 4". I've run this
> >>> without the +4 and it doesn't seem to be needed. And notes (1) and
> >>> (4) on that page seem to say this, as far as I understand them.
> >>
> >>
> >> I'm not sure I do either :-)
> >>
> >> Here's why I did it:
> >>
> >> I discovered that in order to get the right "seconds until alarm"
> >> value from the datetime for now and the alarm datetime by subtracting
> >> one datetime object from another, I needed the alarm datetime to be in
> >> the future. But, since you can set an alarm for 09:00 tomorrow at
> >> 22:00 today, I needed the alarm datetime to not use today's date. (If
> >> you use today's, you end up with seconds *since* 09:00 this morning,
> >> not the desired seconds *until* 09:00 tomorrow morning.) Since
> >> timedelta_object.seconds discards all difference save the seconds save
> >> those from the hours, minutes, and seconds difference in the two
> >> datetime objects, it doesn't matter what date the alarm datetime is
> >> set to. (The day information is in timedelta_object.days.)
> >>
> >> Or, so I thought. I'd first tried getting the alarm datetime by simply
> >> taking the date component of datetime.datetime.now() and adding to the
> >> day value. That works fine, provided you are not on the last day of
> >> the month. But, when checking boundary cases before posting the code I
> >> sent, I discovered this sort of thing:
> >>
> >> >>> last_day_of_june = datetime.datetime(2004, 6, 30) # long for clarity
> >> >>> ldj = last_day_of_june# short for typing
> >> >>> new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1)
> >>
> >> Traceback (most recent call last):
> >>   File "", line 1, in -toplevel-
> >> new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1)
> >> ValueError: day is out of range for month
> >> >>>
> >>
> >> So, adding to the day or the month was out, unless I wanted elaborate
> >> code to determine which to add to under what circumstances. So then I
> >> thought, "Well, just change from now.day + 1 to now.year + 1, and all
> >> problems go away". And then I thought "Ah, but what if I try to run
> >> the script on Feb. 29?
> >>
> >> So, that's why I used now.year + 4. It still leaves open the
> >> possibility of getting bit by the every so often further correction to
> >> the calender, but, I *believe* the next one is due in 2100, so I think
> >> I can live with it. ;-)
> >>
> >> I'm not saying it isn't hackish, though. Better ways surely exist.
> >
> >
> > Brian,
> >
> > I just can't succeed in reproducing the problems with the boundary
> > cases  with the +4 removed. I've tried setting my computer's clock to
> > Nov 30, Feb 29, 2004, and Dec 31, 2004 (without changing the time). It's
> > now about 9 am where I am, and setting the alarm time to 0700 (i.e., on
> > the next day) works fine in all 3 cases. And of course no problem at
> > today's date with setting the alarm time to 07:00.
> >
> > Isn't that what that note (1) on
> >  implies?
> >
> > I did the testing with ,
> > by remarking out the time.sleep() line and noting what the
> > print_hms(sleepSeconds) function prints.
> >
> > Dick
> 
> Hi Dick and all,
> 
> I haven't checked your link yet, but thanks for it. (It's in the 'follow
> when I've time' file.)
> 
> I think this is all moot in light of Tim's post explaining:
> 
> >
> > Actually, you needed simpler code :
> >
> >
> >>> import datetime
> >>> ldj = datetime.datetime(2004, 6, 30)
> >>> new_day = ldj + datetime.timedelta(days=1)
> >>> print new_day
> >
> > 2004-07-01 00:00:00
> 
> Why I thought I needed it was that I was trying to do datetime's work
> for it :-)
> 
> I'd done:
> alarm_datetime = datetime.datetime(now.year+4, now.month, now.day,
> alarm_hour, alarm_minute)
> 
> after trying:
> alarm_datetime = datetime.datetime(now.year, now.month, now.day+1,
> alarm_hour, alarm_minute)
> 
> That did cause problems if the now datetime was the last day of a month
> (see last_day_of_june example for proof). (If you aren't getting the
> same problem is similar circumstances, well, I'm out of ideas on that one.)
> 
> This was all to the end of constructing an alarm_datetime guaranteed to
> be in the future from the user supplied alarm_hour, alarm_minute.
> 
> On the bus today (great place for ideas, the bus ;-), I figured

[Tutor] MemoryError

2004-12-08 Thread Liam Clarke
Hi all, 

I'm playing with a file, and attempting to replace a section with a
string, and using the following command -

seg=codeSt[element:endInd+len(endStr]
codeSt=codeSt.replace(seg, hrefString)

At the replace, I get a MemoryError. It's part of a for loop, but it
gives the error the first time around.

The Python docs say - "Raised when an operation runs out of memory but
the situation may still be rescued (by deleting some objects). The
associated value is a string indicating what kind of (internal)
operation ran out of memory. Note that because of the underlying
memory management architecture (C's malloc() function), the
interpreter may not always be able to completely recover from this
situation; it nevertheless raises an exception so that a stack
traceback can be printed, in case a run-away program was the cause. "

codeSt is a loaded text file that's 228Kb in size. The for loop that
the above code is embedded in, generates a slightly new codeSt each
time.

Now, I had imagined that codeSt=codeSt+10 would destroy the old codeSt
in memory and create a new codeSt. Am I right?

Because, even if the for loop (which will iterate 267 times) were to
keep a new copy of codeSt in memory,  it should only need 59Mb of RAM,
when I've got near half a gig of RAM and virtual memory.

So yeah, I don't know how to troubleshoot this one.

Full code is here - 

http://www.rafb.net/paste/results/ZflMyz31.html

Any help that can be offered gratefully appreciated. I don't want to
to have to learn C++? Malloc has an evil reputation.

Oh, and Python 2.3.4, Windows XP Pro SP1, Athlon 650MHz, 256Mb RAM
20Gb HD, which has 1.6Gb free. In case any of that infos relevant.

: )

Regards

Liam Clarke
-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MemoryError

2004-12-08 Thread Liam Clarke
Oh, and I never knew about .read() for a file object. I always just
used readline/readlines. Silly, really.



On Thu, 9 Dec 2004 11:31:40 +1300, Liam Clarke <[EMAIL PROTECTED]> wrote:
> > I'm not sure why you're getting the MemoryError, but it'd be easier to
> > figure out if you posted the entire text of the traceback.
> 
> 
> Traceback: 
> 
> Line 39: seg=codeSt[element:endInd+len(endStr]
> MemoryError
> 
> Hehe. Helpful, no?
> 
> I think I'll sprinkle print statements throughout as suggested, and
> wrap it in a function for that optimization Jeff mentioned.
> 
> Thanks for the advice, I'll let you know how it goes.
> 
> Regards,
> 
> Liam Clarke
> 
> I didn't think to
> 
> 
> On Wed, 08 Dec 2004 12:29:10 -0800, Jeff Shannon <[EMAIL PROTECTED]> wrote:
> > Liam Clarke wrote:
> >
> > > Hi all,
> > >
> > > I'm playing with a file, and attempting to replace a section with a
> > > string, and using the following command -
> > >
> > > seg=codeSt[element:endInd+len(endStr]
> > > codeSt=codeSt.replace(seg, hrefString)
> > >
> > > At the replace, I get a MemoryError. It's part of a for loop, but it
> > > gives the error the first time around.
> >
> >
> > I'm not sure why you're getting the MemoryError, but it'd be easier to
> > figure out if you posted the entire text of the traceback.
> >
> > A few other pointers --
> >
> > You'll probably get better performance if you put all of this code
> > inside of a function.  Even if you're only running it once, putting it
> > in a function allows the interpreter to do some optimization tricks on
> > locals() which can't be done at the module-global level (where you're
> > running now).  It's just barely possible that just doing this will
> > help with your MemoryError problem.  (You would probably benefit from
> > splitting it into multiple functions, actually.  I'd have the code
> > that finds text and url values each in their own function, for example.)
> >
> > Try adding a line in between those two that prints out the value of
> > element and endInd, and then check that those numbers really are valid
> > indexes into codeSt.  While you're at it, print out hrefString and
> > make sure it looks like it's supposed to.
> >
> > At the start of your program, you have the following:
> >
> >  inp=file("toolkit.txt","r")
> >  codeSt=inp.readlines()
> >  inp.close()
> >  codeSt="".join(codeSt)
> >
> > Since you're not processing by lines, and are explicitly joining all
> > the lines together, why have Python separate them for you?  It would
> > be much more efficient to simply use 'codeSt = inp.read()', with no
> > need to join() afterwards.  The readlines() method effectively does a
> > read() followed by splitting the result into lines; for your purposes,
> > there's no point in splitting the lines if you're just going to join()
> > them immediately.
> >
> > Instead of finding the start and end index of the segment you want to
> > replace, making a copy of that segment, and then scanning your
> > original string to replace that segment with a new chunk, it would
> > probably make more sense to simply grab codeSt before the segment and
> > after the segment and concatenate them with the new chunk.  Thus, your
> > two lines above become
> >
> >  codeSt = codeSt[:element] + hrefString \
> >   + codeSt[endInd+len(endStr)]
> >
> > Once again, this would avoid doing the same work twice.
> >
> > > Now, I had imagined that codeSt=codeSt+10 would destroy the old codeSt
> > > in memory and create a new codeSt. Am I right?
> >
> > Actually, this will probably raise a TypeError (cannot concatenate
> > 'str' and 'int' objects).  ;)  But yes, rebinding codeSt to a new
> > string should allow the old string to be destroyed (if there are no
> > other references to it).
> >
> > Hope that this helps.
> >
> > Jeff Shannon
> > Technician/Programmer
> > Credit International
> >
> >
> >
> >
> > ___
> > Tutor maillist  -  [EMAIL PROTECTED]
> > http://mail.python.org/mailman/listinfo/tutor
> >
> 
> --
> 'There is only one basic human right, and that is to do as you damn well 
> please.
> And with it comes the only basic human duty, to take the consequences.
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MemoryError

2004-12-08 Thread Liam Clarke
> I'm not sure why you're getting the MemoryError, but it'd be easier to
> figure out if you posted the entire text of the traceback.


Traceback: 

Line 39: seg=codeSt[element:endInd+len(endStr]
MemoryError

Hehe. Helpful, no?

I think I'll sprinkle print statements throughout as suggested, and
wrap it in a function for that optimization Jeff mentioned.

Thanks for the advice, I'll let you know how it goes.


Regards,

Liam Clarke

I didn't think to 
On Wed, 08 Dec 2004 12:29:10 -0800, Jeff Shannon <[EMAIL PROTECTED]> wrote:
> Liam Clarke wrote:
> 
> > Hi all,
> >
> > I'm playing with a file, and attempting to replace a section with a
> > string, and using the following command -
> >
> > seg=codeSt[element:endInd+len(endStr]
> > codeSt=codeSt.replace(seg, hrefString)
> >
> > At the replace, I get a MemoryError. It's part of a for loop, but it
> > gives the error the first time around.
> 
> 
> I'm not sure why you're getting the MemoryError, but it'd be easier to
> figure out if you posted the entire text of the traceback.
> 
> A few other pointers --
> 
> You'll probably get better performance if you put all of this code
> inside of a function.  Even if you're only running it once, putting it
> in a function allows the interpreter to do some optimization tricks on
> locals() which can't be done at the module-global level (where you're
> running now).  It's just barely possible that just doing this will
> help with your MemoryError problem.  (You would probably benefit from
> splitting it into multiple functions, actually.  I'd have the code
> that finds text and url values each in their own function, for example.)
> 
> Try adding a line in between those two that prints out the value of
> element and endInd, and then check that those numbers really are valid
> indexes into codeSt.  While you're at it, print out hrefString and
> make sure it looks like it's supposed to.
> 
> At the start of your program, you have the following:
> 
>  inp=file("toolkit.txt","r")
>  codeSt=inp.readlines()
>  inp.close()
>  codeSt="".join(codeSt)
> 
> Since you're not processing by lines, and are explicitly joining all
> the lines together, why have Python separate them for you?  It would
> be much more efficient to simply use 'codeSt = inp.read()', with no
> need to join() afterwards.  The readlines() method effectively does a
> read() followed by splitting the result into lines; for your purposes,
> there's no point in splitting the lines if you're just going to join()
> them immediately.
> 
> Instead of finding the start and end index of the segment you want to
> replace, making a copy of that segment, and then scanning your
> original string to replace that segment with a new chunk, it would
> probably make more sense to simply grab codeSt before the segment and
> after the segment and concatenate them with the new chunk.  Thus, your
> two lines above become
> 
>  codeSt = codeSt[:element] + hrefString \
>   + codeSt[endInd+len(endStr)]
> 
> Once again, this would avoid doing the same work twice.
> 
> > Now, I had imagined that codeSt=codeSt+10 would destroy the old codeSt
> > in memory and create a new codeSt. Am I right?
> 
> Actually, this will probably raise a TypeError (cannot concatenate
> 'str' and 'int' objects).  ;)  But yes, rebinding codeSt to a new
> string should allow the old string to be destroyed (if there are no
> other references to it).
> 
> Hope that this helps.
> 
> Jeff Shannon
> Technician/Programmer
> Credit International
> 
> 
> 
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Could I have used time or datetime modules here?

2004-12-09 Thread Liam Clarke
Hi Brian and Dick, 

I for one have learnt a lot from this combined poke around the
workings of datetime. The datetime.year thing never occurred to me,
yet it was so obvious when I saw it being used.

I give you, my python alarm clock timing mechanism, final version!

http://www.rafb.net/paste/results/qur2Pw95.html

It works on the cmd line - 

python alarm.py 17:30 

Sets the alarm for the next occurrence of 17:30, using nothing  but
datetime.datetime objects, and one timedelta (maybe).

'Twas a good discussion. : )

Liam Clarke

On Thu, 09 Dec 2004 00:12:04 -0500, Brian van den Broek
<[EMAIL PROTECTED]> wrote:
> Brian van den Broek said unto the world upon 2004-12-07 23:57:
> > Dick Moores said unto the world upon 2004-12-07 12:04:
> >
> 
> 
> 
> 
> 
> > The note you reference:
> >
> > date2 is moved forward in time if timedelta.days > 0, or backward if
> > timedelta.days < 0. Afterward date2 - date1 == timedelta.days.
> > timedelta.seconds and timedelta.microseconds are ignored. OverflowError
> > is raised if date2.year would be smaller than MINYEAR or larger than
> > MAXYEAR.
> >
> > presupposes you are adding a timedelta to a datetime as in Tim's
> > suggestion. It makes no promises if you were doing something goofy like
> > I was. (If that is what you were trying to get me to see, sorry, but I
> > missed it.)
> 
> Hey Dick and all,
> 
> I've taken a look at your code and finally seen what you meant, Dick.
> You were trusting datetime (along the same lines that Tim suggested to
> me) and thus weren't facing the problems I'd caused for myself. Sorry
> for missing your point before. Thanks,
> 
> Brian vdB
> 
> >
> > I hope this clarifies things some :-)
> 
> Ah, irony!
> 
> 
> 
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MemoryError

2004-12-09 Thread Liam Clarke
Well, I figured out the memory error relatively easily once I poked
some stuff, I was using codeSt.find instead of codeSt.index, so it was
returning no matches as -1, index raises an error for me, and I wasn't
catering for that -1. The MemoryError occurred when Python wanted to
slice from 160,000 to -1 or 0.

Was quite funny watching 1 Gb of paging file disappear in seconds.

But, I give up. Now, I've got several more bugs pop up. I've got an
index of integers that has the occasional index stored as a string. I
have indexes that start pointing at the right place, but when it comes
time to slice, the right place has moved. Unsure why, I'm specifically
moving from highest to lowest to avoid messing with the index values.
Even if nothing changes, my stored indexes go off course. This is
yuck.

So, I'm going to throw caution to the wind, and try an re approach. It
can't be any more unwieldy and ugly than what I've got going at the
moment.

Thanks for all the help, I'm off to get myself another problem.

Regards,

Liam Clarke

On Wed, 08 Dec 2004 15:25:30 -0800, Jeff Shannon <[EMAIL PROTECTED]> wrote:
> Liam Clarke wrote:
> 
> >>I'm not sure why you're getting the MemoryError, but it'd be easier to
> >>figure out if you posted the entire text of the traceback.
> >
> > Traceback: 
> >
> > Line 39: seg=codeSt[element:endInd+len(endStr]
> > MemoryError
> >
> > Hehe. Helpful, no?
> 
> Actually, it was the "usual bit about in module" that might *be*
> helpful. ;)  Often, something can be determined by the sequence of
> function calls listed there.  Though I suppose, now that I think of
> it, that since your code is all module-level, there wouldn't be any
> function stack in this case...   Still, in general, when asking for
> help with something that throws an exception, it's always best to copy
> & paste the entire text of the exception.
> 
> One thing that I've noticed, which I thought was just a typo in your
> original email but which is duplicated again here (it's not present on
> the web page you linked to) -- you have a mismatched parenthesis in
> your len() call.  It's "[ ... len(endstr]" -- there's no ')' to close
> the function call.  Given that this typo isn't on the web page, I'm
> not sure whether it's actually there in the code you're running or
> not.  I'd have *thought*, however, that if it *is* present, you'd get
> a syntax error rather than a memory error, so it's probably not there
> but you should check it anyhow.  :)
> 
> 
> 
> Jeff Shannon
> Technician/Programmer
> Credit International
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] String matching?

2004-12-09 Thread Liam Clarke
Hi Kent, 

Just wanted to say thanks for the advice on the regular expressions.
I've just created a regular expression which finds all 267 applets, my
.index iterations were producing some cockeyed results, so I tried re
in desperation, and it works, so simply. Looks pretty menacing, but
it's good.

Got to say, that re is very powerful, but that redemo.py you
recommended is brilliant for a beginner. I just wrote my re pattern in
there, and used it to troubleshoot.

So yeah, thanks again.

Regards,

Liam Clarke


On Tue, 07 Dec 2004 21:06:34 -0500, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Liam Clarke wrote:
> > And thanks for the re, hopefully I won't have to use it, but it gives
> > me a starting point to poke the re module from.
> 
> BTW Python comes with a nice tool for experimenting with regular expressions. 
> Try running
> Python23\Tools\Scripts\redemo.py
> 
> Kent
> 
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MemoryError

2004-12-09 Thread Liam Clarke
Hi all, 

Yeah, I should've written this in functions from the get go, but I
thought it would be a simple script. :/

I'll come back to that script when I've had some sleep, my son was
recently born and it's amazing how dramatically lack of sleep affects
my acuity. But, I want to figure out what's going wrong.

That said, the re path is bearing fruit. I love the method finditer(),
 as I can reduce my overly complicated string methods from my original
code to

x=file("toolkit.txt",'r')
s=x.read() 
x.close()
appList=[]

regExIter=reObj.finditer(s) #Here's a re obj I compiled earlier. 

for item in regExIter:
   text=gettextFunc(item.group()) #Will try and stick to string method
for this, but I'll see.
   if not text:
  text="Default" #Will give a text value for the href, so some
lucky human can change it
   url=geturlFunc(item.group()) # The simpler the better, and so far
re has been the simplest
   if not url:
 href = '"" #This will delete the applet, as there are applet's
acting as placeholders
   else:
 href='%s' % (url, text)

   appList.append(item.span(), href)

appList.reverse()

for ((start, end), href) in appList:

 codeSt=codeSt.replace(codeSt[start:end], href)


Of course, that's just a rought draft, but it seems a whole lot
simpler to me. S'pose code needs a modicum of planning.

Oh, and I d/led BeautifulSoup, but I couldn't work it right, so I
tried re, and it suits my needs.

Thanks for all the help.

Regards,

Liam Clarke
On Thu, 09 Dec 2004 11:53:46 -0800, Jeff Shannon <[EMAIL PROTECTED]> wrote:
> Liam Clarke wrote:
> 
> > So, I'm going to throw caution to the wind, and try an re approach. It
> > can't be any more unwieldy and ugly than what I've got going at the
> > moment.
> 
> If you're going to try a new approach, I'd strongly suggest using a
> proper html/xml parser instead of re's.  You'll almost certainly have
> an easier time using a tool that's designed for your specific problem
> domain than you will trying to force a more general tool to work.
> Since you're specifically trying to find (and replace) certain html
> tags and attributes, and that's exactly what html parsers *do*, well,
> the conclusions seems obvious (to me at least). ;)
> 
> There are lots of html parsing tools available in Python (though I've
> never needed one myself). I've heard lots of good things about
> BeautifulSoup...
> 
> 
> 
> Jeff Shannon
> Technician/Programmer
> Credit International
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Capturing Logfile data in Windows

2004-12-09 Thread Liam Clarke
You could have something along the lines of -

import os.path
import time

curTime = os.path.getmtime('log.txt') #Or whatever it's called.

while 1: #or some other loop
   time.sleep(10) #Check logfile every ten seconds.
   if  os.path.getmtime('log.txt') != curTime:
  curTime = os.path.getmtime('log.txt')
  x=file('log.txt','r')...


So basically, just check the modification time. If  the modification
time has changed, then the file's been updated.

It's one way to do it. : )

Liam Clarke

On Thu, 09 Dec 2004 17:28:56 +, Philip Kilner <[EMAIL PROTECTED]> wrote:
> Hi List,
> 
> I have a closed-source application which creates log files. I'd like to
> capture this logfile data as it is crated, and do clever things with it!
> 
> Is this possible? I guess it must be, because there are "tail" type
> utilities for Windows...
> 
> Is it possible in Python? I'd be grateful for any pointers!
> 
> BTW, it doesn't matter either way whether I can somehow pipe the log
> output to my program /without/ the file actually being created, or if I
> can capture it /as/ it is created - I just need to get my mitts on the
> data as it is generated...it would be better if I had the file as well,
> but it is not essential...
> 
> Thanks in Anticipation!
> 
> --
> 
> Regards,
> 
> PhilK
> 
> Email: [EMAIL PROTECTED] / Voicemail & Facsimile: 07092 070518
> 
> "Work as if you lived in the early days of a better nation." - Alasdair Gray
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MemoryError

2004-12-10 Thread Liam Clarke
Hi Kent, 

Thanks for the help, it worked third time around!

The final product is here if you have an interest  - 
http://www.rafb.net/paste/results/XCYthC70.html

But, I think I found a new best friend for this sort of thing - 
(?P.*?)

Being able to label stuff is brilliant.

But yeah, thanks for the help, especially that sub method.

Regards,

Liam Clarke
On Thu, 09 Dec 2004 19:38:12 -0500, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Liam,
> 
> Here's a nifty re trick for you. The sub() method can take a function as the 
> replacement parameter.
> Instead of replacing with a fixed string, the function is called with the 
> match object. Whatever
> string the function returns, is substituted for the match. So you can 
> simplify your code a bit,
> something like this:
> 
> def replaceTag(item):   # item is a match object
>  # This is exactly your code
> 
> 
>  text=gettextFunc(item.group()) #Will try and stick to string method
>   for this, but I'll see.
>  if not text:
> text="Default" #Will give a text value for the href, so some
>   lucky human can change it
>  url=geturlFunc(item.group()) # The simpler the better, and so far
>   re has been the simplest
>  if not url:
>href = '"" #This will delete the applet, as there are applet's
>   acting as placeholders
>  else:
>href='%s' % (url, text)
> 
>  # Now return href
>  return href
> 
> now your loop and replacements get replaced by the single line
> codeSt = reObj.sub(replaceTag, codeSt)
> 
> :-)
> 
> Kent
> 
> 
> 
> 
> Liam Clarke wrote:
> > Hi all,
> >
> > Yeah, I should've written this in functions from the get go, but I
> > thought it would be a simple script. :/
> >
> > I'll come back to that script when I've had some sleep, my son was
> > recently born and it's amazing how dramatically lack of sleep affects
> > my acuity. But, I want to figure out what's going wrong.
> >
> > That said, the re path is bearing fruit. I love the method finditer(),
> >  as I can reduce my overly complicated string methods from my original
> > code to
> >
> > x=file("toolkit.txt",'r')
> > s=x.read()
> > x.close()
> > appList=[]
> >
> > regExIter=reObj.finditer(s) #Here's a re obj I compiled earlier.
> >
> > for item in regExIter:
> >text=gettextFunc(item.group()) #Will try and stick to string method
> > for this, but I'll see.
> >if not text:
> >   text="Default" #Will give a text value for the href, so some
> > lucky human can change it
> >url=geturlFunc(item.group()) # The simpler the better, and so far
> > re has been the simplest
> >if not url:
> >  href = '"" #This will delete the applet, as there are applet's
> > acting as placeholders
> >else:
> >  href='%s' % (url, text)
> >
> >    appList.append(item.span(), href)
> >
> > appList.reverse()
> >
> > for ((start, end), href) in appList:
> >
> >  codeSt=codeSt.replace(codeSt[start:end], href)
> >
> >
> > Of course, that's just a rought draft, but it seems a whole lot
> > simpler to me. S'pose code needs a modicum of planning.
> >
> > Oh, and I d/led BeautifulSoup, but I couldn't work it right, so I
> > tried re, and it suits my needs.
> >
> > Thanks for all the help.
> >
> > Regards,
> >
> > Liam Clarke
> > On Thu, 09 Dec 2004 11:53:46 -0800, Jeff Shannon <[EMAIL PROTECTED]> wrote:
> >
> >>Liam Clarke wrote:
> >>
> >>
> >>>So, I'm going to throw caution to the wind, and try an re approach. It
> >>>can't be any more unwieldy and ugly than what I've got going at the
> >>>moment.
> >>
> >>If you're going to try a new approach, I'd strongly suggest using a
> >>proper html/xml parser instead of re's.  You'll almost certainly have
> >>an easier time using a tool that's designed for your specific problem
> >>domain than you will trying to force a more general tool to work.
> >>Since you're specifically trying to find (and replace) certain html
> >>tags and attributes, and that's exactly what html parsers *do*, well,
> >>the conclusions seems obvious (to me at least). ;)
> >>
> >>There are lots of html parsing tools available in Python (though I've
> >>never needed one myself). I've heard lots of good things about
> >>BeautifulSoup...
> >>
> >>
> >>
> >>Jeff Shannon
> >>Technician/Programmer
> >>Credit International
> >>
> >>___
> >>Tutor maillist  -  [EMAIL PROTECTED]
> >>http://mail.python.org/mailman/listinfo/tutor
> >>
> >
> >
> > 
> ___
> 
> 
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Could I have used time or datetime modules here?

2004-12-10 Thread Liam Clarke
Hi Dick, 

I'm ccing this to the list, for the experienced people to comment on .

Traceback (most recent call last):
>File "", line 1, in -toplevel-
>  import pygame
>File "C:\Python24\lib\site-packages\pygame\__init__.py", line 64, in
> -toplevel-
>  from pygame.base import *
> ImportError: Module use of python23.dll conflicts with this version of
> Python.

As far as I know, you'll either have to - run Python 2.3 or - run
Python 2.3 until they release a new version of Pygame,

Tutors?

Regards,

Liam Clarke

On Fri, 10 Dec 2004 06:38:21 -0800, Dick Moores <[EMAIL PROTECTED]> wrote:
> Liam,
> 
> Glad to find a searchable archive of tutor.
> 
> Searched on PHYTHONPATH there, read a bunch and tried this (pygame is at
> C:\Python23\Lib\site-packages\pygame)
>  >>> import sys
>  >>> sys.path.append('C:\Python23\Lib\site-packages\pygame')
>  >>> import pygame
> Traceback (most recent call last):
>File "", line 1, in -toplevel-
>  import pygame
> ImportError: No module named pygame
> 
> and
> 
>  >>> print sys.path
> ['C:\\Python24\\Lib\\idlelib', 'C:\\Python23',
> 'C:\\WINDOWS\\system32\\python24.zip', 'C:\\Documents and
> Settings\\Dick', 'C:\\Python24\\DLLs', 'C:\\Python24\\lib',
> 'C:\\Python24\\lib\\plat-win', 'C:\\Python24\\lib\\lib-tk',
> 'C:\\Python24', 'C:\\Python24\\lib\\site-packages',
> 'C:\\Python24\\lib\\site-packages\\win32',
> 'C:\\Python24\\lib\\site-packages\\win32\\lib',
> 'C:\\Python24\\lib\\site-packages\\Pythonwin']
> 
> Could the problem be that I've installed Python 2.4? pygame installed
> itself at C:\Python23\Lib\site-packages\pygame.
> 
> Just now I copied pygame to C:\Python24\Lib\site-packages and now get
>  >>> import pygame
> 
> Traceback (most recent call last):
>File "", line 1, in -toplevel-
>  import pygame
>File "C:\Python24\lib\site-packages\pygame\__init__.py", line 64, in
> -toplevel-
>  from pygame.base import *
> ImportError: Module use of python23.dll conflicts with this version of
> Python.
> 
> Dick
> 
> Liam Clarke wrote at 05:17 12/10/2004:
> 
> 
> >Nevermind. Don't need it.
> >
> >Just fire up your interpreter and check out sys.path. Search the tutor
> >list's archives for at ActiveState for PYTHONPATH.
> >
> >Good luck,
> >
> >Liam
> >
> >
> >On Fri, 10 Dec 2004 05:13:05 -0800, Dick Moores <[EMAIL PROTECTED]> wrote:
> > > Don't know. Never used it, anyway. What's the filename, and I'll search
> > > for it on my hard drive.
> > >
> > > Thanks
> > >
> > > Liam Clarke wrote at 04:20 12/10/2004:
> > >
> > >
> > > >Dick,
> > > >
> > > >Do you have MSN Messenger at all?
> > > >
> > > >Liam
> > >
> > >
> >
> >
> >--
> >'There is only one basic human right, and that is to do as you damn well
> >please.
> >And with it comes the only basic human duty, to take the consequences.
> 
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] using a function as a dictionary value?

2004-12-13 Thread Liam Clarke
Hey Justin,

Tricky one this..

as far as I know, and I'm a beginner myself, a dictionary stores a
reference to the function, not the actual function.

So - 

> command = {'1': spam(),
> '2': breakfast(),
> '3': bridgekeeper()
> }

Try this instead - 

command = {'1': spam, '2':breakfast, '3': bridgekeeper}



and

> select = raw_input('Chose an option [1|2|3]: ')
> 
> options = ['1', '2', '3']

> 
> if select in options:
> command[select]

change this to - 

select = raw_input('Chose an option [1|2|3]: ')

if select in command.keys():
 command[select]()



That one had me going round in circles when I first met it.
AFAIK, everything is stored in dictionaries apparently. If you have a
function called 'dude()' you could probably call it as a dictionary of
'dude' from the namespace...

Standard disclaimer - 

Someone more knowledgable would probably be along shortly to point out
a simpler, elegant way to do it, but my way works. Mostly.

HTH

Liam Clarke




> #
> def spam():
> print 'Hello world'
> 
> def breakfast():
> print 'Spam, Spam, Chips, and Spam'
> 
> def bridgekeeper():
> print 'Ask me your questions, Bridgekeeper. I am not afraid.'
> 
> select = raw_input('Chose an option [1|2|3]: ')
> 
> options = ['1', '2', '3']

> 
> if select in options:
> command[select]
> 
> else:
> print 'Selection not recognized.'
> #
>


'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Difference between for i in range(len(object)) andfor i in object

2004-12-13 Thread Liam Clarke
Good luck trying to find a decent Python book for beginners.

 I haven't been able to source Alan Gauld's book yet, (I'm saving for
Amazon's shipping... I live in the Antipodes.), but afaik that's about
the best one out, if his online tutorial (which I highly recommend
Kumar, link at end.) is indicative.

I have the O'Reilly Python in a Nutshell beside me, but it's a
reference only, and sometimes a confusing reference. Took me ages to
figure out what exactly serialization/deserialization meant in
reference to pickling. For my intents, tunring it into a saved thing.
Sure, maybe in binary format or something.

But yeah, once I'd worked my way through 80% of Alan's tutorial, I
found this list, and I'd attribute 75% of my progress since the
tutorial to the amazing help I've received here, and  the other 25% to
messing around in the interpreter or writing code and trying to make
it work.

Thing is, for people like me, you generally either don't know that a
question is a dumb one until someone tells you the answer, (the 'of
course'  moment), or until 5 minutes after you emailed
your query, you find the answer you were looking for...


Kumar, if I may, I have some recommendations for resources to check out. 

http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/index.htm

In my opinion, the best way to familiarise one's self with the
fundamentals of Python.

http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor

A searchable archive of the Tutor group

http://www.ibiblio.org/obp/thinkCSpy/index.htm

A good tutorial on writing code, which happens to use Python

Good luck,

Liam Clarke



On Sun, 12 Dec 2004 09:31:15 -0700, Bob Gailer <[EMAIL PROTECTED]> wrote:
> At 08:27 AM 12/12/2004, kumar s wrote:
> >Thank you for clearing up some mist here.  In fact I was depressed by that
> >e-mail
> 
> I appreciate Alan's response and yours. I forgot that this was the Tutor
> list, as I see so many Python e-mails it is easy to get confused. Please
> resume seeing this list and me as resources. I regret my comments that led
> to your depression.
> 
> >because there are not many tutorials that clearly explains the issues that
> >one faces while trying to code in python.
> 
> So what can we do as a community to provide tutorials that help students
> like you to more easily "get it". Can you give us some ideas as to what is
> missing? Also I 'd be interested in knowing a bit about your academic
> background and field of study. Would you give us a brief CV?
> 
> I taught programming for the Boeing Company. I always wondered "what are
> these students doing here? Why don't they just read the book?" That's how I
> learned almost everything I know about programming. So it can be hard for
> me to understand your struggle.
> 
> Nuf said for now...
> [snip]
> 
> Bob Gailer
> [EMAIL PROTECTED]
> 303 442 2625 home
> 720 938 2625 cell 
> 
> 
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Opening and reading .cvs files in Python

2004-12-14 Thread Liam Clarke
That's a very broad question. You could email it to yourself, check
out the IMAP, POP3, SMTP modules.

Alternatively, you could create an FTP session. Check out ftplib.

Once you've got it you can use the CSV module to read & parse it.

Have fun.

Liam Clarke,


On Tue, 14 Dec 2004 15:18:52 +0200, Johan Geldenhuys
<[EMAIL PROTECTED]> wrote:
>  Hi,
>  I want to find out how to open a .cvs file on a remote Windows machine and
> get file to my local linux folder.
>  
>  Any help would be appreciated.
>  
>  --Johan 
> -- 
> This E-Mail has been scanned 
> Enjoy your day 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] check_range

2004-12-15 Thread Liam Clarke
I'll second this - 

> In general, Python's flexibility with boolean values is a strength of the 
> language and I recommend
> you try to get comfortable with it.

If you come across something, and you're not sure if it'll evaluate
true or false, fire up IDLE or similar intepreter, and test it!

I'd call that another strength of Python. 

Liam Clarke

On Wed, 15 Dec 2004 07:43:57 -0500, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Brian van den Broek wrote:
> > DogWalker said unto the world upon 2004-12-15 00:32:
> >
> >> "Brian van den Broek" <[EMAIL PROTECTED]> said:
> >>> I have a some style suggestions for you, too.
> >>>
> >>> Try it this way:
> >>>
> >>> def check_in_range(value):
> >>>in_range = False
> >>>if 9 < value < 90:
> >>>in_range = True
> >>>return in_range
> >>
> >> Shorter:
> >> def check_in_range(value):
> >> return 9 < value < 90
> >
> >
> > Indeed. Good one. I never seem to think of such very direct ways, but
> > there you have it. It might say more about my psychology than anything
> > else, but I think I'd be tempted to put a brief comment on that code.
> > (Such as # returns True if the test, False otherwise.) My guess is that
> > if I had to read it more than twice, the time spent writing the comment
> > would be more than regained in spending less time scratching my head.
> > This might also be a matter of little experience, too.
> 
> Of course put a comment if you like, but this is very concise, idiomatic code 
> and I hope you will
> get used to it so the comment is not needed.
> 
> The value of the expression '9 < value < 90' is actually a boolean True or 
> False, so testing the
> expression and explicitly returning True or False is redundant. You are using 
> four lines of code to
> do the work of one.
> 
> In general, Python's flexibility with boolean values is a strength of the 
> language and I recommend
> you try to get comfortable with it.
> 
> >
> > At any rate, I certainly would agree that yours is bound to be better in
> > any situation where speed of execution mattered a lot.
> 
> Or readability, IMO.
> 
> Kent
> 
> >
> > Best,
> >
> > Brian vdB
> >
> > ___
> > Tutor maillist  -  [EMAIL PROTECTED]
> > http://mail.python.org/mailman/listinfo/tutor
> >
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] am I missing another simpler structure?

2004-12-15 Thread Liam Clarke
I find multiple returns to be rather useful - 

def isOdd(x):

if not x % 2: return False

return True


On Thu, 16 Dec 2004 01:06:58 -0500, Brian van den Broek
<[EMAIL PROTECTED]> wrote:
> [Brian van den Broek]
> 
>  complicated with:>
> 
> >>import datetime
> >>def is_leap_year(year):
> >>'''-> boolean
> >>
> >>Returns True or False as year is, or is not, a leap year.
> >>'''
> >>is_leap = True
> >>try:
> >>datetime.date(year, 2, 29)
> >>except ValueError:
> >>is_leap = False
> >>return is_leap
> 
> Kent Johnson said unto the world upon 2004-12-15 20:16:
>  > I would write
>  > def is_leap_year(year):
>  > try:
>  > datetime.date(year, 2, 29)
>  > return True
>  > except ValueError:
>  > return False
> 
> Not an adherent of the "only one exit point" doctrine then, hey? I spent
> a while a few weeks ago with a bug in a function that happened because
> I'd not noticed that I had two return statements, so I'm leery of this
> at the moment. (I concede if the function was long enough to hide that
> from me, it was probably too long.) I also like the conceptual purity of
> one way in and one way out. But, in my code above, that is indeed
> purchased at the cost of the ugly and a bit anomalous assignment of True.
> 
> Tim Peters said unto the world upon 2004-12-15 23:14:
> 
> > So far as leap years go, the obvious difference is that February has
> > 29 days in leap years, but only 28 otherwise.  You exploit that above
> > by checking whether trying to construct "February 29th" raises an
> > exception.  That's fine.  At least an equally good way is to note that
> > the difference between March 1 and Februrary 28 is 2 days only in a
> > leap year, so:
> >
> > from datetime import date, timedelta
> > def isleap(year):
> > return (date(3, 1, year) - date(2, 28, year)).days == 2
> 
> 
> 
> > def isleap(year):
> > return (date(year+1, 1, 1) - date(year, 1, 1)).days == 366
> >
> > IOW, if you can think of one way to do it with a Boolean expression,
> > it's common to think of more.  And, of course, that's the kind of
> > practice that makes it feel natural, over time.
> 
> 4 ways all shorter than mine; well, thank goodness I wasn't asking about
> this in Perl ;-)
> 
> Thanks for the examples. Pretty and concise often go together, but they
> seem not to be want to be seen with me. Implausible though my posting
> history may make it sound, I've done a fair bit of work in set theory
> and math. logic. While my proofs work, they are almost never pretty or
> concise. Seems like my code has similar tendencies. I appreciate the
> pushes in a better direction.
> 
> At least I won't be stuck for things to do when it comes time to refactor!
> 
> Thanks to both,
> 
> Brian vdB
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] am I missing another simpler structure?

2004-12-15 Thread Liam Clarke
Alright, so that was a quick example, but

>return not x % 2

A light dawns.

On Thu, 16 Dec 2004 15:58:38 +0900, Guillermo Fernandez Castellanos
<[EMAIL PROTECTED]> wrote:
> Well...
> 
> > I find multiple returns to be rather useful
> > def isOdd(x):
> > if not x % 2: return False
> > return True
> 
> I find this easier though...
> 
> def isOdd(x):
> return not x % 2
> 
> Enjoy,
> 
> Guille
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] A simpler mousetrap

2004-12-16 Thread Liam Clarke
Hi all, 

I'm writing some code, and I want to take a given path + filename, and
change the file extension to *.bak.

In doing so, (entirely internal this function), I am assuming -

That the file will always have an extension
Thathe extension will vary
But, it will follow the general DOS format of name.ext

So, I came up with this -

a="./tc/arc/gab.pct"

x=a.replace(a[a.rfind('.'):len(a)],'.bak')

x="./tc/arc/gab.bak"

So, it works, but it feels a bit, well, hacky to me. Not nearly hacky
as using an regex though ; )

I thought about 

a="./tc/arc/gab.pct"

aList=a.split('.')
aList[-1]='bak'
a=".".join(aList)

but I'm wondering if there's a simpler way, as there usually seems to
be, and it's always so obvious once I'm shown it, like 6 down - Six on
vehicle live in the manse (VI + car). Obvious once you know.

Regards,

Liam Clarke
-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: A simpler mousetrap

2004-12-16 Thread Liam Clarke
x=os.path.splitext(a)[0]+'.bak'

Ah, jolly good, looks a bit simpler. Thanks!

Regards,

Liam Clarke

On Thu, 16 Dec 2004 09:44:03 +0100, Wolfram Kraus
<[EMAIL PROTECTED]> wrote:
> Liam Clarke wrote:
> > Hi all,
> >
> > I'm writing some code, and I want to take a given path + filename, and
> > change the file extension to *.bak.
> >
> > In doing so, (entirely internal this function), I am assuming -
> >
> > That the file will always have an extension
> > Thathe extension will vary
> > But, it will follow the general DOS format of name.ext
> >
> > So, I came up with this -
> >
> > a="./tc/arc/gab.pct"
> >
> > x=a.replace(a[a.rfind('.'):len(a)],'.bak')
> >
> > x="./tc/arc/gab.bak"
> >
> > So, it works, but it feels a bit, well, hacky to me. Not nearly hacky
> > as using an regex though ; )
> >
> > I thought about
> >
> > a="./tc/arc/gab.pct"
> >
> > aList=a.split('.')
> > aList[-1]='bak'
> > a=".".join(aList)
> >
> > but I'm wondering if there's a simpler way, as there usually seems to
> > be, and it's always so obvious once I'm shown it, like 6 down - Six on
> > vehicle live in the manse (VI + car). Obvious once you know.
> >
> > Regards,
> >
> > Liam Clarke
> 
> Hey Liam!
> 
> The os.path module is your friend, especially split and splitext:
> http://docs.python.org/lib/module-os.path.html
> 
> HTH,
> Wolfram
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MemoryError

2004-12-10 Thread Liam Clarke
Yeah, that's a bit of a brute force approach alright. Mainly all the
(\n)?(=\n)?...

I, personally, intend to have words with a Mr William Gates regarding
just what horrors Frontpage inflicts. I also intend to discuss this
with gmail.google.com, as they parsed the text attachment I sent
myself, added it to the message body, (it seems),unattached it, and
added to the mess a wee bit. My emails always seem strangely
formatted, so yes...

But, that said, I've been shown far more horrific regexe's. I saw one
to parse an ISO-8601 date string (in PHP, I think?)

Made mine look elegant and simple...

But, it was good to learn a wee bit about the re module. Now that I've
actually done this, I probably won't need to do it again, but I'll
know a bit more about the appropriate use of re's.
I still prefer string methods for the simple stuff. 
 It did start off as a way to avoid cutting & pasting, ended up as a
pursuit of knowledge.
Oh well. 

Thanks to all for the assistance.

Regards,

Liam Clarke

On Fri, 10 Dec 2004 07:50:25 -0500, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Well, that's a regex only a mother could love. :-) I can see why you were 
> happy to find the
> (?P) form of grouping.
> 
> You should compile textObj and urlObj outside of getVals. You could just pull 
> the four lines that
> create textObj and urlObj outside of the function (into global scope). You 
> just have to compile a
> regex once, then you can use it multiple times. Compiling is relatively slow 
> so pulling it out of
> the loop is an optimization.
> 
> Congrats on getting this working!
> 
> 
> Kent
> 
> Liam Clarke wrote:
> > Hi Kent,
> >
> > Thanks for the help, it worked third time around!
> >
> > The final product is here if you have an interest  -
> > http://www.rafb.net/paste/results/XCYthC70.html
> >
> > But, I think I found a new best friend for this sort of thing -
> > (?P.*?)
> >
> > Being able to label stuff is brilliant.
> >
> > But yeah, thanks for the help, especially that sub method.
> >
> > Regards,
> >
> > Liam Clarke
> ___
> 
> 
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] check_range

2004-12-14 Thread Liam Clarke
Oh, and you can return True and False without quotation marks.

 >f check_range(input):
 >done = "True"
 >  return int(input)

You wil also hit problems with this, unless you're using input() to
get the integer, which causes even more issues.

Apparently, input() evaluates the value returned, so someone who knows
Python could enter a Python to delete your HD...

It's recommended to get all values with raw_input(), which returns all
values as a string, hence the problem with check_range, as it's
comparing a string to a integer.

The way to make sure that an integer gets entered is as follows - 

while 1:
  try:   
input=int(raw_input("Enter number here ")
  except TypeError:
 print "Please enter a number only"
 print
  else:
 print 'Thanks'
  print 'You entered %d' % input
 break

if check_range(input):
  done = True
  return input


That will infinitely loop until an integer is entered. raw_input gets
the string, and int() tries to convert it to an integer. Obviously you
can't convert a non-numeric character to an integer,
x=int('s') will raise an error, TypeError, hence the try/except/else
error catching clauses.

It'll look like this when running - 

Enter number here David
Please enter a number only

Enter number here Henry
Please enter a number only

Enter number here 1.0111010010101010
Thanks
You entered 1   #1.01101001 is a floating number, so int would change
'1.00101' to 1


HTH

Liam Clarke 

On Tue, 14 Dec 2004 18:46:26 -0500, Kent Johnson <[EMAIL PROTECTED]> wrote:
> You misunderstand what range() does. It returns a list of numbers starting 
> with the lower one and up
> to but not including the upper one:
>  >>> range(5)
> [0, 1, 2, 3, 4]
>  >>> range(5, 10)
> [5, 6, 7, 8, 9]
> 
> To test for a number in a range you can use 10 < n < 90:
>  >>> x = 1
>  >>> 10 < x < 90
> False
>  >>> x = 15
>  >>> 10 < x < 90
> True
>  >>> x = 100
>  >>> 10 < x < 90
> False
> 
> Kent
> 
> 
> Marc Gartler wrote:
> > Hi all,
> >
> > I am fairly new to both Python & programming, and am attempting to
> > create a function that will test whether some user input is an integer
> > between 10 and 89, but the check isn't happening...
> >
> > def check_range(myrange):
> > if range(myrange) != range(10,89):
> > return "False"
> > else:
> > return "True"
> >
> > ...this gets called later via:
> > if check_range(input):
> > done = "True"
> > return int(input)
> >
> >
> > What am I doing wrong?
> >
> > Thanks!
> >
> > ___
> > Tutor maillist  -  [EMAIL PROTECTED]
> > http://mail.python.org/mailman/listinfo/tutor
> >
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only ba sic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: tempfile

2004-12-23 Thread Liam Clarke
fileObj=...

fileObj.seek()? Is what I use, although that's for specific byte
positions I believe.


On Fri, 24 Dec 2004 03:09:31 +0430, Lee Harr <[EMAIL PROTECTED]> wrote:
> >I'm using tempfile.  The doc says it is opened 'w+b' so that it can be
> >read and written without closing and reopening.
> >
> >But, for the life of me, I can't find any way to rewind it so I can
> >read what I wrote.
> >
> 
> >>>import tempfile
> >>>import os
> >>>fd, name = tempfile.mkstemp()
> >>>os.write(fd, 'foo')
> 3
> >>>os.lseek(fd, 0, 0)
> 0L
> >>>os.read(fd, 10)
> 'foo'
> 
> 
> >tempfile.mkstemp gives me the file descriptor.  Is there a way to make
> >a file object from a file descriptor?
> >
> 
> Not that I can see:
> http://docs.python.org/lib/os-fd-ops.html
> 
> ... except maybe this, which is not quite the same:
> 
> >>>import tempfile
> >>>import os
> >>>fd, name = tempfile.mkstemp()
> >>>os.write(fd, 'foo')
> 3
> >>>f = open(name)
> >>>f.read()
> 'foo'
> 
> _
> Express yourself instantly with MSN Messenger! Download today it's FREE!
> http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] O.T.

2004-12-28 Thread Liam Clarke
I'm 23, married, 3 month old son, employed in New Zealand's social
welfare department, in a totally non IT role, learning Python purely
out of personal interest and a desire to stop working for New
Zealand's social welfare department someday.

I too climb mountains, having previously been based in a village of 50
people deep in the Southern Alps. I can't ski.


On Tue, 28 Dec 2004 09:10:58 -0700, Bob Gailer <[EMAIL PROTECTED]> wrote:
> I'm 64. Degrees in EE and MDiv. Career a mixture of engineering, computers,
> minister, teacher, 
> Just started a new romantic relationship!
> Programmed in more languages than I care to recall. The more
> interesting/arcane include
> IBM 650: machine language (my first), SOAP, CLASSMATE
> GE 415: FORTRAN, Assembler
> Singer 10: Assembler, Machine language
> PDP 8: FOCAL
> PL/I, APL, 370 Assembler and Machine language
> Motorola 8080?  Assembler and Machine language
> CMS Pipelines
> And finally Python. Sorta like discovering APL. And I have some desire to
> integrate some APL features into Python. Anyone else want to join me in
> that effort?
> 
> Hot topics for me: African Marimba Music (I teach it, design & build
> instruments). I'm also a DJ on public radio for African Music, as well as a
> talk show host.
> Nonviolent Communication as taught by Marshall Rosenberg. A most
> life-transforming process! I highly recommend it. www.cnvc.org.
> 
> Bob Gailer
> [EMAIL PROTECTED]
> 303 442 2625 home
> 720 938 2625 cell 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Array pointers

2005-01-04 Thread Liam Clarke
Hi all, 

Just playing with Pygame, attempting to build a version of Scorched
Earth if you remember it.

I want to represent dirt, and so far I've come up with using a surface array - 

0 644120 64412  64412
00 64412 64412  64412
0 644120 00
64412  644120  644120

Where a 0 indicates no pixel, 64412 is a representative pixel colour mapping.

Now, that works OK, but I wanted to animate each pixel of dirt
falling,so pseudocode -

if there's no pixel below, move value down one, unless value is at the
bottom of the column

so - 

Frame 0 -

0 644120 64412  64412
00 64412 64412  64412
0 644120 00
64412  644120  644120

Frame 1:

0 000  0
0 64412 0 64412   64412
0 64412  64412 64412   64412
64412  64412 0 64412  0



64412
64412
   0
   0

becoming 

   0
64412
64412
   0

I envisage as a two step process  with the below as an intermediate.
This is wasteful, I'm sure.

64412
   0
64412
   0


Frame 2:

0 000  0
0 64412 0 64412  0
0 64412 0 64412   64412
64412  64412   6441264412   64412

Frame 3+

0 000  0
0 64412 0 64412  0
0 64412 0 64412   64412
64412  64412   6441264412   64412



Has anyone used Numeric for this kind of thing before? Any little
quirk of array mathematics  I could exploit?

Or, should I shuffle this one to the back of the ideas folder for when
I've (if ever) learn Cpp?


Regards,

Liam Clarke

PS


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Array pointers

2005-01-04 Thread Liam Clarke
Sorry rephrase - 

So I have a list - 

[0,0,0,0,0,1,1,1,0,1,1,0,1,0]

I want to move all the 1's move to the right, 1 index at a time,
preserving any spacing.

i.e.

[1,0,0,0,0,1,1,1,0,1,1,0,1,0]

[0,1,0,0,0,0,1,1,1,0,1,1,0,1]

[0,0,1,0,0,0,0,1,1,1,0,1,1,1]

[0,0,0,1,0,0,0,0,1,1,1,1,1,1]

[0,0,0,0,1,0,0,0,1,1,1,1,1,1]

[0,0,0,0,0,1,0,0,1,1,1,1,1,1]

[0,0,0,0,0,0,1,0,1,1,1,1,1,1]

[0,0,0,0,0,0,0,1,1,1,1,1,1,1]


Now, I have a whole list of these lists and I create an array of them.
Is there a way to apply these changes wholescale without a large
calculation time?

I'm starting to think I'm going to have to go Cpp for this kind of
direct pixel tweaking stuff.
(640x480 (let alone 1024x768) is a lot of pixels to run through a for... loop)

So yeah, anyone had this before?

Regards,

Liam Clarke

On Tue, 4 Jan 2005 22:36:55 -0500, Byron Saltysiak <[EMAIL PROTECTED]> wrote:
> perhaps I don't understand the question exactly cause I don't remember
> the game but I think a nice way to do this would be to create a list
> of 5-tuples. Randomly generate a 5-tuple and push it onto the
> beginning of the list... pop the last off.
> 
> 
> On Wed, 5 Jan 2005 15:31:59 +1300, Liam Clarke <[EMAIL PROTECTED]> wrote:
> > Hi all,
> >
> > Just playing with Pygame, attempting to build a version of Scorched
> > Earth if you remember it.
> >
> > I want to represent dirt, and so far I've come up with using a surface 
> > array -
> >
> > 0 644120 64412  64412
> > 00 64412 64412  64412
> > 0 644120 00
> > 64412  644120  644120
> >
> > Where a 0 indicates no pixel, 64412 is a representative pixel colour 
> > mapping.
> >
> > Now, that works OK, but I wanted to animate each pixel of dirt
> > falling,so pseudocode -
> >
> > if there's no pixel below, move value down one, unless value is at the
> > bottom of the column
> >
> > so -
> >
> > Frame 0 -
> >
> > 0 644120 64412  64412
> > 00 64412 64412  64412
> > 0 644120 00
> > 64412  644120  644120
> >
> > Frame 1:
> >
> > 0 000  0
> > 0 64412 0 64412   64412
> > 0 64412  64412 64412   64412
> > 64412  64412 0 64412  0
> >
> > 64412
> > 64412
> >0
> >0
> >
> > becoming
> >
> >0
> > 64412
> > 64412
> >0
> >
> > I envisage as a two step process  with the below as an intermediate.
> > This is wasteful, I'm sure.
> >
> > 64412
> >0
> > 64412
> >0
> >
> > Frame 2:
> >
> > 0 000  0
> > 0 64412 0 64412  0
> > 0 64412 0 64412   64412
> > 64412  64412   6441264412   64412
> >
> > Frame 3+
> >
> > 0 000  0
> > 0 64412 0 64412  0
> > 0 64412 0 64412   64412
> > 64412  64412   6441264412   64412
> >
> > Has anyone used Numeric for this kind of thing before? Any little
> > quirk of array mathematics  I could exploit?
> >
> > Or, should I shuffle this one to the back of the ideas folder for when
> > I've (if ever) learn Cpp?
> >
> > Regards,
> >
> > Liam Clarke
> >
> > PS
> >
> > --
> > 'There is only one basic human right, and that is to do as you damn well 
> > please.
> > And with it comes the only basic human duty, to take the consequences.
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regex problem

2005-01-04 Thread Liam Clarke
Hi Michael, 

Is a non regex way any help? I can think of a way that uses string methods - 


space=" "

stringStuff="Stuff with multiple spaces"
indexN = 0 
ranges=[]
while 1:
   try:
  indexN=stringStuff.index(space, indexN)
  if indexN+1 == space:
 indexT = indexN
 while 1:
indexT += 1
if not indexT == " ":
   ranges.append((indexN, indexT))
   break
 indexN=indexT +1
else:
  indexN += 1
except ValueError:
ranges.reverse()
 for (low, high) in ranges:
  stringStuff.replace[stringStuff[low:high], space]

HTH
Liam Clarke
 


On Tue, 4 Jan 2005 15:39:18 -0800, Michael Powe <[EMAIL PROTECTED]> wrote:
> Hello,
> 
> I'm having erratic results with a regex.  I'm hoping someone can
> pinpoint the problem.
> 
> This function removes HTML formatting codes from a text email that is
> poorly exported -- it is supposed to be a text version of an HTML
> mailing, but it's basically just a text version of the HTML page.  I'm
> not after anything elaborate, but it has gotten to be a bit of an
> itch.  ;-)
> 
> def parseFile(inFile) :
> import re
> bSpace = re.compile("^ ")
> multiSpace = re.compile(r"\s\s+")
> nbsp = re.compile(r" ")
> HTMLRegEx =
> 
> re.compile(r"(<|<)/?((!--.*--)|(STYLE.*STYLE)|(P|BR|b|STRONG))/?(>|>)
> ",re.I)
> 
> f = open(inFile,"r")
> lines = f.readlines()
> newLines = []
> for line in lines :
> line = HTMLRegEx.sub(' ',line)
> line = bSpace.sub('',line)
> line = nbsp.sub(' ',line)
> line = multiSpace.sub(' ',line)
> newLines.append(line)
> f.close()
> return newLines
> 
> Now, the main issue I'm looking at is with the multiSpace regex.  When
> applied, this removes some blank lines but not others.  I don't want
> it to remove any blank lines, just contiguous multiple spaces in a
> line.
> 
> BTB, this also illustrates a difference between python and perl -- in
> perl, i can change "line" and it automatically changes the entry in
> the array; this doesn't work in python.  A bit annoying, actually.
> ;-)
> 
> Thanks for any help.  If there's a better way to do this, I'm open to
> suggestions on that regard, too.
> 
> mp
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input to python executable code and design question

2005-01-09 Thread Liam Clarke
Eep.


On Mon, 10 Jan 2005 13:04:33 +1300, Liam Clarke <[EMAIL PROTECTED]> wrote:
> I think you're looking for eval() - but that's a big security hole,
> and wouldn't handle f(x) notation overly well, unless you parse like
> John said.
> 
> 
> On Mon, 10 Jan 2005 12:52:24 +1300 (NZDT), [EMAIL PROTECTED]
> <[EMAIL PROTECTED]> wrote:
> > Quoting Ismael Garrido <[EMAIL PROTECTED]>:
> >
> > > I am trying to make a program that will plot functions. For that, I need
> > > to be able to get an input (the function to be plotted) and execute it.
> > > So, my question is, how do I use the input? I have found no way to
> > > convert the string to some kind of executable code.
> >
> > So you want the user to be able to type something like "f(x) = sin(2*x)" and
> > then your program will plot it --- is that correct?
> >
> > Maybe you could parse it yourself?  I have found SimpleParse quite easy to 
> > use
> > --- http://simpleparse.sourceforge.net/ .  You will need to write your own
> > grammar to describe functions --- something like this, I guess:
> >
> > eqn := fname, '(', varlist, ')=', expr
> > varlist := var, (',', var)*
> >
> > expr := atom, (binop, atom)?
> > atom := var / (fun, '(', expr, ')') / num
> > fun := 'sin' / 'cos' / 'tan' / ...
> >
> > var := char
> > fname := char+
> > num := digit+
> > binop := '+' / '*' / '/' / '-'
> >
> > char := [a-zA-Z]
> > digit := [0-9]
> >
> > although you will need to work on that to get the precedence right and avoid
> > undesired recursion and the like.  SimpleParse will give you a tree (made of
> > nested tuples) representing your function.  You can then have a go at 
> > converting
> > the tree to a function.
> >
> > I guess the standard way to do this would be something like:
> >
> > def convert(node):
> > functionName = node[0]
> > children = node[1]
> > if functionName == '*':
> > return convert(children[0]) * convert(children[1])
> > elif functionName == '+':
> > ...
> >
> > But you may be able to come up with something more clever.
> >
> > Hope this helps.
> >
> > --
> > John.
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> 
> 
> --
> 'There is only one basic human right, and that is to do as you damn well 
> please.
> And with it comes the only basic human duty, to take the consequences.
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Slightly OT - Python/Java

2005-01-09 Thread Liam Clarke
Hi all,

I've been forcing myself to learn Java, and I was wondering if
anyone's used Jython.
To clarify - Jython generates Java bytecode?

Personally, I should've learnt Java first (although my success at that
without my Python experiences would've been limited.)

I find it's real nasty forcing myself to think through very (relative
to Python) narrow hoops to keep the Java compiler happy.

All that stuff with typing variables - I can understand that you'd
want to specify when the compiler needs to reserve 64 bits for a long
integer, but beyond that is the typing really necessary for
performance reasons? As far as I can tell it's merely so that the
compiler can  check for errors which could lead to security problems.
Very frustrating. As is the true/false checking...

(Also very frustrating is having lists that can be comprised only of
one variable type.)

I wrote a simple programme in Python & Java, which iterated from 0 to
10 million,  doing
 i % 13 to determine how many numbers were divisble by 13. (769231
between 0 & 10 million)

Time to write Python programme - 3 minutes.
Time to write Java programme - 30 minutes. (Why can't a non-static
method comparison be called from a static reference? What does that
mean anyway?

Runtime in Python 17.605 seconds (avg over 10 runs)
Runtime in Java 12.302 seoncds (avg over 10 runs)

So yes - if Jython compiles to Java bytecode, and gives that 5 seconds
faster performance, but I write it in Python, and it gives me that 27
minutes of not messing about counting my braces, I'm in heaven. ( I
actually wrote a Python script to count braces.)

Anyone familar?


Regards,

Liam Clarke

PS I'm only learning Java because it's what they teach the COSC 1st
year course that I plan to do.

-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Slightly OT - Python/Java

2005-01-09 Thread Liam Clarke
> 
> > Personally, I should've learnt Java first (although my success at that
> > without my Python experiences would've been limited.)
> 
> I don;t know why you think that would help?
> Or do you mean Java before Jython? If so it depends
> what you intend using Jython for!

I meant learning Java prior to Python. Then, I could've doubled my
elation at discovering Python, having had something to compare it to,
whereas now I've got to grit my teeth and force myself to code.


> No, its allegedly for reliability reasons - if it compiles then
> you should never get a runtime eror due to the wrong kind of
> object being passed. I used to believe passionately in that
> principle, now, after using Python I'm not so convinced it
> matters as much as I thought. THe type conversion functions
> in Java(and C++) can do funny things to data that bring their
> own problems!


So it's protecting me from my own bad programming?
Does that have to be built into a compiler? Couldn't it be an optional
switch and I wear my bad code if it fails? *mutter*

> Its worth learnoing at least one statically/strictly typed language.
> There are some advantages but for me they are outweighed by
> the disadvantages, but then I'm not selling commercial software
> that gets benchmarked against my cometitorsin PC Magazine etc...
> In that scenario every millisecond counts!

I do need to learn a... commercially wide spread language but I
think if I ever got that serious about milliseconds, it'd be time to
learn Cpp & mesh it with Python.

(5 seconds difference over 10 million iterations, That's 0.005
seconds difference per iteration. That's not overly bad.)


Actually, I have the Intel assembler manuals at home, haven't even
looked at 'em. If we're going for speed...

Ah pity. I was hoping I could code for the JVM in Python style; I'd
have to learn Java anyway, but I was thinking long, long term, beyond
my public service walls.

Regards,

Liam Clarke


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Slightly OT - Python/Java

2005-01-10 Thread Liam Clarke
On Mon, 10 Jan 2005 01:33:39 +, Max Noel <[EMAIL PROTECTED]> wrote:
> 
> > (Also very frustrating is having lists that can be comprised only of
> > one variable type.)
> 
> First things first: don't use lists/arrays. Use Collections instead
> (classes like ArrayList, HashMap, etc.). They're much more versatile,
> and akin to lists and dictionaries in Python (sometimes even better).
> Iterators over them are supported.
> And while they can indeed only be comprised of one variable type as
> well, said variable type is Object, from which all classes derive, so
> that's not a problem (you only have to remember to cast as you get()
> something from a Collection).

Hehe, I'm not up to collections yet... working through Learning Java
by O'Reilly.

> > (Why can't a non-static
> > method comparison be called from a static reference? What does that
> > mean anyway?
> 
> Er... What was your code like? (before and after correcting the error)


it was (off top of head here)

public class dude

{
public static void main(String [] args) {

System.out.print(args[0]);
if (doComp(args[0]));
{
System.out.println(" is true");
}
else
{
System.out.println(" is false");
  }

private boolean doComp(String x) {
   int j = new int(x);   #I can't quite remember how I did
this precisely.
   
   if (j==1)
  {
  return True;
  }
   else
  {
   return False;
   }
 }

}


Getting more OT now. 

> > Runtime in Python 17.605 seconds (avg over 10 runs)
> > Runtime in Java 12.302 seoncds (avg over 10 runs)
> 
> Does runtime in Java include startup? Every time you start a java
> program, it has to load a BIG runtime in memory (roughly 30 megs of
> classes -- that's both Java's curse and blessing).

No - it's just - create a datetime object, run iterations, create new
datetime object and compare.

I have no startup lag really. 


> > So yes - if Jython compiles to Java bytecode, and gives that 5 seconds
> > faster performance, but I write it in Python, and it gives me that 27
> > minutes of not messing about counting my braces, I'm in heaven. ( I
> > actually wrote a Python script to count braces.)
> 
> Oh Ghost. You didn't actually write a Java program using a regular
> text editor, did you?
> And of course, it's free (and written in Java). http://www.eclipse.org
>

*sigh* I have no net at home at moment, which is very frustrating when
I want to d/l documentation & editors. For the mo, it's all Notepad.
Ick.

Alan Gauld wrote:
>Actually modern C compilers usually mean that well written C
>can outperform even assembler, to write good assembler is just
>so hard that very few people can outsmart a good comiler...

Good to hear, means I can put off the asm adventure for a looong time.
Of course, that will involve C :/

Cheers, 

Liam Clarke
-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only ba sic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] More and more OT - Python/Java

2005-01-11 Thread Liam Clarke
Out of curiousity, having poked around XML while learning about the
JScript DOM, what are you using it for?

AFAIK, you make up your own tags, and then parse them and display
them, and anyone else could create data using your tags.

Only thing I've seen that uses XML (remember I'm a n00bie in Python,
Java, Jscript and HTML, so I don't see the real indepth stuff) is MSN
Messenger for it's logs. And MS IE can parse that XML.

I've been curious as to how it's implemented.

So yeah, if you want to share your experiences.

Regards,

Liam Clarke


On Tue, 11 Jan 2005 02:19:17 +, Max Noel <[EMAIL PROTECTED]> wrote:
> >   dom4j? What is it? Is it part of the standard Java distribution? If
> > not, where can it be found?
> 
> Update: Okay, looks like it's time to go to bed. The link was in
> bright blue and somehow I didn't see it. D'oh.
> 
> -- Max
> maxnoel_fr at yahoo dot fr -- ICQ #85274019
> "Look at you hacker... A pathetic creature of meat and bone, panting
> and sweating as you run through my corridors... How can you challenge a
> perfect, immortal machine?"
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Time script help sought!

2005-01-11 Thread Liam Clarke
It's kind of easy - 

so that stuff you've got there is in a file called dude.inp, for
argument's sake -


import datetime

filename=file("dude.inp","r")
lineList=filename.readlines()
filename.close()

for line in lineList:
  #This is the hard bit, formatting your in dates
  splitLine=line.split(", ")
  for (item, dat, num, startTime, finishTime) in splitLine:
   
   sepStart=startTime.split(":")
   startHours=sepStart[0]
   startMin=sepStart[1]
   startSec=sepStart[2]

   finishStart= finishTime.split(":")
   finishHours=sepStart[0]
   finishMin=sepStart[1]
   finishSec=sepStart[2]

   #Now for the easy bit, manipulating the time

   startObj = datetime.datetime(01, 1, 1, startHours,
startMin, startSec)
   finishObj = datetime.dateime(01, 1, 1, startHours,
startMin, startSec)

   #If you're going to simply have all times start from 00:00,
you only want the length
   #of the time period right? So

   lengthDelta = finishObj - startObj #Python does the time
calcs for ya!
   lengthObj = datetime.datetime(lengthDelta) 
   

OK - so, once you've formatted the input to get the hours, mins, and
secs, you create a datetime object for each time which is set for that
01/01/1901, at that particular time.
Notice the 01, 1, 1, - you can't use 01 01 for the month and day \

a datetime object goes like this - 
datetime.datetime(year, month, day, hours, minutes, secs)

So, you've got the two datetime objects, Python handles the maths, and gives a 
timedelta object, which you use to create a new datetime object (as a
timedelta object can't use strftime) which you can then use to format
your time with strftime!

Real easy... if there's anything I've messed up, let me know, and I'll
clarify it for you ( I coded something similar at home).

Or if anything needs expansion upon...

Regards,

Liam Clarke


On Tue, 11 Jan 2005 16:51:31 -0500, kevin parks <[EMAIL PROTECTED]> wrote:
> I am still working on it and also fixing the input data. I think for
> simplicity and consistency's sake i will have *all* time values input
> and output as hh:mm:ss maybe that would be easier for now.. so i am
> editing the input stuff now...
> 
> so it should all look like:
> 
> Item_1, DAT_1, 1, 00:00:23, 00:08:23
> 
> Item_2, DAT_1, 2, 00:08:23, 00:09:41
> 
> Item_3, DAT_1, 3, 00:09:41, 00:10:41
> Item_3, DAT_1, 4, 00:10:47, 00:11:19
> Item_3, DAT_1, 5, 00:11:21, 00:11:55
> Item_3, DAT_1, 6, 00:11:58, 00:12:10
> Item_3, DAT_1, 7, 00:12:15, 00:12:45
> Item_3, DAT_1, 8, 00:12:58, 00:24:20
> 
> Item_4, DAT_1, 9, 00:24:33
> Item_4, DAT_1, 10, 00:25:48
> Item_4, DAT_1, 11, 00:29:48
> Item_4, DAT_1, 12, 00:31:46
> Item_4, DAT_1, 13, 00:34:17
> Item_4, DAT_1, 14, 00:35:21
> Item_4, DAT_1, 15, 00:36:06
> Item_4, DAT_1, 16, 00:37:01, 00:37:38
> 
> no comments either i can copy them later...
> 
> this is kind of hard...
> 
> -k
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] More and more OT - Python/Java

2005-01-11 Thread Liam Clarke
So, you've got the XML like - 


 You are standing in front of a stump. A path leads north. 
 N 

and you have a XSL that works like a CSS? 

descript  {font:arial, align:center}
exits style:bolder

Is that a good paraphrasing? How browser dependent would that be? Do
most browsers support XML & XSL?

PS 

What's SAX DOM? I know what a DOM is, but what's the SAX? I saw it in
my Python docs when I was poking XMLParser. If/when I work with XML,
would you recommend Python's standard modules for it?


Regards,

Liam Clarke
On Tue, 11 Jan 2005 23:34:30 +, Max Noel <[EMAIL PROTECTED]> wrote:
> (yes, forgot to CC the list again -- argh!)
> 
> Begin forwarded message:
> 
> > From: Max Noel <[EMAIL PROTECTED]>
> > Date: January 11, 2005 23:33:44 GMT
> > To: Liam Clarke <[EMAIL PROTECTED]>
> > Subject: Re: [Tutor] More and more OT - Python/Java
> >
> >
> > On Jan 11, 2005, at 23:15, Liam Clarke wrote:
> >
> >> Out of curiousity, having poked around XML while learning about the
> >> JScript DOM, what are you using it for?
> >>
> >> AFAIK, you make up your own tags, and then parse them and display
> >> them, and anyone else could create data using your tags.
> >>
> >> Only thing I've seen that uses XML (remember I'm a n00bie in Python,
> >> Java, Jscript and HTML, so I don't see the real indepth stuff) is MSN
> >> Messenger for it's logs. And MS IE can parse that XML.
> >>
> >> I've been curious as to how it's implemented.
> >>
> >> So yeah, if you want to share your experiences.
> >>
> >> Regards,
> >>
> >> Liam Clarke
> >
> >   Well, I plan to use it as a data storage format for a university
> > project (crowd simulation in a shopping center -- coded in Java). I
> > hate binary data formats, and XML is a good unified way to store data
> > as ASCII text, so I figured I'd use it.
> >   Also, XML files can be parsed without too much work, so I can write
> > scripts that will manipulate my data files, in any language ("any"
> > meaning "Python", there).
> >
> >   As a bonus, I've decided to have a look at XSL, which allows me to
> > format a XML file for display in a web browser. It entirely changed my
> > perception of web programming.
> >   I intend to program an on-line browser-based game with some friends
> > of mine later in the year (in Python of course -- I converted them),
> > and now that I've seen what XML and XSL can do, we're so going to use
> > them for data output: the data is in dynamically-generated XML, which
> > links to a (static) XSL stylesheet to tell the browser how to render
> > that data.
> >   Doing things that way has many advantages:
> > 1) Data is separate from formatting. That's always a Good Thing(TM).
> > If I someday decide that I don't like the way the site looks, I
> > theoretically only need to recreate a stylesheet, without touching
> > anything else. (boom! Instant skins!)
> > 2) Most of the "HTML rendering" is going to be done by the user's
> > browser. This, and the way XSL stylesheets are constructed will
> > prevent many bad HTML issues.
> > 3) For the same reason, it will save bandwidth. The XML data will
> > probably take less space than the fully-formatted stuff I'd have to
> > spit out with "regular" HTML, and the XSL stylesheet can probably be
> > cached by the user's browser.
> > 4) In the same line of reasoning, it'll also save CPU time: XML data,
> > being smaller, is generated faster than the equivalent HTML. Granted,
> > the stylesheet is another server request, but it's static, so it puts
> > virtually no load on a server.
> >
> > -- Max
> > maxnoel_fr at yahoo dot fr -- ICQ #85274019
> > "Look at you hacker... A pathetic creature of meat and bone, panting
> > and sweating as you run through my corridors... How can you challenge
> > a perfect, immortal machine?"
> >
> >
> --
> maxnoel_fr at yahoo dot fr -- ICQ #85274019
> "Look at you hacker... A pathetic creature of meat and bone, panting
> and sweating as you run through my corridors... How can you challenge a
> perfect, immortal machine?"
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Time script help sought!

2005-01-12 Thread Liam Clarke
I'm real sorry. 

My standard disclaimer is now amended to include - "Never post untested code"

Disregard everything I wrote above. I feel real bad, so bad that I did
something I very rarely do... write complete code.

See attached txt file. Guaranteed to work, if you still want to turn 

Item_4 DAT 5 12:32:05 12:37:13 Funny crackling noise

into Item_4 DAT 5 00:00:00 00:05:08 Funny crackling noise

Please note comment can be included. Not overly hard.

HTH, 

(And sorry for erroneous datetime stuff. Particularly
datetime.datetime(timedelta object)
That definitely doesn't work.)

Never post untested code

Liam Clarke

On Wed, 12 Jan 2005 10:08:02 -0500, kevin parks <[EMAIL PROTECTED]> wrote:
> thanks everyone... I will look at all the various appraoches folks came
> up with and see what i can learnn from them. I ended doing something
> lame -- a brute force method. I formmatted and reformatted my input
> data and stuffed it in a HUGE dictionary it was stupid and
> kludgy i hope to study all these approaches and learn something
> that may help me do something that is more flexible about the input
> data and is more elegant. here's what i
> came up with ... with my pea sized brain...
> 
> #!/usr/bin/env python
> 
> # New in version 2.3 is the 'datetime' module (see standard library
> reference)
> # http://www.python.org/doc/lib/module-datetime.html
> 
> import datetime
> 
> inseqs = { (1) : ['DAT_1', '01', '00:00:23', '00:08:23'],
> (2) : ['DAT_1', '02', '00:08:23', '00:09:41'],
> (513) : ['DAT_75', '10', '00:59:55', '01:11:05'],
> (514) : ['DAT_75', '11', '01:11:05', '01:16:15'],
> (515) : ['DAT_75', '12', '01:16:15', '01:34:15'],
> (516) : ['DAT_75', '13', '01:34:15', '01:45:15'],
> (517) : ['DAT_75', '14', '01:45:15', '01:48:00'] }
> 
> mykeys = inseqs.keys()  # first make a copy of the keys
> mykeys.sort()   # now sort that copy in place
> 
> for key in mykeys:
>  event = inseqs[key]
>  print '\n','Item #', key, event
>  TD = datetime.timedelta
>  h, m, s = event[2].split(':')
>  zero_adjust = TD(hours=int(h), minutes=int(m),seconds=int(s))
>  #
>  print ' Q___ ', key, event[:2], ': ',
>  for item in event[2:]:
>  hrs, mins, secs, = item.split(':')
>  time1 = TD(hours=int(hrs), minutes=int(mins),seconds=int(secs))
>  print time1 - zero_adjust,
> 
>  print
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
# By Liam Clarke
# A wee bitty of text processing code.
# Written in apology for some very wrong info I gave about using datetime 
objects.
# Golden rule - never post untested code. 
#
# Caveats
#
# This code will always be expecting input like - 
# item_1, DAT, 3, 00:00:00, 12:32:00<, optional comment> 
# Data should be separated by a comma and a space
# Of course, you can just change the constant sep to whatever you want.
#
# While the value of the first 3 values doesn't matter
# The fourth and fifth have to be start and finish
# and the two time values must be in format HH:MM:SS, 24 hour.
#
# IMPORTANT - This was written in Notepad (!), so the TABS are all funky.
# If you want to copy and paste, detabbify and then retab using proper 4 space 
tabs.
# (And of course, change inpFile and outpFile to appropriate names.)
# Python likes forward slashes in paths, they work on all systems.


 




import datetime

# init - inpFile is the data to be processed, sep is what separates the values 
on each line,
# in this case a comma followed by a space. 
# I've read from the file using readlines() instead of read(). This gives a 
list, each line
# being a separate list item. Which makes it easy to step through.



def parseTime(timeStr):
# I love split and a lot of the other string methods
splitTime=timeStr.split(":")
return splitTime


inpFile = "dump.txt"
outpFile = "redumped.txt"
sep = ", "


openFile = file(inpFile, "r")
listOfLines = openFile.readlines()
openFile.close()
newTimes = []


for line in listOfLines:
#Remove superfluous newlines
if line.endswith("\n"):
line=line.rstrip("\n")

#So &qu

Re: [Tutor] Time script help sought!

2005-01-12 Thread Liam Clarke
And I just noticed an error in my correction code!

if len(splitLine) = 5 should be -
if len(splitLine) == 6

Gah

On Thu, 13 Jan 2005 11:48:03 +1300, Liam Clarke <[EMAIL PROTECTED]> wrote:
> I'm real sorry.
> 
> My standard disclaimer is now amended to include - "Never post untested code"
> 
> Disregard everything I wrote above. I feel real bad, so bad that I did
> something I very rarely do... write complete code.
> 
> See attached txt file. Guaranteed to work, if you still want to turn
> 
> Item_4 DAT 5 12:32:05 12:37:13 Funny crackling noise
> 
> into Item_4 DAT 5 00:00:00 00:05:08 Funny crackling noise
> 
> Please note comment can be included. Not overly hard.
> 
> HTH,
> 
> (And sorry for erroneous datetime stuff. Particularly
> datetime.datetime(timedelta object)
> That definitely doesn't work.)
> 
> Never post untested code
> 
> Liam Clarke
> 
> On Wed, 12 Jan 2005 10:08:02 -0500, kevin parks <[EMAIL PROTECTED]> wrote:
> > thanks everyone... I will look at all the various appraoches folks came
> > up with and see what i can learnn from them. I ended doing something
> > lame -- a brute force method. I formmatted and reformatted my input
> > data and stuffed it in a HUGE dictionary it was stupid and
> > kludgy i hope to study all these approaches and learn something
> > that may help me do something that is more flexible about the input
> > data and is more elegant. here's what i
> > came up with ... with my pea sized brain...
> >
> > #!/usr/bin/env python
> >
> > # New in version 2.3 is the 'datetime' module (see standard library
> > reference)
> > # http://www.python.org/doc/lib/module-datetime.html
> >
> > import datetime
> >
> > inseqs = { (1) : ['DAT_1', '01', '00:00:23', '00:08:23'],
> > (2) : ['DAT_1', '02', '00:08:23', '00:09:41'],
> > (513) : ['DAT_75', '10', '00:59:55', '01:11:05'],
> > (514) : ['DAT_75', '11', '01:11:05', '01:16:15'],
> > (515) : ['DAT_75', '12', '01:16:15', '01:34:15'],
> > (516) : ['DAT_75', '13', '01:34:15', '01:45:15'],
> > (517) : ['DAT_75', '14', '01:45:15', '01:48:00'] }
> >
> > mykeys = inseqs.keys()  # first make a copy of the keys
> > mykeys.sort()   # now sort that copy in place
> >
> > for key in mykeys:
> >  event = inseqs[key]
> >  print '\n','Item #', key, event
> >  TD = datetime.timedelta
> >  h, m, s = event[2].split(':')
> >  zero_adjust = TD(hours=int(h), minutes=int(m),seconds=int(s))
> >  #
> >  print ' Q___ ', key, event[:2], ': ',
> >  for item in event[2:]:
> >  hrs, mins, secs, = item.split(':')
> >  time1 = TD(hours=int(hrs), minutes=int(mins),seconds=int(secs))
> >  print time1 - zero_adjust,
> >
> >  print
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> 
> --
> 'There is only one basic human right, and that is to do as you damn well 
> please.
> And with it comes the only basic human duty, to take the consequences.
> 
> 
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] More and more OT - Python/Java

2005-01-12 Thread Liam Clarke
XML, XPath, XML Schema all have basic tutorials at www.w3schools.org

Out of curiosity, how does a node function in a DOM? I'm not very good
at manipulating DOM's, I can do the basics, mainly by passing object
IDs to JS functions, which feels like cheating.




On Wed, 12 Jan 2005 07:57:02 -0500, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Guillermo Fernandez Castellanos wrote:
> > I have not been able to find any recent XML/Python tutorial on the
> > web.
> 
> There is a Python and XML topic guide at python.org
> http://pyxml.sourceforge.net/topics/
> 
> Uche Ogbuji writes regularly about Python and XML for xml.com
> http://www.xml.com/pub/au/84
> 
> Does the xml.dom library have a XPath and XQuery or any SQL-like
> > support? I've understood that it's a pretty basic library...
> 
> My impression is the built-in stuff is pretty basic. If you want to use SAX 
> and DOM for XML in
> Python, the 4Suite add-on is pretty standard.
> http://4suite.org/index.xhtml
> 
> I've also heard good things about libxml2; it includes XPath support
> http://xmlsoft.org/python.html
> 
> IMO Fredrik Lundh's ElementTree package is the easiest way to work with XML 
> from Python. It supports
> a subset of XPath and he has just released a compiled C version
> http://effbot.org/zone/element-index.htm
> 
> Kent
> 
> >
> > Thanks,
> >
> > G
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] List comprehensions

2005-01-12 Thread Liam Clarke
Hi, 

Am I able to achieve something like this - 

def foobar();
# stuff
return

x=[1,1000]

for j=foobar(item) for item in x:

As a comprehension, if you get what I mean... Can I build a for loop
with a function in  for x in x part?

Ack. Having difficulty summing it up properly.



-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehensions

2005-01-12 Thread Liam Clarke
Aah, thank you both - I knew there was a way to do it.

Regards, 

Liam Clarke

PS John - another Kiwi, seems to be a lot of NZers involved in Python
& Python projects. Is  it the No. 8 wire freedom of Python? ; )

On Wed, 12 Jan 2005 18:48:39 -0500, Kent Johnson <[EMAIL PROTECTED]> wrote:
> If you mean for j to be a list of foobar(item) then use
> j=[foobar(item) for item in x]
> 
> The first part of the list comp can be any valid expression.
> 
> Kent
> 
> Liam Clarke wrote:
> > Hi,
> >
> > Am I able to achieve something like this -
> >
> > def foobar();
> > # stuff
> > return
> >
> > x=[1,1000]
> >
> > for j=foobar(item) for item in x:
> >
> > As a comprehension, if you get what I mean... Can I build a for loop
> > with a function in  for x in x part?
> >
> > Ack. Having difficulty summing it up properly.
> >
> >
> >
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is Tkinter the Gui in python

2005-01-12 Thread Liam Clarke
I believe Tkinter + Tix come with your Python install. 
wxPython is another popular GUI, but it is 3rd party.


On Wed, 12 Jan 2005 19:11:06 -, Alan Gauld <[EMAIL PROTECTED]> wrote:
> > Is the standard Tkinter module in python does the GUI - Front -end
> > Interface for Python
> 
> Its the library used for building GUI applications.
> IDLE the Python IDE is built using Tkinter.
> 
> Is that what you mean?
> 
> Alan g.
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Regular expression re.search() object . Please help

2005-01-13 Thread Liam Clarke
...as do I.

openFile=file("probe_pairs.txt","r")
probe_pairs=openFile.readlines()

openFile.close()

indexesToRemove=[]

for lineIndex in range(len(probe_pairs)):

   if probe_pairs[lineIndex].startswith("Name="):
 indexesToRemove.append(lineIndex)

for index in indexesToRemove:
  probe_pairs[index]='""

Could just be

openFile=file("probe_pairs.txt","r")
probe_pairs=openFile.readlines()

openFile.close()

indexesToRemove=[]

for lineIndex in range(len(probe_pairs)):

   if probe_pairs[lineIndex].startswith("Name="):
     probe_pairs[lineIndex]=''





On Fri, 14 Jan 2005 09:38:17 +1300, Liam Clarke <[EMAIL PROTECTED]> wrote:
> > >>> name1 = '[N][a][m][e][=]'
> > >>> for i in range(len(probe_pairs)):
> > key = re.match(name1,probe_pairs[i])
> > key
> >
> > <_sre.SRE_Match object at 0x00E37A68>
> > <_sre.SRE_Match object at 0x00E37AD8>
> > <_sre.SRE_Match object at 0x00E37A68>
> > <_sre.SRE_Match object at 0x00E37AD8>
> > <_sre.SRE_Match object at 0x00E37A68>
> 
> 
> You are overwriting key each time you iterate. key.group() gives the
> matched characters in that object, not a group of objects!!!
> 
> You want
> > >>> name1 = '[N][a][m][e][=]'
> > >>> keys=[]
> > >>> for i in range(len(probe_pairs)):
> > key = re.match(name1,probe_pairs[i])
> > keys.append[key]
> 
> >>> print keys
> 
> > 'Name='
> >
> > 1. My aim:
> > To remove those Name= lines from my probe_pairs
> > list
> 
> Why are you deleting the object key?
> 
> > >>> for i in range(len(probe_pairs)):
> > key = re.match(name1,probe_pairs[i])
> > del key
> > print probe_pairs[i]
> 
> Here's the easy way. Assuming that probe_pairs is stored in a file callde
> probe_pairs.txt
> 
> openFile=file("probe_pairs.txt","r")
> probe_pairs=openFile.readlines()
> 
> openFile.close()
> 
> indexesToRemove=[]
> 
> for lineIndex in range(len(probe_pairs)):
> 
> if probe_pairs[lineIndex].startswith("Name="):
>   indexesToRemove.append(lineIndex)
> 
> for index in indexesToRemove:
>probe_pairs[index]='""
> 
> Try that.
> 
> Argh, my head. You do some strange things to Python.
> 
> Liam Clarke
> 
> On Thu, 13 Jan 2005 10:56:00 -0800 (PST), kumar s <[EMAIL PROTECTED]> wrote:
> > Dear group:
> >
> > My list looks like this: List name = probe_pairs
> > Name=AFFX-BioB-5_at
> > Cell1=96369 N   control AFFX-BioB-5_at
> > Cell2=96370 N   control AFFX-BioB-5_at
> > Cell3=441   3   N   control AFFX-BioB-5_at
> > Cell4=441   4   N   control AFFX-BioB-5_at
> > Name=223473_at
> > Cell1=307   87  N   control 223473_at
> > Cell2=307   88  N   control 223473_at
> > Cell3=367   84  N   control 223473_at
> >
> > My Script:
> > >>> name1 = '[N][a][m][e][=]'
> > >>> for i in range(len(probe_pairs)):
> > key = re.match(name1,probe_pairs[i])
> > key
> >
> > <_sre.SRE_Match object at 0x00E37A68>
> > <_sre.SRE_Match object at 0x00E37AD8>
> > <_sre.SRE_Match object at 0x00E37A68>
> > <_sre.SRE_Match object at 0x00E37AD8>
> > <_sre.SRE_Match object at 0x00E37A68>
> > . (cont. 10K
> > lines)
> >
> > Here it prints a bunch of reg.match objects. However
> > when I say group() it prints only one object why?
> >
> > Alternatively:
> > >>> for i in range(len(probe_pairs)):
> > key = re.match(name1,probe_pairs[i])
> > key.group()
> >
> > 'Name='
> >
> > 1. My aim:
> > To remove those Name= lines from my probe_pairs
> > list
> >
> > with name1 as the pattern, I asked using re.match()
> > method to identify the lines and then remove by using
> > re.sub(pat,'',string) method.  I want to substitute
> > Name=*** line by an empty string.
> >
> > After I get the reg.match object, I tried to remove
> > that match object like this:
> > >>> for i in range(len(probe_pairs)):
> > key = re.match(name1,probe_pairs[i])
> > del key
> > print probe_pairs[i]
>

Re: [Tutor] Re: Is Tkinter the Gui in python

2005-01-13 Thread Liam Clarke
On Fri, 14 Jan 2005 09:51:48 +0900, Guillermo Fernandez Castellanos
<[EMAIL PROTECTED]> wrote:
> > > So tkinter is a good module to use if you only want simple widgets,
> > > but be prepared to switch to something newer when you hit it's
> > limitations.
> > This I agree with totally, fortunately I've yet to hit itslimitations
> > in my fairly simple GUIs.
> Well... there's also Tix... but I don't know if you consider it as
> part of Tk or not.
> 
> It's a bit complicated to get the feel from due to a lack of explicit
> documentation for python, but once you get the tric about the
> Tcl->Python conversion, things get pretty smooth.


Spectix is pretty usable.
-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Regular expression re.search() object . Please help

2005-01-13 Thread Liam Clarke
I'm using 2.3, I was trying to be as explicit as possible. *grin*


On Thu, 13 Jan 2005 22:02:13 -0500, Jacob S. <[EMAIL PROTECTED]> wrote:
> I assume that both you and Liam are using previous-er versions of python?
> Now files are iterators by line and you can do this.
> 
> openFile = open("probe_pairs.txt","r")
> indexesToRemove = []
> for line in openFile:
> if line.startswith("Name="):
> line = ''   ## Ooops, this won't work because it just changes what
> line references or points to or whatever, it doesn't
> ##actually change the object
> openFile.close()
> 
> I think this is a great flaw with using for element in list instead of for
> index in range(len(list))
> 
> Of course you later put IMHO better solutions (list comprehensions,etc.) --
> I just wanted to point out that files have been
> iterators for a few versions now and that is being used more and more. It
> also saves the memory problem of using big files
> and reading them all at once with readlines.
> 
> Jacob
> 
> > Liam Clarke wrote:
> >
> > > openFile=file("probe_pairs.txt","r")
> > > probe_pairs=openFile.readlines()
> > >
> > > openFile.close()
> > >
> > > indexesToRemove=[]
> > >
> > > for lineIndex in range(len(probe_pairs)):
> > >
> > >if probe_pairs[lineIndex].startswith("Name="):
> > >  probe_pairs[lineIndex]=''
> >
> > If the intent is simply to remove all lines that begin with "Name=",
> > and setting those lines to an empty string is just shorthand for that,
> > it'd make more sense to do this with a filtering list comprehension:
> >
> >  openfile = open("probe_pairs.txt","r")
> >  probe_pairs = openfile.readlines()
> >  openfile.close()
> >
> >  probe_pairs = [line for line in probe_pairs \
> >if not line.startswith('Name=')]
> >
> >
> > (The '\' line continuation isn't strictly necessary, because the open
> > list-comp will do the same thing, but I'm including it for
> > readability's sake.)
> >
> > If one wants to avoid list comprehensions, you could instead do:
> >
> >  openfile = open("probe_pairs.txt","r")
> >  probe_pairs = []
> >
> >  for line in openfile.readlines():
> >  if not line.startswith('Name='):
> >  probe_pairs.append(line)
> >
> >  openfile.close()
> >
> > Either way, lines that start with 'Name=' get thrown away, and all
> > other lines get kept.
> >
> > Jeff Shannon
> > Technician/Programmer
> > Credit International
> >
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Posting a large amount of code?

2005-01-16 Thread Liam Clarke
http://www.rafb.net/paste/

is good for when you need to make your code accessible - best of all
it formats the code for you. Just copy & paste your code, and
distribute the link it gives you. Your 'pasted' code expires after 24
hours though.

Regards,

Liam Clarke

On Sun, 16 Jan 2005 02:39:20 -0500, Bill Burns <[EMAIL PROTECTED]> wrote:
> Hello,
> 
> I've been working on a small GUI program (on & off) for a little while now and
> I'd love to have the group (or anyone for that matter) take a look at it and
> give me some pointers. Since I'm not a programmer and I don't do this
> continuously, I don't now if I'm on the right track or not. I'd love to have
> some feedback!
> 
> I had originally posted my program to the list back in Nov. 04.
> 
> The post can be found here:
> http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/2230994
> 
> Since that time it has changed significantly and the amount of code has grown.
> The program is now 552 lines long. According to pycount.py, there's 328 lines
> of code and the rest are docstrings, other comments and blank lines.
> 
> I guess my question is, would it be acceptable to post this much code to the
> list? Maybe this really isn't a lot of code, but it seems like a lot to me, so
> I figured I'd ask first. If it is OK, would it be better to post the code in
> the body of the message or as an attachment? I would think an attachment
> would be better but then maybe attachments are not allowed on the list?
> 
> I've used PyQt and Qt Designer to create this program. The main GUI and one
> other dialog were created with Designer and compiled to python with pyuic.
> These two separate modules are imported into a third module (the main
> program). I'd only send the 'main module' as the other two just contain
> auto-generated code from Designer & pyuic. The 'main module' contains
> the code I've written. Of course, the program will not run unless you have all
> three modules (and PyQt installed).
> 
> I've probably been a little verbose with the comments in the code, but I
> figured if I post it and you don't have the GUI to go along with it, you could
> still get a feel for what the program is doing?
> 
> Let me know. Comments accepted on or off the list.
> 
> Thanks,
> 
> Bill
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Setting the focus to a window

2005-01-16 Thread Liam Clarke
Oops, to the list also.


-- Forwarded message --
From: Liam Clarke <[EMAIL PROTECTED]>
Date: Mon, 17 Jan 2005 09:49:48 +1300
Subject: Re: [Tutor] Setting the focus to a window
To: Orri Ganel <[EMAIL PROTECTED]>


Hi Orri,

What Alan said earlier in the topic. You want to use the Win32UI API,
which Mark Hammond has documented  in a book. You can also download
his WinPython, which includes some documentation, and a link to a
tutorial.

http://starship.python.net/crew/skippy/

Regards,

Liam Clarke

PS the Windows API's are also good for manipulating MS software using
COM objects, don't know how Audacity handles COM/ActiveX


On Sun, 16 Jan 2005 14:51:07 -0500, Orri Ganel <[EMAIL PROTECTED]> wrote:
> Hello all,
>
> As part of a project I'm working on (see archive of previous emails from
> me in the past 2 days or so), I need to change the focus from the
> current window to another window (from Windows Media Player to Audacity
> so that the simulated keypress will have an effect).  I have googled and
> looked in the docs and all, and I can't seem to find a way to do this
> (at least, not with Windows). I found something that sounds about right
> in MacPython, but that doesn't help me . . . Any suggestions on how to
> do this are greatly appreciated.
>
> Thanks in advance,
> Orri
>
> --
> Email: singingxduck AT gmail DOT com
> AIM: singingxduck
> Programming Python for the fun of it.
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


--
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Objects, persistence & getting

2005-01-16 Thread Liam Clarke
Hi all,

Well, one thing learning Java is good for is for thoroughly
demystifying OOP. It's not some magical acronym of programming
goodness, it's just an 'organic' way to organise code.
That, and it looks good on your CV, even if you won't be using it. Like XML.

It's got me thinking about object persistence, though, and plotting as
to how I can use this for my own nefarious ends.

If I understand correctly, once an object is created, as long as
references to it exist, it isn't garbage collected.

So, if module a.py creates an instance of class foo, can method bar in
module b.py access foo without foo being passed directly to bar?

Does that make sense? So, foo is floating around in the namespace, and
bar just wants to grab a field of foo. Can it? I had a poke around the
namespace yesterday, and got lost in hordes of methods that look like
__this__, which is ugly.

Regards,

Liam Clarke
-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Objects, persistence & getting

2005-01-17 Thread Liam Clarke
Law of Demeter?

And, OK I'll just pass references, it was a passing idle thought.
But thanks : )

What kind of languages espouse real OOP? Smalltalk gets mentioned a lot. Ruby?

Regards,

Liam Clarke

On Mon, 17 Jan 2005 07:48:28 -, Alan Gauld <[EMAIL PROTECTED]> wrote:
> > Well, one thing learning Java is good for is for thoroughly
> > demystifying OOP.
> 
> 
> I'd have to disagree here because Java's version of OOP has
> very little to do with real OOP. Java just uss classes as
> a kind of modularisation mechanism and does not make much
> use of tthe real OO features. In fact it doesn't even
> support several of the things that enable real OO
> programming.
> 
> And its class library, a strong feature because it is a
> standard, is dreadful from an OOP p[erspective. In fact
> I usually refer to Java as a Class Oriented Programming
> rather than Object Oriented.
> 
> It is possible to use Java in an OOP way (read Brice Eckel's
> "Thinking in Java" to see how) but the language itself
> encourages a style of programming that is much more like
> Pythons modules than true OOP.
> 
> > It's not some magical acronym of programming
> > goodness, it's just an 'organic' way to organise code.
> 
> Certainly in Java thats true, and indeed even at the
> higher level OOP is a way of organizing code - by
> finding high level abstractions and building tree
> structures based on common intefaces. But Java doesn't
> encourage that structuring as much as Python does!
> 
> 
> > If I understand correctly, once an object is created, as long as
> > references to it exist, it isn't garbage collected.
> 
> Yes.
> 
> > Does that make sense? So, foo is floating around in the namespace,
> and
> > bar just wants to grab a field of foo. Can it?
> 
> It shouldn't - it should be sending a message. One of
> the bad things about Java is it encourages the use
> of getXXX and setXXX style methods which are a total
> anathema to real OOP. They break the Law of Demeter.
> 
> Alan G.
> 
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need advice on streamlining code...

2005-01-17 Thread Liam Clarke
Well, if you're looking to extract the IP & mask you could use a
regEx. They're not to bad

If it's only that line that you're extracting, and it's format doesn't change 

import re
pattern='ifconfig_fxp0="inet (?P*.?) netmask (?P*.?)"
reObj=re.compile(pattern, IGNORECASE)

jay = os.popen("grep ifconfig_fxp0 /etc/rc.conf").readlines()

matches=reObj.search(jay[0])

ip = matches.group('ip')
netmask =matches.group('mask') #You can then do your string splits,
whatever now.

HTH

Liam Clarke

regExs, can be your friends. If you KISS.

On Mon, 17 Jan 2005 11:05:59 -0800 (PST), Chad Crabtree
<[EMAIL PROTECTED]> wrote:
> I can't really think of a more elegant solution than what you have,
> maybe regex's but I hate those.  You *can* reduce the number of lines
> by
> two, and there was a variable you never used.
> HTH
> Eric L. Howard wrote:
> 
> >The following block of code works, and provides the necessary output
> I'm
> >looking for...but I have a feeling that it's working through sheer
> brute
> >force and could be better:
> >
> >insideipgrepfd = os.popen("grep ifconfig_fxp0 /etc/rc.conf")
> >insideipgrep = insideipgrepfd.readlines()
> >
> >
> insideipgrep=os.popen("grep ifconfig_fxp0 /etc/rc.conf").readlines()
> 
> >insideipfield, insideip =
> string.split(string.strip(insideipgrep[0]), "=")
> >
> >
> insideip = string.split(string.strip(insideipgrep[0]), "=")[1]
> 
> >insideipsplit = string.split(insideip, " ")
> >insideipquads = string.split(insideipsplit[1], ".")
> >insidemaskquads = string.split(insideipsplit[4], ".")
> >
> >
> insideipquads=string.split(string.split(insideip, " ")[1],".")
> insidemaskquads = string.split(string.split(insideip, " ")[4], ".")
> 
> >the line in /etc/rc.conf looks like:
> >
> >ifconfig_fxp0="inet 172.31.2.100 netmask 255.255.255.0"
> >
> >Any and all thoughts/pointers are appreciated.
> >
> >~elh
> >
> >
> >
> 
> 
> __
> Do you Yahoo!?
> Meet the all-new My Yahoo! - Try it today!
> http://my.yahoo.com 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need advice on streamlining code...

2005-01-17 Thread Liam Clarke
yeah, I wasn't sure about that readline/lines thing, cos I'm not sure
how popen works.


On Mon, 17 Jan 2005 21:38:37 -0500, Jacob S. <[EMAIL PROTECTED]> wrote:
> I seem to always be the one to suggest this, but --
> 
> "String methods are better than using the string module because the string
> module has been ?deprecated? or will be soon. I think that is the word here.
> So, do this instead."
> 
> insideipgrepfd = os.popen("grep ifconfig_fxp0 /etc/rc.conf")
> insideipgrep = insideipgrepfd.readline()  ## Says same thing below --
> readline() just reads first line
> insideipfield, insideip = insideipgrep[0].strip().split("=")
> insideipsplit = insideip.split()
> insideipquads = insideipsplit[1].split(".")
> insidemaskquads = insideipsplit[4].split(".")
> 
> And, heck, I know it wouldn't be that simple, but if the line stays the same
> but just the numbers change, you can do,
> 
> insideipgrepfd = os.popen("grep ifconfig_fxp0 /etc/rc.conf")
> insideipgrep = insideipgrepfd.readlines()  ##Wait, if you're just using the
> first line use insideipgrepfd.readline()
> insideipgrep = insideipgrep.lstrip("ifconfig_fxp0=\"inet ")
> temp = insideipgrep.split(" netmask ")
> insideipquads = temp[0].split(".")
> insideipmaskquads = temp[1].split(".")
> 
> Warning, code just above is not very stable --  if the text of the line
> changes in anyway it won't work.
> 
> HTH,
> Jacob Schmidt
> 
> > The following block of code works, and provides the necessary output I'm
> > looking for...but I have a feeling that it's working through sheer brute
> > force and could be better:
> >
> >insideipgrepfd = os.popen("grep ifconfig_fxp0 /etc/rc.conf")
> >insideipgrep = insideipgrepfd.readlines()
> >insideipfield, insideip = string.split(string.strip(insideipgrep[0]),
> > "=")
> >insideipsplit = string.split(insideip, " ")
> >insideipquads = string.split(insideipsplit[1], ".")
> >insidemaskquads = string.split(insideipsplit[4], ".")
> >
> > the line in /etc/rc.conf looks like:
> >
> > ifconfig_fxp0="inet 172.31.2.100 netmask 255.255.255.0"
> >
> > Any and all thoughts/pointers are appreciated.
> >
> >~elh
> >
> > --
> > Eric L. Howard   e l h @ o u t r e a c h n e t w o r k s . c o m
> > 
> > www.OutreachNetworks.com313.297.9900
> > 
> > JabberID: [EMAIL PROTECTED] Advocate of the Theocratic Rule
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Objects & Classes...

2005-01-17 Thread Liam Clarke
Curious - what's mod_python?


On Tue, 18 Jan 2005 03:10:44 +, Max Noel <[EMAIL PROTECTED]> wrote:
> 
> On Jan 18, 2005, at 02:59, Jack Cruzan wrote:
> 
> > Wouldn't it though! I haven't checked but doesn't he use xml for his
> > equipment lists - if that was the case it would be worth it to ask him
> > for those files 'eh?
> 
> Last time I checked, he didn't. I have the DAT files here (extracted
> them off a Windows installation of the program) and have been trying to
> write a Python script that would convert them to XML.
> However, the file format is exotic and inconsistent (just like VB,
> some would say ;) ), so I haven't found a way yet to write an
> "universal converter": the script has to be modified for each file. I'm
> pleased neither with this solution, nor with the way my script looks:
> it's ugly.
> 
> At some point, such a converter will have to be written, though,
> unless you want to go through the extreme pleasure of going through 1
> meg of text files by hand.
> 
> Hmm, I really should try to start working again on this web-based SRCG
> idea of mine... The whole thing just screams "database". Daaargh, so
> many things to do, so little time. I suppose no good mod_python
> tutorials have spawned since last time I asked, right?
> 
> -- Max
> maxnoel_fr at yahoo dot fr -- ICQ #85274019
> "Look at you hacker... A pathetic creature of meat and bone, panting
> and sweating as you run through my corridors... How can you challenge a
> perfect, immortal machine?"
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fw: Please submit to tutor list: dictionary update prob

2005-01-19 Thread Liam Clarke
 update_dict(data_holder, filename)
>else:   # file no exist
>write_book(data_holder, filename)
>break
>else:
>d.clear()   #clear dict
>break


There's two elses, but no inital if:
There's a place to start, right there.


On Wed, 19 Jan 2005 21:27:24 -0500, Jacob S. <[EMAIL PROTECTED]> wrote:
> Hi everyone, sent this on to the list as told to.
> cc to eri to verify my sending to list...
> ;-) Jacob
> 
> > dear jacob,
> >
> > sorry to send this to you but if you may, kindly send to tutor list as im
> > no longer subscribed.  my problem is in the update dict portion: it just
> > doesnt update regardless how many contacts i add. kindly advise where
> > my mistake is or code gone wrong. the rest of the options i will do on my
> > own so just hold off the helps for now. appreciate all your good help.
> >
> > please cc to this account.
> >
> > --
> > regards,
> > erimendz
> >
> >
> > #!/usr/bin/env python
> >
> > import cPickle, os, sys, re, stat
> > #import string
> >
> > ## Global variables
> >
> >
> > home = '~'
> > filename = os.path.join(os.path.expanduser(home), 'abook.dat')
> > data_holder = {}
> >
> >
> >
> > ## Functions
> > ##
> >
> >
> > def about_program():
> >print
> >print '\t'*2, 'A simple address book written in Python'
> >raw_input('\nPress  to continue...')
> >
> >
> > ## add_contact ##
> > def add_contact(d):
> >while True:
> >name = add_name()
> >email = add_email()
> >d[name] = email
> >print 'Add another contact? '
> >ans = ask_yes_no()
> >if ans == 0:# no
> >print 'Save to address book? '
> >get_ans = ask_yes_no()
> >if get_ans == 1:# yes
> >#collected = d
> >check = if_file_exist(filename)
> >if check is True:
> >  update_dict(data_holder, filename)
> >else:   # file no exist
> >write_book(data_holder, filename)
> >break
> >else:
> >d.clear()   #clear dict
> >break
> >
> > def add_name():
> >msg = 'Enter contact name: '
> >while True:
> >try:
> >name = raw_input(msg)
> >if len(name) != 0:
> >if len(name) <= 20:
> >return name
> >else:
> >print 'Name too long: please limit to 20 characters'
> >else:
> >print 'Try again: blank not allowed!'
> >except EOFError:# catch ^C-D keypress
> >print
> >
> > def add_email():
> >msg = 'Enter email address: '
> >while True:
> >try:
> >email = raw_input(msg)
> >if len(email) == 0:
> >print 'Blank not allowed!'
> >else:
> >valid_format =
> > r'[EMAIL PROTECTED](\.[-a-z0-9]+)*\.(com$|\
> >edu$|net$|gov$|mil$|org$|int$|aero$|biz$|coop$|
> > museum$|pro$|info$)'
> >valid_email = re.compile(valid_format)
> >if valid_email.match(email):
> >return email
> >else:
> >print '%s is not a valid address: try again!' % email
> >except EOFError:
> >print
> >
> >
> > def ask_yes_no():
> >try:
> > ask = raw_input('Yes or No? [y|N] ')
> > if ask.lower() in ['y', 'ye', 'yes', 'yep', 'ok']:
> > return 1# yes
> > else:
> > return 0# no
> >except EOFError:
> > print
> >
> >
> > def if_file_exist(f):
> >''' test if file exists; returns boolean '''
> >
> >return os.path.exists(os.path.join(os.path.expanduser('~'), f))
> >
> > def get_filesize(f):
> >''' check file size '''
> >
> >return os.stat(os.path.join(os.path.expanduser('~'), f))[stat.ST_SIZE]
> >
> >
> > def write_book(d, f):
> >write = open(f, 'wb')
> >cPickle.dump(d, write)
> >write.close()
> >
> > def update_dict(d, f):
> >''' update the saved dictionary file '''
> >
> >read = open(f, 'rb')
> >newdic = cPickle.load(read)
> >newdic.update(d)
> >read.close()
> >
> >
> >
> >
> > ## view_abook() ##
> > def view_abook(d, f):
> >check = if_file_exist(f)
> >if check is True:
> ># load file and pretty print
> >read = open(f, 'rb')
> >d = cPickle.load(read)
> >for k, v in d.iteritems():
> >print '%s\t%s' % (k, v)
> >read.close()
> >else:
> >print 'no contacts listed!'
> >
> >
> >
> > ## function tester, sort of ##
> > def ifaccessible(f):
> >''' test if file is accessible by user; returns boolean '''
> >
> >return os.access(os.path.join(os.path.expanduser('~'), f), os.F_OK)
> >
> >
> >
> > def main():
> >while True:
> >select = main_menu()
> >   

Re: [Tutor] Unexpected result from decimal

2005-01-19 Thread Liam Clarke
Jacob- one slight flaw/quirk in Python is if you want floating point
computations you have to specify a floating point.

>>> import decimal
>>> decimal.getcontext().prec = 2
>>> a = decimal.Decimal(2)
>>> b = decimal.Decimal(3)
>>> 100*a/b
Decimal("67")
>>> print 100*a/b


try - 

a=decimal.Decimal(2.0)
b = decimal.Decimal(3)
print 100*a/b

Same as writing 100/3.0 as opposed to 100/3. Try it. 

On Wed, 19 Jan 2005 22:07:35 -0500, Tim Peters <[EMAIL PROTECTED]> wrote:
> [Jacob S.]
> >I'm having a problem that is ticking me off. (to put it lightly)
> > Why does decimal do this --  I thought that getcontext().prec
> > was number of decimal places?
> 
> It's unclear what you mean by "decimal places".  From context, you
> _appear_ to mean "number of decimal digits after the radix point".  In
> that case, no, that's not what precision means.  decimal is a
> floating-point type, not a fixed-point type, and precision is the
> total number of significant digits; the location of the radix point is
> irrelevant.  The rules are spelled out in great detail here:
> 
> http://www2.hursley.ibm.com/decimal/
> 
> > >>> import decimal
> > >>> decimal.getcontext().prec = 2
> > >>> a = decimal.Decimal(2)
> > >>> b = decimal.Decimal(3)
> > >>> 100*a/b
> > Decimal("67")
> > >>> print 100*a/b
> > 67
> > >>>
> >
> > Why does it do this?
> 
> It's doing what you told it to do.  It would have helped if you had
> been specific about what you wanted it to do.  For example, did you
> want 66.67, or what?
> 
> > It's really, really, messing things up for me because results are
> > not interpreted in my programs correctly.
> 
> Change your code .  Perhaps this is what you wanted?
> 
> >>> import decimal
> >>> pennies = decimal.Decimal("0.01")
> >>> a = decimal.Decimal(2)
> >>> b = decimal.Decimal(3)
> >>> print 100*a/b
> 66.67
> >>> print (100*a/b).quantize(pennies)
> 66.67
> >>>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] counting no of words

2005-01-20 Thread Liam Clarke
I'd take the easy way out and use winPython's COM objects to open the
doc in word, and save it as .txt
and then - 

f=file("doc.txt",'r')
j=f.read()
j=j.split(" ")
print len(j)



On Thu, 20 Jan 2005 13:59:16 -0500, Roger Merchberger
<[EMAIL PROTECTED]> wrote:
> Rumor has it that Bill Mill may have mentioned these words:
> >[snip]
> >Once you're connected to a word document, you'll have to figure out
> >what the command to count the words in the document is, but that's
> >just a matter of recording a macro in word where you count the words,
> >then repeating it in python.
> 
> Another option would be to write the python program from within
> OpenOffice.org if it's available -- it has facilities of opening and
> accessing word documents as well.
> 
> >I'd help you with that, but I'm on linux.
> 
> Most things I do are on Linux as well; but the OpenOffice solution should
> work equally well on either platform.
> 
> HTH,
> Roger "Merch" Merchberger
> 
> --
> Roger "Merch" Merchberger  --  SysAdmin, Iceberg Computers
> [EMAIL PROTECTED]
> 
> Hi! I am a .signature virus.  Copy me into your .signature to join in!
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Syntactical question / OT Lisp

2005-01-20 Thread Liam Clarke
Hi all, 

(side note - the net is not a luxury when attempting to learn to code) 

Just pondering my coding efforts, and just wanted to clarify something. 

I've got a module called foo.py

foo.py - 

import parrot

class Bar(model.Background):

def __initialize__(self, event):
 #Just a pythoncard variant on init
 self.config=self.loadCfg()


   def loadCfg():
#get some cfg stuff, return as dict
return cfgDict

   def on_aBtn_mouseClick(self, event):
 parrot.Sketch()

app=Bar(main.application)
app.mainloop()


If I wanted the function parrot.Sketch() to access that config
dictionary, I would reference it as

foo.app.config?

Is that right?

Regards,

Liam Clarke
-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Ooer, OT Lisp

2005-01-20 Thread Liam Clarke
Oops, 

and OT ~ Has anyone used Lisp? I've been reading Paul Graham's essays
on how great Lisp is, and how Python is near to implementing features
Lisp had in the 60's. Also found the concept of macros interesting.

Queries - 

1) Anyone here familiar with both?
2) If so, which would you rate as more powerful?
3) What's with all those parentheses?
4)  Perhaps the powerful question's a bit vague, how about ease of
use? I like that the simplest Lisp expression is - , but those
brackets
5) Are you able to point me towards a simplified explanation of how
the 'syntaxless' language can write programmes?

Sorry to play 20 questions.

Regards, 

Liam Clarke

-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Print record x in a file

2005-01-23 Thread Liam Clarke
Don't you mean 

x=random.randint(0, lenoflist) ?? I'm assuming you want an integer.


On Sun, 23 Jan 2005 21:55:27 + (GMT), David Holland
<[EMAIL PROTECTED]> wrote:
>  --- [EMAIL PROTECTED] wrote:
> > Send Tutor mailing list submissions to
> >  tutor@python.org
> >
> > To subscribe or unsubscribe via the World Wide Web,
> > visit
> >  http://mail.python.org/mailman/listinfo/tutor
> > or, via email, send a message with subject or body
> > 'help' to
> >  [EMAIL PROTECTED]
> >
> > You can reach the person managing the list at
> >  [EMAIL PROTECTED]
> >
> > When replying, please edit your Subject line so it
> > is more specific
> > than "Re: Contents of Tutor digest..."
> >
> >
> > Today's Topics:
> >
> >1. Re: Print record x in a file (Kent Johnson)
> >2. How would python messure up in performance?
> > (Kevin)
> >3. Re: How would python messure up in
> > performance? (Max Noel)
> >4. Re: Print record x in a file (David Holland)
> >5. on the way to find pi (Ali Polatel)
> >6. Re: on the way to find pi (Max Noel)
> >7. Re: on the way to find pi (Orri Ganel)
> >
> >
> >
> --
> >
> > Message: 1
> > Date: Sun, 23 Jan 2005 07:46:08 -0500
> > From: Kent Johnson <[EMAIL PROTECTED]>
> > Subject: Re: [Tutor] Print record x in a file
> > Cc: tutor python 
> > Message-ID: <[EMAIL PROTECTED]>
> > Content-Type: text/plain; charset=ISO-8859-1;
> > format=flowed
> >
> >   Since len(listcontents) is one greater than the
> > largest valid index of listcontents, the correct
> > use of randrange() for this problem is
> >x = random.randrange(0, len(listcontents))
> >
> 
> 
> Kent,
> 
> I know that you know far more about python than me but
> is that right ?
> I created file with 4 records and this code did print
> them all randomly:-
> 
> import random
> i = 0
> while i < 10:
> file = open('filename')
> listcontents = file.readlines()
> file.close()
> lenoflist = len(listcontents)-1
> x = random.randrange(0,lenoflist)
> print listcontents[x], i
> i = i +1
> 
> While although this code below does work many times
> nothing is printed out.
> import random
> i = 0
> while i < 10:
> file = open('test.rantxt')
> listcontents = file.readlines()
> file.close()
> lenoflist = len(listcontents)#-1
> x = random.randrange(0,lenoflist)
> print listcontents[x], i
> i = i +1
> 
> 
> ___
> ALL-NEW Yahoo! Messenger - all new features - even more fun! 
> http://uk.messenger.yahoo.com
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Convert string to variable name

2005-01-27 Thread Liam Clarke
I've used something along the lines for Pythoncard, but the names are
generated within strict rules and expectations.

i.e. 

first off â 

#Some code that uses regExs, finds all headings, and
# a asterisk to indicate a date value, returns a iterable object
reHead using finditer()
#which contains two groups, head and date
#date is either a '' or '*' which evals to False/ True for my purposes
#The asterisk isn't important, it's just a non-null.


counter = 0 # I use nums as keys for easy sort/increment
dex={}

for item in reHead:
  dex[counter]={'title':item.group('head'),
  'date': item.group('date') }
   counter += 1

j=cPickle.Pickler(someOpenFile)
j.dump(dex)
someOpenFile.close()



x=cPickle.Unpickler(someOpenFile)
dex2 = x.read()

for key in dex2.keys():
  buttName = '%dbutton' % key
  choiceName = %dchoice % key

  if dex2[key]['date']:
  choiceList=['Past', Present', 'Future']
  else:
   choiceList = ['Highest', 'Lowest', 'Average']

  self.components[buttName] = {
'type': 'button',
'name': buttName,
'label' :
dex2[key]['title']
 â..
  }

  self.components[choiceName] = {
'type': 'choice',
'name': choiceName,
'label' :
"Select option",
'items' :
choiceList,
'stringSelection': choiceList[0] 
 }

 
Only reason I do it this way, as opposed to using a list, is a stylistic choice.
But yeah, you end up iterating a whole lot, and unless the variable
names are generated
predictably, you have a hard time referencing stuff.
So, in conclusion, dynamically named variables are very limited in
their usefulness.



On Thu, 27 Jan 2005 09:21:51 -, Alan Gauld <[EMAIL PROTECTED]> wrote:
> > This is something I've been trying to figure out for some time.  Is
> > there a way in Python to take a string [say something from a
> > raw_input] and make that string a variable name?  I want to to this
> so
> > that I can create class instances on-the-fly, using a user-entered
> > string as the instance name.
> 
> This comes up regularly from beginners and is nearly always a bad
> idea!
> 
> The easy solution is to use a dictionary to store the instances.
> See the OOP topic in my tutor for an example using bankAccounts
> as the objects...
> 
> > could accomplish something similar using a plain old dictionary, but
> I
> > was playing around with the OOP stuff and thought it might be a neat
> > thing to try out.
> 
> A Dictionary is best. The problem is, once you create your new
> variables none of the rest of your code knows aout them so
> how can it access them. And what if someone enters a name that
> is being iused elsewhere in your code? You will overwrite a
> real variable with this new object! Very tricky to control.
> 
> Alan G
> Author of the Learn to Program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Fwd: [Tutor] Control flow

2005-01-29 Thread Liam Clarke
< erk, to the list, to the List!>

if ( bad_weather =='y' ):
   # ask user only if weather is bad.
   b = input ( "Weather is really bad, still go out to jog?[y/n]" )
   if b == 'y':
  go_jogging()

Anyone else notice that he's never gonna go jogging if the weather is bad?
Unless I've got input() wrong, it only takes integers... ?

Regards,

Liam Clarke

--
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Naming conventions (was: Should this be a list comprehension or something?

2005-01-29 Thread Liam Clarke
Just please_don't_use_underscores. 

They_make_my_eyes_go_funny_, _and_code_hard_to_read_in_my_opinion.

_u_n_d_e_r_s_c_o_r_e_s_ _a_r_e__u_g_l_y_

I got out of the habit of using them really fast.
Also, __ & _ tend to have special meaning in Python (which is bad
enough as it is), so I don't use them for that reason as well.


Liam Clarke
On Fri, 28 Jan 2005 22:54:08 -0500, Jacob S. <[EMAIL PROTECTED]> wrote:
> You're my best friend. Everyone else looves camelCase, and I hate it too. It
> doesn't make sense. It doesn't fit English.
> It doesn't fit Spanish. It doesn't fit any other language AFAIK, so why
> should a human (who uses spoken language) to computer interpreter use a
> naming convention that doesn't match spoken language? That's my opinion.
> 
> Jacob Schmidt
> 
> 
> > On Wed, 26 Jan 2005, Sean Perry wrote:
> >
> >> And now, for the pedant in me. I would recommend against naming
> >> functions with initial capital letters. In many languages, this implies
> >> a new type (like your Water class). so CombineWater should be
> >> combineWater.
> >
> > I hate hate hate hate hate camelcase and will never use it.  In my book,
> > if the name has *any* capitals in it, the first letter is capitalized,
> > too.  Anything else is unaesthetic.
> >
> > To me, when I have names that are composed of multiple words (say, "rice
> > quantity"), I have two approaches: distinguishing the words by case
> > (RiceQuantity) or separating by underscores (rice_quantity).
> >
> > I never confuse classes/instances and methods, because I use noun phrases
> > for classes and instances (HeatedWater, VerifiedInput) and verb phrases
> > for the methods (CombineWater, CookRice).  I suppose I could get
> > confusion, for example, when the combination either a noun phrase or
> > verb phrase (SoundOut: is that a name describing the Sound that's being
> > put Out, or is it a method that's is tentatively Sounding Out somthing?)
> > but so far that hasn't been an issue for me.
> >
> > Of course in my case, I write code only for myself, so I have the luxury
> > of not worrying about what Joe in the next cubicle is doing, and what Jane
> > will do when she's trying to read Bob's and my code together.  So I have
> > the luxury of turning my nose up at camelCase.
> >
> > I should add that, the one time I made changes to someone else's Python
> > code for release (a minor patch to nntplib.py), I used the same case
> > conventions already in place in the module.
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Naming conventions (was: Should this be a list comprehension or something?

2005-01-29 Thread Liam Clarke
Don't get me wrong, underscores have their place, 
butNotInEveryVariableName.
That_was_only_slightly_less_annoying, however.

I propose a new syntax -

All methods, shall be called Jacques, or a derivative thereof (Jack, Jake etc.)

All variables, Claude.

Oh, and you could use funny little symbols like @_> to clarify the
whole situation

(in other words, Python is always more readable then certain camels.)


On Sat, 29 Jan 2005 09:10:49 -0500, Kent Johnson <[EMAIL PROTECTED]> wrote:
> iguessthereisnooptionleftexcepttorunwordstogetherwithoutanykindofbreakatall
> 
> thatshouldannoyeveryoneequally
> 
> Kent
> 
> Liam Clarke wrote:
> > Just please_don't_use_underscores.
> >
> > They_make_my_eyes_go_funny_, _and_code_hard_to_read_in_my_opinion.
> >
> > _u_n_d_e_r_s_c_o_r_e_s_ _a_r_e__u_g_l_y_
> >
> > I got out of the habit of using them really fast.
> > Also, __ & _ tend to have special meaning in Python (which is bad
> > enough as it is), so I don't use them for that reason as well.
> >
> >
> > Liam Clarke
> > On Fri, 28 Jan 2005 22:54:08 -0500, Jacob S. <[EMAIL PROTECTED]> wrote:
> >
> >>You're my best friend. Everyone else looves camelCase, and I hate it too. It
> >>doesn't make sense. It doesn't fit English.
> >>It doesn't fit Spanish. It doesn't fit any other language AFAIK, so why
> >>should a human (who uses spoken language) to computer interpreter use a
> >>naming convention that doesn't match spoken language? That's my opinion.
> >>
> >>Jacob Schmidt
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] files in a directory

2005-01-30 Thread Liam Clarke
Hey Kumar, 

You redirect stdin a lot.

try this.

import os

def parse(filename):
   try:
 f1 = open(filename,'r')
   except IOError:
 return
 #Listdir returns a list of files and sub-dirs, and an attempt
 #to open a sub-dir raises an IOError.

   int = f1.read().split('\n')

   my_vals  = intParser(int)

   intParser return a list
   f2  = open('myvalues.txt','a')
   # I appended this one, cos I'm assuming you wanted
   #all the input in one file. For sep files, I'd just do 
   #something like f2  = open(filename+'.txt','w')

   for line in my_vals:
 f2.write(line)
 f2.write('\n')

   f2.close()
   return

kx = os.listdir('your_directory_here')

for filename in kx:
 parse(kx)


So yeah, os.listdir() is your friend. Just remember the try - IOError
block to catch sub-dirs.

Standard disclaimer -

prolly is a better, cleaner, simpler way to do it. But, this way works. 
And it's better (imao) than redirecting stdin all the time.

Regards,

Liam Clarke

On Sun, 30 Jan 2005 00:03:18 -0800 (PST), kumar s <[EMAIL PROTECTED]> wrote:
> Hello.
> 
> I wrote a parser to parse spot intensities. The input
> to this parser i am giving one single file
> 
> f1 = open('my_intensity_file.dml','r')
> int = f1.read().split('\n')
> 
> my_vals  = intParser(int)
> 
> intParser return a list
> f2  = open('myvalues.txt','w')
> for line in my_vals:
>  f2.write(line)
>  f2.write('\n')
> 
> f2.close()
> 
> The problem with this approach is that, i have to give
> on file per a run. I have 50 files to pare and i want
> to do that in one GO.  I kepy those 50 files in one
> directory. Can any one suggest an approach to automate
> this process.
> 
> I tried to use f1 = stdin(...) it did not work. i dont
> know , possible is that i am using incorrect syntax.
> 
> Any suggestions.
> 
> Thank you.
> K
> 
> 
> __
> Do you Yahoo!?
> All your favorites on one personal page â Try My Yahoo!
> http://my.yahoo.com
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


--  
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only ba  sic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Ports / sockets?

2005-01-30 Thread Liam Clarke
Hi, 

I was reading an article about 'honeytrapping' ports to slow down port
scanners, and it made reference to Perl, but I was wondering, how
feasible in Python is a script that waits for requests to (normally
unused) ports, and then malforms a response to those requests?

I'm aware this is illegal in some US states, but this is more of a
'how would you do that' scenario rather than 'I need to do this'.

Sockets tend to use localhost? Java interpreters and Python
interpreters all seem to call localhost.
So, do sockets use ports? Or, do ports use sockets? Or, do programmes
create sockets which can utilise ports? If so, can you access a port
directly in Python?

I always wanted to be able to the nitty gritty stuff like accessing a
particular port, but I always thought I'd have to learn Cpp to do it.

Regards,

Liam Clarke
-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to sum rows and columns of a matrix?

2005-01-31 Thread Liam Clarke
There's a specific package for arrays 

http://www.stsci.edu/resources/software_hardware/numarray

that implements array mathematics. I use it for pixel map manipulation
in pygame, so it's relatively fast.


On Mon, 31 Jan 2005 19:09:59 +0100, Gregor Lingl <[EMAIL PROTECTED]> wrote:
> Hi all of you,
> 
> I'm representing a 4x4 matrix as a 16-element list, e.g.
> 
> m=range(16)
> 
> first 4 elements first row, second four elements second row etc.
> I want to sum rows and columns like
> 
> i-th row:
> 
> sum(m[4*i:4*i+4])
> 
> and ith column:
> 
> sum(m[i::4])
> 
> This seems to be slow because of the formation of the slices.
> I wonder if there is a way using generators or generator-expressions
> (which I didn't study yet) to compute these sums without copying
> parts of the matrix to a new list. (I'd guess that there should exist
> some canonical generator for sequences, which produces their elements
> ..., maybe also for slices ?)
> 
> All comments, hints, solutions are welcome.
> 
> Regards,
> Gregor
> 
> --
> Gregor Lingl
> Reisnerstrasse 3/19
> A-1030 Wien
> 
> Telefon: +43 1 713 33 98
> Mobil:   +43 664 140 35 27
> 
> Autor von "Python für Kids"
> Website: python4kids.net
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Better structure?

2005-02-01 Thread Liam Clarke
> http://www.cs.bell-labs.com/cm/cs/pearls/
That link seems to be dead. Pity. My whole programming experience is
comprised of Ah-Ha's followed by Um's...





-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Presentation

2005-02-02 Thread Liam Clarke
Hi Danny, 

I think that learning Python naturally leads to learning programming.
It's like learning to fly, you learn to fly in a Cessna or Piper
Cherokee. Simple, elegant, easy to operate. You can then focus on the
art of flying, not on how exactly you lower the flaps. Then, once
you're good at flying, you move to the Pitt's Special.

(Actually could you imagine a plane built by Perl enthusiasts...

How do I lower the flaps?
Well, you can push this button, or pull that lever, or lean to the
right, or you could install this cool module that lowers them when you
wink your left eye twice in 5 seconds. Remember, there's more than one
way to do it!)


Regards,

Liam Clarke
On Wed, 2 Feb 2005 00:59:44 -0800 (PST), Danny Yoo
<[EMAIL PROTECTED]> wrote:
> 
> 
> > The community is one of the things I particularly like about Python.  I
> > always hated asking a question in the Perl newsgroups; although you
> > usually got an answer, you were almost certain to be told you're stupid
> > for not already knowing it.
> 
> Hi Terry,
> 
> Just to act as Devil's advocate: the programming language communities are
> large enough to support subcultures.  So the experiences you have had in
> the seedy corners of comp.lang.perl are probably not representative of the
> Perl community as a whole.
> 
> Some newsgroups are notoriously noisy, and even comp.lang.python can get a
> little hairy at times.  The mailing list communities tend to be a bit more
> civilized because they have a strong topical focus.
> 
> For people who do want to learn Perl, the web site:
> 
> http://learn.perl.org/
> 
> and Casey West's 'beginners' Perl mailing list:
> 
> http://www.nntp.perl.org/group/perl.beginners/
> 
> appear to be excellent resources.  So the Perl community there is also
> doing what they can to help folks learn Perl.
> 
> We, as Python programmers, should do one step better: we should help folks
> learn programming as well as Python.  *grin*
> 
> Best of wishes to you!
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Better structure?

2005-02-02 Thread Liam Clarke
Hello all, 


> > So, how would one go about this in a non broken code way? Don't they
> have
> > something like what I'm requesting.

If not,it's a challenge you can implement yourself! Ever use QBasic?
Had a command -

a$ = inkey$(1)

Which would return a key press as a$. 
Very handy for 'press any key. It's next to the space bar. Honest' dialogues. 

Anyway, I come to Python, I want inkey$ damnit! 

So, I examine, and build it - 

import msvcrt

def inkey():
   print "Press any key. It's next to the space bar. Honest."
   while not msvcrt.kbhit():
   pass
   return

Save it, and et voila. Anytime I want my inkey, I import a file called
pause, and call
pause.inkey(). 

Now, how many other peoples would need that?

I use string.lstrip() in the same way you do - to strip prefixes. What
Kent has mentioned is a caveat on using it, that's all.


> 
> And finally remember that Python is built by volunteers mostly.
> You should be pleased the *bothered* to write any of it!
> 

Exactly. You shouldn't complain that something free doesn't have the
precise features you require. If you installed Linux and you can't
play your DirectX capable games, should Linux support DirectX just for
you, or should you install Windows?

Don't mean to sound too censorious, but the Python library is
fantastic, and it's free. It's got some twists, but it's mostly
documented and usually works. Not bad for $0.00 eh?

Regards, 

Liam Clarke


On Wed, 2 Feb 2005 08:52:20 -, Alan Gauld <[EMAIL PROTECTED]> wrote:
> Jacob,
> 
> Writing library code is a difficult and unrewarding task
> - I've been there so I sympathise, however...
> 
> > So, how would one go about this in a non broken code way? Don't they
> have
> > something like what I'm requesting.
> 
> Its not broken, its just different to what you want.
> What you want is much simpler than what lstrip does
> so you can easily code your requirements.
> Try writing the code to do what lstrip actually does
> - its much harder. So the library includes the more
> difficult function and lets you code the easy ones.
> 
> > It seems to me that a few things are flawed in the standard
> distribution.
> 
> No library is perfect - you should try using C!
> 
> But the Python library isually has good reasons for its
> apparent limitations.
> 
> > Little things like the overlooking of adding a method or function to
> decimal
> > for returning an instance with x places right of the decimal.
> 
> But there is very little need to do that. Usually you only want
> to do that in presentation - ie printing. Thus the mechanism
> for doing that is in the string formatting code - where it
> makes sense. Why would limiting the precision of the internal
> number representation be something you'd want to do? Very
> occassionally maybe, but in those cases its easy to fake
> (and it is a fake because the number is in binary and not
> true decimal so its always an approximation - in any language!)
> 
> > quantize, but that's junk and not simple.
> 
> You mean it does a complex job and not the one youd like it to do? :-)
> 
> > Also why shouldn't string methods include stuff like
> > lstrip which do precisely what I request?
> 
> strings do include lstrip() but as I said they couldn't predict
> what you thought it shjould do, so they built it to do what
> they thought would be the most generally useful function.
> Stripping off a string literal is such a trivial programming
> task that you can easily write that yourself. You can even
> subclass string and make it a method if you like.
> 
> > Maybe because they don't want to bother putting
> >
> > def mylstrip(string,stripstring):
> > return string[len(stripstring):]
> >
> > as a method or something?
> > Messy, just plain messy.
> 
> Such a method would indeed be plain messy.
> Do you really want code like this:
> 
> >>> s = "Here is a longish string"
> >>> s.mylstrip('foo')
> >>> print s
> e is a longish string
> >>> s.mylstrip('supercalifragilisticexpalidocious')
> >>> print s
> 
> >>>
> 
> I suspect your function should probably be:
> 
> def mylstrip(str,stripstring):
> if str.startswith(stripstring) and
>len(stripstring) < len(str):
>return str[len(stripstring):]
> 
> But thats just my guess at what *you* really want...
> 
> And finally remember that Python is built by volunteers mostly.
> You should be pleased the *bothered* to write any of it!
> 
> Alan G
> Author of the Learn to Progr

[Tutor] Are you allowed to shoot camels? [kinda OT]

2005-02-02 Thread Liam Clarke
Hi, 

Had the *ahem* joy of learning Perl last night. Egad. Wrote the script
in Python to get it right, and then 'translated' it to Perl. Does the
style of coding Python engenders suit the Perl environment in anyone's
experienc? AFAI can see there is no real 'style' to Perl, apart from
white noise of non alphanumeric characters.

Just wondering if I should bite the bullet and code from scratch in
Perl, or if my Python - Perl is Ok.

Two codes are here - 

Python http://www.rafb.net/paste/results/BVaym940.html
Perl http://www.rafb.net/paste/results/LromA876.html

[OT begins]

By the way, I'm only learning Perl because I need to script some
routine HTML maintenance, and I can't be bothered applying to head
office IT for an install of Python, as the justification involved is
ludicrous, especially considering that my role as defined does not
include scripting.

First impressions of Perl - 

1) I'll use Perl for the regex stuff from now on, Perl is obviously
built for this.

2 ) There's More Than One Way To Do It makes debugging hard - i.e. 
close INFILE; & close (INFILE); are both valid. I like one syntax, cos
it's easier to remember.

3) Some stuff is counter-intuitive - 
$lenOfModList = @moddirList is the Perl equivalent of lenofModList =
len(moddirList)
@someArray = (@someArray, $newValue) is the same as someArray.append(newValue)
I couldn't figure this one out until I read that Perl automatically
flattens lists.

Also, why doesn't if ( not $d eq "a" && not $d eq "c") evaluate to
true for $d = "b" when
if (not $d eq "a") evals to true and if ($d ne "a" && $d ne "c") evals
true also? What's with that?

4) WHAT IS WITH THE STUPID SYMBOLS EVERYWHERE LARRY??!!

I'm not referring to the $ & @, I can see how they could be useful,
although with a list -

@dude = (1, 2, 3), to obtain the 2nd value I would expect $d = @dude[1], 
not $d  = $dude[1], that's counterintuitive also. 

Oh, no, what I'm referring to is stuff like @_, and @!, and @indexFile
=  to read a whole file, and this - I hate Perl for this -
open OUTFILE, ">c:/python23/j/index.htm"

What's the difference between
open OUTFILE, "c:/python23/j/index.htm"   and
open OUTFILE, ">c:/python23/j/index.htm" ?

The first will open index.htm with the handle OUTFILE, to read... 
The second will open index.htm with the handle OUTFILE to write!.

Of course, the documentation I had didn't mention that. It just said
to open it and use
print FILEHANDLE $value; to write. Oh no, I had to find a CGI Perl
tutorial, which mentioned using &lst; to open and &gst; to write (or
something), which I guessed as lesser/greater than.

Why is the read/write modifier part of the filename??? Why is it a > ?
In my opinion, there's only one place a > sign should be, in an
inequality test.

So, Perl in my opinion - 

great for regexes
obviously based around *nix conventions.
Big hodge-podge, oozing with inconsistency. I'd hate to work
collaboratively on a Perl project.
Two steps up from Brainf**k in parts.
Obviously in need of a benevolent dictator a la Guido.

But then, I've been spoilt by clean, smooth (usually) Python. Lovely,
usually consistent Python. Aah, Pytho *dreamy look*


[end OT rant]






-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Are you allowed to shoot camels? [kinda OT]

2005-02-02 Thread Liam Clarke
> I don't find it that bad. Ruby does it as well, and it's perfectly
readable. It's more or less equivalent as if condition: and
if(condition): both being valid in Python.

Yeah, but you'd never call a function foo like this- 

 x = foo

in Python. It's just good to be able to say that a function always has
.
That improves readability (imao).

 >You sure of that? I was under the impression that len(moddirList) in
Perl was $moddirList (@moddirList is the list itself).

Well, my one's correct, but I think yours is also. And this is what gets me. 

@mod = (1,2,3)
$mod = 3
$mod[0] = 1

Is inconsistent. Or at least, the logic behind this is not immediately
apparent to me. I'm always open to illumination on these things
however.

>> if ( not $d eq "a" && not $d eq "c") = False for $d = "b"
>> if ($d ne "a" && $d ne "c") = True

>This probably has to do with operator precedence. It's been lifted
from C, so chances are that && has a higher precedence than eq. Use
parentheses.

Ah... Ironic, I got misled by TMTOWTDI. I figured that if not x=="a"
and not x == "c" evaled as True in Python, and "if (not $d eq "a")"
evaled as True in Perl, that
if ( not $d eq "a" && not $d eq "c") would also eval as true. 
Of course, what's even weirder to me is that 
if ($d ne "a" && $d ne "c") does eval as True, as far as I can see, 

'$d ne "a"' is the same as d != "a" in Python, which is the same as
'if not d == "a"', which, logically, would mean that $d ne "a" is the
same as 'if(not $d eq "a") in which case both tests should handle the
addition of an AND the same.

Once again, illumination is welcomed, as I have a finally that some
subtlety of Boolean logic is eluding me, and a 'x != a' test is
different to 'if not x == a' in a small but significant way.

Max - the foo > std.txt thing explains it, but what about @dude =
, where do the brackets originate from?

This is another issue I'm having with Perl as opposed to Python - Perl
is very much written by *nix users for *nix users, it's implementation
of *nix conventions shows, including the
`` things. Whereas (correct me if I'm wrong), but Python was written
by *nix users for everyone. Python seems very non-OS-denominational in
it's current incarnation, it may have been very *nix orientated prior.

So here comes me, the guy who installed Linux once, failed to see the
big deal and uninstalled it. Up until 3 months ago, my comp was used
for gaming, pure and simple, me being a certified Day of Defeat freak,
and so Windows has always best served my purpose.

Now, I want to programme, so I have to learn Unix conventions to use a
crossplatform language!  It's like asking *nix users to sign a
Microsoft EULA!! (Well, not as bad, but still as anathemic.)


>Fast forward to last summer. In the span of 1 week, I discovered both
Python and Ruby. Fell in love with both and immediately ditched Perl.

How's Ruby? I bookmarked the homepage, but never got around to looking at it.

Oh, and I will say this - Perl > Java (and that's an inequality test,
not a redirection of output)

Cheers,

Liam Clarke



-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Are you allowed to shoot camels? [kinda OT]

2005-02-03 Thread Liam Clarke
>I suppose that one might argue that I *still* just don't really get
>lambdas (and I wouldn't argue with that).  I can see some advantages
>to small inline functions, though I suspect that a more-explicit
>currying mechanism (such as the proposed partial() higher-order
>function) could easily replace such uses.  I'm sorry to say, though,
>that the supposed advantages of anonymity come across as little more
>than handwaving assertions to me, no matter how sincerely they're
>intended.

I'm with Jeff on this one - I've yet to see the light regarding
lambda's. I understand they're used through-out Tkinter GUI stuff, can
anyone put up an example of why a lambda is better? I would like to
'get' the concepts.

Is this one of those conceptual things like OOP?

Or is it a subtlety that a Masters in COSC is necessary to appreciate?


On Thu, 03 Feb 2005 16:06:55 -0800, Jeff Shannon <[EMAIL PROTECTED]> wrote:
> Alan Gauld wrote:
> 
> >
> >>However, Python doesn't need lambdas to be able to write in a
> >>functional style.
> >
> > I disagree Jeff. It does need lambdas to do FP properly, and
> > better lambdas than we have currently. What it doesn't need
> > is the lambda keyword and syntax - although pesonally I like
> > lambda since it is descriptive!
> 
> Well, we'll have to continue to disagree on that. ;)  Personally, I
> can't help but think that 'lambda' is descriptive only to people
> who've experienced it elsewhere, and that that does *not* include the
> majority of the programming community, but I could be mistaken. :)
> 
> >>Functions are first-class objects and can be passed
> >>around quite easily,
> >
> > Yes, but lambdas are more than first class functions, they
> > are anonymous functions! In fact really just callable code
> > blocks, not necessarily functions in the strictest sense
> > (except that every callable in FP is a function...! ;-)
> 
> Well, given that in Python a function is just a callable code block
> that's bound to a name... ;)  Personally, I fail to see why having an
> anonymous function is such a huge conceptual advantage, no matter how
> many times this is proclaimed as truth by lambda-users, but again this
> is just my own impression.
> 
> > Having to define every function before using it would
> > be a big hassle and make code less readable IMHO.
> 
> Here, ISTM that you're emphasizing the in-line nature of lambdas as
> being their key usage point...  And personally, I prefer to have a
> glossary of terms rather than having to decipher jargon by context. ;)
> 
> >>only a few differences between lambdas and named functions in
> >> Python:
> >>
> >>   - Anonymous vs named
> >
> > the key feature
> 
> Again, I fail to see why this is such an advantage -- I've seen
> assertions that it is, over and over again, but never any convincing
> evidence
> 
> >>   - Single expression vs suite of statements
> >
> > A python restriction.
> 
> Well, I *did* specify that I was talking about 'in Python'... ;)
> 
> 
> >>I'd also argue that the inline nature is the *true* differentiating
> >>feature of lambdas -- the fact that they're anonymous is relatively
> >>minor.
> >
> > I agree, if I had an inline mechanism that forced me to
> > provide a name I could just use 'f' over and over and
> > not feel too cheated, but its nicer not to have an artificial
> > name when theres no need.
> 
> Personally, I prefer to have the opportunity to provide a meaningful
> name, and don't see where a generic name is any more restrictive than
> having no name, but again, maybe that's just me.
> 
> >>So, while there are some advantages to having single-use callables
> >>be defined inline
> >
> > The other advantage is the huge conceptial advantage that
> > real lambdas confer. The breakthrough idea of
> >
> > def f(x): return x+x
> >
> > being the same as
> >
> > f = lambda x: x+x
> >
> > is only possible to demonstrate if you have lambda to start with.
> > And yet that concept of a function name being just another variable
> > and the callable code being an object in its own right becomes
> > much more obvious in my opinion. lambda is a learning tool which
> > shows what is really happening whereas def is just syntactic sugar.
> 
> Hm, I understood the idea of functions being just code objects that
> were bound to a name, and could be passed around, stored in
> collections, and effectively renamed, well before I really got a hold
> on lambdas as anything more than some confusing bit of magic.  Of
> course, I started in C, where I was fairly comfortable with the idea
> of function pointers; function objects are a pretty simple step up,
> abstraction-wise, from that.
> 
> I suppose that one might argue that I *still* just don't really get
> lambdas (and I wouldn't argue with that).  I can see some advantages
> to small inline functions, though I suspect that a more-explicit
> currying mechanism (such as the proposed partial() higher-order
> function) could easily replace such uses.  I'm sorry to say, though,
> that t

Re: [Tutor] Better structure?

2005-02-03 Thread Liam Clarke
Alan said -
> Its bad practice to delete a member in the collection being iterated
> but Python copes OK if you just change the current item.

Yeah, that's very bad. Makes for all sorts of subtle errors. I usually
do the iteration as a for i in range(len(someList) type thing, and
collect the indexes - like so

j=[1, 2,3,4, 5,6,7,8]
delIndexes=[]

for index in range(len(j)):
 if not j[index] % 2:
delIndexes.append(index)

delIndexes.reverse()
for item in delIndexes:
 del(j[item])

print j

[1, 3, 5, 7]

Although, (and this will be rough) a list comprehension would be
probably do the same thing
j=[1, 2,3,4, 5,6,7,8]

q = [if not item % 2 for item in j]

I really think I've got that 'if not item % 2' wrong, as I can't test
it, but I'd be hoping for
print q
[1, 3, 5, 7]



-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Are you allowed to shoot camels? [kinda OT]

2005-02-04 Thread Liam Clarke
I had a problem with nested

while 1:
   ... .
   ...
   ... 
   break

blocks. So, I got some sleep, fixed it, and now do everything in my
power to not nest while 1 - break blocks.

Not that it's really relevant.

On Fri, 4 Feb 2005 17:18:49 -0500, Smith, Jeff <[EMAIL PROTECTED]> wrote:
> Please don't take offense.  I should have included the smiley.  To
> reiterate an earlier statement:  I like Python...a lot.  But as with all
> langauges there are some things I don't like and I believe they were
> left out for the wrong reasons.
> 
> On the indentation topic.  I would be curious to know if anyone has had
> an experience where a rogue process or editor has trashed the
> indentation in your Python and how you recovered from it.
> 
> Jeff
> 
> -Original Message-
> From: Marilyn Davis [mailto:[EMAIL PROTECTED]
> Sent: Friday, February 04, 2005 5:07 PM
> To: tutor@python.org
> Subject: RE: [Tutor] Are you allowed to shoot camels? [kinda OT]
> 
> I think Danny was saying that if you don't like:
> 
> if var == 'a':
>print 'a'
> elif var == 'b' or var == 'c':
>print 'b or c'
> elif var == 'd':
>pass
> else:
>print 'default case'
> 
> you might like his dispatch scheme.  And it has been mighty nice and
> handy for me since he taught me, in some special cases.
> 
> I'll whisper that I'm a tiny bit disappointed to see the vaguely
> demeaning 'are you joking' theme that has emerged in here.  It's unusual
> for us to be anything but generous and kind with each other. I guess
> this is a hot topic.  :^)
> 
> Marilyn
> 
> On Fri, 4 Feb 2005, Smith, Jeff wrote:
> 
> > Now who's joking?  Are you saying that
> >
> > switch var:
> >   case 'a':
> >   print 'a'
> >   case 'b' or 'c':
> >   print 'b or c'
> >   case 'd':
> >   pass
> >   default:
> >   print 'default case'
> >
> > Is less clear and maintainable than
> >
> > def do_this_function():
> >   print 'a'
> >
> > def do_that_function():
> >   print 'b or c'
> >
> > def do_pass_function():
> >   pass
> >
> > def do_default_function():
> >   print 'default case'
> >
> > ftable = { 'a' : do_this_function,
> >'b' : do_that_function,
> >'c' : do_that_function,
> >'d' : do_pass_function }
> > ftable.get(var, do_default_function)()
> >
> > Ugh!
> >
> >
> > -Original Message-
> > From: Alan Gauld [mailto:[EMAIL PROTECTED]
> > Sent: Friday, February 04, 2005 1:14 PM
> > To: Smith, Jeff; Jacob S.; [EMAIL PROTECTED];
> > tutor@python.org
> > Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT]
> >
> >
> > > What you are try to do is "execute a block of code based on the
> > value of
> > > a single statement."  if/elif doesn't do that and thereby introduces
> > the
> > > possibility of errors.
> >
> > In that case the best solution is a dictionary jump table. That is
> > more maintainable than either and much faster too. And its also
> > shorter to write. [Especially with lambdas :-)]
> >
> > > Note that the logic intended is that "on-this."  So why force the
> > > programmer to rewrite it N times and thereby introduce the
> > possibility
> > > of N-1 typographical errors...
> >
> > Thats a fair point although the dictionary solution avoids that. OTOH
> > such switches tend to proliferate thropugh code and become a big
> > source of maintenance headaches in their own right - multiple update
> > syndrome across multiple files potentially.
> >
> > > Note that I've left out break.  I'm not convinced that fall-through
> > > is
> >
> > > an important feature in switch and is usually the culpit in the
> > > cases
> > > of abuse.
> >
> > The problem is its so hard to tell when fall though is happening
> > intentionally  or by accident because someone forgot a break
> > sytatement.
> >
> > But when it comes to abuuse the fall through mechanism is one of the
> > worst offenders in C, its just too tempting to be "clever" with it.
> >
> > > This is also true for the ternary operator.  The desired logic is to
> > > assign the value of a variable based on the value of some other
> > > variable.
> >
> > But its not its based on the value of an *expression*. If the test
> > could be limited to a single valiable value it might be justified but
> > its an arbitrary expression. That makes it a conditional statement,
> > which is most clearly represented by an if/else... Well I think so :-)
> >
> > > I also like Perl's unless statement but really prefer
> > > VBs DO/WHILE/UNTIL/LOOP constuct.  Nothing beats it for clarity of
> > > expression.
> >
> > I won't argue on either point, Python's minimalist
> > approach - there's only one way to do it - means a
> > paucity of looping constructs - something I point
> > out in my tutorial. But I can live with it for the
> > other niceties it brings.
> >
> > Alan G.
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/list

Re: [Tutor] Hex to Str - still an open issue

2005-02-05 Thread Liam Clarke
Jacob - just for you, begin your agitation for the next release please ;)

binstring.py, as attached. 
(also pasted up - http://www.rafb.net/paste/results/5feItM57.html)

Creating this, was just a brain teaser, but I was thinking 'what if I
wanted to make this for the standard library.'

And so you can see, I had to include a flag for endianess. But that
was really a cheap trick. If this was going into a standard library,
I'd want to query the OS for endianess. As for the bits, once again,
32 bit is the norm, but 64 bit is here and spreading.

Also, should it display  as 255 or 256? Both are valid,
depending on context.

Thirdly, if I can do it in 2 minutes, (well, the main part), then
should they bother putting it in the standard library considering
also,

- How often, really, are you going to need to present a decimal or hex
as a binary string.

Lastly - this only does base 10 to base 2. Should I include a base 6
to base 2, base 8 to base 2, base 10 to 6, 10 to 8, 8 to 6?

I wouldn't like to write for the standard library, because you can
never please everyone.

But yeah, feel free to use the above, just keep my doc strings and comments.

Regards,

Liam Clarke

On Fri, 4 Feb 2005 23:30:19 -0500, Jacob S. <[EMAIL PROTECTED]> wrote:
> > The binary value is the same as the hex value.
> > The binary representation is 00010100, but
> > unfortunately Python doesn't support binary in
> > its string formatting(although it does in int()!
> 
> Uh, question. Why not? It seems that all simple types should be included.
> Since the computer stores it as binary, why shouldn't python be able to
> display a
> string of it in binary? That seems to be a short coming that should be added
> to the
> next release... IMHO of course.
> Jacob Schmidt
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
##
# binString.py
# by Liam Clarke
#(Let me know when it's included in the standard library ;-))
##

"""Converts a integer base 10 to a string base 2"""

def binary(decimalInt, bigEndian = True, bits = 32, truncExcess = False):
"""
Integer to be converted is essential, Endianess is an optional flag;
me being a Win32 user, Endianess is big by default, defaults to a 32-bit
representation, most integers in Python being 32 bit. truncExcess will 
strip place-holder zeros for succintness.

Oh, and it will represent  as 256, as I'm not sure whether you want
to start counting for zero with this. It's a simple matter to change."""
tempList = ['0' for x in range(bits)]

for bitPlace in range(bits, -1, -1):
if decimalInt - 2**bitPlace >= 0:
tempList[bitPlace] = '1'
decimalInt = decimalInt - 2**bitPlace
if bigEndian:
tempList.reverse()

outPut = ''.join(tempList)

if truncExcess:
if bigEndian:
outPut=outPut.lstrip('0')
else:
outPut=outPut.rstrip('0')

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


Re: [Tutor] Hex to Str - still an open issue

2005-02-05 Thread Liam Clarke
Oh... and while I hate to use acronyms like this, I did indeed LOL.

What happened was, I was feeding the strings I got out into the
Windows calculator to check it was working.

And they worked if they went backwards, and I was wondering why, and I
vaguely recalled something I read in a Java book about 'endianess' and
Windows being bigendian.
So, there you go, thought I, the biggest bit (2**32) goes first, so
Windows must be bigEndian!

Oops. Next time, I'll google.

Thanks Kent for clearing that up.


Sandip - 

Just looking at this - 
i = 456
s = ''
while i:
s = str(i % 2) + s
i/=2

This works, far simpler than mine, which is always infuriating, but my
question is, how exactly?

if I have the number 15, when it divides by 2, it will become 7. Yet
no error is introduced into the binary. Ar. Driving me nuts trying
to figure out how. I thought maybe a larger odd number would do it,
but no.

i = 320977545
s = 1001100111011101010001001

Chuck that into ol' calc, and I get, 320977545. 

Can anyone shed some more light on this?


Regards, 

Liam Clarke


On Sat, 05 Feb 2005 10:48:01 -0500, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Liam,
> 
> I think you misunderstand what endianness is.
> 
> Big-endian and little-endian refer to the way a number is stored as bytes in 
> the underlying memory
> of the computer. This is not something you generally need to worry about in a 
> Python program.
> 
> For example, consider the number 0x12345678. On most modern computers this 
> will be stored in four
> consecutive bytes of computer memory. The individual bytes will contain the 
> values 0x12, 0x34, 0x56,
> 0x78. The question is, what is the order of those bytes in memory? On a 
> big-endian computer, the
> most significant byte - 0x12 - is stored at the lowest memory address, so the 
> sequence of bytes will
> be 0x12, 0x34, 0x56, 0x78. On a little-endian computer, the least-significant 
> byte is stored at the
> lowest address, and the order will be reversed: 0x78, 0x56, 0x34, 0x12.
> 
> Most programming languages will hide this detail from you most of the time. 
> Even in assembly
> language, you generally load and store integers without worrying about 
> endianness. Math operations
> just do the right thing so you don't have to worry about it.
> 
> Endianness becomes an issue when you want to convert between representations, 
> and when binary data
> is shared between computers which may have different endianness.
> 
> For example in a C program you might want to get the high byte of an integer 
> when you know the
> address of the integer. The desired byte will be at (address+0) or 
> (address+3) depending on the
> endianness of the hardware.
> 
> Similarly, if an array of integers is written to a file in a binary 
> representation (not as ASCII
> strings representing the integers, but as 32-bit values), then to correctly 
> read the file you have
> to know the endianness of the data in the file.
> 
> OK, so what does this have to do with converting a number to binary in 
> Python? Well, nothing,
> actually. First, note that 'binary representation' can mean two different 
> things. In the description
> above, I was talking about the actual bit pattern stored in the computer. 
> Python works with binary
> numbers all the time, in this sense, but it is under the hood. The other 
> meaning of 'binary
> representation' is that of a base-2 string representation of a number.
> 
> So if you ask, "How do I convert a number to binary?" you can mean either of 
> these.
> 
> The first one is trivial. If you have a decimal string representation of the 
> number, use int() to
> convert it to binary. If you have an integer already, it's already *in* 
> binary, so you don't have to
> do anything!
> 
> So, "How do I convert a number to binary?", to be interesting, must mean "How 
> do I convert an
> integer to a base-2 string representation?" And how do you do this? Well, you 
> figured out one way
> using the mathematical properties of integers. These operations are 
> independent of endianness, and
> so is the desired result.
> 
> The base-2 string representation of  the number (whose base-16 string 
> representation is) 0x1234 is
> '0001001000110100'. The order of digits here is determined by our convention 
> of writing the most
> significant digits on the left, not by the endianness of the underlying 
> computer.
> 
> OK, this is long enough, I hope I have shed some light...
> Kent
> 
> 
> Liam Clarke wrote:
> > Jacob - just for you, begin your agitation for the next release please ;)
> >
> > binstring.py, as attached.
> > (also past

Re: [Tutor] Re: variation of Unique items question

2005-02-05 Thread Liam Clarke
When someone joins the list, they shoudl receive a welcome email that
contains -


> - a clear description of what you want to do
> - sample data
> - desired results
> - code that attempts to solve the problem

as a helpful hint of how to ask questions.

I have this bookmarked - 
http://catb.org/~esr/faqs/smart-questions.html

"Never assume you are entitled to an answer. You are not; you aren't,
after all, paying for the service. You will earn an answer, if you
earn it, by asking a question that is substantial, interesting, and
thought-provoking â one that implicitly contributes to the experience
of the community rather than merely passively demanding knowledge from
others."

"RTFM has a younger relative. If you get a reply that reads "STFW",
the person who sent it thinks you should have Searched The F**king
Web. He is almost certainly right. Go search it. (The milder version
of this is when you are told "Google is your friend!")"

"Q: My {program, configuration, SQL statement} doesn't work

A:  

This is not a question, and I'm not interested in playing Twenty
Questions to pry your actual question out of you â I have better
things to do.

Q:  

How can I crack root/steal channel-ops privileges/read someone's email?
A:  

You're a lowlife for wanting to do such things and a moron for asking
a hacker to help you."

Arrogant words of wisdom to ask help by. :- )
(But, some of them seem appropriate here from time to time.)


Liam Clarke
On Fri, 04 Feb 2005 10:02:25 -0500, Kent Johnson <[EMAIL PROTECTED]> wrote:
> I will give some credit to you for asking a clear question. You included
> - a clear description of what you want to do
> - sample data
> - desired results
> - code that attempts to solve the problem
> 
> When all of these are present I am much more likely to respond. The first 
> three elements especially
> make a big difference.
> 
> Kent
> 
> Scott Melnyk wrote:
> > Hello.
> >
> > Kent once again you have responded incredibly quickly in a most
> > helpful manor.  I sometimes wonder if the old reference to a
> > "Kent-bot" has some truth to it.
> >
> > Thanks again, I will play with it and keep on going.
> >
> > Scott
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hex to Str - still an open issue

2005-02-06 Thread Liam Clarke
Ah, yeah, gotta get me one of those textbooks.
(Wait a minute, that would mean, my approach wasn't the textbook
approach... /me salvages a little pride.)

While I jest somewhat, that highlights a serious deficiency in my
education that becomes more and more apparent, which is in maths.
Sheesh, if I'd known I wanted to use maths for something I enjoyed, I
would've paid attention in class.

But the remainder thing - would this be why we read binary the way we do?

4 is 001 (on a continuum of 2^0 to 2^n), but using the above approach
we get 100.


Regards,

Liam Clarke

On Sun, 6 Feb 2005 08:44:42 -, Alan Gauld <[EMAIL PROTECTED]> wrote:
> Liam,
> 
> > Just looking at this -
> > i = 456
> > s = ''
> > while i:
> > s = str(i % 2) + s
> > i/=2
> >
> > This works, far simpler than mine, which is always infuriating, but
> my
> > question is, how exactly?
> 
> This is the classic math treatment of how to calculate a binary
> number.
> Just keep dividing by two and take the remainder into the number.
> Almost any math textbook will cover this approach.
> The snag is that from a computing point of view its pretty slow so
> computer texts usually highlught a lookup approach 8instead.
> 
> Alan G.
> 
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Are you allowed to shoot camels? [kinda OT]

2005-02-06 Thread Liam Clarke
Even more OT it would seem, but harking back to the original subject,
Perl isn't looking too bad because I've been working through Java
tonight.

$j = ; is relatively intuitive for a child of Unix, and it's
also documented.

BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
String j = keyboard.readline();

is not intuitive, and is hidden very well in the bowels of Sun's API's.

Scary, when a language makes me think Perl would be nicer. : ) Heh.

Oh, and whoever recommended Eclipse to me? Thank you very much.

On Sat, 5 Feb 2005 08:59:30 -, Alan Gauld <[EMAIL PROTECTED]> wrote:
> 
> > Surely you jest, Alan. :-)
> 
> Smiley noted but...
> 
> > Both perl and awk are turing complete, hence anything perl can do,
> awk
> > can do as well.
> 
> This is a popular misconception.
> 
> Being Turing complete simply means you can implement any algorithm.
> But if the language doesn't provide I/O access for example it is
> impossible to write a device driver, or a comms stack, or any of
> a host of other low level programs. awk is non extendable (unless
> you have the source code!) so you can't do those things. Perl is
> not only extendable but actually comes wth a heap of those kinds
> of features that awk just doesn't have. And no amount of clever
> algorithms can compensate. Awk was designed for one task which it
> does spectacularly well but it was never intended for general
> purpose use.
> 
> I/O is just one example, there are meny more...
> 
> Alan G.
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  1   2   3   4   5   >