From Matthias.Sommer at wincor-nixdorf.com Tue Apr 1 10:53:52 2008 From: Matthias.Sommer at wincor-nixdorf.com (Sommer, Matthias) Date: Tue, 1 Apr 2008 10:53:52 +0200 Subject: [Tutor] simple, probably stupid question: single key in console / idle Message-ID: <8D64EA9FED068444B02447C8EFE810D80BC4D8@DEEXVS03.wincor-nixdorf.com> Hello, I'm just starting programming in Python. ATM I do write some smaller practices. In them I want to read single keys, if pressed. If none pressed I do not want to wait. In the library reference I found "kbhit()" and "getch()" from msvcrt. I import msvcrt (running on Windows) but I cant get it to run. Is ther somewhere a sample I could peek on? And is there somthing not windows specific? My trial code is: import msvcrt def kb(): while( 1 ): if msvcrt.kbhit(): print "key seen" help = msvcrt.getch() #if( help < 255 ): print help, ord( help ) if( ord( help ) == 27 ): print "cancel" break It appears to never see a key. Mit freundlichen Gr??en Matthias Sommer Entwicklung - Firmware/Elektronik ______________________________________________ Wincor Nixdorf Technology GmbH Am Vogelherd 67 D - 98693 Ilmenau, Germany Tel.: +49 (0) 36 77 862-194 Fax: +49 (0) 36 77 862-199 E-Mail: matthias.sommer at wincor-nixdorf.com www.wincor-nixdorf.com -- Wincor Nixdorf Technology GmbH Sitz der Gesellschaft: Paderborn Registergericht Paderborn HRB 3523 Gesch?ftsf?hrer: Eckard Heidloff, J?rgen Wilde, Wolfgang Keller Steuernummer: 339/5884/0020 - Ust-ID Nr.: DE243233085 Diese E-Mail enth?lt vertrauliche Informationen. Wenn Sie nicht der richtige Adressat sind oder diese E-Mail irrt?mlich erhalten haben, informieren Sie bitte sofort den Absender und vernichten Sie diese Mail. Das unerlaubte Kopieren sowie die unbefugte Weitergabe dieser Mail ist nicht gestattet. This e-mail may contain confidential information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorised copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080401/5313e5cd/attachment.htm From onyxtic at gmail.com Tue Apr 1 14:42:43 2008 From: onyxtic at gmail.com (Evans Anyokwu) Date: Tue, 1 Apr 2008 13:42:43 +0100 Subject: [Tutor] Testing 321 Message-ID: Please ignore, switching email address. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080401/283d2096/attachment.htm From alan.gauld at btinternet.com Tue Apr 1 14:43:59 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 Apr 2008 13:43:59 +0100 Subject: [Tutor] simple, probably stupid question: single key in console / idle References: <8D64EA9FED068444B02447C8EFE810D80BC4D8@DEEXVS03.wincor-nixdorf.com> Message-ID: "Sommer, Matthias" wrote > In the library reference I found "kbhit()" and "getch()" from > msvcrt. > I import msvcrt (running on Windows) but I cant get it to run. > Is ther somewhere a sample I could peek on? You can look at the event handling topic in my tutor. It goves an example of reading keys with getch() -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From mlangford.cs03 at gtalumni.org Tue Apr 1 19:30:46 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Tue, 1 Apr 2008 13:30:46 -0400 Subject: [Tutor] Interactive plots... In-Reply-To: References: Message-ID: <82b4f5810804011030t4a7ec76dtef847f6018299f81@mail.gmail.com> If you're just talking about something like this (ascii art) drawing: -------------------------------------------------------------------------------------------- 1:* * * * * * * * * * 0: * * * * * * * * * * * * * * * * * * * --------------------------------------------------------------------------------------------- Then I think you have a relatively simple alternative for a UI: Create a scrollable UI in the toolkit of your choice. It scrolls left to right. Make a series of radiobutton selections with all of the UI components matching the background color. That way you only get the actual clickable dots. Then your users can click on the dot to move it to the opposite position (by overriding the on-click handler). A rough tkinter solution without scrolling, the selection buttons removed, or the switching logic follows this reply. You can make the following nicer by rewriting the click command, and you can probably find a way to make tkinter hide the empty circles or use a different toolkit to implement the same idea. You should be able to put an X axis in to show time or whatever dimension your data is over. --Michael from Tkinter import * def createDataPoint(master,var): rb1 =Radiobutton(master,borderwidth=0,foreground='red',background='white',variable=var,value=1) rb1.grid() rb2=Radiobutton(master,borderwidth=0,foreground='red',background='white',variable=var,value=0) rb2.grid() class Application(Frame): def __init__(self, master=None,data=[1]): Frame.__init__(self, master) self.grid() self.data = data self.createWidgets() def show(self): l = [] for each in self.ivlist: l.append(each.get()) print(l) def createWidgets(self): self.showButton = Button ( self, text="Show", command=self.show ) self.showButton.grid(row=0) self.ivlist = [] for i in range(len(self.data)): iv = IntVar(value=self.data[i]) self.ivlist.append(iv) f = Frame(self) f.grid(column=i+1,row=1) createDataPoint(f,iv) if "__main__"==__name__: data = [1,0,1,0,1,1,1,1,0,1] app = Application(data=data) app.master.title("Flippin DOTS") app.mainloop() On Thu, Mar 27, 2008 at 6:54 PM, David Perlman wrote: > I am thinking about writing a program which will involve, among other > things, displaying a plot of a series of numbers. The idea is that > you could click on the points and move them to change the numbers. > Reverse-plotting, I suppose. It need not be complex; the numbers > will all be zero or one, and it's only necessary to flip the bits, so > click-and-drag is seriously overkill. Really it would be better to > just double-click on a point to switch it from one value to the other. > > Can anyone point me in the right direction? I have written some > programs in python before, including TKinter, but this new project is > beyond the point that I know where to even start looking. :) > > In case you care, the application is in functional brain imaging; the > brain scans generate a certain number of time points (say 500) and > then the motion of the subject is also calculated. Standard practice > is to generate a "censor" file composed of zeros and ones, where zero > indicates that that time point had excessive motion and must be > disregarded. I want to display a graph of the motion over time, and > allow quick and easy interactive editing of the censor time series in > visual parallel to the motion graph. This would save a lot of time; > at present everyone does this in Excel, which being a horrible > Windows program can't be integrated into the predominantly UNIX-based > processing pipeline. And in any case, it requires manually typing > all the zeros, looking back and forth between the graph of motion and > the list of numbers. > > I have already written a program to algorithmically generate the > censor time series from the motion data, but it is absolutely > essential to be able to manually double-check and if necessary make > minor edits. I'd like to be able to keep that functionality in > Python rather than sending everyone back to Excel... if possible! > > Thanks very much for any help. > > -- > -dave---------------------------------------------------------------- > "Pseudo-colored pictures of a person's brain lighting up are > undoubtedly more persuasive than a pattern of squiggles produced by a > polygraph. That could be a big problem if the goal is to get to the > truth." -Dr. Steven Hyman, Harvard > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080401/3890a831/attachment.htm From mlangford.cs03 at gtalumni.org Tue Apr 1 19:51:18 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Tue, 1 Apr 2008 13:51:18 -0400 Subject: [Tutor] Problem with logic while extracting data from binary file In-Reply-To: References: <47E9900C.6080200@alum.rpi.edu> <47EA9D7D.7070008@alum.rpi.edu> <47EC22F4.8030105@alum.rpi.edu> <47EC4E09.5030407@alum.rpi.edu> Message-ID: <82b4f5810804011051i2c3b3091wd1412929b306c18@mail.gmail.com> I tried to extract methods, and invert your logic of your if/else statements as to put shorter code blocks higher, and tried to roll many of your if statements into the checks of the while loops. This is algorithm I ended up with. Is this what you were trying to do? The last while loop is pointless, as you unconditionally return from it. --Michael def basicFields(data,start): group_num = data[start:start+2] element_num = data[start+2:start+4] vl_field = data[start+4:start+8] length = struct.unpack('hh', vl_field)[0] value = data[start+8:(start+8+length)] start = start+8+length element = group_num+element_num return (group_num,element_num,vl_field,length,value,start,element) def parseSequence(data, start): group_num,element_num,vl_field,length,value,pos,element = basicFields(data,start) MY_SEQ = '\xfe\xff\x00\xe0' while start < 536: #length: # 536 group_num,element_num,vl_field,length,value,start,element = basicFields(data,start) if element != MY_SEQ: return element, start, value else: data = value while start < 112: #length: # 112, 112, 116, 116 group_num,element_num,vl_field,length,value,start,element = basicFields(data,start) return element, start, value On Fri, Mar 28, 2008 at 4:24 PM, Bryan Fodness wrote: > > Thanks again, > > Still lost, even with watching the variables. I see that it kicks out of > the loop, but don't understand what I have done to cause this. I'm sorry > for repeated emails, but I have spent multiple days on this. I have added > another while loop that I think should work, but I can't seem to keep it in > the while loop. I feel like I am getting close. > > It seems like it gets everything at the first level , but not the way I > expected. It seems to get the first value inside the first while loop, and > then goes outside the loop to get the next three. I would have expected it > to return the values as it goes through the first while loop (since they are > at the same level), then when it sees the nested identifier, go into the > second while loop and return values. > > Any insight would be wonderful. > > def parseSequence(data, start): > group_num = data[start:start+2] > element_num = data[start+2:start+4] > vl_field = data[start+4:start+8] > length = struct.unpack('hh', vl_field)[0] > value = data[start+8:(start+8+length)] > pos = start+8+length > element = (group_num+element_num) > if element == '\xfe\xff\x00\xe0': > data = value > while start < 536: #length: # 536 > group_num = data[start:start+2] > element_num = data[start+2:start+4] > vl_field = data[start+4:start+8] > length = struct.unpack('hh', vl_field)[0] > value = data[start+8:(start+8+length)] > start = start+8+length > element = (group_num+element_num) > if element == '\xfe\xff\x00\xe0': > data = value > while start < 112: #length: # 112, 112, 116, 116 > group_num = data[start:start+2] > element_num = data[start+2:start+4] > vl_field = data[start+4:start+8] > length = struct.unpack('hh', vl_field)[0] > value = data[start+8:(start+8+length)] > start = start+8+length > element = (group_num+element_num) > return element, start, value > else: > return element, start, value > else: > return element, pos, value > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080401/30f48b01/attachment-0001.htm From pylinuxian at gmail.com Tue Apr 1 23:07:04 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Tue, 1 Apr 2008 21:07:04 +0000 Subject: [Tutor] parse emails as they come in In-Reply-To: <200803312109.49656.cfuller084@thinkingplanet.net> References: <200803280808.20625.cfuller084@thinkingplanet.net> <200803312109.49656.cfuller084@thinkingplanet.net> Message-ID: well, my script is so simple ! nothing complicated #!/usr/bin/python # import re, sys a=open('/home/john/data/file_input.tmp', 'r') b=open('/home/john/data/file_output', 'w') aa=a.readlines() n=0 for L in aa: # I split every line because i only need what's after the ":" # the email comes in the form "field : value" in 17 lines La=L.split(':') n=n+1 # 18 is the last line & it is an empty line that comes with every email # so i quit there. if n==18: sys.exit() # second line is a time value like this one "18:20:45" # i don't need the ":" but i need the numbers elif n==2: # as usual i remove the \n & put a ; in its place and that happens # at the third element La3=re.sub('\n',';',La[3]) # i gather the time value also there is no need for : in between La123=La[1]+La[2]+La3 b.write(La123) # any other line is treated equaly like this # i only replace \n by ; else: La1=re.sub('\n',';',La[1]) b.write(La1) # a little secret : this little script helps me load data from mail to a mysql database by converting it into ; separated values :) On Tue, Apr 1, 2008 at 2:09 AM, Chris Fuller wrote: > Every five lines of the raw email, the headers, or the body? > > A text file is just data. You can navigate however you like, but you need > to > choose a model, to give it some structure for you to work with, > Navigating > around at the byte level is probably going to be tedious, error prone, and > not very useful anyway. Choosing five lines at a time is probably not > going > to be much better. There's no particular reason it can't be ten lines, or > two, unless you pick a model that > > Maybe we could help more if you showed us what this "original script" is. > We > can help you pick a better model if the one implicit in your script isn't > working for you. > > Also, you should probably reply to the mailing list. > I'll be more careful about the reply-to field from now on. > > Cheers > > > On Monday 31 March 2008 14:43, you wrote: > > the mail module seems interesting. but what I was thinking of some way > > that would work on only five lines then moves to the next five lines & > so > > on ... is that possible ? is there a way of navigating a text file ? > > process the line that we want, maybe delete it or maybe add text to it > & > > then save & close the file ? > > > > > > On Fri, Mar 28, 2008 at 1:08 PM, Chris Fuller > > > > > > wrote: > > > The email and mailbox modules might help you out. Multiple email > > > messages will probably parse as an mbox format mailbox. > > > > > > http://docs.python.org/lib/module-email.html > > > http://docs.python.org/lib/module-mailbox.html > > > > > > Cheers > > > > > > On Friday 28 March 2008 03:14, linuxian iandsd wrote: > > > > good morning everybody ! > > > > > > > > I have scripted a small program to parse a 5 lines email message as > it > > > > comes in to my inbox (this is handled by procmail & here is a > wonderful > > > > intro to it : > http://linuxfocus.org/English/November1997/article8.html) > > > > > > > > so every email is being parsed & information is extracted from it. > > > > > > > > but sometimes two or more emails come in at once so the input file > that > > > > > > my > > > > > > > python script has to parse is more than five lines !! my question is > > > > how > > > > > > do > > > > > > > i effeciently manage this from within my original script. > > > > > > > > thanks > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080401/86fd7afa/attachment.htm From alan.gauld at btinternet.com Tue Apr 1 22:29:10 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 Apr 2008 21:29:10 +0100 Subject: [Tutor] simple, probably stupid question: single key in console / idle References: <8D64EA9FED068444B02447C8EFE810D80BC4D8@DEEXVS03.wincor-nixdorf.com> Message-ID: "Alan Gauld" wrote >> I import msvcrt (running on Windows) but I cant get it to run. >> Is ther somewhere a sample I could peek on? > I just noticed the bit about IDLE in the subject. msvcrt only works in a DOS console it won't work in IDLE because IDLE is detecting the keyboard events as GUI events within Tkinter. You will need to run your code in a command console not IDLE. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From steve at alchemy.com Tue Apr 1 23:17:30 2008 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 1 Apr 2008 14:17:30 -0700 Subject: [Tutor] parse emails as they come in In-Reply-To: References: <200803280808.20625.cfuller084@thinkingplanet.net> <200803312109.49656.cfuller084@thinkingplanet.net> Message-ID: <20080401211730.GA75799@dragon.alchemy.com> On Tue, Apr 01, 2008 at 09:07:04PM +0000, linuxian iandsd wrote: > a=open('/home/john/data/file_input.tmp', 'r') > b=open('/home/john/data/file_output', 'w') This is collecting mail as it comes in? If you have a mail rule in place to dump mail into this file_input.tmp file, you could run into trouble if multiple messages arrive close enough together that you get a race condition. I'd suggest just using something like procmail to invoke your Python script directly on the incoming message, so you don't have to dump it to a temporary input file. You'll be guaranteed to see one and only one mail per invocation of your script (although it may invoke several copies of your script at the same time, so plan for that, e.g., don't write to the same output filename every time--or don't write to a file at all, just have your script put the data into MySQL or whatever directly). > aa=a.readlines() > n=0 > for L in aa: Generally speaking, it's better to let Python iterate through the lines of a file. The above code sucks in the entire (possibly huge) file into memory and then iterates over that list. Better: for L in a: or better yet: for lines in input_file: > # a little secret : this little script helps me load data from mail to a > mysql database by converting it into ; separated values :) I'd look at just gathering the raw data into Python variables and then connecting to MySQL directly and executing a SQL statement to import the data straight in. You'll avoid a host of problems with properly quoting data (what if a ';' is in one of the data fields?), as well as making it unnecessary to carry out another post-processing step of gathering this script's output and stuffing it into MySQL. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From wescpy at gmail.com Tue Apr 1 23:46:26 2008 From: wescpy at gmail.com (wesley chun) Date: Tue, 1 Apr 2008 14:46:26 -0700 Subject: [Tutor] [ANN] May 2008 Python course In-Reply-To: <78b3a9580804011444v388d5690m4d9a3931da4523a2@mail.gmail.com> References: <78b3a9580804011444v388d5690m4d9a3931da4523a2@mail.gmail.com> Message-ID: <78b3a9580804011446r3c03d07bl94e001fd492c8bf7@mail.gmail.com> * apologies if you receive cross-posted duplicates * FINAL REMINDER Need to get up-to-speed with Python as quickly as possible? Come join me, Wesley Chun, author of Prentice-Hall's well-received "Core Python Programming," for another comprehensive intro course next month in beautiful Northern California! I look forward to meeting you! If you miss this one, our next courses will likely be in Oct or Nov 2008. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (COMPREHENSIVE) INTRODUCTION TO PYTHON: Mon-Wed, 2008 May 5-7 Although this course may appear to those new to Python, it is also perfect those who have tinkered with it and want to "fill in the gaps" and/or want to get more in-depth formal training. It combines the best of both an introduction to the language as well as a "Python Internals" training course. We will immerse you in the world of Python in only a few days. We will show you more than just its syntax (which you don't really need a book to learn, right?). Knowing more about how Python works under the covers, including the relationship between data objects and memory management, will make you a much more effective Python programmer coming out of the gate. 3 hands-on labs each day will help hammer the concepts home. Come find out why Google, Yahoo!, Disney, ILM/LucasFilm, VMware, OLPC, NASA, Ubuntu, YouTube, and Red Hat all use Python. Users supporting or jumping to Plone, Zope, TurboGears, Django, Pylons, Jython, IronPython, and Mailman will also benefit! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WHERE: near the San Francisco Airport (SFO/San Bruno), CA, USA WEB: http://cyberwebconsulting.com (click "Python Training") LOCALS: easy freeway (101/280/380) with lots of parking plus public transit (BART and CalTrain) access via the San Bruno stations, easily accessible from all parts of the Bay Area VISITORS: free shuttle to/from the airport, free high-speed internet, free breakfast and regular evening receptions; fully-equipped suites See website for costs, venue info, and registration. Discounts are available for multiple registrations as well as for teachers/students. Hope to see you there! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wtfwhoami at gmail.com Wed Apr 2 01:29:21 2008 From: wtfwhoami at gmail.com (Guess?!?) Date: Tue, 1 Apr 2008 16:29:21 -0700 Subject: [Tutor] Sync between Powerpoint slides and Video Message-ID: <8c64f3990804011629k776fbbf7wf5e85f345a992187@mail.gmail.com> Hello All, I recently came across couple of websites (www.parleys.com and www.zentation.com) and loved the sync technology between ppt and streaming video. This makes website experience look fast and impressive. I was just curious to know the how is it all done. What technology/software is being used to sync powerpoint presentations with video? If anyone has delved into implementing this in Python or Zope/Plone frameworks or any other technology ...Please share the knowledge .... Any insight will be appreciated ... Thanks, G Arora. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080401/b9e21f8a/attachment.htm From hunter92383 at gmail.com Wed Apr 2 02:14:37 2008 From: hunter92383 at gmail.com (elis aeris) Date: Tue, 1 Apr 2008 17:14:37 -0700 Subject: [Tutor] how do I use windows.h with python? Message-ID: <674d5ce60804011714t29990dc9paad843e66aabccf2@mail.gmail.com> this is a sample code that use window.h function i THINK. where can I read up on windll ? class RECT(Structure): _fields_ = [ ('left', c_ulong), ('top', c_ulong), ('right', c_ulong), ('bottom', c_ulong) ] # time.sleep(2) GetForegroundWindow = windll.user32.GetForegroundWindow GetWindowRect = windll.user32.GetWindowRect # Grab the foreground window's screen rectangle. rect = RECT() foreground_window = GetForegroundWindow() GetWindowRect(foreground_window, byref(rect)) image = ImageGrab.grab((rect.left, rect.top, rect.right, rect.bottom)) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080401/05e68048/attachment.htm From alan.gauld at btinternet.com Wed Apr 2 02:45:36 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 2 Apr 2008 01:45:36 +0100 Subject: [Tutor] how do I use windows.h with python? References: <674d5ce60804011714t29990dc9paad843e66aabccf2@mail.gmail.com> Message-ID: "elis aeris" wrote > this is a sample code that use window.h function i THINK. > > where can I read up on windll ? The Windows API is documented on the MSDN website. Alternatively find a copy of the Win32API help file, it is usually distributed with development tools like Visual studio, Delphi, etc Try Googling win32.hlp for links to older copies. Also Wikipedia has a good overview with more links. Finally the Pythonwin help file has a lot of the same info but is ISTR more targetted at the MFC classes than the raw Win32 API. If you do intend to use Win32 from Python then Google for ctypes tutorials/examples too. But whatever you want to do there will almost always be easier ways to do it without going near Win32! But if you really want to make life hard for yourself the links above should help get you started. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From hunter92383 at gmail.com Wed Apr 2 02:50:03 2008 From: hunter92383 at gmail.com (elis aeris) Date: Tue, 1 Apr 2008 17:50:03 -0700 Subject: [Tutor] how do I use windows.h with python? In-Reply-To: References: <674d5ce60804011714t29990dc9paad843e66aabccf2@mail.gmail.com> Message-ID: <674d5ce60804011750w630a47a1r2e041bb220663865@mail.gmail.com> I know how to check msdn site, but I don't understand how things are organized under windll where do they have this ? On Tue, Apr 1, 2008 at 5:45 PM, Alan Gauld wrote: > > "elis aeris" wrote > > > this is a sample code that use window.h function i THINK. > > > > where can I read up on windll ? > > The Windows API is documented on the MSDN website. > Alternatively find a copy of the Win32API help file, it is usually > distributed with development tools like Visual studio, Delphi, etc > > Try Googling win32.hlp for links to older copies. > > Also Wikipedia has a good overview with more links. > > Finally the Pythonwin help file has a lot of the same info > but is ISTR more targetted at the MFC classes than the > raw Win32 API. > > If you do intend to use Win32 from Python then Google > for ctypes tutorials/examples too. But whatever you want > to do there will almost always be easier ways to do it > without going near Win32! But if you really want to make > life hard for yourself the links above should help get you > started. > > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080401/cf545711/attachment.htm From pylinuxian at gmail.com Wed Apr 2 08:52:48 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Wed, 2 Apr 2008 06:52:48 +0000 Subject: [Tutor] parse emails as they come in In-Reply-To: <20080401211730.GA75799@dragon.alchemy.com> References: <200803280808.20625.cfuller084@thinkingplanet.net> <200803312109.49656.cfuller084@thinkingplanet.net> <20080401211730.GA75799@dragon.alchemy.com> Message-ID: ok - as i mentioned in my first email i use procmail to put THE BODY of all incoming mail into a file (that is one per incoming email as i use the variable $date-$time in the name). now this file can contain only one email but it can also contain 2 or more (this happens if for example there is a dns problem in the internet, so mail can't make it, but once internet recovers from the dns problem mail rushes in & we may have multiple messages per file. this is also true is i do this cmd : for i in 1 2 3 4 5 6 ; do echo $i | mail -s 'test mail' john ; done well, this file is processed by my script to extract data. the problem is : i can parse 18 lines (that is one email per file) fine, but i need suggestions in parsing it when it contains two emails (that is 18 lines + 18 lines ....) i hope i have explained my problem well this time. i will make the optimizations you told me (directly inserting data into mysql & the lines loop as well) thanks a lot. On Tue, Apr 1, 2008 at 9:17 PM, Steve Willoughby wrote: > On Tue, Apr 01, 2008 at 09:07:04PM +0000, linuxian iandsd wrote: > > a=open('/home/john/data/file_input.tmp', 'r') > > b=open('/home/john/data/file_output', 'w') > > This is collecting mail as it comes in? If you have a mail > rule in place to dump mail into this file_input.tmp file, > you could run into trouble if multiple messages arrive close > enough together that you get a race condition. > > I'd suggest just using something like procmail to invoke > your Python script directly on the incoming message, so > you don't have to dump it to a temporary input file. > You'll be guaranteed to see one and only one mail per > invocation of your script (although it may invoke > several copies of your script at the same time, so plan > for that, e.g., don't write to the same output filename > every time--or don't write to a file at all, just have > your script put the data into MySQL or whatever directly). > > > aa=a.readlines() > > n=0 > > for L in aa: > > Generally speaking, it's better to let Python iterate > through the lines of a file. The above code sucks in > the entire (possibly huge) file into memory and then > iterates over that list. Better: > > for L in a: > > or better yet: > > for lines in input_file: > > > # a little secret : this little script helps me load data from mail to a > > mysql database by converting it into ; separated values :) > > I'd look at just gathering the raw data into Python variables and then > connecting to MySQL directly and executing a SQL statement to import the > data straight in. You'll avoid a host of problems with properly quoting > data (what if a ';' is in one of the data fields?), as well as making it > unnecessary to carry out another post-processing step of gathering this > script's output and stuffing it into MySQL. > > -- > Steve Willoughby | Using billion-dollar satellites > steve at alchemy.com | to hunt for Tupperware. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080402/f7cdf61e/attachment.htm From steve at alchemy.com Wed Apr 2 09:18:00 2008 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 02 Apr 2008 00:18:00 -0700 Subject: [Tutor] parse emails as they come in In-Reply-To: References: <200803280808.20625.cfuller084@thinkingplanet.net> <200803312109.49656.cfuller084@thinkingplanet.net> <20080401211730.GA75799@dragon.alchemy.com> Message-ID: <47F33328.9050609@alchemy.com> linuxian iandsd wrote: > ok - as i mentioned in my first email i use procmail to put THE BODY of all > incoming mail into a file (that is one per incoming email as i use the > variable $date-$time in the name). > > now this file can contain only one email but it can also contain 2 or more > (this happens if for example there is a dns problem in the internet, so mail > can't make it, but once internet recovers from the dns problem mail rushes > in & we may have multiple messages per file. this is also true is i do this Using $date-$time is insufficient since I'll wager a dozen doughnuts that the resolution of $time isn't small enough compared to the speed messages can arrive. But as I tried to explain in my previous mail, this is a problem you don't have to solve. By choosing to use procmail to dump a file with a non-unique name, you create a race condition you then have to deal with in your code. If, on the other hand, you use procmail to _filter_ the message through your script, this cannot possibly happen. You'll get an invocation of your script per message every time. If you have your script directly dump the data into MySQL you never need to write any disk files at all. From alan.gauld at btinternet.com Wed Apr 2 09:42:26 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 2 Apr 2008 08:42:26 +0100 Subject: [Tutor] how do I use windows.h with python? References: <674d5ce60804011714t29990dc9paad843e66aabccf2@mail.gmail.com> <674d5ce60804011750w630a47a1r2e041bb220663865@mail.gmail.com> Message-ID: "elis aeris" wrote >I know how to check msdn site, but I don't understand how things are > organized under windll > > where do they have this ? > >> >> Also Wikipedia has a good overview with more links. >> >> Finally the Pythonwin help file has a lot of the same info >> but is ISTR more targetted at the MFC classes than the >> raw Win32 API. >> Alan G From steve at alchemy.com Wed Apr 2 11:50:18 2008 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 02 Apr 2008 02:50:18 -0700 Subject: [Tutor] parse emails as they come in In-Reply-To: References: <200803280808.20625.cfuller084@thinkingplanet.net> <200803312109.49656.cfuller084@thinkingplanet.net> <20080401211730.GA75799@dragon.alchemy.com> <47F33328.9050609@alchemy.com> Message-ID: <47F356DA.4070303@alchemy.com> linuxian iandsd wrote: > well, i don't know how to pipe the file to my script !! It's how procmail works. Presuming you looked up how to write a procmail rule to save the body of your mail into a file, you should also see right next to it the instructions for piping the message to a program. (It also can be found by a quick Google search, for future reference if you want a quick answer.) You just put a "|" symbol in front of the script name. To save the message to a file, you'd say something like :0: *Subject:.*pattern to look for /home/me/temp_input_file$date$time To pipe it to your script, you'd say something like :0 *Subject:.*pattern to look for |/home/me/scriptname For more information see procmailrc(5) and procmailex(5). Your Python script will see the message input on stdin. > > On Wed, Apr 2, 2008 at 7:18 AM, Steve Willoughby wrote: > >> linuxian iandsd wrote: >>> ok - as i mentioned in my first email i use procmail to put THE BODY of >> all >>> incoming mail into a file (that is one per incoming email as i use the >>> variable $date-$time in the name). >>> >>> now this file can contain only one email but it can also contain 2 or >> more >>> (this happens if for example there is a dns problem in the internet, so >> mail >>> can't make it, but once internet recovers from the dns problem mail >> rushes >>> in & we may have multiple messages per file. this is also true is i do >> this >> >> Using $date-$time is insufficient since I'll wager a dozen doughnuts >> that the resolution of $time isn't small enough compared to the speed >> messages can arrive. >> >> But as I tried to explain in my previous mail, this is a problem you >> don't have to solve. By choosing to use procmail to dump a file with >> a non-unique name, you create a race condition you then have to deal >> with in your code. >> >> If, on the other hand, you use procmail to _filter_ the message >> through your script, this cannot possibly happen. You'll get an >> invocation of your script per message every time. If you have >> your script directly dump the data into MySQL you never need to >> write any disk files at all. >> >> > From pylinuxian at gmail.com Wed Apr 2 12:20:41 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Wed, 2 Apr 2008 10:20:41 +0000 Subject: [Tutor] parse emails as they come in In-Reply-To: <47F356DA.4070303@alchemy.com> References: <200803280808.20625.cfuller084@thinkingplanet.net> <200803312109.49656.cfuller084@thinkingplanet.net> <20080401211730.GA75799@dragon.alchemy.com> <47F33328.9050609@alchemy.com> <47F356DA.4070303@alchemy.com> Message-ID: well, here is a piece of final script : #!/usr/bin/python # import sys b=[] while 1: data = sys.stdin.readline() if data != '\n': b.append(data) else: break for i in (0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16): b[i]=b[i].split(':')[1].strip() #print b[i] b[1]=b[1].split(':') b[1]=b[1][1]+b[1][2]+b[1][3].strip() #print b[1][1]+b[1][2]+b[1][3].strip() bb=",".join(b) print bb mysqlcmd='insert into webdata field1, field2, field3, field4, field5, field6, field7 ..... field17 values (%s)' % bb print mysqlcmd END OF SCRIPT the parsed file looks like this : field1: xxxxx field2: xxxxx .... field17: xxxxx empty line here for end of message On Wed, Apr 2, 2008 at 9:50 AM, Steve Willoughby wrote: > linuxian iandsd wrote: > > > well, i don't know how to pipe the file to my script !! > > > > It's how procmail works. Presuming you looked up how to write > a procmail rule to save the body of your mail into a file, you > should also see right next to it the instructions for piping > the message to a program. (It also can be found by a quick > Google search, for future reference if you want a quick answer.) > > You just put a "|" symbol in front of the script name. > > To save the message to a file, you'd say something like > > :0: > *Subject:.*pattern to look for > /home/me/temp_input_file$date$time > > To pipe it to your script, you'd say something like > > :0 > *Subject:.*pattern to look for > |/home/me/scriptname > > For more information see procmailrc(5) and procmailex(5). > > Your Python script will see the message input on stdin. > > > > > On Wed, Apr 2, 2008 at 7:18 AM, Steve Willoughby > > wrote: > > > > linuxian iandsd wrote: > > > > > > > ok - as i mentioned in my first email i use procmail to put THE BODY > > > > of > > > > > > > all > > > > > > > incoming mail into a file (that is one per incoming email as i use > > > > the > > > > variable $date-$time in the name). > > > > > > > > now this file can contain only one email but it can also contain 2 > > > > or > > > > > > > more > > > > > > > (this happens if for example there is a dns problem in the internet, > > > > so > > > > > > > mail > > > > > > > can't make it, but once internet recovers from the dns problem mail > > > > > > > rushes > > > > > > > in & we may have multiple messages per file. this is also true is i > > > > do > > > > > > > this > > > > > > Using $date-$time is insufficient since I'll wager a dozen doughnuts > > > that the resolution of $time isn't small enough compared to the speed > > > messages can arrive. > > > > > > But as I tried to explain in my previous mail, this is a problem you > > > don't have to solve. By choosing to use procmail to dump a file with > > > a non-unique name, you create a race condition you then have to deal > > > with in your code. > > > > > > If, on the other hand, you use procmail to _filter_ the message > > > through your script, this cannot possibly happen. You'll get an > > > invocation of your script per message every time. If you have > > > your script directly dump the data into MySQL you never need to > > > write any disk files at all. > > > > > > > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080402/54405d8e/attachment.htm From hihiren1 at gmail.com Wed Apr 2 13:21:25 2008 From: hihiren1 at gmail.com (hiren kumar) Date: Wed, 2 Apr 2008 16:51:25 +0530 Subject: [Tutor] Question about Python ORM Message-ID: Hi, I am very much new to Python and it's available framework. When I search the over net about Python ORM, I found there are so many ORMs available and I was confused between them? I don't understand where to go? :( Can you please tell me something about Python ORM? Regards, Kumar -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080402/65d2f879/attachment.htm From andreas at kostyrka.org Wed Apr 2 13:25:05 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 02 Apr 2008 13:25:05 +0200 Subject: [Tutor] Question about Python ORM In-Reply-To: References: Message-ID: <1207135505.8299.91.camel@localhost> There are many as you said yourself. Recommendation: sqlalchemy.org Andreas Am Mittwoch, den 02.04.2008, 16:51 +0530 schrieb hiren kumar: > Hi, > > I am very much new to Python and it's available framework. > > When I search the over net about Python ORM, I found there are so many > ORMs available and I was confused between them? I don't understand > where to go? :( > > Can you please tell me something about Python ORM? > > Regards, > Kumar > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080402/3d195431/attachment.pgp From wwerner at swbell.net Wed Apr 2 14:07:53 2008 From: wwerner at swbell.net (WW) Date: Wed, 2 Apr 2008 07:07:53 -0500 Subject: [Tutor] asyncore/asynchat Message-ID: <333efb450804020507h33afd581va6a4820b5ba711e6@mail.gmail.com> Hi, I'm new to the list, and fairly new-ish to python. I'd rate my programming experience as beginning-intermediate, and I've had some experience with c++ and VBS, and I'm currently a freshman CS major. Now to my question(s?). I'm really interested in learning some socket driven programming, specifically asyncore/asynchat. I don't need the power or complication of twisted, but I'm having serious trouble finding any decent tutorials about asyncore/asychat... so where can I find a good tutuorial? Thanks for the help, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080402/80d7388b/attachment.htm From andreas at kostyrka.org Wed Apr 2 14:27:26 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 02 Apr 2008 14:27:26 +0200 Subject: [Tutor] asyncore/asynchat In-Reply-To: <333efb450804020507h33afd581va6a4820b5ba711e6@mail.gmail.com> References: <333efb450804020507h33afd581va6a4820b5ba711e6@mail.gmail.com> Message-ID: <1207139246.8299.102.camel@localhost> Well, the source is easy enough to read. Although I wouldn't call Twisted a complication. If all you want is your async server Hello World example, asyncore is fine. If you intend to use the stuff for serious things, one usually starts to reinvent/reimplement Twisted anyway. Andreas Am Mittwoch, den 02.04.2008, 07:07 -0500 schrieb WW: > Hi, I'm new to the list, and fairly new-ish to python. I'd rate my > programming experience as beginning-intermediate, and I've had some > experience with c++ and VBS, and I'm currently a freshman CS major. > > Now to my question(s?). > > I'm really interested in learning some socket driven programming, > specifically asyncore/asynchat. I don't need the power or complication > of twisted, but I'm having serious trouble finding any decent > tutorials about asyncore/asychat... so where can I find a good > tutuorial? > > Thanks for the help, > Wayne > > -- > To be considered stupid and to be told so is more painful than being > called gluttonous, mendacious, violent, lascivious, lazy, cowardly: > every weakness, every vice, has found its defenders, its rhetoric, its > ennoblement and exaltation, but stupidity hasn't. - Primo Levi > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080402/370a1ff5/attachment.pgp From kent37 at tds.net Wed Apr 2 15:44:50 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 02 Apr 2008 09:44:50 -0400 Subject: [Tutor] asyncore/asynchat In-Reply-To: <333efb450804020507h33afd581va6a4820b5ba711e6@mail.gmail.com> References: <333efb450804020507h33afd581va6a4820b5ba711e6@mail.gmail.com> Message-ID: <47F38DD2.2090308@tds.net> WW wrote: > I'm really interested in learning some socket driven programming, > specifically asyncore/asynchat. I don't need the power or complication > of twisted, but I'm having serious trouble finding any decent tutorials > about asyncore/asychat... so where can I find a good tutuorial? Googling 'python asyncore' seems to find quite a few resources. Kent From mlangford.cs03 at gtalumni.org Wed Apr 2 16:04:04 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Wed, 2 Apr 2008 10:04:04 -0400 Subject: [Tutor] Question about Python ORM In-Reply-To: <1207135505.8299.91.camel@localhost> References: <1207135505.8299.91.camel@localhost> Message-ID: <82b4f5810804020704x4270b8e3y7848b1c97291d258@mail.gmail.com> If you do sqlalchemy, I recommend you at least also look at sqlsoup to help making your mappings easier: http://www.sqlalchemy.org/trac/wiki/SqlSoup If you don't want to write mappers and you don't need the relational database, ZODB also works: http://www.zope.org/Products/StandaloneZODB --Michael On Wed, Apr 2, 2008 at 7:25 AM, Andreas Kostyrka wrote: > There are many as you said yourself. Recommendation: sqlalchemy.org > > Andreas > > Am Mittwoch, den 02.04.2008, 16:51 +0530 schrieb hiren kumar: > > Hi, > > > > I am very much new to Python and it's available framework. > > > > When I search the over net about Python ORM, I found there are so many > > ORMs available and I was confused between them? I don't understand > > where to go? :( > > > > Can you please tell me something about Python ORM? > > > > Regards, > > Kumar > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080402/8ca9d1a4/attachment-0001.htm From bryan.fodness at gmail.com Wed Apr 2 16:44:10 2008 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Wed, 2 Apr 2008 10:44:10 -0400 Subject: [Tutor] Using split with a backslash Message-ID: I have a data pair separated by a backslash. I didn' t think it would see an end of line if the backslash was inside the quotes. Can this be done? I don't have a choice in what the separator is. >>> LeafJawPositions='-42.000000000001\29.800000000001' >>> LeafJawPositions '-42.000000000001\x029.800000000001' >>> x1, x2 = LeafJawPositions.split('\x0') ValueError: invalid \x escape >>> x1, x2 = LeafJawPositions.split('\') SyntaxError: EOL while scanning single-quoted string >>> -- "The game of science can accurately be described as a never-ending insult to human intelligence." - Jo?o Magueijo -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080402/e87b5c02/attachment.htm From dkuhlman at rexx.com Wed Apr 2 17:40:38 2008 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 2 Apr 2008 08:40:38 -0700 Subject: [Tutor] Using split with a backslash In-Reply-To: References: Message-ID: <20080402154037.GA44187@cutter.rexx.com> On Wed, Apr 02, 2008 at 10:44:10AM -0400, Bryan Fodness wrote: > I have a data pair separated by a backslash. I didn' t think it would see > an end of line if the backslash was inside the quotes. > Can this be done? I don't have a choice in what the separator is. > > >>> LeafJawPositions='-42.000000000001\29.800000000001' > >>> LeafJawPositions > '-42.000000000001\x029.800000000001' > >>> x1, x2 = LeafJawPositions.split('\x0') > ValueError: invalid \x escape > >>> x1, x2 = LeafJawPositions.split('\') > > SyntaxError: EOL while scanning single-quoted string > >>> In a literal string, backslash is an escape character. In order to include a backslash in a literal string, type two backslashes. Example: x1, x2 = LeafJawPositions.split('\\') See http://docs.python.org/ref/strings.html Another example: In [1]: a = 'abc\\def\\ghi' In [2]: len(a) Out[2]: 11 In [3]: a.split('\') ------------------------------------------------------------ File "", line 1 a.split('\') ^ SyntaxError: EOL while scanning single-quoted string In [4]: a.split('\\') Out[4]: ['abc', 'def', 'ghi'] - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From sander.sweers at gmail.com Wed Apr 2 17:57:17 2008 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 2 Apr 2008 08:57:17 -0700 Subject: [Tutor] Using split with a backslash In-Reply-To: References: Message-ID: On Wed, Apr 2, 2008 at 7:44 AM, Bryan Fodness wrote: > I have a data pair separated by a backslash. I didn' t think it would see > an end of line if the backslash was inside the quotes. The backlash is seen as an escape character. Try the below, notice the string prefix r and that the backslash is now escaped by another backslash. >>> LeafJawPositions=r'-42.000000000001\29.800000000001' >>> LeafJawPositions '-42.000000000001\\29.800000000001' >>> x1, x2 = LeafJawPositions.split('\\') >>> x1, x2 ('-42.000000000001', '29.800000000001') See http://docs.python.org/ref/strings.html for more info. Greets Sander From alan.gauld at btinternet.com Wed Apr 2 17:57:35 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 2 Apr 2008 16:57:35 +0100 Subject: [Tutor] Using split with a backslash References: Message-ID: "Bryan Fodness" wrote > I have a data pair separated by a backslash. > I didn' t think it would see an end of line if the backslash > was inside the quotes. Backslashes don't indicate end of line, they indicate a continuation of a line. ie they tell Python to *ignore* the end of line... > Can this be done? I don't have a choice in what the separator is. Of course. >>> LeafJawPositions='-42.000000000001\29.800000000001' >>> LeafJawPositions '-42.000000000001\x029.800000000001' This is reporting \2 as \x02 - which is one character You need to treat the string as raw characters: >>> LeafJawPositions=r'-42.000000000001\29.800000000001' >>> LeafJawPositions '-42.000000000001\\29.800000000001' Note the double \. >>> LeafJawPositions.split('\\') ['-42.000000000001', '29.800000000001'] >>> HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bryan.fodness at gmail.com Wed Apr 2 18:14:34 2008 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Wed, 2 Apr 2008 12:14:34 -0400 Subject: [Tutor] Using split with a backslash In-Reply-To: References: Message-ID: Thanks everyone, I was trying it this way. x1, x2 = LeafJawPositions.split(r'\\') On Wed, Apr 2, 2008 at 11:00 AM, Michael Connors wrote: > > >>> LeafJawPositions='-42.000000000001\29.800000000001' > > >>> LeafJawPositions > > '-42.000000000001\x029.800000000001' > > >>> x1, x2 = LeafJawPositions.split('\x0') > > ValueError: invalid \x escape > > >>> x1, x2 = LeafJawPositions.split('\') > > > > SyntaxError: EOL while scanning single-quoted string > > >>> > > > > Hi, > The backslash is used for escaping special characters in a string. In > order to do what you are trying to do, you would need to escape the > backslash using a backslash. > You need to do this in two places in the above code. > LeafJawPositions='-42.000000000001\\29.800000000001' > > and > > x1, x2 = LeafJawPositions.split('\\') > > http://docs.python.org/ref/strings.html > > Regards, > Michael > > -- "The game of science can accurately be described as a never-ending insult to human intelligence." - Jo?o Magueijo -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080402/e0b32e4a/attachment.htm From kent37 at tds.net Wed Apr 2 18:23:30 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 02 Apr 2008 12:23:30 -0400 Subject: [Tutor] Using split with a backslash In-Reply-To: References: Message-ID: <47F3B302.1080007@tds.net> Bryan Fodness wrote: > Thanks everyone, > I was trying it this way. > > x1, x2 = LeafJawPositions.split(r'\\') That is a string containing *two* backslashes. Kent From kungfukoi at gmail.com Wed Apr 2 18:44:22 2008 From: kungfukoi at gmail.com (Jeffrey Dates) Date: Wed, 2 Apr 2008 12:44:22 -0400 Subject: [Tutor] Newb Learning Question Message-ID: <1128c3c40804020944r35be5459p3d4752002c6fd8c3@mail.gmail.com> Greetings, I have no previous experience in scripting. Python is my first language... I'm currently trying to build a logic model for how to 'think' in Python, so please excuse my ignorance. Currently, I'm running through some basic 101 tutorials, to wrap my head around solving problems. I'm looking for some advice on how to solve the following exercise: "Write a program that prints the first letter of a string that comes after 'm' in the alphabet." I hope this is not too elementary. I do understand basic, basic concepts. iteration, for loops, etc. Just having trouble with syntax, and how to format my logic. thank you in advance for any help or examples. Jeffrey Dates www.kungfukoi.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080402/f22a3d36/attachment.htm From kungfukoi at gmail.com Wed Apr 2 18:50:41 2008 From: kungfukoi at gmail.com (Jeffrey Dates) Date: Wed, 2 Apr 2008 12:50:41 -0400 Subject: [Tutor] Newb Learning Question In-Reply-To: <1128c3c40804020944r35be5459p3d4752002c6fd8c3@mail.gmail.com> References: <1128c3c40804020944r35be5459p3d4752002c6fd8c3@mail.gmail.com> Message-ID: <1128c3c40804020950x4ebb7200waaccb108405a5597@mail.gmail.com> Sorry forgot to post what I had so far: for code in range(ord("a"), ord("z") +1): if code == ord("m"): print chr(code +1) Now, this solves for the first letter after "M", but doesn't do it via a string.... thanks, Jeffrey Dates www.kungfukoi.com On Wed, Apr 2, 2008 at 12:44 PM, Jeffrey Dates wrote: > Greetings, > > I have no previous experience in scripting. Python is my first > language... > I'm currently trying to build a logic model for how to 'think' in Python, > so please excuse my ignorance. > > Currently, I'm running through some basic 101 tutorials, to wrap my head > around solving problems. > I'm looking for some advice on how to solve the following exercise: > > "Write a program that prints the first letter of a string that comes after > 'm' in the alphabet." > > I hope this is not too elementary. > > I do understand basic, basic concepts. iteration, for loops, etc. > Just having trouble with syntax, and how to format my logic. > > thank you in advance for any help or examples. > > Jeffrey Dates > www.kungfukoi.com > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080402/24068fb8/attachment.htm From steve at alchemy.com Wed Apr 2 19:12:44 2008 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 2 Apr 2008 10:12:44 -0700 Subject: [Tutor] parse emails as they come in In-Reply-To: References: <200803280808.20625.cfuller084@thinkingplanet.net> <200803312109.49656.cfuller084@thinkingplanet.net> <20080401211730.GA75799@dragon.alchemy.com> <47F33328.9050609@alchemy.com> <47F356DA.4070303@alchemy.com> Message-ID: <20080402171244.GA38514@dragon.alchemy.com> On Wed, Apr 02, 2008 at 10:20:41AM +0000, linuxian iandsd wrote: > well, here is a piece of final script : > > #!/usr/bin/python > # > > import sys > > b=[] > while 1: > data = sys.stdin.readline() > if data != '\n': > b.append(data) > else: > break I'd keep working on that loop a bit in accordance with the advice you've already received. I'm still not sure why you're not using Python's ability to iterate over lines of the file directly. I think it may be simpler to process the data as it comes in rather than storing it in an array and then go through it again. > for i in (0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16): > b[i]=b[i].split(':')[1].strip() > #print b[i] > > b[1]=b[1].split(':') > b[1]=b[1][1]+b[1][2]+b[1][3].strip() > #print b[1][1]+b[1][2]+b[1][3].strip() I'd also suggest checking out regular expressions. You may find a simpler approach to parsing your data than all this splitting on colons. > bb=",".join(b) > print bb > > mysqlcmd='insert into webdata field1, field2, field3, field4, field5, > field6, field7 ..... field17 values (%s)' % bb Here you have a very common mistake, but an extremely dangerous one, so I'd like to point it out to you. You're pasting together strings with commas between them and then pasting that straight into a SQL statement. You need to be careful to make sure that the data in bb is valid SQL syntax. In particular, what if any of the strings contain commas? You'd get extra fields. What if they contain SQL commands (maybe as a coincidence or maybe not)? You could make the insert command fail, or corrupt or destroy your whole database depending on what's in bb. The good news is that it's really easy to cover that situation. The MySQL interface libraries support a special kind of statement where it will handle that for you. You just need to supply the list of values (not a list you joined up yourself). Like this: cursor_object_to_database.execute('insert into webdata field1, field2, field3, (etc.), field17 values (%s, %s, %s, %s, %s, (etc.), %s)', *b) (this is for the MySQLdb module) Also, how confident are you that the mail format might not be wrong? Some error checking might be good to add at some point. > > On Wed, Apr 2, 2008 at 9:50 AM, Steve Willoughby wrote: > > > linuxian iandsd wrote: > > > > > well, i don't know how to pipe the file to my script !! > > > > > > > It's how procmail works. Presuming you looked up how to write > > a procmail rule to save the body of your mail into a file, you > > should also see right next to it the instructions for piping > > the message to a program. (It also can be found by a quick > > Google search, for future reference if you want a quick answer.) > > > > You just put a "|" symbol in front of the script name. > > > > To save the message to a file, you'd say something like > > > > :0: > > *Subject:.*pattern to look for > > /home/me/temp_input_file$date$time > > > > To pipe it to your script, you'd say something like > > > > :0 > > *Subject:.*pattern to look for > > |/home/me/scriptname > > > > For more information see procmailrc(5) and procmailex(5). > > > > Your Python script will see the message input on stdin. > > > > > > > > > On Wed, Apr 2, 2008 at 7:18 AM, Steve Willoughby > > > wrote: > > > > > > linuxian iandsd wrote: > > > > > > > > > ok - as i mentioned in my first email i use procmail to put THE BODY > > > > > of > > > > > > > > > all > > > > > > > > > incoming mail into a file (that is one per incoming email as i use > > > > > the > > > > > variable $date-$time in the name). > > > > > > > > > > now this file can contain only one email but it can also contain 2 > > > > > or > > > > > > > > > more > > > > > > > > > (this happens if for example there is a dns problem in the internet, > > > > > so > > > > > > > > > mail > > > > > > > > > can't make it, but once internet recovers from the dns problem mail > > > > > > > > > rushes > > > > > > > > > in & we may have multiple messages per file. this is also true is i > > > > > do > > > > > > > > > this > > > > > > > > Using $date-$time is insufficient since I'll wager a dozen doughnuts > > > > that the resolution of $time isn't small enough compared to the speed > > > > messages can arrive. > > > > > > > > But as I tried to explain in my previous mail, this is a problem you > > > > don't have to solve. By choosing to use procmail to dump a file with > > > > a non-unique name, you create a race condition you then have to deal > > > > with in your code. > > > > > > > > If, on the other hand, you use procmail to _filter_ the message > > > > through your script, this cannot possibly happen. You'll get an > > > > invocation of your script per message every time. If you have > > > > your script directly dump the data into MySQL you never need to > > > > write any disk files at all. > > > > > > > > > > > > > > > > > > > -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From steve at alchemy.com Wed Apr 2 19:14:09 2008 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 2 Apr 2008 10:14:09 -0700 Subject: [Tutor] Using split with a backslash In-Reply-To: References: Message-ID: <20080402171409.GB38514@dragon.alchemy.com> On Wed, Apr 02, 2008 at 10:44:10AM -0400, Bryan Fodness wrote: > I have a data pair separated by a backslash. I didn' t think it would see > an end of line if the backslash was inside the quotes. > Can this be done? I don't have a choice in what the separator is. > > >>> LeafJawPositions='-42.000000000001\29.800000000001' > >>> LeafJawPositions > '-42.000000000001\x029.800000000001' > >>> x1, x2 = LeafJawPositions.split('\x0') > ValueError: invalid \x escape > >>> x1, x2 = LeafJawPositions.split('\') Try x1, x2 = LeafJawPositions.split('\\') -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From taserian at gmail.com Wed Apr 2 19:28:18 2008 From: taserian at gmail.com (taserian) Date: Wed, 2 Apr 2008 13:28:18 -0400 Subject: [Tutor] Newb Learning Question In-Reply-To: <1128c3c40804020950x4ebb7200waaccb108405a5597@mail.gmail.com> References: <1128c3c40804020944r35be5459p3d4752002c6fd8c3@mail.gmail.com> <1128c3c40804020950x4ebb7200waaccb108405a5597@mail.gmail.com> Message-ID: <70dbc4d40804021028n696ebb1cn6921c1a20b7fad5a@mail.gmail.com> On Wed, Apr 2, 2008 at 12:50 PM, Jeffrey Dates wrote: > Sorry forgot to post what I had so far: > > for code in range(ord("a"), ord("z") +1): > if code == ord("m"): > print chr(code +1) > > Now, this solves for the first letter after "M", but doesn't do it via a > string.... > > thanks, Let's think about the problem in pseudocode: If the first letter in the string comes after m in the alphabet, print that letter. Otherwise, if the second letter comes after m in the alphabet, print *that* letter. etc. etc. So what you want is to *iterate* through the characters that make up the string (from start to end) until you find a character that comes after "m". Your code above seems to *iterate* through all the characters from "a" to "z", not the characters of a given string. See if you can fix that first, then we'll talk about the next step. Tony R. aka Taser > > Jeffrey Dates > www.kungfukoi.com > > > > > > > On Wed, Apr 2, 2008 at 12:44 PM, Jeffrey Dates > wrote: > > > Greetings, > > > > I have no previous experience in scripting. Python is my first > > language... > > I'm currently trying to build a logic model for how to 'think' in > > Python, so please excuse my ignorance. > > > > Currently, I'm running through some basic 101 tutorials, to wrap my head > > around solving problems. > > I'm looking for some advice on how to solve the following exercise: > > > > "Write a program that prints the first letter of a string that comes > > after 'm' in the alphabet." > > > > I hope this is not too elementary. > > > > I do understand basic, basic concepts. iteration, for loops, etc. > > Just having trouble with syntax, and how to format my logic. > > > > thank you in advance for any help or examples. > > > > Jeffrey Dates > > www.kungfukoi.com > > > > > > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080402/7da29948/attachment.htm From bgailer at alum.rpi.edu Wed Apr 2 19:29:27 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Wed, 02 Apr 2008 13:29:27 -0400 Subject: [Tutor] Newb Learning Question In-Reply-To: <1128c3c40804020944r35be5459p3d4752002c6fd8c3@mail.gmail.com> References: <1128c3c40804020944r35be5459p3d4752002c6fd8c3@mail.gmail.com> Message-ID: <47F3C277.4010909@alum.rpi.edu> Jeffrey Dates wrote: > Greetings, > > I have no previous experience in scripting. Python is my first > language... > I'm currently trying to build a logic model for how to 'think' in > Python, so please excuse my ignorance. > > Currently, I'm running through some basic 101 tutorials, to wrap my > head around solving problems. > I'm looking for some advice on how to solve the following exercise: > > "Write a program that prints the first letter of a string that comes > after 'm' in the alphabet." > > what I had so far: > > for code in range(ord("a"), ord("z") +1): > if code == ord("m"): > print chr(code +1) > > Now, this solves for the first letter after "M" which is NOT what the exercise wants! Consider "are you ready?". Which character is the first that comes after 'm' in the alphabet."? BTW did you mean after "m"? Caps and lower case are different. > , but doesn't do it via a string.... I for one am reluctant to just give an answer. I prefer to lead you to a solution. So, I suggest you write a program to: assign a candidate string to a variable (choose a string that has at least one letter that "comes after 'm'") test each character to see if it "comes after 'm'" print that character stop Do as much as you can, and ask more questions. -- Bob Gailer 919-636-4239 Chapel Hill, NC From kungfukoi at gmail.com Wed Apr 2 20:26:42 2008 From: kungfukoi at gmail.com (Jeffrey Dates) Date: Wed, 2 Apr 2008 14:26:42 -0400 Subject: [Tutor] Newb Learning Question In-Reply-To: <47F3C277.4010909@alum.rpi.edu> References: <1128c3c40804020944r35be5459p3d4752002c6fd8c3@mail.gmail.com> <47F3C277.4010909@alum.rpi.edu> Message-ID: <1128c3c40804021126t5268850cnf644466878730e2@mail.gmail.com> That's Bob, and Tony, exactly what I'm looking for. ( not the answer, but the path to it... ) Let me get back to you with my result after I study this a bit. thanks!! Jeffrey Dates www.kungfukoi.com On undefined, bob gailer wrote: > Jeffrey Dates wrote: > > Greetings, > > > > I have no previous experience in scripting. Python is my first > > language... > > I'm currently trying to build a logic model for how to 'think' in > > Python, so please excuse my ignorance. > > > > Currently, I'm running through some basic 101 tutorials, to wrap my > > head around solving problems. > > I'm looking for some advice on how to solve the following exercise: > > > > "Write a program that prints the first letter of a string that comes > > after 'm' in the alphabet." > > > > what I had so far: > > > > for code in range(ord("a"), ord("z") +1): > > if code == ord("m"): > > print chr(code +1) > > > > Now, this solves for the first letter after "M" > > which is NOT what the exercise wants! > > Consider "are you ready?". Which character is the first that comes after > 'm' in the alphabet."? > > BTW did you mean after "m"? Caps and lower case are different. > > > , but doesn't do it via a string.... > > I for one am reluctant to just give an answer. I prefer to lead you to a > solution. > > So, I suggest you write a program to: > assign a candidate string to a variable (choose a string that has at > least one letter that "comes after 'm'") > test each character to see if it "comes after 'm'" > print that character > stop > > Do as much as you can, and ask more questions. > > -- > Bob Gailer > 919-636-4239 Chapel Hill, NC > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080402/d292386d/attachment.htm From washakie at gmail.com Thu Apr 3 01:05:21 2008 From: washakie at gmail.com (John) Date: Wed, 2 Apr 2008 23:05:21 +0000 Subject: [Tutor] help with slice In-Reply-To: References: <15837808.post@talk.nabble.com> <1204669733.14387.8.camel@localhost> <47CDDA1C.9020402@gmail.com> Message-ID: Thanks all for the posts, I guess I'm thinking in 'matrices' and in a matlab syntax. So I was trying to get the third element of a list of lists, or lists in a dictionay in syntax like matlab (yes, I should be using numpy or scipy). Anyway, Alan's final suggestion (and everyone else's) has helped me better understand list syntax. Thanks again. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080402/b50e3155/attachment.htm From alan.gauld at btinternet.com Thu Apr 3 01:31:47 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 3 Apr 2008 00:31:47 +0100 Subject: [Tutor] Newb Learning Question References: <1128c3c40804020944r35be5459p3d4752002c6fd8c3@mail.gmail.com><47F3C277.4010909@alum.rpi.edu> <1128c3c40804021126t5268850cnf644466878730e2@mail.gmail.com> Message-ID: "Jeffrey Dates" wrote > Let me get back to you with my result after I study this a bit. > thanks!! One wee tip you might find useful. To test if a lertter comes after 'm you could a) create a string with all letters after m >>> after_m = 'nopqrstuvwxyz' then test whether your characters were in after_m: >>> if c in after_m: print c OR b) see if the ascii value of your character is bigger than the ascii value of 'm' And you can check the ascii value using ord() There are pros and cons to both approaches. Pick the one you like best, we can debate the ideal solution for any given case later... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at alum.rpi.edu Thu Apr 3 02:01:16 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Wed, 02 Apr 2008 20:01:16 -0400 Subject: [Tutor] Newb Learning Question In-Reply-To: References: <1128c3c40804020944r35be5459p3d4752002c6fd8c3@mail.gmail.com><47F3C277.4010909@alum.rpi.edu> <1128c3c40804021126t5268850cnf644466878730e2@mail.gmail.com> Message-ID: <47F41E4C.6030807@alum.rpi.edu> Alan Gauld wrote: > "Jeffrey Dates" wrote > > >> Let me get back to you with my result after I study this a bit. >> thanks!! >> > > One wee tip you might find useful. > > To test if a lertter comes after 'm you could > > a) create a string with all letters after m > > >>>> after_m = 'nopqrstuvwxyz' >>>> > > then test whether your characters were in after_m: > > >>>> if c in after_m: print c >>>> > > OR > > b) see if the ascii value of your character is bigger > than the ascii value of 'm' And you can check the > ascii value using ord() > 3rd alternative: if c > 'm': print c > There are pros and cons to both approaches. > Pick the one you like best, we can debate > the ideal solution for any given case later... > > -- Bob Gailer 919-636-4239 Chapel Hill, NC From alan.gauld at btinternet.com Thu Apr 3 09:48:57 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 3 Apr 2008 08:48:57 +0100 Subject: [Tutor] Newb Learning Question References: <1128c3c40804020944r35be5459p3d4752002c6fd8c3@mail.gmail.com><47F3C277.4010909@alum.rpi.edu> <1128c3c40804021126t5268850cnf644466878730e2@mail.gmail.com> <47F41E4C.6030807@alum.rpi.edu> Message-ID: "bob gailer" wrote > 3rd alternative: if c > 'm': print c Wow! Amazingly I just assumed you couldn't directly compare characters with boolean tests. I don't know why I thought that since it must be possible for string comparisons, but I did. You learn something new every day, :-) Alan G. From thankyouforthevenom1971 at hotmail.co.uk Thu Apr 3 00:15:10 2008 From: thankyouforthevenom1971 at hotmail.co.uk (dean garrad) Date: Wed, 2 Apr 2008 23:15:10 +0100 Subject: [Tutor] a pyball python app Message-ID: hi there.. im not sure if you can help or you would want to but i fort i may aswell give it a try. i am currently trying to edit a python app it is a normal green ball game that comes with python it uses nokia n95 accel to move around. i have been trying to make more than one ball on the screen at the same time . do you think it is possable ? i have attached the script to this e mail and would be greatful for any advice thanks. dean. _________________________________________________________________ Amazing prizes every hour with Live Search Big Snap http://www.bigsnapsearch.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080402/7f2ee39e/attachment.htm -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: trialaccelball.py Url: http://mail.python.org/pipermail/tutor/attachments/20080402/7f2ee39e/attachment.txt From kent37 at tds.net Thu Apr 3 13:35:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 Apr 2008 07:35:14 -0400 Subject: [Tutor] a pyball python app In-Reply-To: References: Message-ID: <47F4C0F2.7060601@tds.net> dean garrad wrote: > i am currently trying to edit a python app > > it is a normal green ball game that comes with python it uses nokia n95 > accel to move around. > > i have been trying to make more than one ball on the screen at the same > time . > > do you think it is possable ? The attachment seems to be a modified version that moves text around on the screen, not a ball. The program uses global variables to hold the state of the moving image, in particular the lists that hold location and speed. Adding a second image while keeping the same programming style would involve a lot of code duplication. What I suggest is to create a Ball object that holds the location and speed of the ball. The movement code could also go into the Ball class. Get this working with one ball. Then it should be pretty easy to add a second ball. Kent From kent37 at tds.net Thu Apr 3 14:57:05 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 Apr 2008 08:57:05 -0400 Subject: [Tutor] a pyball python app In-Reply-To: References: <47F4C0F2.7060601@tds.net> Message-ID: <47F4D421.7000007@tds.net> dean garrad wrote: > this one is the working version of 1 ball that can move around the > screen im sorry the other one i sent was a test one ive been trying out.. > > i cant seam to find it as easy to get it to work with 2 balls on screen. > anything i try doesnt effect the script. What have you tried? Do you understand my suggestion? Kent PS Please use Reply All to reply to the list > > > when i tes out there is always just 1 ball there the only thing i change > by accident is the acceleration and gravity of the ball also the size. From kent37 at tds.net Thu Apr 3 16:16:37 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 Apr 2008 10:16:37 -0400 Subject: [Tutor] a pyball python app In-Reply-To: References: <47F4C0F2.7060601@tds.net> <47F4D421.7000007@tds.net> Message-ID: <47F4E6C5.8000809@tds.net> dean garrad wrote: > i kind of understood what you were saying but not sure how to go by this > i am still new to python script and learning it as much as i can. OK. Do you understand how the current script works? If not, what parts are confusing? Do you understand object-oriented programming at all (classes)? If not, you should probably read some tutorials and get at least a basic understanding. You could add another ball by brute-force copying of lots of code, or by making a list of (location, speed) values for each ball, but the code will end up simpler and easier to understand if you use a class to hold the parameters for the ball. Kent From thankyouforthevenom1971 at hotmail.co.uk Thu Apr 3 16:01:00 2008 From: thankyouforthevenom1971 at hotmail.co.uk (dean garrad) Date: Thu, 3 Apr 2008 15:01:00 +0100 Subject: [Tutor] a pyball python app In-Reply-To: <47F4D421.7000007@tds.net> References: <47F4C0F2.7060601@tds.net> <47F4D421.7000007@tds.net> Message-ID: i kind of understood what you were saying but not sure how to go by this i am still new to python script and learning it as much as i can. here is a video of the script in action http://youtube.com/watch?v=zqZeANFBmis i did not create the script only trying to modify it. i have permission from the developer to modify. > Date: Thu, 3 Apr 2008 08:57:05 -0400 > From: kent37 at tds.net > To: thankyouforthevenom1971 at hotmail.co.uk; tutor at python.org > Subject: Re: [Tutor] a pyball python app > > dean garrad wrote: > > > this one is the working version of 1 ball that can move around the > > screen im sorry the other one i sent was a test one ive been trying out.. > > > > i cant seam to find it as easy to get it to work with 2 balls on screen. > > anything i try doesnt effect the script. > > What have you tried? Do you understand my suggestion? > > Kent > > PS Please use Reply All to reply to the list > > > > > > when i tes out there is always just 1 ball there the only thing i change > > by accident is the acceleration and gravity of the ball also the size. _________________________________________________________________ Win 100?s of Virgin Experience days with BigSnapSearch.com http://www.bigsnapsearch.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080403/ee667259/attachment.htm From thankyouforthevenom1971 at hotmail.co.uk Thu Apr 3 16:27:16 2008 From: thankyouforthevenom1971 at hotmail.co.uk (dean garrad) Date: Thu, 3 Apr 2008 15:27:16 +0100 Subject: [Tutor] a pyball python app In-Reply-To: <47F4E6C5.8000809@tds.net> References: <47F4C0F2.7060601@tds.net> <47F4D421.7000007@tds.net> <47F4E6C5.8000809@tds.net> Message-ID: this is the part im lil confused about to add the extra ball location=[img.size[0]/2,img.size[1]/2] speed=[0.,0.] blobsize=16 xs,ys=img.size[0]-blobsize,img.size[1]-blobsize acceleration=0.05 friction = 0.993 import time start_time=time.clock() n_frames=0 i tried copying but it did nothing do i need to copy it and change something so the python app dont read the same txt twice and jus do nothing? also on the txt bellow if i add another bal somehow i dotn have to copy or change the txt bellow do i? it should create same value for both balls? x_bounce_factor = .8 * (1 - min(6,abs(sense_conn.delta[0])) / 9) y_bounce_factor = .8 * (1 - min(6,abs(sense_conn.delta[1])) / 9) if location[0]>xs: location[0]=xs-(location[0]-xs) speed[0]= -x_bounce_factor * speed[0] speed[1]=0.90*speed[1] if location[0]<0: location[0]=-location[0] speed[0]= -x_bounce_factor * speed[0] speed[1]=0.90*speed[1] if location[1]>ys: location[1]=ys-(location[1]-ys) speed[0]=0.90*speed[0] speed[1]= -y_bounce_factor * speed[1] if location[1]<0: location[1]=-location[1] speed[0]=0.90*speed[0] speed[1]= -y_bounce_factor * speed[1] im just confused on how to get the programme to add another ball into it and keep everything the same.. i tried changing and copying some of the script but the app jus loads the whole ball script twice and seperate ball on each. also could you link advise any good tuturials that would help me ive read some on the net but need more help really. thank you for your time. . > Date: Thu, 3 Apr 2008 10:16:37 -0400 > From: kent37 at tds.net > To: thankyouforthevenom1971 at hotmail.co.uk > CC: tutor at python.org > Subject: Re: [Tutor] a pyball python app > > dean garrad wrote: > > i kind of understood what you were saying but not sure how to go by this > > i am still new to python script and learning it as much as i can. > > OK. Do you understand how the current script works? If not, what parts > are confusing? > > Do you understand object-oriented programming at all (classes)? If not, > you should probably read some tutorials and get at least a basic > understanding. > > You could add another ball by brute-force copying of lots of code, or by > making a list of (location, speed) values for each ball, but the code > will end up simpler and easier to understand if you use a class to hold > the parameters for the ball. > > Kent _________________________________________________________________ Win 100?s of Virgin Experience days with BigSnapSearch.com http://www.bigsnapsearch.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080403/957557d1/attachment-0001.htm From kent37 at tds.net Thu Apr 3 16:34:26 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 Apr 2008 10:34:26 -0400 Subject: [Tutor] a pyball python app In-Reply-To: References: <47F4C0F2.7060601@tds.net> <47F4D421.7000007@tds.net> <47F4E6C5.8000809@tds.net> Message-ID: <47F4EAF2.6050305@tds.net> dean garrad wrote: > > > this is the part im lil confused about to add the extra ball > > location=[img.size[0]/2,img.size[1]/2] > speed=[0.,0.] > i tried copying but it did nothing do i need to copy it and change > something so the python app dont read the same txt twice and jus do nothing? If you want to just copy/paste, you will have to copy all the lines using location and speed and change the copies to something like location2 and speed2. Of course you should also change the starting location or speed so the two balls don't draw in the same place! > also on the txt bellow if i add another bal somehow i dotn have to copy > or change the txt bellow do i? it should create same value for both balls? You have to duplicate all the location and speed code, using the new names. > also could you link advise any good tuturials that would help me ive > read some on the net but need more help really. The first two tutorials listed here are popular: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Kent PS Please subscribe to the list so I don't have to moderate all your requests through. From nomb85 at comcast.net Thu Apr 3 17:17:51 2008 From: nomb85 at comcast.net (Nathan McBride) Date: Thu, 03 Apr 2008 11:17:51 -0400 Subject: [Tutor] socket / over network In-Reply-To: <47F4EAF2.6050305@tds.net> References: <47F4C0F2.7060601@tds.net> <47F4D421.7000007@tds.net> <47F4E6C5.8000809@tds.net> <47F4EAF2.6050305@tds.net> Message-ID: <47F4F51F.8030309@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hey guys, I'm pretty tired of the lame backup solution we have at work. Could anyone point me to a (more or less newbieish) example of how to have python open a socket on one box and get data from it, then have another box write to it over the network? I'm having trouble finding something like this. Thanks, Nate -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org iD8DBQFH9PUf/n+duykW6K8RAvXMAKCE5708Bly/9fzHFZu45cd/d11WGQCdGNcG PWcbs2jjZXv7b586aNAnSv4= =9uBW -----END PGP SIGNATURE----- From jdates at kungfukoi.com Thu Apr 3 17:21:11 2008 From: jdates at kungfukoi.com (Jeffrey Dates) Date: Thu, 3 Apr 2008 11:21:11 -0400 Subject: [Tutor] Newb Learning Question In-Reply-To: References: <1128c3c40804020944r35be5459p3d4752002c6fd8c3@mail.gmail.com> <47F3C277.4010909@alum.rpi.edu> <1128c3c40804021126t5268850cnf644466878730e2@mail.gmail.com> <47F41E4C.6030807@alum.rpi.edu> Message-ID: <1128c3c40804030821r1c7bf4cw28cc02ece0d774e1@mail.gmail.com> > > > 3rd alternative: if c > 'm': print c > after futzing around with interpreting the problem, I ended up with a solution that utilizes the character comparison. "Write a program that prints the first letter of a string that comes after 'm' in the alphabet." s = "this is my string" for i in s: if i > 'm': print i break Thanks for all the help everyone. Seems so obvious now.. ;-) I'm sure I'll be back with some more newb questions in the future. ;-) jeff. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080403/8561f826/attachment.htm From kungfukoi at gmail.com Thu Apr 3 17:32:54 2008 From: kungfukoi at gmail.com (Jeffrey Dates) Date: Thu, 3 Apr 2008 11:32:54 -0400 Subject: [Tutor] Which Python Script Editor of Choice? Message-ID: <1128c3c40804030832q77b2405fkba6472552194dfaa@mail.gmail.com> Hello, So as I'm starting to get into writing some scripts, I'm looking for recommendations for a nifty script editor. Ideally a freeware/shareware solution until I can justify a purchase of something more beefy. Currently I'm using PSPad, however it's pretty dumb and doesn't recognize Python context. Which, I suppose is fine, but would be nice if there was one. Especially since I'm learning. My run time environment is IDLE. Any thoughts or preferences would be appreciated. thanks! Jeffrey Dates www.kungfukoi.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080403/a52832c3/attachment.htm From alan.gauld at btinternet.com Thu Apr 3 17:44:34 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 3 Apr 2008 16:44:34 +0100 Subject: [Tutor] socket / over network References: <47F4C0F2.7060601@tds.net> <47F4D421.7000007@tds.net> <47F4E6C5.8000809@tds.net> <47F4EAF2.6050305@tds.net> <47F4F51F.8030309@comcast.net> Message-ID: "Nathan McBride" wrote Hi Nathan, Please don't reply to an existing message to start a new discussion. It messes up those of us using threaded mail/news readers and increases the likelihood that your message will be missed. > I'm pretty tired of the lame backup solution we have at work. > Could anyone point me to a (more or less newbieish) example of how > to > have python open a socket on one box and get data from it, then have > another > box write to it over the network? For a very simple example of using a socket you could try the Network Programming topic in my tutorial. There is also a HowTo or Topic guide on the Python web site that gives a more detailed example. That having been said, backups are usually best done using OS tools or if you must roll your own then using ftp or similar as a file transfer mechanism rather than trying to send a bytestream over a socket. ftp can handle broken connections etc more easily. Detecting and fixing errors over a socket stream is non trivial and for backups is pretty much essential!! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Apr 3 17:57:10 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 3 Apr 2008 16:57:10 +0100 Subject: [Tutor] Which Python Script Editor of Choice? References: <1128c3c40804030832q77b2405fkba6472552194dfaa@mail.gmail.com> Message-ID: "Jeffrey Dates" wrote > So as I'm starting to get into writing some scripts, I'm looking for > recommendations for a nifty script editor. Ideally a > freeware/shareware > solution until I can justify a purchase of something more beefy. editor choice is a sensitive topic for programmers and tends to lead to religious wars. > Currently I'm using PSPad, however it's pretty dumb and doesn't > recognize > Python context. Which, I suppose is fine, but would be nice if > there was > one. Especially since I'm learning. If you are on Windows then the Pythonwin editor is pretty good. Or for a simple editor you can use Scite which is the same editor engine as Pythonwin but includes multiple tabbed panes. But doesn't include an interactive shell. At the other end of the scale you can install PyDev into the eclipse editor which is a good solution if you already use Eclipse for anything else. emacs and vim can both be made Python aware too. And there are lots of others that each has their followers. SPE and Ala Mode(comes with wxPython) are others that I personally tried and found OK. My normal tools are: Pythonwin for short coding sessions or when using the >>> prompt a lot. For longer coding sesssions I use the 3 window approach: vijm for editing, a DOS(Cygwin) window for running the code and another Cygwin window running the Python >>> prompt. And Alt-Tab to switch between them. > My run time environment is IDLE. But IDLE should never be your main run time environment. It is an IDE for developing code but you should run the code under the interpreter within the OS, you will generally get better (more predicatable!) results that way. The IDLE editor is OK too of course but I assumed you didn't want it for some reason? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at alum.rpi.edu Thu Apr 3 18:03:00 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Thu, 03 Apr 2008 12:03:00 -0400 Subject: [Tutor] Which Python Script Editor of Choice? In-Reply-To: <1128c3c40804030832q77b2405fkba6472552194dfaa@mail.gmail.com> References: <1128c3c40804030832q77b2405fkba6472552194dfaa@mail.gmail.com> Message-ID: <47F4FFB4.8050001@alum.rpi.edu> Jeffrey Dates wrote: > Hello, > > So as I'm starting to get into writing some scripts, I'm looking for > recommendations for a nifty script editor. Ideally a > freeware/shareware solution until I can justify a purchase of > something more beefy. I use Python for Windows and really like it. It is free. http://sourceforge.net/projects/pywin32/ > > Currently I'm using PSPad, however it's pretty dumb and doesn't > recognize Python context. I went to the PSPad site, but found no way to download the editor. Am I missing something? > My run time environment is IDLE. It is more accurate to say "My development environment is IDLE." The underlying Python interpreter is the runtime. -- Bob Gailer 919-636-4239 Chapel Hill, NC From bgailer at alum.rpi.edu Thu Apr 3 18:07:05 2008 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 03 Apr 2008 12:07:05 -0400 Subject: [Tutor] Which Python Script Editor of Choice? In-Reply-To: <1128c3c40804030832q77b2405fkba6472552194dfaa@mail.gmail.com> References: <1128c3c40804030832q77b2405fkba6472552194dfaa@mail.gmail.com> Message-ID: <47F500A9.4080106@alum.rpi.edu> [snip] > I went to the PSPad site, but found no way to download the editor. Am > I missing something? Ignore that. Something on the home page did not display correctly. Refresh fixed that. -- Bob Gailer 919-636-4239 Chapel Hill, NC From andreas at kostyrka.org Thu Apr 3 18:15:09 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 03 Apr 2008 18:15:09 +0200 Subject: [Tutor] Which Python Script Editor of Choice? In-Reply-To: References: <1128c3c40804030832q77b2405fkba6472552194dfaa@mail.gmail.com> Message-ID: <1207239309.19833.0.camel@localhost> Eric and SPE are also nice. The good thing here is that the majority of IDEs for Python are free. Andreas Am Donnerstag, den 03.04.2008, 16:57 +0100 schrieb Alan Gauld: > "Jeffrey Dates" wrote > > > So as I'm starting to get into writing some scripts, I'm looking for > > recommendations for a nifty script editor. Ideally a > > freeware/shareware > > solution until I can justify a purchase of something more beefy. > > editor choice is a sensitive topic for programmers and > tends to lead to religious wars. > > > Currently I'm using PSPad, however it's pretty dumb and doesn't > > recognize > > Python context. Which, I suppose is fine, but would be nice if > > there was > > one. Especially since I'm learning. > > If you are on Windows then the Pythonwin editor is pretty good. > > Or for a simple editor you can use Scite which is the same editor > engine as Pythonwin but includes multiple tabbed panes. But > doesn't include an interactive shell. > > At the other end of the scale you can install PyDev into the > eclipse editor which is a good solution if you already use > Eclipse for anything else. > > emacs and vim can both be made Python aware too. > > And there are lots of others that each has their followers. > SPE and Ala Mode(comes with wxPython) are others that > I personally tried and found OK. > > My normal tools are: > Pythonwin for short coding sessions or when using the >>> > prompt a lot. > For longer coding sesssions I use the 3 window approach: > vijm for editing, a DOS(Cygwin) window for running the code and > another Cygwin window running the Python >>> prompt. > And Alt-Tab to switch between them. > > > My run time environment is IDLE. > > But IDLE should never be your main run time environment. > It is an IDE for developing code but you should run the code > under the interpreter within the OS, you will generally get better > (more predicatable!) results that way. The IDLE editor is > OK too of course but I assumed you didn't want it for > some reason? > > HTH, > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080403/f4fc0892/attachment-0001.pgp From jdates at kungfukoi.com Thu Apr 3 18:19:59 2008 From: jdates at kungfukoi.com (Jeffrey Dates) Date: Thu, 3 Apr 2008 12:19:59 -0400 Subject: [Tutor] Which Python Script Editor of Choice? In-Reply-To: <1207239309.19833.0.camel@localhost> References: <1128c3c40804030832q77b2405fkba6472552194dfaa@mail.gmail.com> <1207239309.19833.0.camel@localhost> Message-ID: <1128c3c40804030919j5a74c56eo6c5cae5def782e38@mail.gmail.com> Ah thanks guy!! Yeah, I guess I didn't mean which is the 'best'... Just some options. Thanks, I'll check out the ones you listed! I'm on Windows btw. Jeffrey Dates www.kungfukoi.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080403/1b4444d6/attachment.htm From tonytraductor at linguasos.org Thu Apr 3 18:44:17 2008 From: tonytraductor at linguasos.org (Anthony Baldwin) Date: Thu, 03 Apr 2008 12:44:17 -0400 Subject: [Tutor] Which Python Script Editor of Choice? In-Reply-To: <1207239309.19833.0.camel@localhost> References: <1128c3c40804030832q77b2405fkba6472552194dfaa@mail.gmail.com> <1207239309.19833.0.camel@localhost> Message-ID: <47F50961.5040909@linguasos.org> Andreas Kostyrka wrote: > Eric and SPE are also nice. > > The good thing here is that the majority of IDEs for Python are free. > > Andreas > > Am Donnerstag, den 03.04.2008, 16:57 +0100 schrieb Alan Gauld: > >> "Jeffrey Dates" wrote >> >> >>> So as I'm starting to get into writing some scripts, I'm looking for >>> recommendations for a nifty script editor. Ideally a >>> freeware/shareware >>> solution until I can justify a purchase of something more beefy. >>> >> editor choice is a sensitive topic for programmers and >> tends to lead to religious wars. >> >> >> I use TickleText (http://sourceforge.net/projects/tickletext/ ) It doesn't have python syntax highlighting though. I'm really just starting with python, and mostly hack tcl.tk, in which TickleText is written. It's good for writing html and LaTeX, and other stuff, too, and has some other useful features. It's certainly not as fat and bloated as Emacs (hehe...Emacs is cool, really). I used to use medit or kate. But then I made Tickle Text. Kdevelop is nice if you want a full IDE that does recognize python syntax. And, of course, if you are using Linux. I don't use KDE (use fluxbox), but I like some of these KDE tools. /tony -- Anthony Baldwin http://www.BaldwinLinguas.com Translation & Interpreting http://www.TransProCalc.org Free translation project mgmt software From pylinuxian at gmail.com Thu Apr 3 18:52:06 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Thu, 3 Apr 2008 16:52:06 +0000 Subject: [Tutor] socket / over network In-Reply-To: References: <47F4D421.7000007@tds.net> <47F4E6C5.8000809@tds.net> <47F4EAF2.6050305@tds.net> <47F4F51F.8030309@comcast.net> Message-ID: re-inventing the wheel ? http://www.howtoforge.com/linux_backuppc > > > On Thu, Apr 3, 2008 at 3:44 PM, Alan Gauld > wrote: > > > "Nathan McBride" wrote > > > > Hi Nathan, > > > > Please don't reply to an existing message to start a new discussion. > > It messes up those of us using threaded mail/news readers and > > increases the likelihood that your message will be missed. > > > > > I'm pretty tired of the lame backup solution we have at work. > > > Could anyone point me to a (more or less newbieish) example of how > > > to > > > have python open a socket on one box and get data from it, then have > > > another > > > box write to it over the network? > > > > For a very simple example of using a socket you could try the > > Network Programming topic in my tutorial. > > > > There is also a HowTo or Topic guide on the Python web site > > that gives a more detailed example. > > > > That having been said, backups are usually best done using > > OS tools or if you must roll your own then using ftp or similar > > as a file transfer mechanism rather than trying to send a > > bytestream over a socket. ftp can handle broken connections > > etc more easily. Detecting and fixing errors over a socket > > stream is non trivial and for backups is pretty much essential!! > > > > -- > > Alan Gauld > > Author of the Learn to Program web site > > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080403/4d201858/attachment.htm From thankyouforthevenom1971 at hotmail.co.uk Thu Apr 3 19:04:10 2008 From: thankyouforthevenom1971 at hotmail.co.uk (dean garrad) Date: Thu, 3 Apr 2008 18:04:10 +0100 Subject: [Tutor] a pyball python app In-Reply-To: <47F4EAF2.6050305@tds.net> References: <47F4C0F2.7060601@tds.net> <47F4D421.7000007@tds.net> <47F4E6C5.8000809@tds.net> <47F4EAF2.6050305@tds.net> Message-ID: hi i signed onto the site it asked me to. :). can i talk to ya now more ? im not sure if i am in wrong place to send e mail to you still i still ahving problems with the ball script this is the script at the moment how it stands with 1 ball working fine and i have been trying to add another ball to the script. i coppied the txt and added a location2 aswell as location. but it didnt seam to work :S import appuifw from graphics import * import e32 import sensor class SensorConnection(object): delta = [] def __init__(self): """Connect to the sensor.""" sens = sensor.sensors()['AccSensor'] self.s = sensor.Sensor(sens['id'], sens['category']) self.s.connect(self.callme) def callme(self, state): self.delta = [] for key in ['data_1', 'data_2', 'data_3']: val = state[key] self.delta.append(int(val + 40)/80) def cleanup(self): """Cleanup after yourself. *Must be called* before exiting.""" self.s.disconnect() sense_conn = SensorConnection() appuifw.app.screen='full' img=None def handle_redraw(rect): if img: canvas.blit(img) appuifw.app.body=canvas=appuifw.Canvas( redraw_callback=handle_redraw) img=Image.new(canvas.size) running=1 def quit(): global running running=0 appuifw.app.exit_key_handler=quit location=[img.size[0]/2,img.size[1]/2] speed=[0.,0.] blobsize=16 xs,ys=img.size[0]-blobsize,img.size[1]-blobsize acceleration=0.05 friction = 0.993 import time start_time=time.clock() n_frames=0 # To speed things up, we prerender the text. labeltext=u'Tilt the phone to move' textrect=img.measure_text(labeltext, font='normal')[0] text_img=Image.new((textrect[2]-textrect[0],textrect[3]-textrect[1])) text_img.clear(0) text_img.text((-textrect[0],-textrect[1]),labeltext,fill=0xffffff,font='normal') while running: img.clear(0) img.blit(text_img, (0,0)) img.point((location[0]+blobsize/2,location[1]+blobsize/2), 0x00ff00,width=blobsize) handle_redraw(()) e32.ao_yield() e32.reset_inactivity() speed[0]*=friction speed[1]*=friction location[0]+=speed[0] location[1]+=speed[1] n_frames+=1 if not sense_conn: continue if not len(sense_conn.delta): continue x_bounce_factor = .8 * (1 - min(6,abs(sense_conn.delta[0])) / 9) y_bounce_factor = .8 * (1 - min(6,abs(sense_conn.delta[1])) / 9) if location[0]>xs: location[0]=xs-(location[0]-xs) speed[0]= -x_bounce_factor * speed[0] speed[1]=0.90*speed[1] if location[0]<0: location[0]=-location[0] speed[0]= -x_bounce_factor * speed[0] speed[1]=0.90*speed[1] if location[1]>ys: location[1]=ys-(location[1]-ys) speed[0]=0.90*speed[0] speed[1]= -y_bounce_factor * speed[1] if location[1]<0: location[1]=-location[1] speed[0]=0.90*speed[0] speed[1]= -y_bounce_factor * speed[1] speed[0] -= (sense_conn.delta[1]) * acceleration speed[1] -= (sense_conn.delta[0]) * acceleration speed[0] = max(min(xs / 2, speed[0]), -xs/2) speed[1] = max(min(ys / 2, speed[1]), -ys/2) end_time=time.clock() total=end_time-start_time sense_conn.cleanup() print "%d frames, %f seconds, %f FPS, %f ms/frame."%(n_frames,total, n_frames/total, total/n_frames*1000.) > Date: Thu, 3 Apr 2008 10:34:26 -0400 > From: kent37 at tds.net > To: thankyouforthevenom1971 at hotmail.co.uk > CC: tutor at python.org > Subject: Re: [Tutor] a pyball python app > > dean garrad wrote: > > > > > > this is the part im lil confused about to add the extra ball > > > > location=[img.size[0]/2,img.size[1]/2] > > speed=[0.,0.] > > > i tried copying but it did nothing do i need to copy it and change > > something so the python app dont read the same txt twice and jus do nothing? > > If you want to just copy/paste, you will have to copy all the lines > using location and speed and change the copies to something like > location2 and speed2. Of course you should also change the starting > location or speed so the two balls don't draw in the same place! > > > also on the txt bellow if i add another bal somehow i dotn have to copy > > or change the txt bellow do i? it should create same value for both balls? > > You have to duplicate all the location and speed code, using the new names. > > > also could you link advise any good tuturials that would help me ive > > read some on the net but need more help really. > > The first two tutorials listed here are popular: > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > Kent > > PS Please subscribe to the list so I don't have to moderate all your > requests through. _________________________________________________________________ The next generation of Windows Live is here http://www.windowslive.co.uk/get-live -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080403/90acc349/attachment.htm From mlangford.cs03 at gtalumni.org Thu Apr 3 19:15:34 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Thu, 3 Apr 2008 13:15:34 -0400 Subject: [Tutor] Which Python Script Editor of Choice? In-Reply-To: <1128c3c40804030832q77b2405fkba6472552194dfaa@mail.gmail.com> References: <1128c3c40804030832q77b2405fkba6472552194dfaa@mail.gmail.com> Message-ID: <82b4f5810804031015y6446fbbfgee3ee5b5c88d9c78@mail.gmail.com> Asking a programmer which editor to use is like asking which religion is best. I use VIM and IPython and shell scripts (I mostly program on windows, but sometimes on Linux as well). There are several options. I'm considering looking into PIDA, which is a "IDE you make from tools you already use" but haven't had time to try to check it out on windows. Eric4 and Wingware are both very fully developed. Komodo also often gets props from the "IDE People" I've known. Other "IDE" choices go as follow, DrPython, pyCrust, emacs, VIM (has IDE addons), IronPython/VisualStudio, Boa Constrictor, and Eclipse. I do often suggest to people who are just starting out: Learn to program without an IDE, then use one after 6 mo/a year. Many people who go this way, program with or without one just fine. Those who start right away always using IDE's can just plain die when they hit an environment where they don't have one (due to time, money, location, or whatever). Btw, if people know of good IDE's other than PIDA that are free, run on windows and linux and allow use of VIM as the editor, please let me know. --Michael On Thu, Apr 3, 2008 at 11:32 AM, Jeffrey Dates wrote: > Hello, > > So as I'm starting to get into writing some scripts, I'm looking for > recommendations for a nifty script editor. Ideally a freeware/shareware > solution until I can justify a purchase of something more beefy. > > Currently I'm using PSPad, however it's pretty dumb and doesn't recognize > Python context. Which, I suppose is fine, but would be nice if there was > one. Especially since I'm learning. > > My run time environment is IDLE. > > Any thoughts or preferences would be appreciated. > thanks! > > Jeffrey Dates > www.kungfukoi.com > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080403/981df247/attachment-0001.htm From sirgnip at gmail.com Thu Apr 3 19:28:52 2008 From: sirgnip at gmail.com (Scott Nelson) Date: Thu, 3 Apr 2008 12:28:52 -0500 Subject: [Tutor] Which Python Script Editor of Choice? In-Reply-To: <82b4f5810804031015y6446fbbfgee3ee5b5c88d9c78@mail.gmail.com> References: <1128c3c40804030832q77b2405fkba6472552194dfaa@mail.gmail.com> <82b4f5810804031015y6446fbbfgee3ee5b5c88d9c78@mail.gmail.com> Message-ID: <2682ac9b0804031028w36668405hc581166a4be12f68@mail.gmail.com> > > Komodo also often gets props from the "IDE People" I've known. To throw another one into the mix, ActiveState has a free/open source version of its Komodo IDE called "Komodo Edit". I downloaded it and played with it for a few minutes awhile ago. Seems pretty slick. Anyone have any first hand experience with this one? It also supports more than just Python (also does Perl, PHP, Ruby, Rails, etc.) http://www.activestate.com/Products/komodo_ide/komodo_edit.mhtml (FWIW, most of the time, I use PythonWin to edit code and a command prompt to run scripts) > Btw, if people know of good IDE's other than PIDA that are free, run on windows and linux and allow use of VIM as the editor, please let me know. Looking at Komodo Edit's page, it supports Win/Mac/Linux, has "Vi emulation", and is free (not crippled in any way that I know of. It just has a smaller feature set when compared to the full Komodo). -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080403/a5c8e1dd/attachment.htm From kent37 at tds.net Thu Apr 3 20:16:02 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 Apr 2008 14:16:02 -0400 Subject: [Tutor] a pyball python app In-Reply-To: References: <47F4C0F2.7060601@tds.net> <47F4D421.7000007@tds.net> <47F4E6C5.8000809@tds.net> <47F4EAF2.6050305@tds.net> Message-ID: <47F51EE2.5020401@tds.net> dean garrad wrote: > i still ahving problems with the ball script this is the script at the > moment how it stands with 1 ball working fine and i have been trying to > add another ball to the script. > > i coppied the txt and added a location2 aswell as location. but it didnt > seam to work :S I don't see where you added location2. I think you are over your head with this project. I recommend you spend some time with a tutorial and some simpler programs, then come back to this one. Perhaps one goal would be to understand how your current program works. Kent From sander.sweers at gmail.com Thu Apr 3 20:17:05 2008 From: sander.sweers at gmail.com (Sander Sweers) Date: Thu, 3 Apr 2008 11:17:05 -0700 Subject: [Tutor] Newb Learning Question In-Reply-To: References: <1128c3c40804020944r35be5459p3d4752002c6fd8c3@mail.gmail.com> <47F3C277.4010909@alum.rpi.edu> <1128c3c40804021126t5268850cnf644466878730e2@mail.gmail.com> <47F41E4C.6030807@alum.rpi.edu> <1128c3c40804030821r1c7bf4cw28cc02ece0d774e1@mail.gmail.com> Message-ID: Should be replying to the list....Sorry :( On Thu, Apr 3, 2008 at 11:14 AM, Sander Sweers wrote: > On Thu, Apr 3, 2008 at 8:21 AM, Jeffrey Dates wrote: > > > > 3rd alternative: if c > 'm': print c > > > > > > "Write a program that prints the first letter of a string that comes after > > 'm' in the alphabet." > > > > s = "this is my string" > > for i in s: > > if i > 'm': > > print i > > break > > One potential problem you will have is with upper case letters. > > >>> 'N' > 'm' > False > > To make input all lower case use .lower() > > >>> 'N'.lower() > 'm' > True > > Greets > Sander > From jdates at kungfukoi.com Thu Apr 3 20:37:50 2008 From: jdates at kungfukoi.com (Jeffrey Dates) Date: Thu, 3 Apr 2008 14:37:50 -0400 Subject: [Tutor] Newb Learning Question In-Reply-To: References: <1128c3c40804020944r35be5459p3d4752002c6fd8c3@mail.gmail.com> <47F3C277.4010909@alum.rpi.edu> <1128c3c40804021126t5268850cnf644466878730e2@mail.gmail.com> <47F41E4C.6030807@alum.rpi.edu> <1128c3c40804030821r1c7bf4cw28cc02ece0d774e1@mail.gmail.com> Message-ID: <1128c3c40804031137y2e6dd078ie46b6896941f238f@mail.gmail.com> Exellent suggestion! thanks! On Thu, Apr 3, 2008 at 2:17 PM, Sander Sweers wrote: > Should be replying to the list....Sorry :( > > On Thu, Apr 3, 2008 at 11:14 AM, Sander Sweers > wrote: > > On Thu, Apr 3, 2008 at 8:21 AM, Jeffrey Dates > wrote: > > > > > 3rd alternative: if c > 'm': print c > > > > > > > > > > > "Write a program that prints the first letter of a string that comes > after > > > 'm' in the alphabet." > > > > > > s = "this is my string" > > > for i in s: > > > if i > 'm': > > > print i > > > break > > > > One potential problem you will have is with upper case letters. > > > > >>> 'N' > 'm' > > False > > > > To make input all lower case use .lower() > > > > >>> 'N'.lower() > 'm' > > True > > > > Greets > > Sander > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080403/fb60fdbc/attachment.htm From srilyk at gmail.com Thu Apr 3 20:40:10 2008 From: srilyk at gmail.com (W W) Date: Thu, 3 Apr 2008 13:40:10 -0500 Subject: [Tutor] Which Python Script Editor of Choice? In-Reply-To: <82b4f5810804031015y6446fbbfgee3ee5b5c88d9c78@mail.gmail.com> References: <1128c3c40804030832q77b2405fkba6472552194dfaa@mail.gmail.com> <82b4f5810804031015y6446fbbfgee3ee5b5c88d9c78@mail.gmail.com> Message-ID: <333efb450804031140l10b3fb40ge82732967b019649@mail.gmail.com> On Thu, Apr 3, 2008 at 12:15 PM, Michael Langford wrote: > Many people who go this way, program with or without one just fine. Those who start right away always using IDE's can just plain die when they hit an environment where they don't have one (due to time, money, location, or whatever). > > Btw, if people know of good IDE's other than PIDA that are free, run on windows and linux and allow use of VIM as the editor, please let me know. I personally use VIM/vi as my editor. The best thing about using VIM (at least when it comes to testing) is the ability to run command line arguments from vim. :!python hand_grenade.py would run your script (assuming you started editing in whatever directory). Auto complete (the use of works too. I've never used an IDE aside from the MS Visual Studio for our CS I class - and I find it to be horrible overkill, confusing, and less powerful than vim and g++ from the command line under ubuntu. I suppose my method isn't an IDE, but it works for me (and so far I don't see any reason to change, if I need to edit multiple files at a time I can :split windows, yada yada). Find whatever suits you, and good luck in the hunt -Wayne From srilyk at gmail.com Thu Apr 3 20:46:29 2008 From: srilyk at gmail.com (W W) Date: Thu, 3 Apr 2008 13:46:29 -0500 Subject: [Tutor] a pyball python app In-Reply-To: <47F51EE2.5020401@tds.net> References: <47F4C0F2.7060601@tds.net> <47F4D421.7000007@tds.net> <47F4E6C5.8000809@tds.net> <47F4EAF2.6050305@tds.net> <47F51EE2.5020401@tds.net> Message-ID: <333efb450804031146g530feb2drbb3fd1c713c4eedf@mail.gmail.com> Dean, Here's a tutorial/book that you should check out: http://www.greenteapress.com/thinkpython/ How to Think Like a (Python) Programmer by Allen B. Downey He generously has a free PDF to download, and the book makes use of some code - swampy.py I think if you 1) Read the book and try the examples, and at least try /some/ of the assignments, and 2) Examine the source code of the swampy program, you'll learn how to do exactly what you want - create two different balls (or technically, as many as you'd like/the phone will run). Good luck! -Wayne On Thu, Apr 3, 2008 at 1:16 PM, Kent Johnson wrote: > dean garrad wrote: > > > i still ahving problems with the ball script this is the script at the > > moment how it stands with 1 ball working fine and i have been trying to > > add another ball to the script. > > > > i coppied the txt and added a location2 aswell as location. but it didnt > > seam to work :S > > I don't see where you added location2. > > I think you are over your head with this project. I recommend you spend > some time with a tutorial and some simpler programs, then come back to > this one. Perhaps one goal would be to understand how your current > program works. > > Kent > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From dkuhlman at rexx.com Thu Apr 3 21:46:45 2008 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 3 Apr 2008 12:46:45 -0700 Subject: [Tutor] Which Python Script Editor of Choice? In-Reply-To: <1128c3c40804030832q77b2405fkba6472552194dfaa@mail.gmail.com> References: <1128c3c40804030832q77b2405fkba6472552194dfaa@mail.gmail.com> Message-ID: <20080403194645.GA30997@cutter.rexx.com> On Thu, Apr 03, 2008 at 11:32:54AM -0400, Jeffrey Dates wrote: > Hello, > > So as I'm starting to get into writing some scripts, I'm looking for > recommendations for a nifty script editor. Ideally a freeware/shareware > solution until I can justify a purchase of something more beefy. > > Currently I'm using PSPad, however it's pretty dumb and doesn't recognize > Python context. Which, I suppose is fine, but would be nice if there was > one. Especially since I'm learning. > If you are looking for text editors, this page will give you more choices than you want: http://en.wikipedia.org/wiki/Comparison_of_text_editors My favorites are: - Jed - Emacs - SciTE - Jedit (but only if you have lots of memory) Jed, Emacs, and SciTE are scriptable. SciTe, perhaps, is not. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From kent37 at tds.net Thu Apr 3 22:05:28 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 Apr 2008 16:05:28 -0400 Subject: [Tutor] Which Python Script Editor of Choice? In-Reply-To: <20080403194645.GA30997@cutter.rexx.com> References: <1128c3c40804030832q77b2405fkba6472552194dfaa@mail.gmail.com> <20080403194645.GA30997@cutter.rexx.com> Message-ID: <47F53888.6030708@tds.net> Dave Kuhlman wrote: > If you are looking for text editors, this page will give you more > choices than you want: > > http://en.wikipedia.org/wiki/Comparison_of_text_editors And this: http://wiki.python.org/moin/PythonEditors When I worked on Windows I used TextPad, it's inexpensive but not free. Kent From mlangford.cs03 at gtalumni.org Thu Apr 3 23:12:15 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Thu, 3 Apr 2008 17:12:15 -0400 Subject: [Tutor] Which Python Script Editor of Choice? In-Reply-To: <333efb450804031140l10b3fb40ge82732967b019649@mail.gmail.com> References: <1128c3c40804030832q77b2405fkba6472552194dfaa@mail.gmail.com> <82b4f5810804031015y6446fbbfgee3ee5b5c88d9c78@mail.gmail.com> <333efb450804031140l10b3fb40ge82732967b019649@mail.gmail.com> Message-ID: <82b4f5810804031412l5368974eqfd7217d7ae643193@mail.gmail.com> When you have you use Visual Studio, I suggest using the beautiful and wonder ViEmu. Best $90 I ever spent: http://www.viemu.com/ On Thu, Apr 3, 2008 at 2:40 PM, W W wrote: > On Thu, Apr 3, 2008 at 12:15 PM, Michael Langford > wrote: > > Many people who go this way, program with or without one just fine. > Those who start right away always using IDE's can just plain die when they > hit an environment where they don't have one (due to time, money, location, > or whatever). > > > > Btw, if people know of good IDE's other than PIDA that are free, run on > windows and linux and allow use of VIM as the editor, please let me know. > > I personally use VIM/vi as my editor. The best thing about using VIM > (at least when it comes to testing) is the ability to run command line > arguments from vim. > > :!python hand_grenade.py > > would run your script (assuming you started editing in whatever > directory). Auto complete (the use of works too. I've never used > an IDE aside from the MS Visual Studio for our CS I class - and I find > it to be horrible overkill, confusing, and less powerful than vim and > g++ from the command line under ubuntu. > > I suppose my method isn't an IDE, but it works for me (and so far I > don't see any reason to change, if I need to edit multiple files at a > time I can :split windows, yada yada). > > Find whatever suits you, and good luck in the hunt > -Wayne > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080403/771e88b5/attachment-0001.htm From oltarasenko at gmail.com Fri Apr 4 10:03:14 2008 From: oltarasenko at gmail.com (Oleg Oltar) Date: Fri, 4 Apr 2008 11:03:14 +0300 Subject: [Tutor] Unittest traceback Message-ID: Hi! I am trying to use unittest in python first time. But have a strange traceback each time I run my sample tests. Can you please explain why I have it. No info about it in the doc. e.g. the code is import unittest import squaren class TestCases(unittest.TestCase): def setUp(self): pass def testsmall(self): self.assertEqual(True, True) if __name__ == '__main__': unittest.main() And the traceback is ---------------------------------------------------------------------- Ran 1 test in 0.000s OK Traceback (most recent call last): File "/tmp/py359hJx", line 14, in unittest.main() File "/opt/local/lib/python2.5/unittest.py", line 768, in __init__ self.runTests() File "/opt/local/lib/python2.5/unittest.py", line 806, in runTests sys.exit(not result.wasSuccessful()) SystemExit: False -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080404/3eafad1c/attachment.htm From kent37 at tds.net Fri Apr 4 13:36:16 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 04 Apr 2008 07:36:16 -0400 Subject: [Tutor] Unittest traceback In-Reply-To: References: Message-ID: <47F612B0.7020907@tds.net> Oleg Oltar wrote: > Hi! > > I am trying to use unittest in python first time. But have a strange > traceback each time I run my sample tests. How are you running the test? My guess is that you are running it in an IDE or something that shows the normal system exit exception. Calling sys.exit() raises the SystemExit exception with a result code. Normally this is not shown by the runner. In Python False == 0 so your program is exiting normally with a code of 0 (no error). It is probably the program runner that is showing the traceback. Try running the program from the command line. Kent > Can you please explain why I have it. No info about it in the doc. > e.g. the code is > > import unittest > import squaren > > class TestCases(unittest.TestCase): > def setUp(self): > pass > > def testsmall(self): > self.assertEqual(True, True) > > > > if __name__ == '__main__': > unittest.main() > > And the traceback is > > ---------------------------------------------------------------------- > Ran 1 test in 0.000s > > OK > Traceback (most recent call last): > File "/tmp/py359hJx", line 14, in > unittest.main() > File "/opt/local/lib/python2.5/unittest.py", line 768, in __init__ > self.runTests() > File "/opt/local/lib/python2.5/unittest.py", line 806, in runTests > sys.exit(not result.wasSuccessful()) > SystemExit: False From oltarasenko at gmail.com Fri Apr 4 13:50:12 2008 From: oltarasenko at gmail.com (Oleg Oltar) Date: Fri, 4 Apr 2008 14:50:12 +0300 Subject: [Tutor] Fwd: Unittest traceback In-Reply-To: References: <47F612B0.7020907@tds.net> Message-ID: ---------- Forwarded message ---------- From: Oleg Oltar Date: Fri, Apr 4, 2008 at 2:49 PM Subject: Re: [Tutor] Unittest traceback To: Kent Johnson Yes! Tried in command line. works fine there. Not sure howto customize my IDE correctly. I use Emacs. Thanks, Oleg On Fri, Apr 4, 2008 at 2:36 PM, Kent Johnson wrote: > Oleg Oltar wrote: > > > Hi! > > I am trying to use unittest in python first time. But have a strange > > traceback each time I run my sample tests. > > > > How are you running the test? My guess is that you are running it in an > IDE or something that shows the normal system exit exception. > > Calling sys.exit() raises the SystemExit exception with a result code. > Normally this is not shown by the runner. > > In Python False == 0 so your program is exiting normally with a code of 0 > (no error). It is probably the program runner that is showing the traceback. > > Try running the program from the command line. > > Kent > > > Can you please explain why I have it. No info about it in the doc. e.g. > > the code is > > > > import unittest > > import squaren > > > > class TestCases(unittest.TestCase): > > def setUp(self): > > pass > > > > def testsmall(self): > > self.assertEqual(True, True) > > > > > > > > if __name__ == '__main__': > > unittest.main() > > > > And the traceback is > > ---------------------------------------------------------------------- > > Ran 1 test in 0.000s > > > > OK > > Traceback (most recent call last): > > File "/tmp/py359hJx", line 14, in > > unittest.main() > > File "/opt/local/lib/python2.5/unittest.py", line 768, in __init__ > > self.runTests() > > File "/opt/local/lib/python2.5/unittest.py", line 806, in runTests > > sys.exit(not result.wasSuccessful()) > > SystemExit: False > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080404/794acccb/attachment.htm From rdm at rcblue.com Fri Apr 4 16:12:11 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 04 Apr 2008 07:12:11 -0700 Subject: [Tutor] Don't miss "Python-by-example - new online guide to Python Standard Library" Message-ID: <20080404141243.55FCF1E400F@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080404/8e49a5e0/attachment.htm From brnstrmrs at gmail.com Fri Apr 4 17:15:22 2008 From: brnstrmrs at gmail.com (Brain Stormer) Date: Fri, 4 Apr 2008 11:15:22 -0400 Subject: [Tutor] Interactive physics simulation over web Message-ID: <24bc7f6c0804040815s57b3d9ferdc1ff7774db1e178@mail.gmail.com> I am working on a physics simulation and would like to publish it on the web. The simulation requires input fields, mouse action (picking points in a display pane) and movie like feature with play, pause, skip forward and skip backward. I was wondering if this can be done using Python and a Python web tool kit like Django. I can see that this can be done using Java/Java Script but don't feel like re-familiarizing myself to Java. I looked into the Python web programming pagebut it didn't answer my questions. My goal is keep this simulation completely written in Python. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080404/5afd8865/attachment.htm From pylinuxian at gmail.com Fri Apr 4 17:36:34 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Fri, 4 Apr 2008 15:36:34 +0000 Subject: [Tutor] Don't miss "Python-by-example - new online guide to Python Standard Library" In-Reply-To: <20080404141243.55FCF1E400F@bag.python.org> References: <20080404141243.55FCF1E400F@bag.python.org> Message-ID: well, good to see something like this comming ... i used to browse for hours to find nothing but long long documentation & not a single real life example... but i guess its because i m used to the old 'howto' way of ducumentation ... On Fri, Apr 4, 2008 at 2:12 PM, Dick Moores wrote: > A new one-man project, just getting started. > < http://www.lightbird.net/py-by-example/> > > This guide aims to show examples of use of all Python Library Reference > functions, methods and classes. At this point, only the more widely used > modules were added and only functions use examples are given. Python version > 2.5 was used for examples unless noted otherwise. Example of output of a > function is shown in the form of function_call(args) # [result]: > > math.sqrt(9) # 3.0 > > > See the thread in the python-list archive: > > Dick Moores > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080404/cf52bf01/attachment.htm From adam.jtm30 at gmail.com Fri Apr 4 17:42:33 2008 From: adam.jtm30 at gmail.com (Adam Bark) Date: Fri, 4 Apr 2008 16:42:33 +0100 Subject: [Tutor] Interactive physics simulation over web In-Reply-To: <24bc7f6c0804040815s57b3d9ferdc1ff7774db1e178@mail.gmail.com> References: <24bc7f6c0804040815s57b3d9ferdc1ff7774db1e178@mail.gmail.com> Message-ID: On 04/04/2008, Brain Stormer wrote: > > I am working on a physics simulation and would like to publish it on the > web. The simulation requires input fields, mouse action (picking points in > a display pane) and movie like feature with play, pause, skip forward and > skip backward. I was wondering if this can be done using Python and a > Python web tool kit like Django. I can see that this can be done using > Java/Java Script but don't feel like re-familiarizing myself to Java. I > looked into the Python web programming pagebut it didn't answer my questions. My goal is keep this simulation > completely written in Python. I think you can use Jython in a Java applet, that might be what you're looking for. HTH, Adam. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080404/090300d6/attachment-0001.htm From mail at timgolden.me.uk Fri Apr 4 17:48:11 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 04 Apr 2008 16:48:11 +0100 Subject: [Tutor] Don't miss "Python-by-example - new online guide to Python Standard Library" In-Reply-To: References: <20080404141243.55FCF1E400F@bag.python.org> Message-ID: <47F64DBB.6060404@timgolden.me.uk> linuxian iandsd wrote: > well, good to see something like this comming ... i used to browse for hours > to find nothing but long long documentation & not a single real life > example... but i guess its because i m used to the old 'howto' way of > ducumentation ... It's one of those things; people learn in different ways. Some people prefer dry reference guides; others like the cookbook approach (I do myself). Still others want a complete worked example. And so on. For me, documentation in its many forms is a *vital* part of any software project, especially Open Source stuff. The more people who put together coherent examples, articles, hints, tips etc., the better for the rest of the community. TJG From kent37 at tds.net Fri Apr 4 17:53:46 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 04 Apr 2008 11:53:46 -0400 Subject: [Tutor] Interactive physics simulation over web In-Reply-To: References: <24bc7f6c0804040815s57b3d9ferdc1ff7774db1e178@mail.gmail.com> Message-ID: <47F64F0A.8030103@tds.net> Adam Bark wrote: > I think you can use Jython in a Java applet, that might be what you're > looking for. Yes, but it does increase the size of the download considerably since jython.jar is needed by the browser. Kent From kent37 at tds.net Fri Apr 4 17:55:06 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 04 Apr 2008 11:55:06 -0400 Subject: [Tutor] Interactive physics simulation over web In-Reply-To: <24bc7f6c0804040815s57b3d9ferdc1ff7774db1e178@mail.gmail.com> References: <24bc7f6c0804040815s57b3d9ferdc1ff7774db1e178@mail.gmail.com> Message-ID: <47F64F5A.5030900@tds.net> Brain Stormer wrote: > I am working on a physics simulation and would like to publish it on the > web. The simulation requires input fields, mouse action (picking points > in a display pane) and movie like feature with play, pause, skip forward > and skip backward. I was wondering if this can be done using Python and > a Python web tool kit like Django. I can see that this can be done > using Java/Java Script but don't feel like re-familiarizing myself to > Java. I looked into the Python web programming page > but it didn't answer my > questions. My goal is keep this simulation completely written in Python. You can use Python and Django for the server-side of this but for the client side you probably want to look at JavaScript and / or Flash. Kent From midnightjulia at gmail.com Fri Apr 4 19:01:07 2008 From: midnightjulia at gmail.com (Julia) Date: Fri, 4 Apr 2008 19:01:07 +0200 Subject: [Tutor] Don't miss "Python-by-example - new online guide to Message-ID: > > Message: 4 > Date: Fri, 04 Apr 2008 07:12:11 -0700 > From: Dick Moores > Subject: [Tutor] Don't miss "Python-by-example - new online guide to > Python Standard Library" > To: Python Tutor List > Message-ID: <20080404141243.55FCF1E400F at bag.python.org> > Content-Type: text/plain; charset="us-ascii" > > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20080404/8e49a5e0/attachment-0001.htm I really appreciate guides that cut to the core directly. Great work Moores :) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080404/1e33a77b/attachment.htm From byogi at yahoo.com Fri Apr 4 19:33:55 2008 From: byogi at yahoo.com (yogi) Date: Fri, 4 Apr 2008 10:33:55 -0700 (PDT) Subject: [Tutor] Python Newbie: Lost in Loop Message-ID: <345864.14330.qm@web43133.mail.sp1.yahoo.com> Hi all, I ?m a Python Newbie. Just 48 hrs into Python. I am trying to parse a file which is tab spaced. head -5 of the file in question. 1 rs3094315 0 792429 1 rs6672353 0 817376 1 rs4040617 0 819185 1 rs2980300 0 825852 1 rs2905036 0 832343 1 rs4245756 0 839326 1 rs4075116 0 1043552 1 rs9442385 0 1137258 1 rs10907175 0 1170650 1 rs2887286 0 1196054 column[0] increments [1-22]. column [1] has values I?m interested in columns [2] Its a Zero column [3] has values which I pass for range boundary. My Python code #/bin/python import sys, csv, re # This programme finds the SNPs from the range passed from the select option ## But first for fixed values. gen = 16 rval0l = 6009890 rval0u = 6009939 rval1l = 0 rval1u = 0 types = (int, str, int, int) fis = csv.reader(open("divs.map", "rb"), delimiter='\t', quoting=csv.QUOTE_NONE) # csv splits columns and this file is tab spaced # Reading file line by line and using Regex to match the gene. for row in fis: #if re.search("^[1-9]\-^[1-9]\:^[1-9]\-^[1-9]", row [3]): if (str(gen) == str(row[0])): print 'Match for 16 found looking for SNPs in range between '+ str(rval0l),str(rval0u)+' ' for row[2] in range (rval0l,rval0u): print row My Python code is not behaving as I want it to be. When I pass the range values . The Code should parse the file. Match the value of Col3. look for values in col(3) within the range limit (Which it does) print rows Matching the criteria.(which it does not). It prints rows which are not even the file. Can somebody point me in the right direction. Thanks in advance yogesh ____________________________________________________________________________________ You rock. That's why Blockbuster's offering you one month of Blockbuster Total Access, No Cost. http://tc.deals.yahoo.com/tc/blockbuster/text5.com From kent37 at tds.net Fri Apr 4 19:55:17 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 04 Apr 2008 13:55:17 -0400 Subject: [Tutor] Python Newbie: Lost in Loop In-Reply-To: <345864.14330.qm@web43133.mail.sp1.yahoo.com> References: <345864.14330.qm@web43133.mail.sp1.yahoo.com> Message-ID: <47F66B85.4080903@tds.net> yogi wrote: > Hi all, > I ?m a Python Newbie. Just 48 hrs into Python. > I am trying to parse a file which is tab spaced. You're close... > My Python code > #/bin/python > import sys, csv, re > > # This programme finds the SNPs from the range passed from > the select option > ## But first for fixed values. > gen = 16 > rval0l = 6009890 > rval0u = 6009939 > rval1l = 0 > rval1u = 0 > types = (int, str, int, int) > fis = csv.reader(open("divs.map", "rb"), delimiter='\t', > quoting=csv.QUOTE_NONE) # csv splits columns and this file > is tab spaced > # Reading file line by line and using Regex to match the > gene. > for row in fis: > #if re.search("^[1-9]\-^[1-9]\:^[1-9]\-^[1-9]", row > [3]): > if (str(gen) == str(row[0])): row[0] is already a string so this could be if str(gen) == row[0] or if gen == int(row[0]) > print 'Match for 16 found looking for SNPs > in range between '+ str(rval0l),str(rval0u)+' ' > for row[2] in range (rval0l,rval0u): > print row This is confused. I think you want all the rows where row[3] (not 2) is between rval0l and rval0u? So just make this another condition: if rval0l <= int(row[3]) <= rval0u: print row Aside to the list: Did anyone else know that you can assign to a list element as the target of a for statement? In [6]: row=range(3) In [8]: for row[2] in range(5): print row ...: ...: [0, 1, 0] [0, 1, 1] [0, 1, 2] [0, 1, 3] [0, 1, 4] Color me surprised. Kent From cappy2112 at gmail.com Fri Apr 4 20:26:43 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Fri, 4 Apr 2008 11:26:43 -0700 Subject: [Tutor] Don't miss "Python-by-example - new online guide to Message-ID: <8249c4ac0804041126n7b56a387pa5373ddf435bac08@mail.gmail.com> Date: Fri, 04 Apr 2008 07:12:11 -0700 From: Dick Moores Subject: [Tutor] Don't miss "Python-by-example - new online guide to Python Standard Library" To: Python Tutor List Message-ID: <20080404141243.55FCF1E400F at bag.python.org> Dick- there was no url with your message. Also See Python Module Of The Week, by Doug Hellman http://www.doughellmann.com/projects/PyMOTW/ Doug also has regular columns in Python Magazine- http://pymag.phparch.com/ a great publication targeted mostly for beginner-intermediate level Pythonistas -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080404/ae4db887/attachment.htm From alan.gauld at btinternet.com Fri Apr 4 20:27:43 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 4 Apr 2008 19:27:43 +0100 Subject: [Tutor] Python Newbie: Lost in Loop References: <345864.14330.qm@web43133.mail.sp1.yahoo.com> <47F66B85.4080903@tds.net> Message-ID: "Kent Johnson" wrote > Aside to the list: > Did anyone else know that you can assign to a list element > as the target of a for statement? Nope, and in fact I was just trying it out at the >>> prompt when your message came in! On a general point for the OP, I doubt if you need the csv module for this. You could generate the required data list using a simple string split() and a single list comprehension: fis = [line.split() for line in infile] Which might simplify things slightly. Also it might help processing to sort the list based on the range value. But it depends on what other extractions/processing need to be done. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From eric at ericwalstad.com Fri Apr 4 20:42:51 2008 From: eric at ericwalstad.com (Eric Walstad) Date: Fri, 04 Apr 2008 11:42:51 -0700 Subject: [Tutor] Python Newbie: Lost in Loop In-Reply-To: <345864.14330.qm@web43133.mail.sp1.yahoo.com> References: <345864.14330.qm@web43133.mail.sp1.yahoo.com> Message-ID: <47F676AB.3040501@ericwalstad.com> Hi Yogi, welcome to Python! yogi wrote: ... > if (str(gen) == str(row[0])): > print 'Match for 16 found Is the conversion to string really necessary? Even if it is, do it once for gen, when you define it: gen = '16' so you don't have to convert on every iteration of the loop. I think you want gen to be a integer, though, because you later compare it to other integers in your range(). ... > for row[2] in range (rval0l,rval0u): > print row I don't think this bit is doing what you think it is. For each iteration you are assigning a value to the third element in the row list: row[2] = 6009890 row[2] = 6009891 ... row[2] = 6009938 etc. I don't think you want to loop over the range but instead want to check to see if row[2] is between rval0l and rval0u. You can do that by using if x in some_list which will return true if x is a member of the list. range() will give you the list of values to check against (but only create that list once unless it changes on each row you are processing and in your code example, it's not changing). Remember, it's easy and enlightening to test code on the Python command line: >>> rval0l = 6009890 >>> rval0u = 6009939 >>> range(rval0l,rval0u) [6009890, 6009891, 6009892, 6009893, 6009894, 6009895, 6009896, 6009897, 6009898, 6009899, 6009900, 6009901, 6009902, 6009903, 6009904, 6009905, 6009906, 6009907, 6009908, 6009909, 6009910, 6009911, 6009912, 6009913, 6009914, 6009915, 6009916, 6009917, 6009918, 6009919, 6009920, 6009921, 6009922, 6009923, 6009924, 6009925, 6009926, 6009927, 6009928, 6009929, 6009930, 6009931, 6009932, 6009933, 6009934, 6009935, 6009936, 6009937, 6009938] >>> my_range = range(rval0l,rval0u) >>> 6009893 in my_range True >>> 5 in my_range False gen = 16 idx_snp = 2 my_range = range(rval0l,rval0u) for row in file: snp = int(row[idx_snp]) if snp == gen: print 'Found %s' % gen if snp in my_range: print "Found match:", row Eric. PS, if your input file is as simple as your example, the csv module isn't getting you much benefit/complexity: for row in open("divs.map"): fields = row.split('\t') print fields From jeff at drinktomi.com Fri Apr 4 23:04:03 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Fri, 4 Apr 2008 14:04:03 -0700 Subject: [Tutor] Which Python Script Editor of Choice? In-Reply-To: <82b4f5810804031015y6446fbbfgee3ee5b5c88d9c78@mail.gmail.com> References: <1128c3c40804030832q77b2405fkba6472552194dfaa@mail.gmail.com> <82b4f5810804031015y6446fbbfgee3ee5b5c88d9c78@mail.gmail.com> Message-ID: <67C25E78-E138-401D-B1BB-7E1CB471D997@drinktomi.com> Jeffrey Dates wrote: > So as I'm starting to get into writing some scripts, I'm looking for > recommendations for a nifty script editor. Ideally a freeware/ > shareware solution until I can justify a purchase of something more > beefy. > > Currently I'm using PSPad, however it's pretty dumb and doesn't > recognize Python context. Which, I suppose is fine, but would be > nice if there was one. Especially since I'm learning. I use Eclipse+PyDev plugin+commercial ($30) PyDev extensions (which runs for free, but nags every hour or so.) I has a feature set that no other python IDE has at this point. (Let me qualify that: I haven't looked at the Iron Python tools on windows, and they might be better, but I don't do much in the windows world so I haven't looked at it yet.) - Jeff Younker - jeff at drinktomi.com - From rdm at rcblue.com Sat Apr 5 00:06:20 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 04 Apr 2008 15:06:20 -0700 Subject: [Tutor] Don't miss "Python-by-example - new online guide to In-Reply-To: <8249c4ac0804041126n7b56a387pa5373ddf435bac08@mail.gmail.co m> References: <8249c4ac0804041126n7b56a387pa5373ddf435bac08@mail.gmail.com> Message-ID: <20080404220630.A86581E4012@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080404/573a1e3e/attachment.htm From katcipis at inf.ufsc.br Sat Apr 5 03:26:26 2008 From: katcipis at inf.ufsc.br (Tiago Katcipis) Date: Fri, 04 Apr 2008 22:26:26 -0300 Subject: [Tutor] Question about global variables on modules Message-ID: <47F6D542.5010001@inf.ufsc.br> I know its not such a pretty thing to have global variables but its only for an exercise my teacher told to do. Its a function to calculate the results of a matrix using jacob. I want to inside the module (inside a function on the module )assign a value to a global variable, but the only way i found to do this inside the own module function is importing the module inside himself. Is there another way of doing this? its kind odd to import the module to himself, i think :-) here goes the code <============> import lineares_jacob *ERRO_FINAL = 0.0* def obter_respostas(matriz, incognitas, erro_max): erro = erro_max * 10 n = len(matriz) while(erro >= erro_max): novas_incognitas = [] y_um = (2.0 + (1.0 * incognitas[1]) - (1.0 * incognitas[4999])) / 3.0 novas_incognitas.append(y_um) for i in range(1 , (n - 1)): yi = ( (2.0 * i) + incognitas[i - 1] + incognitas[i + 1] ) / (2.0 + i) novas_incognitas.append(yi) y_cinc_mil = (10000.0 - incognitas[0] + incognitas[4998]) / 5002.0 novas_incognitas.append(y_cinc_mil) maior = novas_incognitas[0] - incognitas[0] for i in range(1, 5000): dif = novas_incognitas[i] - incognitas[i] if(dif > maior): maior = dif erro = maior incognitas = novas_incognitas *lineares_jacob.ERRO_FINAL = erro* return incognitas From byogi at yahoo.com Sat Apr 5 04:24:14 2008 From: byogi at yahoo.com (yogi) Date: Fri, 4 Apr 2008 19:24:14 -0700 (PDT) Subject: [Tutor] Python Newbie: Lost in Loop In-Reply-To: <47F66B85.4080903@tds.net> Message-ID: <729391.50820.qm@web43132.mail.sp1.yahoo.com> Hi all , Thanks for the input. I must add Kent's solution was the fastest. The actual file to parse is 12MB. Though Eric's solution was more readable ( atleast for me). Now that I have the logic and code right I have to work on the real problem. Thanks in advance, yogesh ____________________________________________________________________________________ You rock. That's why Blockbuster's offering you one month of Blockbuster Total Access, No Cost. http://tc.deals.yahoo.com/tc/blockbuster/text5.com From sierra_mtnview at sbcglobal.net Sat Apr 5 05:37:55 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 04 Apr 2008 20:37:55 -0700 Subject: [Tutor] Diff for Python Message-ID: <47F6F413.3070302@sbcglobal.net> Is there a Linux diff-like command for Python code? I'd like to see the difference between two py files. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "Philosophy is questions that may never be answered. Religion is answers that may never be questioned" -- Anon Web Page: From tonytraductor at linguasos.org Sat Apr 5 05:58:51 2008 From: tonytraductor at linguasos.org (Anthony Baldwin) Date: Fri, 04 Apr 2008 23:58:51 -0400 Subject: [Tutor] Question about global variables on modules In-Reply-To: <47F6D542.5010001@inf.ufsc.br> References: <47F6D542.5010001@inf.ufsc.br> Message-ID: <47F6F8FB.6080500@linguasos.org> Tiago Katcipis wrote: > I know its not such a pretty thing to have global variables but its only > for an exercise my teacher told to do. Its a function to calculate the > results of a matrix using jacob. I want to inside the module (inside a > function on the module )assign a value to a global variable, but the > only way i found to do this inside the own module function is importing > the module inside himself. Is there another way of doing this? its kind > odd to import the module to himself, i think :-) > > here goes the code > Oi, Tiago N?o sei muito bem como funciona em Python, sendo que j? estou come?ando a aprender-lo, mais, deve ter algo como o "uplevel" em Tcl, n?o? Tcl's uplevel sets a vari?vel pelo namespace global. Ou talvez algo como set ::var value (esse funciona em tcl pra set a vari?vel globalmente mas dentro de um proc)? /tony -- Anthony Baldwin http://www.BaldwinLinguas.com Translation & Interpreting http://www.TransProCalc.org Free translation project mgmt software http://www.LinguasOS.org Linux for Translators From byogi at yahoo.com Sat Apr 5 07:05:05 2008 From: byogi at yahoo.com (yogi) Date: Fri, 4 Apr 2008 22:05:05 -0700 (PDT) Subject: [Tutor] Code optmisation Message-ID: <304770.91464.qm@web43136.mail.sp1.yahoo.com> Hi , Here is my first usable Python code. The code works. Here is what I'm trying to do. I have two huge text files. After some processing, One is 12M (file A) and the other 1M (file B) . The files have columns which are of interest to me. I 'm trying to match entries of column [0] on file A and B If it is true proceed to find entries (Rows in file A) in range provided by columns [1] [2] and [3] [4] in file B. Column [1] and [3] define the lower bounds of the range Column [3] and [4] define the upper bounds of the range I also have put a variation of value so that I can lookup +/- var. #/bin/python import sys, os, csv, re x = 0 #Define Zero for now var = 1000000 #Taking the variation # This programme finds the SNPs from the range passed # csv splits columns and this file is tab spaced fis = csv.reader(open("divs.map", "rb"), delimiter='\t', quoting=csv.QUOTE_NONE) for row in fis: # csv splits columns and this file is "," spaced gvalues = csv.reader(open("genvalues", "rb"), delimiter=',', quoting=csv.QUOTE_NONE) for gvalue in gvalues: # To see Columns (chr) Match if row[0] == gvalue[0]: # If Column 3 (range) is Zero print row if int(gvalue[3]) == x: a = int(gvalue[1]) - var b = int(gvalue[2]) + var + 1 if int(a <= int(row[3]) <= b): print row # If Column 3 (range) is not zero find matches and print row else: a = int(gvalue[1]) - var b = int(gvalue[2]) + var + 1 if int(a <= int(row[3]) <= b): print row c = int(gvalue[3]) - var d = int(gvalue[4]) + var + 1 if int(c <= int(row[3]) <= d): print row ----------------------------------------------------- Question1 : Is there a better way ? Question2 : For now I'm using shells time call for calculating time required. Does Python provide a more fine grained check. Question 2: If I have convert this code into a function. Should I ? def parse(): ... ... ... ... parse () ____________________________________________________________________________________ You rock. That's why Blockbuster's offering you one month of Blockbuster Total Access, No Cost. http://tc.deals.yahoo.com/tc/blockbuster/text5.com From carroll at tjc.com Sat Apr 5 07:59:42 2008 From: carroll at tjc.com (Terry Carroll) Date: Fri, 4 Apr 2008 22:59:42 -0700 (PDT) Subject: [Tutor] Diff for Python In-Reply-To: <47F6F413.3070302@sbcglobal.net> Message-ID: On Fri, 4 Apr 2008, Wayne Watson wrote: > Is there a Linux diff-like command for Python code? I'd like to see the > difference between two py files. You could just use diff. Python itself also has difflib: http://python.org/doc/2.5/lib/module-difflib.html From alan.gauld at btinternet.com Sat Apr 5 09:17:18 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 5 Apr 2008 08:17:18 +0100 Subject: [Tutor] Question about global variables on modules References: <47F6D542.5010001@inf.ufsc.br> Message-ID: "Tiago Katcipis" wrote > results of a matrix using jacob. I want to inside the module (inside > a > function on the module )assign a value to a global variable, but the > only way i found to do this inside the own module function is > importing > the module inside himself. Is there another way of doing this? Look at the 'global' keyword. Explained further in the 'What's in a Name' topic of my tutorial. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Apr 5 09:44:00 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 5 Apr 2008 08:44:00 +0100 Subject: [Tutor] Code optmisation References: <304770.91464.qm@web43136.mail.sp1.yahoo.com> Message-ID: "yogi" wrote > #/bin/python > import sys, os, csv, re > x = 0 #Define Zero for now > var = 1000000 #Taking the variation > # This programme finds the SNPs from the range passed > # csv splits columns and this file is tab spaced > fis = csv.reader(open("divs.map", "rb"), delimiter='\t', > quoting=csv.QUOTE_NONE) > for row in fis: > # csv splits columns and this file is "," spaced > gvalues = csv.reader(open("genvalues", "rb"), delimiter=',', > quoting=csv.QUOTE_NONE) Move this outside the loop otherwise you re-read the file for every line in the other file - slow! > for gvalue in gvalues: > # To see Columns (chr) Match > if row[0] == gvalue[0]: > # If Column 3 (range) is Zero print row > if int(gvalue[3]) == x: > a = int(gvalue[1]) - var > b = int(gvalue[2]) + var + 1 > if int(a <= int(row[3]) <= b): > print row I'd probably use names like 'lo' and 'hi' instead of 'a' and 'b' but thats a nit pick... but you don't want to convert the result of the test to an int, the result is a boolean and you never use the int you create so its just wasted processing power... > # If Column 3 (range) is not zero find matches and print row > else: > a = int(gvalue[1]) - var > b = int(gvalue[2]) + var + 1 Repeated code, you could move this above the if test since its used by both conditions. Easier to maintain if you change the rules... > if int(a <= int(row[3]) <= b): > print row again you don;t need the int() conversion. > c = int(gvalue[3]) - var > d = int(gvalue[4]) + var + 1 > if int(c <= int(row[3]) <= > d): and again. You do this so often I'd consider making it a helper function def inLimits(min, max, val): lo = int(min) - var hi = int(max) + var + 1 return lo <= int(val) <= hi Your else clause then becomes else: if inLmits(gvalue[1],gvalue[2],row[3]) print row if inLimits(gvalue[3], gvalue[4], row[3] print row Which is slightly more readable I think. > Question1 : Is there a better way ? There's always a better way. As a general rule for processing large volumes of data I tend to go for a SQL database. But thats mainly based on my experience that if you want to do one lot of queries you'll eventually want to do more - and SQL is designed for doing queries on large datasets, Python isn't (although Python can do SQL...). > Question2 : For now I'm using shells time call for calculating > time required. Does Python provide a more fine grained check. try timeit... > Question 2: If I have convert this code into a function. > Should I ? Only if you have a need to reuse it in a bigger context or of you want to parameterize it. You could maybe break it out into smaller helper functions such as the one I suggested above. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From srilyk at gmail.com Sat Apr 5 13:09:29 2008 From: srilyk at gmail.com (W W) Date: Sat, 5 Apr 2008 06:09:29 -0500 Subject: [Tutor] Diff for Python In-Reply-To: References: <47F6F413.3070302@sbcglobal.net> Message-ID: <333efb450804050409k5031dfb4u50e58650a99690bb@mail.gmail.com> Vim also has a similar command On Sat, Apr 5, 2008 at 12:59 AM, Terry Carroll wrote: > On Fri, 4 Apr 2008, Wayne Watson wrote: > > > Is there a Linux diff-like command for Python code? I'd like to see the > > difference between two py files. > > You could just use diff. > > Python itself also has difflib: > > http://python.org/doc/2.5/lib/module-difflib.html > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From srilyk at gmail.com Sat Apr 5 13:24:16 2008 From: srilyk at gmail.com (W W) Date: Sat, 5 Apr 2008 06:24:16 -0500 Subject: [Tutor] Code optmisation In-Reply-To: References: <304770.91464.qm@web43136.mail.sp1.yahoo.com> Message-ID: <333efb450804050424u38385086q6c988cd89827e474@mail.gmail.com> On Sat, Apr 5, 2008 at 2:44 AM, Alan Gauld wrote: > "yogi" wrote > > Question 2: If I have convert this code into a function. > > Should I ? > > Only if you have a need to reuse it in a bigger context > or of you want to parameterize it. You could maybe break > it out into smaller helper functions such as the one I > suggested above. Personally, functions are always fun! ... And useful. Even if you don't need to play with them later, there's no loss, because the exercise is in and of itself a good one. Plus, I think functions tend (though not always) force you to clean up your code: As Alan has mentioned, there are a few places that you duplicate code. The exercise of converting to functions will often point out the fact that you have multiple code. Have fun! -Wayne From eric at ericwalstad.com Sat Apr 5 22:10:07 2008 From: eric at ericwalstad.com (Eric Walstad) Date: Sat, 5 Apr 2008 13:10:07 -0700 Subject: [Tutor] Diff for Python In-Reply-To: <47F7D2F9.5000607@sbcglobal.net> References: <47F6F413.3070302@sbcglobal.net> <47F7D2F9.5000607@sbcglobal.net> Message-ID: And my whoops, I should have sent my first one to the list, too. I don't run Windows very often. I think 'WinDiff' is what I used there. Have you tried that? There's always cygwin, too. Eric. On Sat, Apr 5, 2008 at 12:28 PM, Wayne Watson wrote: > > Whoop, I should have specified I'm on Win XP. > > > Eric Walstad wrote: > Hi Wayne, > > On Fri, Apr 4, 2008 at 8:37 PM, Wayne Watson > wrote: > > > Is there a Linux diff-like command for Python code? I'd like to see the > difference between two py files. > > Why don't you just use diff? > What OS are you on? > > diff -Bu fileone.py filezero.py From alan.gauld at btinternet.com Sun Apr 6 00:04:42 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 5 Apr 2008 23:04:42 +0100 Subject: [Tutor] Diff for Python References: <47F6F413.3070302@sbcglobal.net><47F7D2F9.5000607@sbcglobal.net> Message-ID: On Windows you can use FC - File Compare. Its not as powerful as diff but it will highlight differences. Help FC will get you the switch options. Or just use cygwin - any Unix user on Windows should get cygwin as a matter of course IMHO! :-) Alan G. "Eric Walstad" wrote in message news:c436fcd20804051310v4676817tef4bc9c3672b2869 at mail.gmail.com... > And my whoops, I should have sent my first one to the list, too. > > I don't run Windows very often. I think 'WinDiff' is what I used > there. Have you tried that? > > There's always cygwin, too. > > Eric. > On Sat, Apr 5, 2008 at 12:28 PM, Wayne Watson > wrote: >> >> Whoop, I should have specified I'm on Win XP. >> >> >> Eric Walstad wrote: >> Hi Wayne, >> >> On Fri, Apr 4, 2008 at 8:37 PM, Wayne Watson >> wrote: >> >> >> Is there a Linux diff-like command for Python code? I'd like to >> see the >> difference between two py files. >> >> Why don't you just use diff? >> What OS are you on? >> >> diff -Bu fileone.py filezero.py > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From marc.tompkins at gmail.com Sun Apr 6 00:47:09 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sat, 5 Apr 2008 15:47:09 -0700 Subject: [Tutor] Diff for Python In-Reply-To: References: <47F6F413.3070302@sbcglobal.net> <47F7D2F9.5000607@sbcglobal.net> Message-ID: <40af687b0804051547l70acae16u54a1aa0b1182b492@mail.gmail.com> Sorry - forgot to reply to the list the first time... On Sat, Apr 5, 2008 at 3:04 PM, Alan Gauld wrote: > On Windows you can use FC - File Compare. > Its not as powerful as diff but it will highlight differences. > On Windows, I've tried a bunch of diff tools - it's probably the way my brain is wired, but I generally find it harder to understand what the diff tool is telling me than it would have been to print out the damn files and compare them on paper. I feel like I'm being given clues so I can work out the puzzle myself... if I wanted that, I would do a crossword, not use a software tool. So my tool of choice (since I discovered it about three months ago) is the Compare plugin in Notepad++. It simply displays the files in separate child windows, forcibly aligns them with "soft" newlines, and synchronizes the windows' scrollbars to keep them lined up side by side. It also shades the lines in different colors depending on whether the lines are the same in both files, or one file has a line that the other doesn't, or both files have the line but different versions. None of this is new, of course, but I've never used a tool before that got it all so _right_ and made it so simple to use and to read. (Open two or more files in the editor, hit Alt-D, read. If necessary, cut and paste between the windows - hit Alt-D again to resync - read.) I'm sure there are more sophisticated choices. Honestly, I sometimes feel a little guilty using it, 'cause I think I ought to be working harder... I'm sure that both vi and emacs do this in a way that mere mortals such as I cannot appreciate, but I think you must have had to start using either vi or emacs at a very early age to be able to enjoy the experience. I'm putting on my flame-retardant Nomex suit as I type this. (Tying this thread in with one from last week...) As a general-purpose Windows editor, I definitely recommend Notepad++. (It's free, but I moved to it from TextPad, in which I had invested $50. If you knew me, you'd know what high praise this is for Notepad++.) For Python / wxPython development, though, I love me some SPE. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080405/dc14a33b/attachment.htm From rdm at rcblue.com Sun Apr 6 06:35:20 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 05 Apr 2008 21:35:20 -0700 Subject: [Tutor] PyMOTW: difflib Message-ID: <20080406043551.966921E4014@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080405/a797db93/attachment.htm From alan.gauld at btinternet.com Sun Apr 6 09:44:35 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 6 Apr 2008 07:44:35 +0000 (GMT) Subject: [Tutor] Fw: Diff for Python Message-ID: <199193.99758.qm@web86701.mail.ukl.yahoo.com> forwarding to tutor. Mark, please use Reply-All for tutor messages... ----- Forwarded Message ---- From: Marc Tompkins To: Alan Gauld Sent: Saturday, 5 April, 2008 11:45:47 PM Subject: Re: [Tutor] Diff for Python On Sat, Apr 5, 2008 at 3:04 PM, Alan Gauld wrote: On Windows you can use FC - File Compare. Its not as powerful as diff but it will highlight differences. On Windows, I've tried a bunch of diff tools - it's probably the way my brain is wired, but I generally find it harder to understand what the diff tool is telling me than it would have been to print out the damn files and compare them on paper. I feel like I'm being given clues so I can work out the puzzle myself... if I wanted that, I would do a crossword, not use a software tool. So my tool of choice (since I discovered it about three months ago) is the Compare plugin in Notepad++. It simply displays the files in separate child windows, forcibly aligns them with "soft" newlines, and synchronizes the windows' scrollbars to keep them lined up side by side. It also shades the lines in different colors depending on whether the lines are the same in both files, or one file has a line that the other doesn't, or both files have the line but different versions. None of this is new, of course, but I've never used a tool before that got it all so _right_ and made it so simple to use and to read. (Open two or more files in the editor, hit Alt-D, read. If necessary, cut and paste between the windows - hit Alt-D again to resync - read.) I'm sure there are more sophisticated choices. Honestly, I sometimes feel a little guilty using it, 'cause I think I ought to be working harder... I'm sure that both vi and emacs do this in a way that mere mortals such as I cannot appreciate, but I think you must have had to start using either vi or emacs at a very early age to be able to enjoy the experience. I'm putting on my flame-retardant Nomex suit as I type this. (Tying this thread in with one from last week...) As a general-purpose Windows editor, I definitely recommend Notepad++. (It's free, but I moved to it from TextPad, in which I had invested $50. If you knew me, you'd know what high praise this is for Notepad++.) For Python / wxPython development, though, I love me some SPE. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080406/a3c167d5/attachment.htm From rdm at rcblue.com Sun Apr 6 11:13:57 2008 From: rdm at rcblue.com (Dick Moores) Date: Sun, 06 Apr 2008 02:13:57 -0700 Subject: [Tutor] Diff for Python In-Reply-To: References: <47F6F413.3070302@sbcglobal.net> <47F7D2F9.5000607@sbcglobal.net> Message-ID: <20080406091423.16E721E4008@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080406/f9796768/attachment-0001.htm From mwalsh at groktech.org Sun Apr 6 17:24:27 2008 From: mwalsh at groktech.org (Martin Walsh) Date: Sun, 06 Apr 2008 10:24:27 -0500 Subject: [Tutor] PyMOTW: difflib In-Reply-To: <20080406043551.966921E4014@bag.python.org> References: <20080406043551.966921E4014@bag.python.org> Message-ID: <47F8EB2B.2060103@groktech.org> Dick Moores wrote: > See < http://blog.doughellmann.com/2007/10/pymotw-difflib.html> > > And my try with the Differ example, < > http://py77.python.pastebin.com/f41ec1ae8>, which also shows the error, > > "E:\Python25\pythonw.exe" -u "E:\PythonWork\demo_pymotw-difflib.py" > Traceback (most recent call last): > File "E:\PythonWork\demo_pymotw-difflib.py", line 12, in > from difflib_data import * > ImportError: No module named difflib_data > > What is difflib_data ? It is the example data provided with the PyMOTW tutorial. Near the top of the article (from the link you provided) you'll see the heading "Test Data". I assume the author wants you to copy and paste the source into a new file named difflib_data.py in your working dir. Alternatively, it looks like you can download all the source and example data for all PyMOTWs in one compressed file: http://www.doughellmann.com/projects/PyMOTW/ PyMOTW has a cheese shop entry also (http://pypi.python.org/), so one would assume you could get the source with easy_install as well, but I've never tried it. HTH, Marty > > Thanks, > > Dick Moores From rdm at rcblue.com Sun Apr 6 18:33:04 2008 From: rdm at rcblue.com (Dick Moores) Date: Sun, 06 Apr 2008 09:33:04 -0700 Subject: [Tutor] PyMOTW: difflib In-Reply-To: <47F8EB2B.2060103@groktech.org> References: <20080406043551.966921E4014@bag.python.org> <47F8EB2B.2060103@groktech.org> Message-ID: <20080406163321.462851E400C@bag.python.org> At 08:24 AM 4/6/2008, Martin Walsh wrote: >Dick Moores wrote: > > See < http://blog.doughellmann.com/2007/10/pymotw-difflib.html> > > > > And my try with the Differ example, > > , which also shows the error, > > > > "E:\Python25\pythonw.exe" -u "E:\PythonWork\demo_pymotw-difflib.py" > > Traceback (most recent call last): > > File "E:\PythonWork\demo_pymotw-difflib.py", line 12, in > > from difflib_data import * > > ImportError: No module named difflib_data > > > > What is difflib_data ? > >It is the example data provided with the PyMOTW tutorial. > >Near the top of the article (from the link you provided) you'll see the >heading "Test Data". I assume the author wants you to copy and paste the >source into a new file named difflib_data.py in your working dir. >Alternatively, it looks like you can download all the source and example >data for all PyMOTWs in one compressed file: >http://www.doughellmann.com/projects/PyMOTW/ Thanks very much for figuring that out for me, and so clearly explaining it. I downloaded that compressed file and found difflib_data.py (see it at ). Copied the data into my demo_pymotw-difflib.py, deleted the line "from difflib_data import *", and ran it. See it and the output at Dick Moores ================================ UliPad <>: http://code.google.com/p/ulipad/ From alan.gauld at btinternet.com Sun Apr 6 23:22:51 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 6 Apr 2008 22:22:51 +0100 Subject: [Tutor] PyMOTW: difflib References: <20080406043551.966921E4014@bag.python.org><47F8EB2B.2060103@groktech.org> <20080406163321.462851E400C@bag.python.org> Message-ID: "Dick Moores" wrote > I downloaded that compressed file and found difflib_data.py (see it > at ). Copied the data > into > my demo_pymotw-difflib.py, deleted the line "from difflib_data > import > *", and ran it I'm curious. Why did you do that? Why not just leave the import as it was? Alan G. From rdm at rcblue.com Sun Apr 6 23:36:18 2008 From: rdm at rcblue.com (Dick Moores) Date: Sun, 06 Apr 2008 14:36:18 -0700 Subject: [Tutor] PyMOTW: difflib In-Reply-To: References: <20080406043551.966921E4014@bag.python.org> <47F8EB2B.2060103@groktech.org> <20080406163321.462851E400C@bag.python.org> Message-ID: <20080406213631.503911E4019@bag.python.org> At 02:22 PM 4/6/2008, Alan Gauld wrote: >"Dick Moores" wrote > > > I downloaded that compressed file and found difflib_data.py (see it > > at ). Copied the data > > into > > my demo_pymotw-difflib.py, deleted the line "from difflib_data > > import > > *", and ran it > >I'm curious. Why did you do that? >Why not just leave the import as it was? OK, I put it back in, changing the filename to demo_pymotw-difflib_error.py. See for the code and the ImportError: No module named difflib_data. Or is there something I don't understand here? Dick ================================ UliPad <>: http://code.google.com/p/ulipad/ From alan.gauld at btinternet.com Mon Apr 7 01:39:21 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 7 Apr 2008 00:39:21 +0100 Subject: [Tutor] PyMOTW: difflib References: <20080406043551.966921E4014@bag.python.org><47F8EB2B.2060103@groktech.org><20080406163321.462851E400C@bag.python.org> <20080406213631.503911E4019@bag.python.org> Message-ID: "Dick Moores" wrote >> > Copied the data into my demo_pymotw-difflib.py, >> > deleted the line "from difflib_data import *", >> > and ran it >> >>I'm curious. Why did you do that? > OK, I put it back in, changing the filename to > demo_pymotw-difflib_error.py. > See for the code and the > ImportError: No module named difflib_data. You still have the copied data which will overwrite the values imported however to import it you need to have the path set up correctly. Is the difflib_data.py in the same folder as difflib.py? Your code should only need to be: a.. import difflib a.. from difflib_data import * a.. a.. d = difflib.Differ() a.. diff = d.compare(text1_lines, text2_lines) a.. print '\n'.join(list(diff)) And provided both modules are visible to Python it should work. Copying the data works too but I was just curious why you needed to... Alan G. From rdm at rcblue.com Mon Apr 7 03:11:47 2008 From: rdm at rcblue.com (Dick Moores) Date: Sun, 06 Apr 2008 18:11:47 -0700 Subject: [Tutor] PyMOTW: difflib In-Reply-To: References: <20080406043551.966921E4014@bag.python.org> <47F8EB2B.2060103@groktech.org> <20080406163321.462851E400C@bag.python.org> <20080406213631.503911E4019@bag.python.org> Message-ID: <20080407011158.A950C1E400C@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080406/697f5fd9/attachment.htm From nomb85 at comcast.net Mon Apr 7 04:07:49 2008 From: nomb85 at comcast.net (Nathan McBride) Date: Sun, 06 Apr 2008 22:07:49 -0400 Subject: [Tutor] socket / over network In-Reply-To: References: <47F4C0F2.7060601@tds.net> <47F4D421.7000007@tds.net> <47F4E6C5.8000809@tds.net> <47F4EAF2.6050305@tds.net> <47F4F51F.8030309@comcast.net> Message-ID: <47F981F5.6080401@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Alan Gauld wrote: > "Nathan McBride" wrote > > Hi Nathan, > > Please don't reply to an existing message to start a new discussion. > It messes up those of us using threaded mail/news readers and > increases the likelihood that your message will be missed. > >> I'm pretty tired of the lame backup solution we have at work. >> Could anyone point me to a (more or less newbieish) example of how >> to >> have python open a socket on one box and get data from it, then have >> another >> box write to it over the network? > > For a very simple example of using a socket you could try the > Network Programming topic in my tutorial. > > There is also a HowTo or Topic guide on the Python web site > that gives a more detailed example. > > That having been said, backups are usually best done using > OS tools or if you must roll your own then using ftp or similar > as a file transfer mechanism rather than trying to send a > bytestream over a socket. ftp can handle broken connections > etc more easily. Detecting and fixing errors over a socket > stream is non trivial and for backups is pretty much essential!! > Going off of wha tyou said, if I choose to use ftp, is there a way i could do everything from within python including the server to get the files? Is there like a ftp module for python to help in the passing of the files between the computers? Thanks, Nate -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org iD8DBQFH+YH1/n+duykW6K8RAhv+AJoCDvQip6Q1wJSh3dEoRZoC4Gx3oACdF0DK oQXQTccEnkEz0mf/Qo4Ywqo= =QRMr -----END PGP SIGNATURE----- From kim.hawtin at adelaide.edu.au Mon Apr 7 04:30:48 2008 From: kim.hawtin at adelaide.edu.au (Kim Hawtin) Date: Mon, 07 Apr 2008 12:00:48 +0930 Subject: [Tutor] socket / over network In-Reply-To: <47F981F5.6080401@comcast.net> References: <47F4C0F2.7060601@tds.net> <47F4D421.7000007@tds.net> <47F4E6C5.8000809@tds.net> <47F4EAF2.6050305@tds.net> <47F4F51F.8030309@comcast.net> <47F981F5.6080401@comcast.net> Message-ID: <47F98758.109@adelaide.edu.au> Hi Nathan, Nathan McBride wrote: > Alan Gauld wrote: >> "Nathan McBride" wrote >>> I'm pretty tired of the lame backup solution we have at work. >>> Could anyone point me to a (more or less newbieish) example of how >>> to >>> have python open a socket on one box and get data from it, then have >>> another >>> box write to it over the network? >> For a very simple example of using a socket you could try the >> Network Programming topic in my tutorial. > >> There is also a HowTo or Topic guide on the Python web site >> that gives a more detailed example. > >> That having been said, backups are usually best done using >> OS tools or if you must roll your own then using ftp or similar >> as a file transfer mechanism rather than trying to send a >> bytestream over a socket. ftp can handle broken connections >> etc more easily. Detecting and fixing errors over a socket >> stream is non trivial and for backups is pretty much essential!! > > Going off of wha tyou said, if I choose to use ftp, is there a way i > could do everything from within python including the server to get the > files? Is there like a ftp module for python to help in the passing of > the files between the computers? There are number of problems with FTP around security and firewalls, etc. This might be overkill, but perhaps you could use Twisted with SSH/SCP to get files around? See; [Twisted-Python] Twisted SCP http://twistedmatrix.com/pipermail/twisted-python/2005-December/012180.html Perhaps using Rsync and SSH might be more appropriate; http://www.howtoforge.com/rsync_incremental_snapshot_backups regards, Kim -- Operating Systems, Services and Operations Information Technology Services, The University of Adelaide kim.hawtin at adelaide.edu.au From devj1988 at gmail.com Sat Apr 5 08:26:08 2008 From: devj1988 at gmail.com (devj) Date: Fri, 4 Apr 2008 23:26:08 -0700 (PDT) Subject: [Tutor] MemoryError !!! Help Required Message-ID: <16510068.post@talk.nabble.com> Hi, I am making a web crawler using Python.To avoid dupliacy of urls,i have to maintain lists of downloaded urls and to-be-downloaded urls ,of which the latter grows exponentially,resulting in a MemoryError exception .What are the possible ways to avoid this ?? -- View this message in context: http://www.nabble.com/MemoryError-%21%21%21-Help-Required-tp16510068p16510068.html Sent from the Python - tutor mailing list archive at Nabble.com. From tiagokatcipis at gmail.com Sat Apr 5 03:25:30 2008 From: tiagokatcipis at gmail.com (Tiago Katcipis) Date: Fri, 04 Apr 2008 22:25:30 -0300 Subject: [Tutor] Question about global variables on modules Message-ID: <47F6D50A.40304@gmail.com> I know its not such a pretty thing to have global variables but its only for an exercise my teacher told to do. Its a function to calculate the results of a matrix using jacob. I want to inside the module (inside a function on the module )assign a value to a global variable, but the only way i found to do this inside the own module function is importing the module inside himself. Is there another way of doing this? its kind odd to import the module to himself, i think :-) here goes the code <============> import lineares_jacob *ERRO_FINAL = 0.0* def obter_respostas(matriz, incognitas, erro_max): erro = erro_max * 10 n = len(matriz) while(erro >= erro_max): novas_incognitas = [] y_um = (2.0 + (1.0 * incognitas[1]) - (1.0 * incognitas[4999])) / 3.0 novas_incognitas.append(y_um) for i in range(1 , (n - 1)): yi = ( (2.0 * i) + incognitas[i - 1] + incognitas[i + 1] ) / (2.0 + i) novas_incognitas.append(yi) y_cinc_mil = (10000.0 - incognitas[0] + incognitas[4998]) / 5002.0 novas_incognitas.append(y_cinc_mil) maior = novas_incognitas[0] - incognitas[0] for i in range(1, 5000): dif = novas_incognitas[i] - incognitas[i] if(dif > maior): maior = dif erro = maior incognitas = novas_incognitas *lineares_jacob.ERRO_FINAL = erro* return incognitas From tom.haynes at ozemail.com.au Mon Apr 7 03:26:22 2008 From: tom.haynes at ozemail.com.au (Tom Haynes) Date: Mon, 7 Apr 2008 11:26:22 +1000 Subject: [Tutor] Creating Sudoku Message-ID: <000b01c8984e$63b61ed0$2b225c70$@haynes@ozemail.com.au> G?day, I am trying to create a simple Sudoku game that takes a simple raw_input of a, r, c or something similar (where a = row, r = column, c = number to place there) and place it in a Sudoku game square. I have tried many times to start it from different angles and just can?t do it. If someone could help step me through what needs to be done that would be greatly appreciated! Thanks, Tom No virus found in this outgoing message. Checked by AVG. Version: 7.5.519 / Virus Database: 269.22.8/1362 - Release Date: 6/04/2008 11:12 AM -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080407/c391a298/attachment.htm From rabidpoobear at gmail.com Mon Apr 7 07:31:30 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 07 Apr 2008 00:31:30 -0500 Subject: [Tutor] Creating Sudoku In-Reply-To: <000b01c8984e$63b61ed0$2b225c70$@haynes@ozemail.com.au> References: <000b01c8984e$63b61ed0$2b225c70$@haynes@ozemail.com.au> Message-ID: <47F9B1B2.2020107@gmail.com> Tom Haynes wrote: > > G?day, > > > > I am trying to create a simple Sudoku game that takes a simple > raw_input of a, r, c or something similar (where a = row, r = column, > c = number to place there) and place it in a Sudoku game square. I > have tried many times to start it from different angles and just can?t > do it. If someone could help step me through what needs to be done > that would be greatly appreciated! > Sounds like you need to have a 2-dimensional list to store your values. The first and second indexes of the list would correspond to the row/column variables you have, and the value would be the actual value at each location. You may want to initialize your list to some value (fill it with something). You could also use a dictionary, but it would probably not be worthwhile. You would also probably want to use the int(some_value) conversion on your raw_inputs so you can use the values to index your list. Let us know if this is not enough of a hint! Hope it goes okay. -Luke From rabidpoobear at gmail.com Mon Apr 7 07:32:53 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 07 Apr 2008 00:32:53 -0500 Subject: [Tutor] MemoryError !!! Help Required In-Reply-To: <16510068.post@talk.nabble.com> References: <16510068.post@talk.nabble.com> Message-ID: <47F9B205.4040606@gmail.com> devj wrote: > Hi, > I am making a web crawler using Python.To avoid dupliacy of urls,i have to > maintain lists of downloaded urls and to-be-downloaded urls ,of which the > latter grows exponentially,resulting in a MemoryError exception .What are > the possible ways to avoid this ?? > get more RAM, store the list on your hard drive, etc. etc. Why are you trying to do this? Are you sure you can't use existing tools for this such as wget? -Luke From andreas at kostyrka.org Mon Apr 7 08:25:11 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 07 Apr 2008 08:25:11 +0200 Subject: [Tutor] MemoryError !!! Help Required In-Reply-To: <47F9B205.4040606@gmail.com> References: <16510068.post@talk.nabble.com> <47F9B205.4040606@gmail.com> Message-ID: <1207549512.20984.5.camel@localhost> Am Montag, den 07.04.2008, 00:32 -0500 schrieb Luke Paireepinart: > devj wrote: > > Hi, > > I am making a web crawler using Python.To avoid dupliacy of urls,i have to > > maintain lists of downloaded urls and to-be-downloaded urls ,of which the > > latter grows exponentially,resulting in a MemoryError exception .What are > > the possible ways to avoid this ?? > > > get more RAM, store the list on your hard drive, etc. etc. > Why are you trying to do this? Are you sure you can't use existing > tools for this such as wget? > -Luke Also traditional solutions involve e.g. remembering a hash value. Plus if you go for a simple file based solution, you probably should store it by hostname, e.g.: http://123.45.67.87/abc/def/text.html => file("127/45/67/87", "w").write("/abc/def/text.html") (guess you need to run os.makedirs as needed :-P) These makes it scaleable (by not storying to many files in one directory, and by leaving out the common element so the files are smaller and faster to read), while keeping the code relative simple. Another solution would be shelve, but you have to keep in mind that if you are unlucky you might loose the database. (Some of the DBs that anydbm might not survive power loss, or other problems to well) Andreas > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080407/df2e4af0/attachment.pgp From alan.gauld at btinternet.com Mon Apr 7 09:16:39 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 7 Apr 2008 08:16:39 +0100 Subject: [Tutor] socket / over network References: <47F4C0F2.7060601@tds.net> <47F4D421.7000007@tds.net> <47F4E6C5.8000809@tds.net> <47F4EAF2.6050305@tds.net> <47F4F51F.8030309@comcast.net> <47F981F5.6080401@comcast.net> Message-ID: "Nathan McBride" wrote > Going off of wha tyou said, if I choose to use ftp, is there a way i > could do everything from within python including the server to get > the > files? Is there like a ftp module for python to help in the passing > of > the files between the computers? Yes, there is an ftp module in the standard library. Alan G From alan.gauld at btinternet.com Mon Apr 7 09:23:46 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 7 Apr 2008 08:23:46 +0100 Subject: [Tutor] PyMOTW: difflib References: <20080406043551.966921E4014@bag.python.org><47F8EB2B.2060103@groktech.org><20080406163321.462851E400C@bag.python.org><20080406213631.503911E4019@bag.python.org> <20080407011158.A950C1E400C@bag.python.org> Message-ID: "Dick Moores" wrote in message > Even if there weren't a path problem, my understanding is that > from difflib_data import * would only import the functions in > difflib_data.py; There are none. import imports names. Any names, not just functions. After all, function names are just names like any other sqr = lambda x: x*x is exactly the same as def sqr(x): return x*x In both cases import will give you access to sqr as a name So in your case the names text1, text2, text1_lines and text2_lines will all be made available within your script. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jatinder.singh2 at wipro.com Mon Apr 7 11:02:28 2008 From: jatinder.singh2 at wipro.com (root) Date: Mon, 07 Apr 2008 14:32:28 +0530 Subject: [Tutor] create new user In-Reply-To: References: Message-ID: <1207558948.3158.28.camel@localhost.localdomain> Hi All. Hope you are Good and Doing Well.I am Working on a web based application .I need your pretty help for this all as I have to work in Python and I am New to this.. I want to write a python script in which will create a new user and password.please tell me ,how it will be passible....??? I googled for this but could not find any good solution .At present I am using a shell script that create new user and this script is called in python . Would you please suggest me python code that create new user. waiting for your's reply regards Jatinder The information contained in this electronic message and any attachments to this message are intended for the exclusive use of the addressee(s) and may contain proprietary, confidential or privileged information. If you are not the intended recipient, you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately and destroy all copies of this message and any attachments. WARNING: Computer viruses can be transmitted via email. The recipient should check this email and any attachments for the presence of viruses. The company accepts no liability for any damage caused by any virus transmitted by this email. www.wipro.com From michael.miesner at gmail.com Mon Apr 7 14:06:37 2008 From: michael.miesner at gmail.com (Michael Miesner) Date: Mon, 7 Apr 2008 06:06:37 -0600 Subject: [Tutor] glade integration Message-ID: <8f6846bb0804070506y7d782be8i8c12fef411b3f77@mail.gmail.com> Hi- I am totally new to python and I cant figure out how to integrate a glade file into a python file. Is it as simple as referencing the glade file, or must the XML code from the glade file be copied in? Sorry to ask such a basic question. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080407/b9ea9932/attachment.htm From srilyk at gmail.com Mon Apr 7 14:52:55 2008 From: srilyk at gmail.com (W W) Date: Mon, 7 Apr 2008 07:52:55 -0500 Subject: [Tutor] Creating Sudoku In-Reply-To: <47F9B1B2.2020107@gmail.com> References: <47F9B1B2.2020107@gmail.com> Message-ID: <333efb450804070552rc32131ar23c6f528c6a4b5f3@mail.gmail.com> Actually, a dictionary might be a good idea. I just played with this so youcan get a little picture. >>> foo = {'1a': 3, '1b': 4} >>> row = raw_input("Row: ") Row: 1 >>> col = raw_input("Column: ") Column: b >>> val = raw_input("Value: ") Value: 1 >>> foo[row+col] = val >>> foo {'1a': 3, '1b': '1'} You could easily run int(val) to convert to the integer value to store in the dict. The other benefit is that python ignores whitespace in between dictionary elements, so you could do something to the effect of foo = {'1a': 1, '1b':2, '1c':3, '2a': 0, '2b': 9, '2c': 6} Or something of similar nature. I suppose in favor of a 2d list, the loop would be a little more straighforward. With a dict, the pairs are in no particular order, so you would have to basically create the same loop for a 2d array, and then convert the values to strings. Either way, good luck! -Wayne On 4/7/08, Luke Paireepinart wrote: > Tom Haynes wrote: > > > > G'day, > > > > > > > > I am trying to create a simple Sudoku game that takes a simple > > raw_input of a, r, c or something similar (where a = row, r = column, > > c = number to place there) and place it in a Sudoku game square. I > > have tried many times to start it from different angles and just can't > > do it. If someone could help step me through what needs to be done > > that would be greatly appreciated! > > > > Sounds like you need to have a 2-dimensional list to store your values. > The first and second indexes of the list would correspond to the > row/column variables you have, and the value would be the actual value > at each location. You may want to initialize your list to some value > (fill it with something). You could also use a dictionary, but it would > probably not be worthwhile. > You would also probably want to use the int(some_value) conversion on > your raw_inputs so you can use the values to index your list. > Let us know if this is not enough of a hint! Hope it goes okay. > -Luke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From kent37 at tds.net Mon Apr 7 15:40:39 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 07 Apr 2008 09:40:39 -0400 Subject: [Tutor] Code optmisation In-Reply-To: <304770.91464.qm@web43136.mail.sp1.yahoo.com> References: <304770.91464.qm@web43136.mail.sp1.yahoo.com> Message-ID: <47FA2457.9000502@tds.net> yogi wrote: Some small optimizations inline, more important comments after the code. > #/bin/python > import sys, os, csv, re > x = 0 #Define Zero for now > var = 1000000 #Taking the variation > # This programme finds the SNPs from the range passed > # csv splits columns and this file is tab spaced > fis = csv.reader(open("divs.map", "rb"), delimiter='\t', quoting=csv.QUOTE_NONE) > for row in fis: > # csv splits columns and this file is "," spaced > gvalues = csv.reader(open("genvalues", "rb"), delimiter=',', quoting=csv.QUOTE_NONE) If gvalues contains all integers you could say gvalues = map(int, gvalues) to convert the whole list to ints at once, then you could remove the individual int(gvalue[x]) calls below. > for gvalue in gvalues: > # To see Columns (chr) Match > if row[0] == gvalue[0]: > # If Column 3 (range) is Zero print row > if int(gvalue[3]) == x: > a = int(gvalue[1]) - var > b = int(gvalue[2]) + var + 1 > if int(a <= int(row[3]) <= b): No need for int() here and below, the result of the comparison is a boolean which is what the if statement wants. > print row > # If Column 3 (range) is not zero find matches and print row > else: > a = int(gvalue[1]) - var > b = int(gvalue[2]) + var + 1 > if int(a <= int(row[3]) <= b): > print row > c = int(gvalue[3]) - var > d = int(gvalue[4]) + var + 1 > if int(c <= int(row[3]) <= d): > print row > There will probably be other micro-optimizations you can do but first you need to fix your algorithm. > ----------------------------------------------------- > > Question1 : Is there a better way ? Yes. You don't say how long the above takes to run but if by 12M you mean 12,000,000 then I think the running time will be measured in months. The biggest problem (other than reading genvalues from disk 12M times, as Alan pointed out) is that the body of the inner loop will be executed 12M*1M times. You have to look for ways to get away from that product term. Two possibilities: - If the two files are sorted, you could walk through them in parallel finding and printing matches as you go. If the files are not sorted, you could sort them yourself, either reading the entire file into memory and sorting with Python, or using an external disk sort such as Linux sort(1). With this approach you would make a single pass through each file. - Build a dict mapping gvalue[0] to a list of ranges for the gvalue. Precompute the ranges (int conversion and var offsets) so when you access the values you only have to compare, no arithmetic. Then for each row in fis, look up row[0] in the dict, iterate through the ranges associated with that value and print the matches. How well the second approach works will depend on the number of different gvalue[0] values. If there are none, it won't cut down on the size of the inner loop at all. If there are many, it will help considerably. > Question 2: If I have convert this code into a function. > Should I ? Yes. Access to local variables in a function is faster than access to global variables. Kent From srilyk at gmail.com Mon Apr 7 16:36:40 2008 From: srilyk at gmail.com (W W) Date: Mon, 7 Apr 2008 09:36:40 -0500 Subject: [Tutor] MemoryError !!! Help Required In-Reply-To: <1207549512.20984.5.camel@localhost> References: <16510068.post@talk.nabble.com> <47F9B205.4040606@gmail.com> <1207549512.20984.5.camel@localhost> Message-ID: <333efb450804070736m619cb14bxb5420c47b5d79ecf@mail.gmail.com> I don't have a lot of experience, but I would suggest dictionaries (which use hash values). A possible scenario would be somthing similar to Andreas' visited = dict() url = "http://www.monty.com" file = "/spam/holyhandgrenade/three.html" visited[url] = file unvisited = dict() url = "http://www.bringoutyourdead.org" file = "/fleshwound.html" unvisited[url] = file url = "http://129.29.3.59" file = "foo.php" unvisited[url] = file (of course, functions, loops, etc. would clear up some repetitions) Now that I think about it... It would probably work better to keep the visited urls in a dict (assuming that list is smaller) and the unvisited ones in a FIFO file, though I'm not 100% sure on that. If you were simply unconcerned with speed, you could easily keep both lists stored as csv files, and load each to compare against each URL, for each url in newurl: try visited[url]: except KeyError: #This means the URL hasn't been visited that's probably the easiest way to compare dict values. A possible good idea, if you were going that route (reading each file) is to create a dir for each 1st char in the url (after http://, and a separate one for http://www. since those are the most common, and yes some sites like www.uca.edu don't allow http://uca.edu). Good luck! -Wayne On 4/7/08, Andreas Kostyrka wrote: > > Am Montag, den 07.04.2008, 00:32 -0500 schrieb Luke Paireepinart: > > > devj wrote: > > > Hi, > > > I am making a web crawler using Python.To avoid dupliacy of urls,i have to > > > maintain lists of downloaded urls and to-be-downloaded urls ,of which the > > > latter grows exponentially,resulting in a MemoryError exception .What are > > > the possible ways to avoid this ?? > > > > > get more RAM, store the list on your hard drive, etc. etc. > > Why are you trying to do this? Are you sure you can't use existing > > tools for this such as wget? > > -Luke > > > Also traditional solutions involve e.g. remembering a hash value. > > Plus if you go for a simple file based solution, you probably should > store it by hostname, e.g.: > http://123.45.67.87/abc/def/text.html => file("127/45/67/87", > "w").write("/abc/def/text.html") > (guess you need to run os.makedirs as needed :-P) > > These makes it scaleable (by not storying to many files in one > directory, and by leaving out the common element so the files are > smaller and faster to read), while keeping the code relative simple. > > Another solution would be shelve, but you have to keep in mind that if > you are unlucky you might loose the database. (Some of the DBs that > anydbm might not survive power loss, or other problems to well) > > > Andreas > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From rabidpoobear at gmail.com Mon Apr 7 16:48:32 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 07 Apr 2008 09:48:32 -0500 Subject: [Tutor] glade integration In-Reply-To: <8f6846bb0804070506y7d782be8i8c12fef411b3f77@mail.gmail.com> References: <8f6846bb0804070506y7d782be8i8c12fef411b3f77@mail.gmail.com> Message-ID: <47FA3440.1050506@gmail.com> Michael Miesner wrote: > Hi- > I am totally new to python and I cant figure out how to integrate a > glade file into a python file. Is it as simple as referencing the > glade file, or must the XML code from the glade file be copied in? > Sorry to ask such a basic question. XML is how glade stores its formatting internally. You have to use glade to generate the python code. Look for instructions on the glade website on how to do this. You'll end up with wxPython code. Just make sure you have wxPython installed, and then fill in the blank spots it tells you to in the generated code. -Luke From rabidpoobear at gmail.com Mon Apr 7 16:54:33 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 07 Apr 2008 09:54:33 -0500 Subject: [Tutor] Creating Sudoku In-Reply-To: <333efb450804070552rc32131ar23c6f528c6a4b5f3@mail.gmail.com> References: <47F9B1B2.2020107@gmail.com> <333efb450804070552rc32131ar23c6f528c6a4b5f3@mail.gmail.com> Message-ID: <47FA35A9.7060105@gmail.com> W W wrote: > Actually, a dictionary might be a good idea. > I just played with this so youcan get a little picture. > [snip] > > You could easily run int(val) to convert to the integer value to store > in the dict. The other benefit is that python ignores whitespace in > between dictionary elements, so you could do something to the effect > of > What are you talking about? I don't understand what you mean by "ignores whitespace between dictionary elements." > foo = {'1a': 1, '1b':2, '1c':3, > '2a': 0, '2b': 9, '2c': 6} > > Or something of similar nature. > > I suppose in favor of a 2d list, the loop would be a little more > straighforward. With a dict, the pairs are in no particular order, so > you would have to basically create the same loop for a 2d array, and > then convert the values to strings. > It's also easier if the 2d list is pre-initialized to "-"s, for example, then he can just print it out directly, and it'll format correctly. With the dictionary he has to jump through some hoops, and by his original post we can infer that he's probably not completely comfortable with Python yet, so it'll probably be harder for him to understand how to do this. I can provide example code showing how simple it'd be, but then it'd give away the answer. From eric at ericwalstad.com Mon Apr 7 17:16:35 2008 From: eric at ericwalstad.com (Eric Walstad) Date: Mon, 7 Apr 2008 08:16:35 -0700 Subject: [Tutor] Code optmisation In-Reply-To: <304770.91464.qm@web43136.mail.sp1.yahoo.com> References: <304770.91464.qm@web43136.mail.sp1.yahoo.com> Message-ID: Hi Yogi On Fri, Apr 4, 2008 at 10:05 PM, yogi wrote: > Hi , > Here is my first usable Python code. > The code works. Woohoo! congratulations. > Here is what I'm trying to do. > I have two huge text files. After some processing, One is 12M (file A) and the other 1M (file B) . > The files have columns which are of interest to me. ... > Question1 : Is there a better way ? I admit that I didn't spend too much time trying to understand your code. But at first glance your logic looks like it could be easily represented in SQL. I bet a relational database could do your lookup faster than doing it in pure Python. I do this kind of thing frequently: use python to import delimited data into a relational database like PostgreSQL, add indexes where they make sense, query the database for the results. It can all be done from inside Python but it doesn't have to be. SELECT a.* FROM a INNER JOIN b ON a.field0=b.field0 WHERE b.field3=0 AND a.field3 >= (b.field1-1000000) AND a.field3 <= (b.field2+1000001) ... etc. > Question2 : For now I'm using shells time call for calculating time required. Does Python provide a more fine grained check. I think so but I've not used it: timeit. Search this mailing list's archives for 'timeit' and/or at the Python command line: import timeit help(timeit) > Question 2: If I have convert this code into a function. > Should I ? Yes, especially if it helps make your code easier to read and understand. From srilyk at gmail.com Mon Apr 7 17:34:41 2008 From: srilyk at gmail.com (W W) Date: Mon, 7 Apr 2008 10:34:41 -0500 Subject: [Tutor] Creating Sudoku In-Reply-To: <47FA35A9.7060105@gmail.com> References: <47F9B1B2.2020107@gmail.com> <333efb450804070552rc32131ar23c6f528c6a4b5f3@mail.gmail.com> <47FA35A9.7060105@gmail.com> Message-ID: <333efb450804070834o3c4efc1am4d645b0afd758cb@mail.gmail.com> On 4/7/08, Luke Paireepinart wrote: > W W wrote: > What are you talking about? I don't understand what you mean by "ignores > whitespace between dictionary elements." > > > foo = {'1a': 1, '1b':2, '1c':3, > > '2a': 0, '2b': 9, '2c': 6} Exactly that. If you were to write: foo = {'1a': 1, '1b':2, '1c':3} foo['2a'] = 0 You would get a nifty error. -Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From tannhauser at nerdshack.com Mon Apr 7 17:07:42 2008 From: tannhauser at nerdshack.com (tannhauser) Date: Mon, 7 Apr 2008 17:07:42 +0200 Subject: [Tutor] Re: glade integration In-Reply-To: <47FA3440.1050506@gmail.com> References: <8f6846bb0804070506y7d782be8i8c12fef411b3f77@mail.gmail.com> <47FA3440.1050506@gmail.com> Message-ID: <20080407150742.GA27962@nerdshack.com> On Mon, 07.04, 09:48, Luke Paireepinart wrote: > Michael Miesner wrote: > > Hi- > > I am totally new to python and I cant figure out how to integrate a > > glade file into a python file. Is it as simple as referencing the > > glade file, or must the XML code from the glade file be copied in? > > Sorry to ask such a basic question. Use libglade and pygtk. Have a look at http://www.learningpython.com, the glade/pygtk-tutorials were really helpful for me. http://www.learningpython.com/2006/05/07/creating-a-gui-using-pygtk-and-glade/ http://www.learningpython.com/2006/05/30/building-an-application-with-pygtk-and-glade/ th From rabidpoobear at gmail.com Mon Apr 7 17:53:11 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 07 Apr 2008 10:53:11 -0500 Subject: [Tutor] Creating Sudoku In-Reply-To: <333efb450804070834o3c4efc1am4d645b0afd758cb@mail.gmail.com> References: <47F9B1B2.2020107@gmail.com> <333efb450804070552rc32131ar23c6f528c6a4b5f3@mail.gmail.com> <47FA35A9.7060105@gmail.com> <333efb450804070834o3c4efc1am4d645b0afd758cb@mail.gmail.com> Message-ID: <47FA4367.2030303@gmail.com> W W wrote: > On 4/7/08, Luke Paireepinart wrote: > >> W W wrote: >> What are you talking about? I don't understand what you mean by "ignores >> whitespace between dictionary elements." >> >> >>> foo = {'1a': 1, '1b':2, '1c':3, >>> '2a': 0, '2b': 9, '2c': 6} >>> > > Exactly that. If you were to write: > > foo = {'1a': 1, '1b':2, '1c':3} > foo['2a'] = 0 > > You would get a nifty error. > You mean that the dictionary _definition_ ignores whitespace between elements? That's quite different than the dictionary itself ignoring whitespace. That implies that foo['1b'] is the same element as foo['1 b'], hence the source of my confusion. That's not a feature of dictionaries, but of the comma. You can easily do the following: x = [1, 2, 3, 4] if you want. Same with tuples and various other things. Python just realizes that if it doesn't see a closing brace/bracket, but sees a comma, that more will probably be coming on the next line. You can do the same thing with backslash, if your statement does not end in a comma: for example, x = 1 + 1 + \ 2 + 3 + 5 \ + 8 + 13 Also, did you test the code that "generates an error?" It works fine for me. >>> foo = {'1a': 'b'} >>> foo['2b'] = 0 >>> print foo['2b'] 0 >>> Hope that helps, -Luke From andrei.petre at gmail.com Mon Apr 7 18:01:38 2008 From: andrei.petre at gmail.com (Andrei Petre) Date: Mon, 7 Apr 2008 19:01:38 +0300 Subject: [Tutor] Creating Sudoku In-Reply-To: <47FA4367.2030303@gmail.com> References: <47F9B1B2.2020107@gmail.com> <333efb450804070552rc32131ar23c6f528c6a4b5f3@mail.gmail.com> <47FA35A9.7060105@gmail.com> <333efb450804070834o3c4efc1am4d645b0afd758cb@mail.gmail.com> <47FA4367.2030303@gmail.com> Message-ID: <3576e740804070901r4732e133j34276f96dae47aed@mail.gmail.com> A good place to look at : http://www.norvig.com/sudoku.html On Mon, Apr 7, 2008 at 6:53 PM, Luke Paireepinart wrote: > W W wrote: > > On 4/7/08, Luke Paireepinart wrote: > > > >> W W wrote: > >> What are you talking about? I don't understand what you mean by > "ignores > >> whitespace between dictionary elements." > >> > >> > >>> foo = {'1a': 1, '1b':2, '1c':3, > >>> '2a': 0, '2b': 9, '2c': 6} > >>> > > > > Exactly that. If you were to write: > > > > foo = {'1a': 1, '1b':2, '1c':3} > > foo['2a'] = 0 > > > > You would get a nifty error. > > > You mean that the dictionary _definition_ ignores whitespace between > elements? > That's quite different than the dictionary itself ignoring whitespace. > That implies that > foo['1b'] is the same element as foo['1 b'], hence the source of my > confusion. > > That's not a feature of dictionaries, but of the comma. > You can easily do the following: > x = [1, 2, > 3, 4] > if you want. > Same with tuples and various other things. > Python just realizes that if it doesn't see a closing brace/bracket, but > sees a comma, that more will probably be coming on the next line. > You can do the same thing with backslash, if your statement does not end > in a comma: for example, > x = 1 + 1 + \ > 2 + 3 + 5 \ > + 8 + 13 > > Also, did you test the code that "generates an error?" > It works fine for me. > >>> foo = {'1a': 'b'} > >>> foo['2b'] = 0 > >>> print foo['2b'] > 0 > >>> > > Hope that helps, > -Luke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080407/15f4f6a7/attachment.htm From dkuhlman at rexx.com Mon Apr 7 18:23:08 2008 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Mon, 7 Apr 2008 09:23:08 -0700 Subject: [Tutor] Question about global variables on modules In-Reply-To: <47F6D50A.40304@gmail.com> References: <47F6D50A.40304@gmail.com> Message-ID: <20080407162308.GA21262@cutter.rexx.com> On Fri, Apr 04, 2008 at 10:25:30PM -0300, Tiago Katcipis wrote: > I know its not such a pretty thing to have global variables but its only > for an exercise my teacher told to do. Its a function to calculate the > results of a matrix using jacob. I want to inside the module (inside a > function on the module )assign a value to a global variable, but the > only way i found to do this inside the own module function is importing > the module inside himself. Is there another way of doing this? its kind > odd to import the module to himself, i think :-) If you want to assign a value to a global variable from within a function, use the global statement. Examples: A_GLOBAL_VALUE = 0 # Example: assign value to local variable def t1(): a_value = 4 return a_value * 3 # Example: assign value to global variable def t2(): global A_GLOBAL_VALUE A_GLOBAL_VALUE = 4 return a_value * 3 # Example: get (but do not set) the value of a global variable def t3(): a_value = A_GLOBAL_VALUE print a_value def test(): print t1() print t2() print A_GLOBAL_VALUE print t3() test() See http://docs.python.org/ref/global.html. Note that to *get* (not set) the value of a global variable from within a function, you do not need to use the global statement. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From andreas at kostyrka.org Mon Apr 7 18:40:51 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 07 Apr 2008 18:40:51 +0200 Subject: [Tutor] MemoryError !!! Help Required In-Reply-To: <333efb450804070736m619cb14bxb5420c47b5d79ecf@mail.gmail.com> References: <16510068.post@talk.nabble.com> <47F9B205.4040606@gmail.com> <1207549512.20984.5.camel@localhost> <333efb450804070736m619cb14bxb5420c47b5d79ecf@mail.gmail.com> Message-ID: <1207586451.2742.7.camel@localhost> Hint: MemoryError suggests that his dicts have filled up his address space (probably). 1-3GB on Linux, 2?GB on Windows. At least for 32bit versions. So storing the whole URL in memory is probably out of question, storing it only in some form of files might be slightly slow, so one compromise would be to store sets of hashes for URLs that have been seen. This way unseen URLs could be recognized without a visit to the disc, and URLs where the hashvalue is in the seen set, could be queued at the end, and all urls to one hostname could be checked all at the same time when reading the file. Andreas Am Montag, den 07.04.2008, 09:36 -0500 schrieb W W: > I don't have a lot of experience, but I would suggest dictionaries > (which use hash values). > > A possible scenario would be somthing similar to Andreas' > > visited = dict() > > url = "http://www.monty.com" > file = "/spam/holyhandgrenade/three.html" > > visited[url] = file > > unvisited = dict() > > url = "http://www.bringoutyourdead.org" > file = "/fleshwound.html" > > unvisited[url] = file > > url = "http://129.29.3.59" > file = "foo.php" > > unvisited[url] = file > > (of course, functions, loops, etc. would clear up some repetitions) > > Now that I think about it... It would probably work better to keep the > visited urls in a dict (assuming that list is smaller) and the > unvisited ones in a FIFO file, though I'm not 100% sure on that. > > If you were simply unconcerned with speed, you could easily keep both > lists stored as csv files, and load each to compare against each URL, > > for each url in newurl: > try visited[url]: > except KeyError: > #This means the URL hasn't been visited > > that's probably the easiest way to compare dict values. A possible > good idea, if you were going that route (reading each file) is to > create a dir for each 1st char in the url (after http://, and a > separate one for > http://www. since those are the most common, and yes some sites like > www.uca.edu don't allow http://uca.edu). > > Good luck! > -Wayne > > On 4/7/08, Andreas Kostyrka wrote: > > > > Am Montag, den 07.04.2008, 00:32 -0500 schrieb Luke Paireepinart: > > > > > devj wrote: > > > > Hi, > > > > I am making a web crawler using Python.To avoid dupliacy of urls,i have to > > > > maintain lists of downloaded urls and to-be-downloaded urls ,of which the > > > > latter grows exponentially,resulting in a MemoryError exception .What are > > > > the possible ways to avoid this ?? > > > > > > > get more RAM, store the list on your hard drive, etc. etc. > > > Why are you trying to do this? Are you sure you can't use existing > > > tools for this such as wget? > > > -Luke > > > > > > Also traditional solutions involve e.g. remembering a hash value. > > > > Plus if you go for a simple file based solution, you probably should > > store it by hostname, e.g.: > > http://123.45.67.87/abc/def/text.html => file("127/45/67/87", > > "w").write("/abc/def/text.html") > > (guess you need to run os.makedirs as needed :-P) > > > > These makes it scaleable (by not storying to many files in one > > directory, and by leaving out the common element so the files are > > smaller and faster to read), while keeping the code relative simple. > > > > Another solution would be shelve, but you have to keep in mind that if > > you are unlucky you might loose the database. (Some of the DBs that > > anydbm might not survive power loss, or other problems to well) > > > > > > Andreas > > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080407/6f3abd84/attachment.pgp From jdprothero at gmail.com Mon Apr 7 19:09:15 2008 From: jdprothero at gmail.com (Jerrold Prothero) Date: Mon, 7 Apr 2008 13:09:15 -0400 Subject: [Tutor] Writing dictionaries to a file Message-ID: <41fb634c0804071009m3dfc50aeg7517ff65abf8c0d0@mail.gmail.com> I've been trying to understand how writing a dictionary to a file & reading it back should work. It's been suggested that if I had a clue, I'd use pickle, but since I started looking at the csv (comma separated values) module, which also supports writing dictionaries out to a file, I at least wanted to understand how it's supposed to work with csv. Relevant Python 2.5 documentation sections are 9.1.1 and 9.1.4. My question boils down to this: what does writerows want as an argument for a dictionary? Here's my set-up code (which executes without error) from csv import * d = {"a" : 1, "b" : 2} f = open("test", "wb") w = DictWriter(f, d.keys()) # Python docs 2.5, Section 9.1.1 Here are three guesses at how to call writerows, with error traces. 1) w.writerows(d.items()) Traceback (most recent call last): File "", line 1, in w.writerows(d.items()) File "C:\Python25\lib\csv.py", line 129, in writerows rows.append(self._dict_to_list(rowdict)) File "C:\Python25\lib\csv.py", line 118, in _dict_to_list for k in rowdict.keys(): AttributeError: 'tuple' object has no attribute 'keys' 2) w.writerows(d) Traceback (most recent call last): File "", line 1, in w.writerows(d) File "C:\Python25\lib\csv.py", line 129, in writerows rows.append(self._dict_to_list(rowdict)) File "C:\Python25\lib\csv.py", line 118, in _dict_to_list for k in rowdict.keys(): AttributeError: 'str' object has no attribute 'keys' 3) w.writerows(d.iteritems()) Traceback (most recent call last): File "", line 1, in w.writerows(d.iteritems()) File "C:\Python25\lib\csv.py", line 129, in writerows rows.append(self._dict_to_list(rowdict)) File "C:\Python25\lib\csv.py", line 118, in _dict_to_list for k in rowdict.keys(): AttributeError: 'tuple' object has no attribute 'keys' >From Section 9.1.4 it looks like I'm supposed to do something with the str() function, but I'm not sure what. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080407/2fc2dab6/attachment.htm From rabidpoobear at gmail.com Mon Apr 7 19:16:33 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 07 Apr 2008 12:16:33 -0500 Subject: [Tutor] Writing dictionaries to a file In-Reply-To: <41fb634c0804071009m3dfc50aeg7517ff65abf8c0d0@mail.gmail.com> References: <41fb634c0804071009m3dfc50aeg7517ff65abf8c0d0@mail.gmail.com> Message-ID: <47FA56F1.4040500@gmail.com> Jerrold Prothero wrote: > > I've been trying to understand how writing a dictionary to a file & > reading > it back should work. > [snip] > > Here are three guesses at how to call writerows, with error traces. > [snip] > 2) > > w.writerows(d) > > Traceback (most recent call last): > File "", line 1, in > w.writerows(d) > File "C:\Python25\lib\csv.py", line 129, in writerows > rows.append(self._dict_to_list(rowdict)) > File "C:\Python25\lib\csv.py", line 118, in _dict_to_list > for k in rowdict.keys(): > AttributeError: 'str' object has no attribute 'keys' This error sounds like d is a string, not a dictionary. Are you sure it's a dictionary? -Luke From rdm at rcblue.com Mon Apr 7 19:23:57 2008 From: rdm at rcblue.com (Dick Moores) Date: Mon, 07 Apr 2008 10:23:57 -0700 Subject: [Tutor] PyMOTW: difflib In-Reply-To: References: <20080406043551.966921E4014@bag.python.org> <47F8EB2B.2060103@groktech.org> <20080406163321.462851E400C@bag.python.org> <20080406213631.503911E4019@bag.python.org> <20080407011158.A950C1E400C@bag.python.org> Message-ID: <20080407172425.AE8851E4017@bag.python.org> At 12:23 AM 4/7/2008, Alan Gauld wrote: >"Dick Moores" wrote in message > > > Even if there weren't a path problem, my understanding is that > > from difflib_data import * would only import the functions in > > difflib_data.py; There are none. > >import imports names. Any names, not just functions. >After all, function names are just names like any other > >sqr = lambda x: x*x > >is exactly the same as > >def sqr(x): return x*x > >In both cases import will give you access to sqr as a name > >So in your case the names text1, text2, text1_lines and >text2_lines will all be made available within your script. I'm having trouble with the concept of a name in Python. Is a name the same as anything defined? Such as a, where a = 5 b, where b = [3,4,5] c, where c = "Alan" five(), where def five(): return 5 sqr, where sqr = lambda x: x*x square, where def sqr(x): return x*x Are there other kinds of possibilities? names of classes? names of modules? Dick ================================ UliPad <>: http://code.google.com/p/ulipad/ From mlangford.cs03 at gtalumni.org Mon Apr 7 19:59:05 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Mon, 7 Apr 2008 13:59:05 -0400 Subject: [Tutor] glade integration In-Reply-To: <20080407150742.GA27962@nerdshack.com> References: <8f6846bb0804070506y7d782be8i8c12fef411b3f77@mail.gmail.com> <47FA3440.1050506@gmail.com> <20080407150742.GA27962@nerdshack.com> Message-ID: <82b4f5810804071059s852dbecvf097cb43d99b895d@mail.gmail.com> While on the topic of glade, does anyone know of a working gui builder for glade on windows? WinGlade appears to have been linkjacked or hacked. --Michael On Mon, Apr 7, 2008 at 11:07 AM, tannhauser wrote: > On Mon, 07.04, 09:48, Luke Paireepinart wrote: > > Michael Miesner wrote: > > > Hi- > > > I am totally new to python and I cant figure out how to integrate a > > > glade file into a python file. Is it as simple as referencing the > > > glade file, or must the XML code from the glade file be copied in? > > > Sorry to ask such a basic question. > > Use libglade and pygtk. Have a look at http://www.learningpython.com, the > glade/pygtk-tutorials > were really helpful for me. > > > http://www.learningpython.com/2006/05/07/creating-a-gui-using-pygtk-and-glade/ > > http://www.learningpython.com/2006/05/30/building-an-application-with-pygtk-and-glade/ > > > th > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080407/9be8ed30/attachment.htm From mlangford.cs03 at gtalumni.org Mon Apr 7 20:09:45 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Mon, 7 Apr 2008 14:09:45 -0400 Subject: [Tutor] glade integration In-Reply-To: <82b4f5810804071059s852dbecvf097cb43d99b895d@mail.gmail.com> References: <8f6846bb0804070506y7d782be8i8c12fef411b3f77@mail.gmail.com> <47FA3440.1050506@gmail.com> <20080407150742.GA27962@nerdshack.com> <82b4f5810804071059s852dbecvf097cb43d99b895d@mail.gmail.com> Message-ID: <82b4f5810804071109n687b80f7rab4190ba5cc7bad9@mail.gmail.com> Well there you go. Just needed to look elsewhere: http://sourceforge.net/project/showfiles.php?group_id=98754 On Mon, Apr 7, 2008 at 1:59 PM, Michael Langford < mlangford.cs03 at gtalumni.org> wrote: > While on the topic of glade, does anyone know of a working gui builder for > glade on windows? WinGlade appears to have been linkjacked or hacked. > --Michael > > > On Mon, Apr 7, 2008 at 11:07 AM, tannhauser > wrote: > > > On Mon, 07.04, 09:48, Luke Paireepinart wrote: > > > Michael Miesner wrote: > > > > Hi- > > > > I am totally new to python and I cant figure out how to integrate a > > > > glade file into a python file. Is it as simple as referencing the > > > > glade file, or must the XML code from the glade file be copied in? > > > > Sorry to ask such a basic question. > > > > Use libglade and pygtk. Have a look at http://www.learningpython.com, > > the glade/pygtk-tutorials > > were really helpful for me. > > > > > > http://www.learningpython.com/2006/05/07/creating-a-gui-using-pygtk-and-glade/ > > > > http://www.learningpython.com/2006/05/30/building-an-application-with-pygtk-and-glade/ > > > > > > th > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > Michael Langford > Phone: 404-386-0495 > Consulting: http://www.RowdyLabs.com > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080407/f05e2bc2/attachment.htm From alan.gauld at btinternet.com Mon Apr 7 20:22:06 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 7 Apr 2008 19:22:06 +0100 Subject: [Tutor] PyMOTW: difflib References: <20080406043551.966921E4014@bag.python.org><47F8EB2B.2060103@groktech.org><20080406163321.462851E400C@bag.python.org><20080406213631.503911E4019@bag.python.org><20080407011158.A950C1E400C@bag.python.org> <20080407172425.AE8851E4017@bag.python.org> Message-ID: "Dick Moores" wrote > I'm having trouble with the concept of a name in Python. > > Is a name the same as anything defined? Yes pretty much anything that has a name. It could be a variable, a class, a module, a function, anything that you can refer to or can refer to an object (bearing in mind that modules, functions and classes are objects in Python!) Its worth spending the time reading and playing with this because its a fundamental concept in Python and once understood many of the seeming anomolies become clear. I tend to think of it this way. Python does most things using dictionaries. The names we define in our code are merely keys into some semi-hidden dictionaries. The values of the dictionaries are the things the names reference - values, classes, functions etc When you import a module (import x) you reference the module dictionary so still need to derefence it (eg. sys.exit) When you import from a module (from x import *) you copy the keys into your local dictionary so you don't need to dereference them. That's almost certainly not a technically correct explanation of how importing really works but its conceptually how I think about it. :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Apr 7 20:29:21 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 7 Apr 2008 19:29:21 +0100 Subject: [Tutor] glade integration References: <8f6846bb0804070506y7d782be8i8c12fef411b3f77@mail.gmail.com><47FA3440.1050506@gmail.com> <20080407150742.GA27962@nerdshack.com> <82b4f5810804071059s852dbecvf097cb43d99b895d@mail.gmail.com> Message-ID: "Michael Langford" wrote > While on the topic of glade, does anyone know of a working gui > builder for > glade on windows? WinGlade appears to have been linkjacked or > hacked. > --Michael I tried several free or shareware/trialware GUI builders for wxPython. None of them were entirely satisfactory although SPE showed promise. The Dabo and PythonCard ones looked OK but both required learning a more or less non-standard API to wxPython... If anyone knows of a good working wxPython GUI builder I'm interested too. Alan G. From alan.gauld at btinternet.com Mon Apr 7 20:26:00 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 7 Apr 2008 19:26:00 +0100 Subject: [Tutor] create new user References: <1207558948.3158.28.camel@localhost.localdomain> Message-ID: "root" wrote > I want to write a python script in which will create a new user and > password.please tell me ,how it will be passible....??? It depends on how you are building your web app. If you are using TurboGears as your framework then it provides user admin (and security) out of the box. I suspect Django and some other frameworks will do the same. If your web app is more than trivvial (and with multiple users accounts it must be!) I would strongly recommend adopting a framework and taking time to learn it. You will be repaid many times over in saved effort and improved quality! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Apr 7 20:33:16 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 7 Apr 2008 19:33:16 +0100 Subject: [Tutor] Writing dictionaries to a file References: <41fb634c0804071009m3dfc50aeg7517ff65abf8c0d0@mail.gmail.com> Message-ID: "Jerrold Prothero" wrote > It's been suggested that if I had a clue, I'd use pickle Shelve is based on Pickle and makes a file look somewhat like a dictionary. It might do all you need and is a standard module. > looking at the csv (comma separated values) module, which also > supports > writing dictionaries out to a file, I at least wanted to understand > how it's > supposed to work with csv. Can't help there I'm afraid. Alan G. From mlangford.cs03 at gtalumni.org Mon Apr 7 20:39:57 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Mon, 7 Apr 2008 14:39:57 -0400 Subject: [Tutor] glade integration In-Reply-To: References: <8f6846bb0804070506y7d782be8i8c12fef411b3f77@mail.gmail.com> <47FA3440.1050506@gmail.com> <20080407150742.GA27962@nerdshack.com> <82b4f5810804071059s852dbecvf097cb43d99b895d@mail.gmail.com> Message-ID: <82b4f5810804071139u774dd608kef58eba78ef847b5@mail.gmail.com> I've also tried to use XRCed, but it crashes more often then a paper airplane, at least on Windows Vista. (XRC files are a XML layout manager interface that can be loaded by wxPython to separate GUI from code). If anyone knows a nice XRC builder, that would suffice. --Michael On Mon, Apr 7, 2008 at 2:29 PM, Alan Gauld wrote: > > "Michael Langford" wrote > > > While on the topic of glade, does anyone know of a working gui > > builder for > > glade on windows? WinGlade appears to have been linkjacked or > > hacked. > > --Michael > > I tried several free or shareware/trialware GUI builders for wxPython. > None of them were entirely satisfactory although SPE showed promise. > The Dabo and PythonCard ones looked OK but both required learning > a more or less non-standard API to wxPython... > > If anyone knows of a good working wxPython GUI builder I'm interested > too. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080407/14662e21/attachment-0001.htm From tannhauser at nerdshack.com Mon Apr 7 20:06:15 2008 From: tannhauser at nerdshack.com (tannhauser) Date: Mon, 7 Apr 2008 20:06:15 +0200 Subject: [Tutor] Re: glade integration In-Reply-To: <20080407150742.GA27962@nerdshack.com> References: <8f6846bb0804070506y7d782be8i8c12fef411b3f77@mail.gmail.com> <47FA3440.1050506@gmail.com> <20080407150742.GA27962@nerdshack.com> Message-ID: <20080407180615.GA15136@nerdshack.com> http://gazpacho.sicem.biz/ has a build for windows. th From malaclypse2 at gmail.com Mon Apr 7 21:08:41 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 7 Apr 2008 15:08:41 -0400 Subject: [Tutor] Writing dictionaries to a file In-Reply-To: <41fb634c0804071009m3dfc50aeg7517ff65abf8c0d0@mail.gmail.com> References: <41fb634c0804071009m3dfc50aeg7517ff65abf8c0d0@mail.gmail.com> Message-ID: <16651e80804071208v154b02d3ueacd9d0fa3b72aeb@mail.gmail.com> On Mon, Apr 7, 2008 at 1:09 PM, Jerrold Prothero wrote: > Relevant Python 2.5 documentation sections are 9.1.1 and 9.1.4. My > question boils down to this: what does writerows want as an argument > for a dictionary? A list of dictionaries. One dictionary for each row you would like to output. If you want to write out a single row, you can pass a single dictionary to writerow() instead of using writerows(). -- Jerry From kent37 at tds.net Mon Apr 7 21:33:45 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 07 Apr 2008 15:33:45 -0400 Subject: [Tutor] PyMOTW: difflib In-Reply-To: References: <20080406043551.966921E4014@bag.python.org><47F8EB2B.2060103@groktech.org><20080406163321.462851E400C@bag.python.org><20080406213631.503911E4019@bag.python.org><20080407011158.A950C1E400C@bag.python.org> <20080407172425.AE8851E4017@bag.python.org> Message-ID: <47FA7719.3080000@tds.net> Alan Gauld wrote: > "Dick Moores" wrote >> Is a name the same as anything defined? > > Yes pretty much anything that has a name. > > Its worth spending the time reading and playing with > this because its a fundamental concept in Python > and once understood many of the seeming anomolies > become clear. Yes, I strongly agree. There is a bit of an aha moment when you realize, "oh, they are all just names in namespaces." > I tend to think of it this way. Python does most things > using dictionaries. The names we define in our code > are merely keys into some semi-hidden dictionaries. > The values of the dictionaries are the things the names > reference - values, classes, functions etc Nitpick: I think of it that way too but it is not always correct. Many names are stored as key/value pairs in dicts but local variables are stored in a pre-allocated array and accessed by offset. There are probably other exceptions also. For example: In [13]: import dis In [15]: def foo(): ....: a = 10 In [16]: dis.dis(foo) 2 0 LOAD_CONST 1 (10) 3 STORE_FAST 0 (a) 6 LOAD_CONST 0 (None) 9 RETURN_VALUE The STORE_FAST instruction is storing the (reference to) the value 10 at offset 0 in the local storage section of the stack frame. > When you import a module (import x) you reference the > module dictionary so still need to derefence it (eg. sys.exit) > When you import from a module (from x import *) you > copy the keys into your local dictionary so you don't > need to dereference them. > > That's almost certainly not a technically correct explanation > of how importing really works but its conceptually how I > think about it. :-) My take on this: When you import a module, you bind a name in the current namespace to the module object. So import x binds the name 'x' to the module object. Attributes of the module - any names at global scope in the module - are available using normal attribute access syntax, e.g. x.a You can also import module x and bind it to a different name, e.g. import x as xx When you import specific attributes of a module, then the value of the module attribute is bound to a name in the current namespace. For example from x import a binds x.a to the name a. Here again, you can use a different name: from x import a as b binds x.a to the name b. from x import * is similar except every public attribute of x is bound to a local name. HTH someone! Kent From srilyk at gmail.com Mon Apr 7 21:37:15 2008 From: srilyk at gmail.com (W W) Date: Mon, 7 Apr 2008 14:37:15 -0500 Subject: [Tutor] Creating Sudoku In-Reply-To: <47FA4367.2030303@gmail.com> References: <47F9B1B2.2020107@gmail.com> <333efb450804070552rc32131ar23c6f528c6a4b5f3@mail.gmail.com> <47FA35A9.7060105@gmail.com> <333efb450804070834o3c4efc1am4d645b0afd758cb@mail.gmail.com> <47FA4367.2030303@gmail.com> Message-ID: <333efb450804071237o56c4fef4r462b963042ad49@mail.gmail.com> On Mon, Apr 7, 2008 at 10:53 AM, Luke Paireepinart wrote: > Also, did you test the code that "generates an error?" > It works fine for me. > >>> foo = {'1a': 'b'} > >>> foo['2b'] = 0 > >>> print foo['2b'] > 0 > >>> You're missing 4 spaces in front of foo['2b'] = 0, and hence, an error :P -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From kent37 at tds.net Mon Apr 7 21:45:01 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 07 Apr 2008 15:45:01 -0400 Subject: [Tutor] Creating Sudoku In-Reply-To: <47FA4367.2030303@gmail.com> References: <47F9B1B2.2020107@gmail.com> <333efb450804070552rc32131ar23c6f528c6a4b5f3@mail.gmail.com> <47FA35A9.7060105@gmail.com> <333efb450804070834o3c4efc1am4d645b0afd758cb@mail.gmail.com> <47FA4367.2030303@gmail.com> Message-ID: <47FA79BD.4040001@tds.net> Luke Paireepinart wrote: > You mean that the dictionary _definition_ ignores whitespace between > elements? > > That's not a feature of dictionaries, but of the comma. > You can easily do the following: > x = [1, 2, > 3, 4] > if you want. > Same with tuples and various other things. > Python just realizes that if it doesn't see a closing brace/bracket, but > sees a comma, that more will probably be coming on the next line. That's not quite right. It is the open brace/bracket/parenthesis that tells Python to continue the line; the comma is not part of it. For example, this works: In [17]: a=1,2,3,4 but inserting a newline, even after a comma, breaks it into two statements: In [24]: a=1,2, In [25]: 3,4 Out[25]: (3, 4) In [26]: a Out[26]: (1, 2) OTOH, if there is an open bracket, the comma can come on the next line: In [21]: a=[1 ....: ,2,3,4] In [22]: a Out[22]: [1, 2, 3, 4] Kent From kent37 at tds.net Mon Apr 7 21:50:05 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 07 Apr 2008 15:50:05 -0400 Subject: [Tutor] Writing dictionaries to a file In-Reply-To: <41fb634c0804071009m3dfc50aeg7517ff65abf8c0d0@mail.gmail.com> References: <41fb634c0804071009m3dfc50aeg7517ff65abf8c0d0@mail.gmail.com> Message-ID: <47FA7AED.7010505@tds.net> Jerrold Prothero wrote: > > I've been trying to understand how writing a dictionary to a file & reading > it back should work. > > It's been suggested that if I had a clue, I'd use pickle, but since I > started > looking at the csv (comma separated values) module, which also supports > writing dictionaries out to a file, I at least wanted to understand how it's > supposed to work with csv. The csv module writes one dictionary per row of the CSV file. It is intended for storing repeated data, though you could just read and write a single row. When it reads the data back, everything will be returned as a string. This may not be the best fit for your situation. Kent From gtxy20 at gmail.com Mon Apr 7 22:44:58 2008 From: gtxy20 at gmail.com (GTXY20) Date: Mon, 7 Apr 2008 16:44:58 -0400 Subject: [Tutor] C# defaultdict question Message-ID: <39cb7e5d0804071344u2e85acco585f5bf34499bb10@mail.gmail.com> Hello all, Sadly I need to convert a great python application into C# .Net. I have been pretty successful so far but I was wondering if anyone knew of something similar to a python defaultdict(int) in C#. In python I am doing: g = {} (where the value in the key value pair is a tuple of values) f = defaultdict(int) In order to get totals of particular values within each tuple within the complete dictionary g I do: for values in g.values(): for item in values: f[item]+=1 I can accomplish this in C# by converting the values (which are stored as a List) from a C# dictionary to an Array then looping through the Array but was wondering if anyone had a different take or thoughts how to do this in C# as easily as it is done in Python. Thanks. G. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080407/37553148/attachment.htm From rdm at rcblue.com Mon Apr 7 23:57:41 2008 From: rdm at rcblue.com (Dick Moores) Date: Mon, 07 Apr 2008 14:57:41 -0700 Subject: [Tutor] PyMOTW: difflib In-Reply-To: <47FA7719.3080000@tds.net> References: <20080406043551.966921E4014@bag.python.org> <47F8EB2B.2060103@groktech.org> <20080406163321.462851E400C@bag.python.org> <20080406213631.503911E4019@bag.python.org> <20080407011158.A950C1E400C@bag.python.org> <20080407172425.AE8851E4017@bag.python.org> <47FA7719.3080000@tds.net> Message-ID: <20080407215752.E0AD81E400A@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080407/1d1e6b5f/attachment.htm From rdm at rcblue.com Tue Apr 8 00:15:32 2008 From: rdm at rcblue.com (Dick Moores) Date: Mon, 07 Apr 2008 15:15:32 -0700 Subject: [Tutor] PyMOTW: difflib In-Reply-To: <7.1.0.9.2.20080407143904.080bff70@rcblue.com> References: <20080406043551.966921E4014@bag.python.org> <47F8EB2B.2060103@groktech.org> <20080406163321.462851E400C@bag.python.org> <20080406213631.503911E4019@bag.python.org> <20080407011158.A950C1E400C@bag.python.org> <20080407172425.AE8851E4017@bag.python.org> <47FA7719.3080000@tds.net> <7.1.0.9.2.20080407143904.080bff70@rcblue.com> Message-ID: <20080407221545.5E6021E4013@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080407/bd40476c/attachment-0001.htm From kent37 at tds.net Tue Apr 8 00:26:18 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 07 Apr 2008 18:26:18 -0400 Subject: [Tutor] dis.dis (was: PyMOTW: difflib) In-Reply-To: <20080407215752.E0AD81E400A@bag.python.org> References: <20080406043551.966921E4014@bag.python.org> <47F8EB2B.2060103@groktech.org> <20080406163321.462851E400C@bag.python.org> <20080406213631.503911E4019@bag.python.org> <20080407011158.A950C1E400C@bag.python.org> <20080407172425.AE8851E4017@bag.python.org> <47FA7719.3080000@tds.net> <20080407215752.E0AD81E400A@bag.python.org> Message-ID: <47FA9F8A.3070208@tds.net> Dick Moores wrote: > Could you give a blow-by-blow on the dis.dis()? That's a bit more than I have time for ATM but it's not really that hard to at least get a general understanding of what is going on. Here is a list of the bytecode instructions that may help: http://docs.python.org/lib/bytecodes.html Kent From alan.gauld at btinternet.com Tue Apr 8 01:52:25 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Apr 2008 00:52:25 +0100 Subject: [Tutor] PyMOTW: difflib References: <20080406043551.966921E4014@bag.python.org><47F8EB2B.2060103@groktech.org><20080406163321.462851E400C@bag.python.org><20080406213631.503911E4019@bag.python.org><20080407011158.A950C1E400C@bag.python.org><20080407172425.AE8851E4017@bag.python.org> <47FA7719.3080000@tds.net> <20080407215752.E0AD81E400A@bag.python.org> Message-ID: "Dick Moores" wrote > Could you give a blow-by-blow on the dis.dis()? I'll have a go but I've never actually studied Python P-Code, this is based on my 8080 and 68000 assembler experience! > In [22]: def f(x): > ....: if x%2: > ....: return "odd" > ....: else: > ....: return "even" > ....: > ....: > > In [23]: dis.dis(f) > 2 0 LOAD_FAST 0 (x) > 3 LOAD_CONST 1 (2) load x and 2 into two temporary storage areas (registers in conventional assembler) > 6 BINARY_MODULO Do the modulo operation and store the result in a temporary location (accumulator in assembler) > 7 JUMP_IF_FALSE 8 (to 18) If the result is zero(false) go to instruction 18 (I don't know what the 8 signifies, I thought a program counter offset but that would make it a jump to 15...) > 10 POP_TOP else (ie modulo result is non zero) pop the top - I'm not sure what that does exactly but I assume it pops a value of some stack into the accumulator area? > 3 11 LOAD_CONST 2 ('odd') > 14 RETURN_VALUE Load 'odd' into storage area 2 and then return it? > 15 JUMP_FORWARD 5 (to 23) Not sure about this bit... > >> 18 POP_TOP This was target of our previous jump if false instruiction > 5 19 LOAD_CONST 3 ('even') > 22 RETURN_VALUE So it loads 'even' and then returns it to the caller. > >> 23 LOAD_CONST 0 (None) > 26 RETURN_VALUE I assume this is the default return value in case there is no other returns, so not used here. I'm no expert but I'm sure someone else can fix up my errors but its very like any other kind of assembler - you just need to look up the behaviour of each op code. Alan G. From marc.tompkins at gmail.com Tue Apr 8 02:13:49 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 7 Apr 2008 17:13:49 -0700 Subject: [Tutor] PyMOTW: difflib In-Reply-To: References: <20080406043551.966921E4014@bag.python.org> <20080406213631.503911E4019@bag.python.org> <20080407011158.A950C1E400C@bag.python.org> <20080407172425.AE8851E4017@bag.python.org> <47FA7719.3080000@tds.net> <20080407215752.E0AD81E400A@bag.python.org> Message-ID: <40af687b0804071713u1db01e77m223541d8f9b65670@mail.gmail.com> On Mon, Apr 7, 2008 at 4:52 PM, Alan Gauld wrote: > "Dick Moores" wrote > > > Could you give a blow-by-blow on the dis.dis()? > > I'll have a go but I've never actually studied Python P-Code, > this is based on my 8080 and 68000 assembler experience! > ... > I'm no expert but I'm sure someone else can fix up my errors > but its very like any other kind of assembler - you just need > to look up the behaviour of each op code. > > Alan G. > > Stop it, you two! You're bringing back painful memories... I do believe I'm having a flashback to my Z-80 days... The horror! The horror! Has there been any research on assembler-induced PTSD, I wonder? Thank Guido for Python, where we can forget all our low-level cares... or at least we COULD... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080407/8d0fc872/attachment.htm From kent37 at tds.net Tue Apr 8 04:20:22 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 07 Apr 2008 22:20:22 -0400 Subject: [Tutor] PyMOTW: difflib In-Reply-To: References: <20080406043551.966921E4014@bag.python.org><47F8EB2B.2060103@groktech.org><20080406163321.462851E400C@bag.python.org><20080406213631.503911E4019@bag.python.org><20080407011158.A950C1E400C@bag.python.org><20080407172425.AE8851E4017@bag.python.org> <47FA7719.3080000@tds.net> <20080407215752.E0AD81E400A@bag.python.org> Message-ID: <47FAD666.6090200@tds.net> Alan Gauld wrote: > "Dick Moores" wrote > >> Could you give a blow-by-blow on the dis.dis()? > > I'll have a go but I've never actually studied Python P-Code, > this is based on my 8080 and 68000 assembler experience! Some hits, some misses. I'll correct to the best of my knowledge. One thing you need to know is that the Python VM is a stack machine, not register-based. Think Forth or Postscript, not 8080. > >> In [22]: def f(x): >> ....: if x%2: >> ....: return "odd" >> ....: else: >> ....: return "even" >> ....: >> ....: >> >> In [23]: dis.dis(f) >> 2 0 LOAD_FAST 0 (x) >> 3 LOAD_CONST 1 (2) > > load x and 2 into two temporary storage areas > (registers in conventional assembler) No, it pushes x and 2 onto the stack. 0 and 1 are the indices into the local variable list (in the stack frame) and the function's constant list (part of the function). The values in parentheses are helpful comments by dis, not part of the code itself. > >> 6 BINARY_MODULO > > Do the modulo operation and store the result in a temporary > location (accumulator in assembler) The arguments are the top two items on the stack, the result is left on the stack. > >> 7 JUMP_IF_FALSE 8 (to 18) > > If the result is zero(false) Yes, but not the way you think it works. It is checking the top of the stack (TOS in the docs), not some flag set by the modulo operation the way an 8080 would. > go to instruction 18 > (I don't know what the 8 signifies, I thought a > program counter offset but that would make it > a jump to 15...) Probably an offset to the PC value of the next instruction. Again, the part in parens is a helpful comment. > >> 10 POP_TOP > > else (ie modulo result is non zero) pop the top - I'm > not sure what that does exactly but I assume it pops > a value of some stack into the accumulator area? Just pops the stack, the value is no longer needed after the test. > >> 3 11 LOAD_CONST 2 ('odd') >> 14 RETURN_VALUE > > Load 'odd' into storage area 2 and then return it? Load odd *from* offset 2 to the stack and return it. > >> 15 JUMP_FORWARD 5 (to 23) > > Not sure about this bit... I think this is junk. The Python compiler does very little optimization, even simple peephole optimizations. This looks like boilerplate code emitted to skip the 'else' clause. The boilerplate is left in even though the code is not reachable. > >> >> 18 POP_TOP > > This was target of our previous jump if false instruiction > >> 5 19 LOAD_CONST 3 ('even') >> 22 RETURN_VALUE > > So it loads 'even' and then returns it to the caller. > >> >> 23 LOAD_CONST 0 (None) >> 26 RETURN_VALUE > > I assume this is the default return value in case there is no > other returns, so not used here. More leftover junk. BTW there are several recipes in the cookbook that rely on hacking the bytecodes directly from Python. Here are some: http://tinyurl.com/6xn55p This one by Raymond Hettinger optimizes references to globals by automatically converting them to references to locals. "The speed-up is substantial (trading one or more dictionary lookups for a single C-speed array lookup)." http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 Kent From rabidpoobear at gmail.com Tue Apr 8 09:25:33 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 08 Apr 2008 02:25:33 -0500 Subject: [Tutor] Creating Sudoku In-Reply-To: <47FA79BD.4040001@tds.net> References: <47F9B1B2.2020107@gmail.com> <333efb450804070552rc32131ar23c6f528c6a4b5f3@mail.gmail.com> <47FA35A9.7060105@gmail.com> <333efb450804070834o3c4efc1am4d645b0afd758cb@mail.gmail.com> <47FA4367.2030303@gmail.com> <47FA79BD.4040001@tds.net> Message-ID: <47FB1DED.5010107@gmail.com> > That's not quite right. It is the open brace/bracket/parenthesis that > tells Python to continue the line; the comma is not part of it. [snip] Thanks for the correction, Kent. -Luke From Garry.Willgoose at newcastle.edu.au Tue Apr 8 09:12:25 2008 From: Garry.Willgoose at newcastle.edu.au (Garry Willgoose) Date: Tue, 08 Apr 2008 17:12:25 +1000 Subject: [Tutor] capturing exceptions from an exec statement Message-ID: I'm writing a (very simple) command line window for use within my Tkinter GUI menu driven program (Aside: I want to provide a Matlab like command line capability within an otherwise menu driven program ... but where the script language is Python). The guts of executing the command are (where commandtext is a text variable captured from my command line window) try: exec(commandtext) except: print 'failed to execute command' # we'll do something more sophisticated in due course The question is if commandtext contains invalid python I thought exec raised an exception that I could capture. I seem unable to get this to throw an exception no matter what is in commandtext. I assume I'm missing something simple here. Alternatively should I open a process with popen ... I want to be able to modify variables in the existing scope and the way I read popen I can't do that. ==================================================================== Prof Garry Willgoose, Australian Professorial Fellow in Environmental Engineering, Director, Centre for Climate Impact Management (C2IM), School of Engineering, The University of Newcastle, Callaghan, 2308 Australia. Centre webpage: www.c2im.org.au Phone: (International) +61 2 4921 6050 (Tues-Fri AM); +61 2 6545 9574 (Fri PM-Mon) FAX: (International) +61 2 4921 6991 (Uni); +61 2 6545 9574 (personal and Telluric) Env. Engg. Secretary: (International) +61 2 4921 6042 email: garry.willgoose at newcastle.edu.au; g.willgoose at telluricresearch.com email-for-life: garry.willgoose at alum.mit.edu personal webpage: www.telluricresearch.com/garry ==================================================================== "Do not go where the path may lead, go instead where there is no path and leave a trail" Ralph Waldo Emerson ==================================================================== From andreas at kostyrka.org Tue Apr 8 10:18:37 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 08 Apr 2008 10:18:37 +0200 Subject: [Tutor] capturing exceptions from an exec statement In-Reply-To: References: Message-ID: <1207642717.7649.0.camel@localhost> Python 2.4.5 (#2, Mar 12 2008, 00:15:51) [GCC 4.2.3 (Debian 4.2.3-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> try: ... exec("raise ValueError") ... except: ... print "raised some exception" ... import sys ... print sys.exc_info() ... raised some exception (, , ) >>> Something like this? Andreas Am Dienstag, den 08.04.2008, 17:12 +1000 schrieb Garry Willgoose: > I'm writing a (very simple) command line window for use within my > Tkinter GUI menu driven program (Aside: I want to provide a Matlab > like command line capability within an otherwise menu driven > program ... but where the script language is Python). The guts of > executing the command are (where commandtext is a text variable > captured from my command line window) > > try: > exec(commandtext) > except: > print 'failed to execute command' # we'll do something > more sophisticated in due course > > The question is if commandtext contains invalid python I thought exec > raised an exception that I could capture. I seem unable to get this > to throw an exception no matter what is in commandtext. I assume I'm > missing something simple here. > > Alternatively should I open a process with popen ... I want to be > able to modify variables in the existing scope and the way I read > popen I can't do that. > > > ==================================================================== > Prof Garry Willgoose, > Australian Professorial Fellow in Environmental Engineering, > Director, Centre for Climate Impact Management (C2IM), > School of Engineering, The University of Newcastle, > Callaghan, 2308 > Australia. > > Centre webpage: www.c2im.org.au > > Phone: (International) +61 2 4921 6050 (Tues-Fri AM); +61 2 6545 9574 > (Fri PM-Mon) > FAX: (International) +61 2 4921 6991 (Uni); +61 2 6545 9574 (personal > and Telluric) > Env. Engg. Secretary: (International) +61 2 4921 6042 > > email: garry.willgoose at newcastle.edu.au; > g.willgoose at telluricresearch.com > email-for-life: garry.willgoose at alum.mit.edu > personal webpage: www.telluricresearch.com/garry > ==================================================================== > "Do not go where the path may lead, go instead where there is no path > and leave a trail" > Ralph Waldo Emerson > ==================================================================== > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080408/ef8fcb5b/attachment.pgp From alan.gauld at btinternet.com Tue Apr 8 10:48:38 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Apr 2008 09:48:38 +0100 Subject: [Tutor] capturing exceptions from an exec statement References: <1207642717.7649.0.camel@localhost> Message-ID: "Andreas Kostyrka" wrote >>> try: >... exec("raise ValueError") >... except: >... print "raised some exception" >... import sys >... print sys.exc_info() >... >raised some exception >(, instance at >0xb7d6738c>, ) > >Something like this? I think the Gary means he wants an exception raised if the code fed to exec is invalid, not if the code raises an exception. But exec seemed to raise all the usual errors in the cases I tried. Gary, can you give us a concrete example of the kind of error you expect but don't see? Also, I don't know if you have come across the cmd module but it might be useful in this context... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From Garry.Willgoose at newcastle.edu.au Tue Apr 8 11:05:47 2008 From: Garry.Willgoose at newcastle.edu.au (Garry Willgoose) Date: Tue, 8 Apr 2008 19:05:47 +1000 Subject: [Tutor] capturing exceptions from an exec statement In-Reply-To: <1207642717.7649.0.camel@localhost> References: <1207642717.7649.0.camel@localhost> Message-ID: <2B09598B-5B4F-407A-BBED-1EE9F1D00620@newcastle.edu.au> Andreas, Alan, Oops ... I'm embarassed to admit the problem seems to have gone away. I don't know maybe in my testing I fed it some valid python. But anyway I made sure to feed it something that was invalid it now works fine. Its been a long day .... Sorry to bother you. Alan thanks for the reference to module cmd ... I didn't know about it and I'll have a look at it to see if its a more robust soln to my problem. > Python 2.4.5 (#2, Mar 12 2008, 00:15:51) > [GCC 4.2.3 (Debian 4.2.3-2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> try: > ... exec("raise ValueError") > ... except: > ... print "raised some exception" > ... import sys > ... print sys.exc_info() > ... > raised some exception > (, > , at 0xb7d65aa4>) >>>> > > Something like this? > > Andreas > > Am Dienstag, den 08.04.2008, 17:12 +1000 schrieb Garry Willgoose: >> I'm writing a (very simple) command line window for use within my >> Tkinter GUI menu driven program (Aside: I want to provide a Matlab >> like command line capability within an otherwise menu driven >> program ... but where the script language is Python). The guts of >> executing the command are (where commandtext is a text variable >> captured from my command line window) >> >> try: >> exec(commandtext) >> except: >> print 'failed to execute command' # we'll do something >> more sophisticated in due course >> >> The question is if commandtext contains invalid python I thought exec >> raised an exception that I could capture. I seem unable to get this >> to throw an exception no matter what is in commandtext. I assume I'm >> missing something simple here. >> >> Alternatively should I open a process with popen ... I want to be >> able to modify variables in the existing scope and the way I read >> popen I can't do that. >> >> >> ==================================================================== >> Prof Garry Willgoose, >> Australian Professorial Fellow in Environmental Engineering, >> Director, Centre for Climate Impact Management (C2IM), >> School of Engineering, The University of Newcastle, >> Callaghan, 2308 >> Australia. >> >> Centre webpage: www.c2im.org.au >> >> Phone: (International) +61 2 4921 6050 (Tues-Fri AM); +61 2 6545 9574 >> (Fri PM-Mon) >> FAX: (International) +61 2 4921 6991 (Uni); +61 2 6545 9574 (personal >> and Telluric) >> Env. Engg. Secretary: (International) +61 2 4921 6042 >> >> email: garry.willgoose at newcastle.edu.au; >> g.willgoose at telluricresearch.com >> email-for-life: garry.willgoose at alum.mit.edu >> personal webpage: www.telluricresearch.com/garry >> ==================================================================== >> "Do not go where the path may lead, go instead where there is no path >> and leave a trail" >> Ralph Waldo Emerson >> ==================================================================== >> >> >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor ==================================================================== Prof Garry Willgoose, Australian Professorial Fellow in Environmental Engineering, Director, Centre for Climate Impact Management (C2IM), School of Engineering, The University of Newcastle, Callaghan, 2308 Australia. Centre webpage: www.c2im.org.au Phone: (International) +61 2 4921 6050 (Tues-Fri AM); +61 2 6545 9574 (Fri PM-Mon) FAX: (International) +61 2 4921 6991 (Uni); +61 2 6545 9574 (personal and Telluric) Env. Engg. Secretary: (International) +61 2 4921 6042 email: garry.willgoose at newcastle.edu.au; g.willgoose at telluricresearch.com email-for-life: garry.willgoose at alum.mit.edu personal webpage: www.telluricresearch.com/garry ==================================================================== "Do not go where the path may lead, go instead where there is no path and leave a trail" Ralph Waldo Emerson ==================================================================== From srilyk at gmail.com Tue Apr 8 12:50:15 2008 From: srilyk at gmail.com (W W) Date: Tue, 8 Apr 2008 05:50:15 -0500 Subject: [Tutor] Writing dictionaries to a file In-Reply-To: <47FA7AED.7010505@tds.net> References: <41fb634c0804071009m3dfc50aeg7517ff65abf8c0d0@mail.gmail.com> <47FA7AED.7010505@tds.net> Message-ID: <333efb450804080350p503e2df8pa76bd8a06386222@mail.gmail.com> On Mon, Apr 7, 2008 at 2:50 PM, Kent Johnson wrote: > Jerrold Prothero wrote: > > > > I've been trying to understand how writing a dictionary to a file & reading > > it back should work. > > > > It's been suggested that if I had a clue, I'd use pickle, but since I > > started > > looking at the csv (comma separated values) module, which also supports > > writing dictionaries out to a file, I at least wanted to understand how it's > > supposed to work with csv. > > The csv module writes one dictionary per row of the CSV file. It is > intended for storing repeated data, though you could just read and write > a single row. When it reads the data back, everything will be returned > as a string. This may not be the best fit for your situation. I was toying around with dictionaries/files/etc, and it's possible to loop over the dictionary, writing each key/value pair to the file on one line with a comma between them for items in dictionary.items(): file.write("%s,%s\n" % items) Then it's simple enough to read the file using csv.reader() (I think that's the right one) which turns the values into lists. So {3:"Hello"} => "3","Hello" => ['3', 'Hello], if you were to loop over the output (I haven't toyed with this, so I'm not sure if running csv.reader() on readline(s?) would be faster, or some sort of loading the lists into some other type of object), you could easily assign them to a dict: for row in filedata: mydict[row[0]] = row[1] And if you knew certain values might be ints, you could use try: mydict[int(row[0])] = row[1] except ValueError: mydict[row[0]] = row[1] Hope this helps! -Wayne From kent37 at tds.net Tue Apr 8 13:30:00 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 08 Apr 2008 07:30:00 -0400 Subject: [Tutor] Creating Sudoku In-Reply-To: <47FB1DED.5010107@gmail.com> References: <47F9B1B2.2020107@gmail.com> <333efb450804070552rc32131ar23c6f528c6a4b5f3@mail.gmail.com> <47FA35A9.7060105@gmail.com> <333efb450804070834o3c4efc1am4d645b0afd758cb@mail.gmail.com> <47FA4367.2030303@gmail.com> <47FA79BD.4040001@tds.net> <47FB1DED.5010107@gmail.com> Message-ID: <47FB5738.2050007@tds.net> Luke Paireepinart wrote: > >> That's not quite right. It is the open brace/bracket/parenthesis that >> tells Python to continue the line; the comma is not part of it. [snip] > Thanks for the correction, Kent. You're welcome; here is a reference: http://docs.python.org/ref/implicit-joining.html Kent From kent37 at tds.net Tue Apr 8 13:42:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 08 Apr 2008 07:42:36 -0400 Subject: [Tutor] Writing dictionaries to a file In-Reply-To: <333efb450804080350p503e2df8pa76bd8a06386222@mail.gmail.com> References: <41fb634c0804071009m3dfc50aeg7517ff65abf8c0d0@mail.gmail.com> <47FA7AED.7010505@tds.net> <333efb450804080350p503e2df8pa76bd8a06386222@mail.gmail.com> Message-ID: <47FB5A2C.3050106@tds.net> W W wrote: > I was toying around with dictionaries/files/etc, and it's possible to > loop over the dictionary, writing each key/value pair to the file on > one line with a comma between them > And if you knew certain values might be ints, you could use > > try: mydict[int(row[0])] = row[1] This is converting the key, not the value. > > except ValueError: mydict[row[0]] = row[1] And if the value looks like an int but shouldn't be interpreted as one? For example a zip code? This is getting crazy enough that I have to show how easy it is to do with pickle. I used a dict with a mix of types for both keys and values to show that they are restored correctly: To save a dict in a pickle: In [27]: from pickle import dump, load In [38]: d = { 'a':1, 'b':'2', ('c', 'd'):(3, 4) } In [39]: f=open('pickle.dat', 'w') In [40]: dump(d, f) In [41]: f.close() To load the dict back: In [42]: f=open('pickle.dat') In [43]: d2=load(f) In [44]: f.close() In [45]: d2 Out[45]: {'a': 1, 'b': '2', ('c', 'd'): (3, 4)} Note that this is the simplest example. There are some performance improvements possible - use a binary pickle protocol and cPickle - but for most usage I don't think you will notice the difference. Kent From dineshbvadhia at hotmail.com Tue Apr 8 19:35:37 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Tue, 8 Apr 2008 10:35:37 -0700 Subject: [Tutor] Google App Engine Message-ID: Hi! Google announced an app server that allows pure Python developed applications/services to use their infrastructure. This maybe of use to many on this list. Further details can be found at: http://appengine.google.com/ The SDK include a modified Python 2.5.2 and Django 0.96.1, WebOb 0.9 and PyYAML 3.05. As an aside, does anyone here have experience of WebOb and specifically is it a mini web framework (like webpy)? Cheers Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080408/a38dc705/attachment.htm From andreas at kostyrka.org Tue Apr 8 19:50:35 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 08 Apr 2008 19:50:35 +0200 Subject: [Tutor] Google App Engine In-Reply-To: References: Message-ID: <1207677035.7649.20.camel@localhost> To summerize, it's Python 2.5.2, gutted to remove any chance of storing anything local. Plus you can define patterns that get mapped to Python CGI scripts. Included are also a number of APIs e.g. for data storage (that look at first glance visually similiar to Django models), an API to authenticate users against the Google user database, Network access, and so on. No long running code, no threads, no forks, no exec, and so on. All in all it looks interestingly, the only drawback being that the initial batch of 10000 accounts are already taken ;( Andreas Am Dienstag, den 08.04.2008, 10:35 -0700 schrieb Dinesh B Vadhia: > Hi! Google announced an app server that allows pure Python developed > applications/services to use their infrastructure. This maybe of use > to many on this list. Further details can be found at: > http://appengine.google.com/ > > The SDK include a modified Python 2.5.2 and Django 0.96.1, WebOb 0.9 > and PyYAML 3.05. > > As an aside, does anyone here have experience of WebOb and > specifically is it a mini web framework (like webpy)? > > Cheers > > Dinesh > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080408/49433a79/attachment.pgp From hcvst at zabox.eu Wed Apr 9 10:40:10 2008 From: hcvst at zabox.eu (H.C. v. Stockhausen) Date: Wed, 9 Apr 2008 10:40:10 +0200 Subject: [Tutor] Google App Engine In-Reply-To: References: Message-ID: <20080409084010.GA12839@h736144.serverkompetenz.net> On Tue, Apr 08, 2008 at 10:35:37AM -0700, Dinesh B Vadhia wrote: > Hi! Google announced an app server that allows pure Python developed applications/services to use their infrastructure. This maybe of use to many on this list. Further details can be found at: http://appengine.google.com/ > > The SDK include a modified Python 2.5.2 and Django 0.96.1, WebOb 0.9 and PyYAML 3.05. > > As an aside, does anyone here have experience of WebOb and specifically is it a mini web framework (like webpy)? > > Cheers > > Dinesh Hi, how safe is it to just run the dev server, as I didn't get one of the prerelease accounts either. I'm running one in a XEN sandbox on Debian Etch using the Nginxi HTTP server to proxy domain:80 to localhost:8080 Regards HC From kent37 at tds.net Wed Apr 9 14:04:03 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 09 Apr 2008 08:04:03 -0400 Subject: [Tutor] Google App Engine In-Reply-To: <20080409084010.GA12839@h736144.serverkompetenz.net> References: <20080409084010.GA12839@h736144.serverkompetenz.net> Message-ID: <47FCB0B3.5090606@tds.net> H.C. v. Stockhausen wrote: > On Tue, Apr 08, 2008 at 10:35:37AM -0700, Dinesh B Vadhia wrote: >> Hi! Google announced an app server > how safe is it to just run the dev server, as I didn't get one of the prerelease accounts either. If by 'safe' you mean 'secure', I don't really know but I guess it is probably pretty safe. The dev server is based on BaseHTTPServer and other elements of the Python std lib. If by 'safe' you mean 'robust', then no. I wouldn't use the dev server for a production server: - The dev server is single-threaded - it only serves one request at a time. - The datastore is written in Python so it will probably not match the performance of PostgreSQL or the native Google Apps datastore. - The default datastore stores all objects in memory so it will not scale well. - User login is stubbed out There is a google group where you might get a more detailed answer: http://groups.google.com/group/google-appengine Kent From gloomdemon at gmail.com Wed Apr 9 14:29:35 2008 From: gloomdemon at gmail.com (Gloom Demon) Date: Wed, 9 Apr 2008 15:29:35 +0300 Subject: [Tutor] Tutor Digest, Vol 50, Issue 9 In-Reply-To: References: Message-ID: <38446940804090529p8fb2859x2e9c82d0b376d355@mail.gmail.com> Hello :-) Can someone please explain to me ho can I find out how many elements are there in one record of a list? The problem is as follows: I have a txt file from which I read data into Python. The file looks something like this: 01 bla bla bla 23,15 2345,67 02 alb alb 2,4 890,1 03 bal bla alb lab 567,12345 87,45 .... I need to be able to discriminate the string parts from the numeric ones. Since the number of words in the file can vary, I have to be able to find out when they are finished and when the floats come in mystring[0]-> always integer mystring[1]-> string (word) mystring[1-X]-> last string (word) mystring[X+1]-> always float mystring[X+2]-> always float it would have been nice if I could find out the total number of the fields in one list record so that I could then adress them via a variable. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080409/5cc78f6f/attachment.htm From pylinuxian at gmail.com Wed Apr 9 14:50:25 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Wed, 9 Apr 2008 12:50:25 +0000 Subject: [Tutor] socket / over network In-Reply-To: References: <47F4D421.7000007@tds.net> <47F4E6C5.8000809@tds.net> <47F4EAF2.6050305@tds.net> <47F4F51F.8030309@comcast.net> <47F981F5.6080401@comcast.net> Message-ID: in case it helps here is a very basic example: import MySQLdb, glob, os, re, shutil from ftplib import FTP a=file_to_fetch ftp=FTP('ftp_server') ftp.login('user_name','password') try: aa=ftp.nlst(a) b='/home/a' bb=os.path.basename(aa[0]) e=os.path.basename(b) c=open(b, 'wb') ftp.retrbinary('RETR '+aa[0], c.write) c.close() well u just copied some pieces of my own code to maybe help you get started with ftp as you maybe don't know that you have to open a file for writing & then write into it the stream from ftp retrieve cmd. On Mon, Apr 7, 2008 at 7:16 AM, Alan Gauld wrote: > > "Nathan McBride" wrote > > > Going off of wha tyou said, if I choose to use ftp, is there a way i > > could do everything from within python including the server to get > > the > > files? Is there like a ftp module for python to help in the passing > > of > > the files between the computers? > > Yes, there is an ftp module in the standard library. > > Alan G > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080409/d2bab293/attachment.htm From ruivaldo at gmail.com Wed Apr 9 14:59:01 2008 From: ruivaldo at gmail.com (rui) Date: Wed, 9 Apr 2008 09:59:01 -0300 Subject: [Tutor] Tutor Digest, Vol 50, Issue 9 In-Reply-To: <38446940804090529p8fb2859x2e9c82d0b376d355@mail.gmail.com> References: <38446940804090529p8fb2859x2e9c82d0b376d355@mail.gmail.com> Message-ID: Hi Gloom, You should give a look at the method "split" (of the string objects) and int. The first is used do break a string into smaller pieces and the other to convert a string to an int object, raising an exception when it is not possible. On Wed, Apr 9, 2008 at 9:29 AM, Gloom Demon wrote: > Hello :-) > > Can someone please explain to me ho can I find out how many elements are > there in one record of a list? > > The problem is as follows: > > I have a txt file from which I read data into Python. > > The file looks something like this: > > 01 bla bla bla 23,15 2345,67 > 02 alb alb 2,4 890,1 > 03 bal bla alb lab 567,12345 87,45 > .... > > I need to be able to discriminate the string parts from the numeric ones. > > Since the number of words in the file can vary, I have to be able to find out when they are finished > and when the floats come in > > mystring[0]-> always integer > mystring[1]-> string (word) > mystring[1-X]-> last string (word) > mystring[X+1]-> always float > mystring[X+2]-> always float > > it would have been nice if I could find out the total number of the fields > in one list record so that I could then adress them via a variable. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Ruivaldo Neto -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080409/d630cfd5/attachment.htm From kent37 at tds.net Wed Apr 9 15:00:29 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 09 Apr 2008 09:00:29 -0400 Subject: [Tutor] Tutor Digest, Vol 50, Issue 9 In-Reply-To: <38446940804090529p8fb2859x2e9c82d0b376d355@mail.gmail.com> References: <38446940804090529p8fb2859x2e9c82d0b376d355@mail.gmail.com> Message-ID: <47FCBDED.4040007@tds.net> Gloom Demon wrote: > Hello :-) > > Can someone please explain to me ho can I find out how many elements are > there in one record of a list? The len() function gives the length of a list. > I have a txt file from which I read data into Python. > > The file looks something like this: > > 01 bla bla bla 23,15 2345,67 > 02 alb alb 2,4 890,1 > 03 bal bla alb lab 567,12345 87,45 > .... > > I need to be able to discriminate the string parts from the numeric ones. > Since the number of words in the file can vary, I have to be able to find out when they are finished > and when the floats come in You can also use slice indexing with negative numbers to index from the end: In [50]: data = '''01 bla bla bla 23,15 2345,67 ....: 02 alb alb 2,4 890,1 ....: 03 bal bla alb lab 567,12345 87,45 ....: '''.splitlines() In [51]: for line in data: ....: line = line.split() # Break the line at whitespace ....: print len(line) # Number of elements in the line ....: print line[1:-2] ....: print line[-2:] ....: print ....: ....: 6 ['bla', 'bla', 'bla'] ['23,15', '2345,67'] 5 ['alb', 'alb'] ['2,4', '890,1'] 7 ['bal', 'bla', 'alb', 'lab'] ['567,12345', '87,45'] Negative indices index from the end of the list, so line[1:-2] gives you the elements from line[1] up to but not including line[-2] which is the next-to-last element. Kent From pylinuxian at gmail.com Wed Apr 9 15:32:17 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Wed, 9 Apr 2008 13:32:17 +0000 Subject: [Tutor] Tutor Digest, Vol 50, Issue 9 In-Reply-To: References: <38446940804090529p8fb2859x2e9c82d0b376d355@mail.gmail.com> Message-ID: On Wed, Apr 9, 2008 at 12:59 PM, rui wrote: > Hi Gloom, > > > > You should give a look at the method "split" (of the string objects) and > int. > > The first is used do break a string into smaller pieces and the other to > convert a string to an int object, raising an exception when it is not > possible. > > > On Wed, Apr 9, 2008 at 9:29 AM, Gloom Demon wrote: > > > Hello :-) > > > > Can someone please explain to me ho can I find out how many elements are > > there in one record of a list? > > > > The problem is as follows: > > > > I have a txt file from which I read data into Python. > > > > The file looks something like this: > > > > 01 bla bla bla 23,15 2345,67 > > 02 alb alb 2,4 890,1 > > 03 bal bla alb lab 567,12345 87,45 > > .... > > > > I need to be able to discriminate the string > > parts from the numeric ones. > > > > Since the number of words in the file can vary, I have to be able to find out when they are finished > > and when the floats come in > > > > mystring[0]-> always integer > > mystring[1]-> string (word) > > mystring[1-X]-> last string (word) > > mystring[X+1]-> always float > > mystring[X+2]-> always float > > > > it would have been nice if I could find out the total number of the > > fields in one list record so that I could then adress them via a variable. > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -- > Ruivaldo Neto > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > my guess would be something like this : a=open('/home/some_file.txt') for line in a: tmp_list_1=line.split() num_floats=0 num_strings=0 for i in tmp_list_1: if type(i) == int: num_floats=num_floats+1 else: num_strings=num_strings+1 if you explain more you case maybe i can get more ideas - hope this helps -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080409/fafd8243/attachment-0001.htm From kepalapening at gmail.com Wed Apr 9 15:53:18 2008 From: kepalapening at gmail.com (Kepala Pening) Date: Wed, 09 Apr 2008 21:53:18 +0800 Subject: [Tutor] Tutor Digest, Vol 50, Issue 9 Message-ID: <20080409.135318.812.1@SELINAPPORTABLE> import re items = [] for line in open('data.txt'): items.append(re.sub('\n', '', line).split(' ')) ----- Original Message ----- From: "Gloom Demon" To: tutor at python.org Date: Wed, 9 Apr 2008 15:29:35 +0300 Subject: Re: [Tutor] Tutor Digest, Vol 50, Issue 9 Hello :-) Can someone please explain to me ho can I find out how many elements are there in one record of a list? The problem is as follows: I have a txt file from which I read data into Python. The file looks something like this: 01 bla bla bla 23,15 2345,67 02 alb alb 2,4 890,1 03 bal bla alb lab 567,12345 87,45 .... I need to be able to discriminate the string parts from the numeric ones. Since the number of words in the file can vary, I have to be able to find out when they are finished and when the floats come in mystring[0]-> always integer mystring[1]-> string (word) mystring[1-X]-> last string (word) mystring[X+1]-> always float mystring[X+2]-> always float it would have been nice if I could find out the total number of the fields in one list record so that I could then adress them via a variable. From kent37 at tds.net Wed Apr 9 16:08:44 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 09 Apr 2008 10:08:44 -0400 Subject: [Tutor] Tutor Digest, Vol 50, Issue 9 In-Reply-To: <20080409.135318.812.1@SELINAPPORTABLE> References: <20080409.135318.812.1@SELINAPPORTABLE> Message-ID: <47FCCDEC.2020004@tds.net> Kepala Pening wrote: > import re > > items = [] > for line in open('data.txt'): > items.append(re.sub('\n', '', line).split(' ')) Hmm. So much to say about so little code! - the re.sub() is not needed - the split() will remove the trailing newline: In [53]: 'a b\n'.split() Out[53]: ['a', 'b'] - you don't need re to replace a fixed character, you can use str.replace(): In [55]: 'a b\n'.replace('\n', '') Out[55]: 'a b' - If you just want to strip the trailing newline you can use strip() or rstrip(), with or without args, depending on how strict you want to be: In [56]: 'a b\n'.strip() Out[56]: 'a b' - It's not clear that the OP wants a list of lines, but if so, a list comprehension is much more succinct: items = [ line.split() for line in open('data.txt') ] would do the job just fine. Kent From hcvst at zabox.eu Wed Apr 9 16:34:46 2008 From: hcvst at zabox.eu (H.C. v. Stockhausen) Date: Wed, 9 Apr 2008 16:34:46 +0200 Subject: [Tutor] Google App Engine In-Reply-To: <47FCB0B3.5090606@tds.net> References: <20080409084010.GA12839@h736144.serverkompetenz.net> <47FCB0B3.5090606@tds.net> Message-ID: <20080409143446.GA14105@h736144.serverkompetenz.net> On Wed, Apr 09, 2008 at 08:04:03AM -0400, Kent Johnson wrote: > H.C. v. Stockhausen wrote: > > On Tue, Apr 08, 2008 at 10:35:37AM -0700, Dinesh B Vadhia wrote: > >> Hi! Google announced an app server > > > how safe is it to just run the dev server, as I didn't get one of the prerelease accounts either. > > If by 'safe' you mean 'secure', I don't really know but I guess it is > probably pretty safe. The dev server is based on BaseHTTPServer and > other elements of the Python std lib. > > If by 'safe' you mean 'robust', then no. I wouldn't use the dev server > for a production server: > - The dev server is single-threaded - it only serves one request at a > time. > - The datastore is written in Python so it will probably not match the > performance of PostgreSQL or the native Google Apps datastore. > - The default datastore stores all objects in memory so it will not > scale well. > - User login is stubbed out Thanks for your reply, Kent. I woulnd't expect the dev server to scale too well either. Security is what I was mainly concerned with. Just in case, I have resricted access to the development console at /_ah/admin through HTTP basic authentication. Thanks, HC From oldmantaggie at gmail.com Wed Apr 9 17:39:52 2008 From: oldmantaggie at gmail.com (John Chandler) Date: Wed, 9 Apr 2008 10:39:52 -0500 Subject: [Tutor] Process that starts processes Message-ID: <8e087c6d0804090839v41a5f466p3c2f3dd265ddab98@mail.gmail.com> I have been searching for a while but I can't seem to find anything that will do this, so... In my python program I am starting a process using subprocess.Popen. This is working fine, but the process I am starting starts several other processes. Is there any way (using subprocess or a different module) to control the processes the original creates (by control I mean feed them input, capture output, and kill them). I hope that is enough information (its pretty much all I have). Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080409/c1e3af0c/attachment.htm From rdm at rcblue.com Wed Apr 9 18:43:13 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 09 Apr 2008 09:43:13 -0700 Subject: [Tutor] Doubts about Pylint Message-ID: <20080409164337.256BD1E4005@bag.python.org> I'd never used Pylint until yesterday, when I discovered that Ulipad had a Pylint plugin that enabled me to run Pylint on scripts within Ulipad. But I'm wondering about some of the results. I noticed that it was complaining that my variable names violated convention. Here's an image of running Pylint on a script with only 7 lines: Since when is 'az' a bad variable name? And 'AZ' is OK? And I tried Pylint on an official Python module file, calendar.py. Look what I got when all the checkboxes are checked!!: Comments? Dick Moores ================================ UliPad <>: http://code.google.com/p/ulipad/ From eric at ericwalstad.com Wed Apr 9 18:58:32 2008 From: eric at ericwalstad.com (Eric Walstad) Date: Wed, 9 Apr 2008 09:58:32 -0700 Subject: [Tutor] Doubts about Pylint In-Reply-To: <20080409164337.256BD1E4005@bag.python.org> References: <20080409164337.256BD1E4005@bag.python.org> Message-ID: On Wed, Apr 9, 2008 at 9:43 AM, Dick Moores wrote: > I'd never used Pylint until yesterday ... > Since when is 'az' a bad variable name? And 'AZ' is OK? ... > Comments? I understand that Pylint settings and output are *very* customizable. I seem to remember talk about a PEP['Style Guilde'] config but I don't know if that ever happened. From aezell at gmail.com Wed Apr 9 18:59:27 2008 From: aezell at gmail.com (Alex Ezell) Date: Wed, 9 Apr 2008 11:59:27 -0500 Subject: [Tutor] Doubts about Pylint In-Reply-To: <20080409164337.256BD1E4005@bag.python.org> References: <20080409164337.256BD1E4005@bag.python.org> Message-ID: <71dd7f400804090959v1ec4f58fs9589ec369bedfc95@mail.gmail.com> On Wed, Apr 9, 2008 at 11:43 AM, Dick Moores wrote: > Comments? Since we started using code profilers and checkers like pyLint etc., we've had a motto: "This is a guide. It is not the gospel." Take from pylint what you think helps and ignore the rest. It's just a tool and you can choose how to use it. That is, unless you want to actually change pylint. I'm sure there's opportunity to do that, as well, if you are so inclined. All that said, your "az" example seems a little silly on pylint's part. :) /alex From rdm at rcblue.com Wed Apr 9 19:12:32 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 09 Apr 2008 10:12:32 -0700 Subject: [Tutor] Doubts about Pylint In-Reply-To: <71dd7f400804090959v1ec4f58fs9589ec369bedfc95@mail.gmail.co m> References: <20080409164337.256BD1E4005@bag.python.org> <71dd7f400804090959v1ec4f58fs9589ec369bedfc95@mail.gmail.com> Message-ID: <20080409171245.E7B7B1E4005@bag.python.org> At 09:59 AM 4/9/2008, Alex Ezell wrote: >On Wed, Apr 9, 2008 at 11:43 AM, Dick Moores wrote: > > Comments? > >Since we started using code profilers and checkers like pyLint etc., >we've had a motto: > >"This is a guide. It is not the gospel." > >Take from pylint what you think helps and ignore the rest. It's just a >tool and you can choose how to use it. Your advice is well-taken. But 2 points/puzzlements. 1. Why does Pylint advocate variable names be in all caps? I thought I should reserve all caps for indicating a constant.. 2. Why is the code in many official Python modules (in Python25\Lib) so sloppy by Pylint standards? See those many warnings and errors in >That is, unless you want to actually change pylint. I'm sure there's >opportunity to do that, as well, if you are so inclined. > >All that said, your "az" example seems a little silly on pylint's part. :) Dick Moores ================================ UliPad <>: http://code.google.com/p/ulipad/ From malaclypse2 at gmail.com Wed Apr 9 19:14:52 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 9 Apr 2008 13:14:52 -0400 Subject: [Tutor] Doubts about Pylint In-Reply-To: <20080409164337.256BD1E4005@bag.python.org> References: <20080409164337.256BD1E4005@bag.python.org> Message-ID: <16651e80804091014x7288b0a6n9a48cedcaf392c42@mail.gmail.com> On Wed, Apr 9, 2008 at 12:43 PM, Dick Moores wrote: > I'd never used Pylint until yesterday, when I discovered that Ulipad > had a Pylint plugin that enabled me to run Pylint on scripts within > Ulipad. But I'm wondering about some of the results. I noticed that > it was complaining that my variable names violated convention. Here's > an image of running Pylint on a script with only 7 lines: > > > Since when is 'az' a bad variable name? And 'AZ' is OK? Note: I've never used pylint before, so this is all speculation based on a bit of reading of the pylint web page[1] and PEP 8 [2]. In your code snippet, az is a global variable. Pylint has a regular expression that determines if a global variable name matches your coding convention. By default, that regex is (([A-Z_][A-Z1-9_]*)|(__.*__))$. At a guess, that's because pylint's author believes the only global variables you should have are psuedo-constants, and that they should have all uppercase names. That seems reasonable to me, if a bit strict. That particular check does not line up with the PEP 8 coding conventions, which just suggest that global variables follow the same naming rules as functions. I haven't gone through pylint in a lot of detail, but it looks like most of the other regular expressions are designed to default to the PEP 8 coding style conventions, or something close to them. If your coding conventions are different from the defaults pylint assumes, you'll probably need to do some setup. > And I tried Pylint on an official Python module file, calendar.py. > Look what I got when all the checkboxes are > checked!!: > > Comments? Most of that looks like valid complaints about calendar.py. The one exception that jumps out at me is the warning about a relative import from __future__. At lot of the other warnings probably depend on the context. For instance, the single-character variable names are ugly, but if they're used inside a loop or a list comprehension they are probably fine. Other than the fact that it's a long list, did *you* have any comments? You present this list like it's a bad thing, but it seems to me that pylint is doing exactly what it should. Do you think that there's something wrong with pylint? Are you just surprised that calendar.py doesn't adhere to pylint's coding guidelines? 1: http://www.logilab.org/card/pylintfeatures 2: http://www.python.org/dev/peps/pep-0008/ From rdm at rcblue.com Wed Apr 9 19:28:48 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 09 Apr 2008 10:28:48 -0700 Subject: [Tutor] Doubts about Pylint In-Reply-To: <16651e80804091014x7288b0a6n9a48cedcaf392c42@mail.gmail.com > References: <20080409164337.256BD1E4005@bag.python.org> <16651e80804091014x7288b0a6n9a48cedcaf392c42@mail.gmail.com> Message-ID: <20080409172902.E6D771E400F@bag.python.org> At 10:14 AM 4/9/2008, Jerry Hill wrote: >Other than the fact that it's a long list, did *you* have any >comments? You present this list like it's a bad thing, but it seems >to me that pylint is doing exactly what it should. Do you think that >there's something wrong with pylint? Are you just surprised that >calendar.py doesn't adhere to pylint's coding guidelines? Yes, I didn't make that clear. See my previous post, which seems to have crossed yours. >1: http://www.logilab.org/card/pylintfeatures >2: http://www.python.org/dev/peps/pep-0008/ Thanks for these links. Knew about #2, but not #1. Dick ================================ UliPad <>: http://code.google.com/p/ulipad/ From bgailer at gmail.com Wed Apr 9 20:05:40 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 09 Apr 2008 14:05:40 -0400 Subject: [Tutor] Google App Engine In-Reply-To: References: Message-ID: <47FD0574.6050804@gmail.com> I watched the Campfire videos. Very interesting. Big drawback: no support for join queries. Reasons given seemed pretty weak. How would one migrate an existing app that has hundreds of (in some cases) involved joins? The only way I can see is to write a bunch of queries and then "join" them in the python code. Seems ugly. Would be nice also to see support for GWT (and pyjamas). -- Bob Gailer 919-636-4239 Chapel Hill, NC From kent37 at tds.net Wed Apr 9 20:28:32 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 09 Apr 2008 14:28:32 -0400 Subject: [Tutor] Google App Engine In-Reply-To: <47FD0574.6050804@gmail.com> References: <47FD0574.6050804@gmail.com> Message-ID: <47FD0AD0.6050005@tds.net> bob gailer wrote: > I watched the Campfire videos. Very interesting. > > Big drawback: no support for join queries. Reasons given seemed pretty > weak. Because the underlying datastore (BigTable) doesn't support them? I'm not sure but I think this is a key to the scalability of the data store. > How would one migrate an existing app that has hundreds of (in some > cases) involved joins? The only way I can see is to write a bunch of > queries and then "join" them in the python code. Seems ugly. Yes, I think so too. My guess is that if you started from scratch with GAE you would structure the data differently. Or maybe GAE just isn't suitable for that kind of app. > Would be nice also to see support for GWT (and pyjamas). What is the barrier to using pyjamas? Kent From dineshbvadhia at hotmail.com Wed Apr 9 13:12:21 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Wed, 9 Apr 2008 04:12:21 -0700 Subject: [Tutor] List comprehensions Message-ID: Here is a for loop operating on a list of string items: data = ["string 1", "string 2", "string 3", "string 4", "string 5", "string 6", "string 7", "string 8", "string 9", "string 10", "string 11"] result = "" for item in data: result = item + "\n" print result I want to replace the for loop with a List Comrehension (or whatever) to improve performance (as the data list will be >10,000]. At each stage of the for loop I want to print the result ie. [print (item + "\n") for item in data] But, this doesn't work as the inclusion of the print causes an invalid syntax error. Any thoughts? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080409/c41ba535/attachment.htm From kent37 at tds.net Wed Apr 9 21:40:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 09 Apr 2008 15:40:36 -0400 Subject: [Tutor] List comprehensions In-Reply-To: References: Message-ID: <47FD1BB4.5050108@tds.net> Dinesh B Vadhia wrote: > Here is a for loop operating on a list of string items: > > data = ["string 1", "string 2", "string 3", "string 4", "string 5", > "string 6", "string 7", "string 8", "string 9", "string 10", "string 11"] > > result = "" > for item in data: > result = item + "\n" > print result I'm not sure what your goal is here. Do you mean to be accumulating all the values in data into result? Your sample code does not do that. > I want to replace the for loop with a List Comrehension (or whatever) to > improve performance (as the data list will be >10,000]. At each stage > of the for loop I want to print the result ie. > > [print (item + "\n") for item in data] > > But, this doesn't work as the inclusion of the print causes an invalid > syntax error. You can't include a statement in a list comprehension. Anyway the time taken to print will swamp any advantage you get from the list comp. If you just want to print the items, a simple loop will do it: for item in data: print item + '\n' Note this will double-space the output since print already adds a newline. If you want to create a string with all the items with following newlines, the classic way to do this is to build a list and then join it. To do it with the print included, try result = [] for item in data: newItem = item + '\n' print newItem result.append(newItem) result = ''.join(result) Kent From malaclypse2 at gmail.com Wed Apr 9 21:44:38 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 9 Apr 2008 15:44:38 -0400 Subject: [Tutor] List comprehensions In-Reply-To: References: Message-ID: <16651e80804091244t37665731x8b6f5cd174b8caff@mail.gmail.com> On Wed, Apr 9, 2008 at 7:12 AM, Dinesh B Vadhia wrote: > I want to replace the for loop with a List Comrehension (or whatever) to > improve performance (as the data list will be >10,000]. At each stage of > the for loop I want to print the result ie. List comprehensions are for building lists, not consuming them. If you want to do something with every element in a list, other than building a new list with it, you should be using a for loop. > [print (item + "\n") for item in data] > > But, this doesn't work as the inclusion of the print causes an invalid > syntax error. > > Any thoughts? Don't do this. Perhaps you could share a small piece of code that you think is too slow, and ask for advice in speeding it up? If you're not sure which small pieces of code are too slow, you need to profile your application to find out. See the documentation for python's profile module. If you don't have enough code written to profile, then it's probably too early to be doing these optimizations. -- Jerry From pylinuxian at gmail.com Wed Apr 9 22:01:35 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Wed, 9 Apr 2008 20:01:35 +0000 Subject: [Tutor] List comprehensions In-Reply-To: <16651e80804091244t37665731x8b6f5cd174b8caff@mail.gmail.com> References: <16651e80804091244t37665731x8b6f5cd174b8caff@mail.gmail.com> Message-ID: On Wed, Apr 9, 2008 at 7:44 PM, Jerry Hill wrote: > On Wed, Apr 9, 2008 at 7:12 AM, Dinesh B Vadhia > wrote: > > I want to replace the for loop with a List Comrehension (or whatever) to > > improve performance (as the data list will be >10,000]. At each stage > of > > the for loop I want to print the result ie. > > List comprehensions are for building lists, not consuming them. If > you want to do something with every element in a list, other than > building a new list with it, you should be using a for loop. > > > [print (item + "\n") for item in data] > > > > But, this doesn't work as the inclusion of the print causes an invalid > > syntax error. > > > > Any thoughts? > > Don't do this. > > Perhaps you could share a small piece of code that you think is too > slow, and ask for advice in speeding it up? If you're not sure which > small pieces of code are too slow, you need to profile your > application to find out. See the documentation for python's profile > module. If you don't have enough code written to profile, then it's > probably too early to be doing these optimizations. > > -- > Jerry > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > if you explain the source of the list, what do you want to change in it, what destination will it take, i m sure the guys here will help a lot. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080409/e0f56428/attachment.htm From dineshbvadhia at hotmail.com Wed Apr 9 22:15:32 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Wed, 9 Apr 2008 13:15:32 -0700 Subject: [Tutor] List comprehensions References: <47FD1BB4.5050108@tds.net> Message-ID: Sorry, let's start again. Here is a for loop operating on a list of string items: data = ["string 1", "string 2", "string 3", "string 4", "string 5", "string 6", "string 7", "string 8", "string 9", "string 10", "string 11"] result = "" for item in data: result = item print result I want to replace the for loop with another structure to improve performance (as the data list will contain >10,000 string items]. At each iteration of the for loop the result is printed (in fact, the result is sent from the server to a browser one result line at a time) The for loop will be called continuously and this is another reason to look for a potentially better structure preferably a built-in. Hope this makes sense! Thank-you. Dinesh ----- Original Message ----- From: Kent Johnson To: Dinesh B Vadhia Cc: tutor at python.org Sent: Wednesday, April 09, 2008 12:40 PM Subject: Re: [Tutor] List comprehensions Dinesh B Vadhia wrote: > Here is a for loop operating on a list of string items: > > data = ["string 1", "string 2", "string 3", "string 4", "string 5", > "string 6", "string 7", "string 8", "string 9", "string 10", "string 11"] > > result = "" > for item in data: > result = item + "\n" > print result I'm not sure what your goal is here. Do you mean to be accumulating all the values in data into result? Your sample code does not do that. > I want to replace the for loop with a List Comrehension (or whatever) to > improve performance (as the data list will be >10,000]. At each stage > of the for loop I want to print the result ie. > > [print (item + "\n") for item in data] > > But, this doesn't work as the inclusion of the print causes an invalid > syntax error. You can't include a statement in a list comprehension. Anyway the time taken to print will swamp any advantage you get from the list comp. If you just want to print the items, a simple loop will do it: for item in data: print item + '\n' Note this will double-space the output since print already adds a newline. If you want to create a string with all the items with following newlines, the classic way to do this is to build a list and then join it. To do it with the print included, try result = [] for item in data: newItem = item + '\n' print newItem result.append(newItem) result = ''.join(result) Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080409/58ac11f9/attachment.htm From pylinuxian at gmail.com Wed Apr 9 22:31:55 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Wed, 9 Apr 2008 20:31:55 +0000 Subject: [Tutor] List comprehensions In-Reply-To: References: <47FD1BB4.5050108@tds.net> Message-ID: i can't think of anything but a loop here UNLESS you take the list from its source one element at a time, process it & then print the result. example of this would be : list comes in from standard input. list comes from a database list is read from a file. so again where the list comes from is important. if its standard input then you program will be easy & won't use any memory i guess. import sys # cgi & cgitb if going web data = sys.stdin.readline() print data On Wed, Apr 9, 2008 at 8:15 PM, Dinesh B Vadhia wrote: > Sorry, let's start again. > > Here is a for loop operating on a list of string items: > > data = ["string 1", "string 2", "string 3", "string 4", "string 5", > "string 6", "string 7", "string 8", "string 9", "string 10", "string 11"] > > result = "" > for item in data: > result = item > print result > > I want to replace the for loop with another structure to improve > performance (as the data list will contain >10,000 string items]. At each > iteration of the for loop the result is printed (in fact, the result is sent > from the server to a browser one result line at a time) > > The for loop will be called continuously and this is another reason to > look for a potentially better structure preferably a built-in. > > Hope this makes sense! Thank-you. > > Dinesh > > > > ----- Original Message ----- *From:* Kent Johnson > *To:* Dinesh B Vadhia > *Cc:* tutor at python.org > *Sent:* Wednesday, April 09, 2008 12:40 PM > *Subject:* Re: [Tutor] List comprehensions > > Dinesh B Vadhia wrote: > > Here is a for loop operating on a list of string items: > > > > data = ["string 1", "string 2", "string 3", "string 4", "string 5", > > "string 6", "string 7", "string 8", "string 9", "string 10", "string > 11"] > > > > result = "" > > for item in data: > > result = item + "\n" > > print result > > I'm not sure what your goal is here. Do you mean to be accumulating all > the values in data into result? Your sample code does not do that. > > > I want to replace the for loop with a List Comrehension (or whatever) to > > > improve performance (as the data list will be >10,000]. At each stage > > of the for loop I want to print the result ie. > > > > [print (item + "\n") for item in data] > > > > But, this doesn't work as the inclusion of the print causes an invalid > > syntax error. > > You can't include a statement in a list comprehension. Anyway the time > taken to print will swamp any advantage you get from the list comp. > > If you just want to print the items, a simple loop will do it: > > for item in data: > print item + '\n' > > Note this will double-space the output since print already adds a newline. > > If you want to create a string with all the items with following > newlines, the classic way to do this is to build a list and then join > it. To do it with the print included, try > > result = [] > for item in data: > newItem = item + '\n' > print newItem > result.append(newItem) > result = ''.join(result) > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080409/d55397b1/attachment-0001.htm From kent37 at tds.net Wed Apr 9 22:48:28 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 09 Apr 2008 16:48:28 -0400 Subject: [Tutor] List comprehensions In-Reply-To: References: <47FD1BB4.5050108@tds.net> Message-ID: <47FD2B9C.10209@tds.net> Dinesh B Vadhia wrote: > Here is a for loop operating on a list of string items: > > data = ["string 1", "string 2", "string 3", "string 4", "string 5", > "string 6", "string 7", "string 8", "string 9", "string 10", "string 11"] > > result = "" > for item in data: > result = item > print result > > I want to replace the for loop with another structure to improve > performance (as the data list will contain >10,000 string items]. At > each iteration of the for loop the result is printed (in fact, the > result is sent from the server to a browser one result line at a time) Any savings you have from optimizing this loop will be completely swamped by the network time. Why do you think this is a bottleneck? You could use [ sys.stdout.write(some operation on item) for item in data ] but I consider this bad style and I seriously doubt you will see any difference in performance. > The for loop will be called continuously and this is another reason to > look for a potentially better structure preferably a built-in. What do you mean 'called continuously'? Kent From malaclypse2 at gmail.com Wed Apr 9 22:58:53 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 9 Apr 2008 16:58:53 -0400 Subject: [Tutor] List comprehensions In-Reply-To: References: <47FD1BB4.5050108@tds.net> Message-ID: <16651e80804091358o69645f99xeccd6990a27f623@mail.gmail.com> On Wed, Apr 9, 2008 at 4:15 PM, Dinesh B Vadhia wrote: > Sorry, let's start again. This version really isn't any more helpful than the first one. I know you corrected the sample code, but you haven't addressed any of the fundamental questions that Kent or I asked. > I want to replace the for loop with another structure to improve performance > (as the data list will contain >10,000 string items]. At each iteration of > the for loop the result is printed (in fact, the result is sent from the > server to a browser one result line at a time) Are you looking for a different data structure to hold your list of strings, or are you looking for a replacement for the for loop? How long does it take to generate your list? How long does each iteration of your for loop take? What are acceptable times for each of these? You need to know these things before you can seriously optimize anything. If building up the list takes a long time and you only use it once, consider using a generator instead of building the whole list and then processing it. This spreads out the time to create the list and operates on each piece of data as soon as it's available. I don't think you're going to find a replacement for a for loop that is inherently faster. You keep talking about list comprehensions, but I don't see how a list comprehension is even appropriate for the problem you're describing. > The for loop will be called continuously and this is another reason to look > for a potentially better structure preferably a built-in. Again, it would be helpful to discuss actual bits of code, so we can see if there are places you can gain some performance. It's hard to optimize psuedocode, because there are sometimes very minor changes you can make which affect performance quite a bit. For instance, attribute lookup in python is relatively slow. If you can hoist any attribute lookups out of your loop, you will get some performance increases. Also, you should mention what version of python you're using and what platform it's running on. -- Jerry From malaclypse2 at gmail.com Wed Apr 9 23:02:20 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 9 Apr 2008 17:02:20 -0400 Subject: [Tutor] List comprehensions In-Reply-To: <47FD2B9C.10209@tds.net> References: <47FD1BB4.5050108@tds.net> <47FD2B9C.10209@tds.net> Message-ID: <16651e80804091402ueaefc36ifb43e26c9f7833cd@mail.gmail.com> On Wed, Apr 9, 2008 at 4:48 PM, Kent Johnson wrote: > You could use > [ sys.stdout.write(some operation on item) for item in data ] > > but I consider this bad style and I seriously doubt you will see any > difference in performance. This really isn't a good idea. It will take just as long as the for loop, plus it builds a list with the return code for each call to sys.stdout.write() call (which is probably None). Then after building the list with > 10,000 entries of None, it throws it away. That can't be good for performance. -- Jerry From alan.gauld at btinternet.com Thu Apr 10 00:09:43 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 9 Apr 2008 23:09:43 +0100 Subject: [Tutor] Process that starts processes References: <8e087c6d0804090839v41a5f466p3c2f3dd265ddab98@mail.gmail.com> Message-ID: "John Chandler" wrote > working fine, but the process I am starting starts several other > processes. > Is there any way (using subprocess or a different module) to control > the > processes the original creates (by control I mean feed them input, > capture > output, and kill them). Its tricky but if you know their names and they are only produced from your master you could use 'ps' and 'grep' to get the pids. You can then attach to the pids. But its very messy. It is probably more reliable to replace your top level process with Python code, but that depends on how complex that code is... Thee may be other ways to get the pids using lower level proc type calls but you still have the problem of identifying which pids you are interested in! All I can think of at this time of night! Alan G. From alan.gauld at btinternet.com Thu Apr 10 00:15:47 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 9 Apr 2008 23:15:47 +0100 Subject: [Tutor] Doubts about Pylint References: <20080409164337.256BD1E4005@bag.python.org> Message-ID: "Dick Moores" wrote > Since when is 'az' a bad variable name? And 'AZ' is OK? When it is a constant. pyLint sees that you are assigning a numeroc literal and so thinks that this may be a definition of a constant value. If you disd someting like A = 8 az = A It may well be happy since A is a constant and the variable is being assigned the constant rather than the literal. All lint tools are by tradition very exacting, even the C version which pyLint is modelled on is notorious for throwing irrelevant errors - like not checking the return value of a printf() function (printf returns the number of characters printed but virtually nobody ever checks that!) As another poster said treat it in the spirit it is intended, a tool to highlight *possible* causes for concern not definite causes. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From queprime at gmail.com Thu Apr 10 01:04:08 2008 From: queprime at gmail.com (Que Prime) Date: Wed, 9 Apr 2008 16:04:08 -0700 Subject: [Tutor] Copy script Message-ID: <17285ccf0804091604u2c53d9f0hc2ffed3f56153858@mail.gmail.com> I have a folder of 150,000 pdf files and I need to copy 20,000 of them to another folder. The ones I need to copy are in a .txt file. Attached is a sample of the input .txt file and a dos directory of the folder containing the files. I'm not sure of the best way to accomplish this. Thank you in advance for your help. Sample input file: 12347424 12347425 12347426 12347427 Sample dir on folder: 03/20/2008 09:21 AM 145,257 000000011479 [7ac0c741-9d2f-4a1d-9dbf-8de27ca0abb4].pdf 03/20/2008 09:21 AM 154,655 000000011600 [cd752a5a-388a-4bad-9a52-fb3711f685b8].pdf 03/20/2008 09:21 AM 145,556 000000015234 [4344f5ff-fa58-4e20-bf27-697c71a81fbc].pdf 03/20/2008 09:21 AM 152,785 000012347424 [44cc0d43-a80d-4415-8e92-b6a4f62986b4].pdf 03/20/2008 09:21 AM 145,551 000012347425 [0ea7b60a-3631-4f64-91fa-6e385296f18f].pdf -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080409/f56edd54/attachment.htm -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: dir.txt Url: http://mail.python.org/pipermail/tutor/attachments/20080409/f56edd54/attachment.txt -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: missing.txt Url: http://mail.python.org/pipermail/tutor/attachments/20080409/f56edd54/attachment-0001.txt From alan.gauld at btinternet.com Thu Apr 10 02:46:49 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Apr 2008 01:46:49 +0100 Subject: [Tutor] Copy script References: <17285ccf0804091604u2c53d9f0hc2ffed3f56153858@mail.gmail.com> Message-ID: "Que Prime" wrote >I have a folder of 150,000 pdf files and I need to copy 20,000 of >them to > another folder. The ones I need to copy are in a .txt file. Sounds straightforward but... > Attached is a > sample of the input .txt file and a dos directory of the folder > containing > the files. I'm not sure of the best way to accomplish this. > > Thank you in advance for your help. > > Sample input file: > > 12347424 > 12347425 > > Sample dir on folder: > 03/20/2008 09:21 AM 145,257 000000011479 > [7ac0c741-9d2f-4a1d-9dbf-8de27ca0abb4].pdf I don;t see how the input file relates to the pdf files? Which part of the pdf file does the input numbers refer to? However it may be that the DOS FOR command with the /F option may be adapted to do what you want. It iterates over the content of a file performing a command per item in the file... Try Help FOR to get more info and try experimenting... DOS is a braindead beast but does sometimes have the facilities needed... The XP DOS commands are considerably more powerful than the old DOS set. Some of them even have a Unix like backtick facility! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at gmail.com Thu Apr 10 04:05:43 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 09 Apr 2008 22:05:43 -0400 Subject: [Tutor] Copy script In-Reply-To: References: <17285ccf0804091604u2c53d9f0hc2ffed3f56153858@mail.gmail.com> Message-ID: <47FD75F7.30100@gmail.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080409/98690c29/attachment-0001.htm From kent37 at tds.net Thu Apr 10 04:14:11 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 09 Apr 2008 22:14:11 -0400 Subject: [Tutor] Copy script In-Reply-To: <17285ccf0804091604u2c53d9f0hc2ffed3f56153858@mail.gmail.com> References: <17285ccf0804091604u2c53d9f0hc2ffed3f56153858@mail.gmail.com> Message-ID: <47FD77F3.2080009@tds.net> Que Prime wrote: > I have a folder of 150,000 pdf files and I need to copy 20,000 of them > to another folder. The ones I need to copy are in a .txt file. > Attached is a sample of the input .txt file and a dos directory of the > folder containing the files. I'm not sure of the best way to accomplish > this. So a sample filename is 000012347425 [0ea7b60a-3631-4f64-91fa-6e385296f18f].pdf and you would want to copy this because 12347425 is in the txt file? If that is correct understanding, I think I would - read the txt file and put all the numbers in a set. - iterate through the file names in the source dir - isolate the initial number part of the file name, strip the leading 0's - check if the initial number is in the set - if so, then copy the file Are all the files in one directory? If so I guess you will have to have enough memory to hold all the file names (as well as the set of numbers) and probably a bit of patience! I don't know a way to generate the sequence without creating the full list. Kent > Thank you in advance for your help. > > Sample input file: > > 12347424 > 12347425 > 12347426 > 12347427 > > > Sample dir on folder: > 03/20/2008 09:21 AM 145,257 000000011479 > [7ac0c741-9d2f-4a1d-9dbf-8de27ca0abb4].pdf > 03/20/2008 09:21 AM 154,655 000000011600 > [cd752a5a-388a-4bad-9a52-fb3711f685b8].pdf > 03/20/2008 09:21 AM 145,556 000000015234 > [4344f5ff-fa58-4e20-bf27-697c71a81fbc].pdf > 03/20/2008 09:21 AM 152,785 000012347424 > [44cc0d43-a80d-4415-8e92-b6a4f62986b4].pdf > 03/20/2008 09:21 AM 145,551 000012347425 > [0ea7b60a-3631-4f64-91fa-6e385296f18f].pdf > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From tonytraductor at linguasos.org Thu Apr 10 04:30:36 2008 From: tonytraductor at linguasos.org (Anthony Baldwin) Date: Wed, 09 Apr 2008 22:30:36 -0400 Subject: [Tutor] Copy script In-Reply-To: References: <17285ccf0804091604u2c53d9f0hc2ffed3f56153858@mail.gmail.com> Message-ID: <47FD7BCC.2000701@linguasos.org> Alan Gauld wrote: > "Que Prime" wrote > > >> I have a folder of 150,000 pdf files and I need to copy 20,000 of >> them to >> another folder. The ones I need to copy are in a .txt file. >> Assuming the text file is a list of those to be copied, wouldn't a simple bash script do the trick? (don't know about windows, but this would work on Mac or Linux, and, I assume there must be a way to do this with a windows command line script of some sort.) #!/bin/bash cd /path/to/dir/with/files/and/list llistofiles=$(cat "your .txt file here") echo "Copying files..." for each i in $listofiles do cp $i /path/to/other/folder/$i echo "All done...b'bye..." exit Or, perhaps with tcl #!/usr/bin/wish set listofiles [read "your txt file here"] puts "Copying files..." foreach a {$listofiles} { file copy $a /path/to/target/dir } puts "All done...b'bye..." exit I imagine python could do something quite similar, but confess I am just lurking on this list and have barely begun to learn python. /tony -- Anthony Baldwin http://www.BaldwinLinguas.com Translation & Interpreting http://www.TransProCalc.org Free translation project mgmt software http://www.LinguasOS.org Linux for Translators From rdm at rcblue.com Thu Apr 10 07:45:47 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 09 Apr 2008 22:45:47 -0700 Subject: [Tutor] Doubts about Pylint In-Reply-To: References: <20080409164337.256BD1E4005@bag.python.org> Message-ID: <20080410054558.DF0CA1E400D@bag.python.org> At 03:15 PM 4/9/2008, Alan Gauld wrote: >"Dick Moores" wrote > > > Since when is 'az' a bad variable name? And 'AZ' is OK? > >When it is a constant. >pyLint sees that you are assigning a numeric literal and >so thinks that this may be a definition of a constant value. > >If you did something like > >A = 8 >az = A > >It may well be happy since A is a constant and the variable >is being assigned the constant rather than the literal. Thanks, Alan, but I tried your A = 8 az = A and got the same complaint about az. Dick ================================ UliPad <>: http://code.google.com/p/ulipad/ From dineshbvadhia at hotmail.com Thu Apr 10 08:15:44 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Wed, 9 Apr 2008 23:15:44 -0700 Subject: [Tutor] List comprehensions References: <47FD1BB4.5050108@tds.net> <47FD2B9C.10209@tds.net> Message-ID: Kent I'm using a Javascript autocomplete plugin for an online web application/service. Each time a user inputs a character, the character is sent to the backend Python program which searches for the character in a list of >10,000 string items. Once it finds the character, the backend will return that string and N other adjacent string items where N can vary from 20 to 150. Each string item is sent back to the JS in separate print statements. Hence, the for loop. Now, N = 20 to 150 is not a lot (for a for loop) but this process is performed each time the user enters a character. Plus, there will be thousands (possibly more) users at a time. There is also the searching of the >10,000 string items using the entered character. All of this adds up in terms of performance. I haven't done any profiling yet as we are still building the system but it seemed sensible that replacing the for loop with a built-in would help. Maybe not? Hope that helps. Dinesh ----- Original Message ----- From: Kent Johnson To: Dinesh B Vadhia Cc: tutor at python.org Sent: Wednesday, April 09, 2008 1:48 PM Subject: Re: [Tutor] List comprehensions Dinesh B Vadhia wrote: > Here is a for loop operating on a list of string items: > > data = ["string 1", "string 2", "string 3", "string 4", "string 5", > "string 6", "string 7", "string 8", "string 9", "string 10", "string 11"] > > result = "" > for item in data: > result = item > print result > > I want to replace the for loop with another structure to improve > performance (as the data list will contain >10,000 string items]. At > each iteration of the for loop the result is printed (in fact, the > result is sent from the server to a browser one result line at a time) Any savings you have from optimizing this loop will be completely swamped by the network time. Why do you think this is a bottleneck? You could use [ sys.stdout.write(some operation on item) for item in data ] but I consider this bad style and I seriously doubt you will see any difference in performance. > The for loop will be called continuously and this is another reason to > look for a potentially better structure preferably a built-in. What do you mean 'called continuously'? Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080409/a3c9df4f/attachment.htm From alan.gauld at btinternet.com Thu Apr 10 09:52:23 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Apr 2008 08:52:23 +0100 Subject: [Tutor] List comprehensions References: <47FD1BB4.5050108@tds.net><47FD2B9C.10209@tds.net> Message-ID: "Dinesh B Vadhia" wrote i > I'm using a Javascript autocomplete plugin for an online > web application/service. Each time a user inputs a character, > the character is sent to the backend Python program which > searches for the character in a list of >10,000 string items. Eeek! That will be incredibly slow over any kind of network other than fast gigabit! try doing a ping from the client to the server. If it over the internet you will be lucky to get less that 100ms, over a fast LAN it might be around 30ms. Add in the transmission time for your data - (ie 150*ave string length*10/average bandwidth) That network delay will swamp any optimisation of a for loop. It is likely to come out around 10ms so your total delay between each character becomes 40-110ms or a maximum typing rate of 9-25 characters per second. The latter will feel slightly clunky but the former will feel very sluggish. And on anything less than a good internet connection the rate could drop off to around 1 character per second! And anyone using a mobile GPRS connection for access would be crippled. Alan G. From alan.gauld at btinternet.com Thu Apr 10 09:57:24 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Apr 2008 08:57:24 +0100 Subject: [Tutor] Doubts about Pylint References: <20080409164337.256BD1E4005@bag.python.org> <20080410054558.DF0CA1E400D@bag.python.org> Message-ID: "Dick Moores" wrote >>A = 8 >>az = A >> >>It may well be happy since A is a constant and the variable >>is being assigned the constant rather than the literal. > > Thanks, Alan, but I tried your > > A = 8 > az = A > > and got the same complaint about az. OK, In that case its probably the fact its global as suggested by Jerry and the regex approach being used is assuming all globals should be functions or classes or Consts... The bottom line is that its highlighting something the author thought might indicate a problem not necessarily a valid error. I once used a version of C lint that had a -v flag that printed an explanatory message along with each reported error, it would be nice if pyLint did the same - a nice wee project for anyone that's feeling bored and wants to contribute something to the Python/Opensource community maybe?!!! :-) Alan G From pylinuxian at gmail.com Thu Apr 10 11:51:04 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Thu, 10 Apr 2008 09:51:04 +0000 Subject: [Tutor] Copy script In-Reply-To: <47FD7BCC.2000701@linguasos.org> References: <17285ccf0804091604u2c53d9f0hc2ffed3f56153858@mail.gmail.com> <47FD7BCC.2000701@linguasos.org> Message-ID: could you do a : "dir /b" inside this directory just so that we can know the real file names. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080410/47824f9f/attachment.htm From pylinuxian at gmail.com Thu Apr 10 12:01:24 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Thu, 10 Apr 2008 10:01:24 +0000 Subject: [Tutor] List comprehensions In-Reply-To: References: <47FD1BB4.5050108@tds.net> <47FD2B9C.10209@tds.net> Message-ID: i think you are using ajax ... which undoubdetly uses an sql database since its based on queries run from whithin the application in the browser whithout the need for refreshing the page ... i would suggest you try serching internet for something like "google autocomplete feature" & i guess the queries are also no that long they have a limit of the results ... for example not more than 20 results per query. than said there would be no loop. just a query (with a limit of 20 rersults) each time a use inputs a character. hope this helps. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080410/2b093794/attachment.htm From pylinuxian at gmail.com Thu Apr 10 12:03:43 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Thu, 10 Apr 2008 10:03:43 +0000 Subject: [Tutor] List comprehensions In-Reply-To: References: <47FD1BB4.5050108@tds.net> <47FD2B9C.10209@tds.net> Message-ID: also if you need to go for 20000 results I propose you use filters & interactive menus which will help you tailor the query to the users desires & thus limit the query results. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080410/1ce73cb2/attachment.htm From srilyk at gmail.com Thu Apr 10 13:31:59 2008 From: srilyk at gmail.com (W W) Date: Thu, 10 Apr 2008 06:31:59 -0500 Subject: [Tutor] List comprehensions In-Reply-To: References: <47FD1BB4.5050108@tds.net> <47FD2B9C.10209@tds.net> Message-ID: <333efb450804100431m4f76051bu283129f87164b129@mail.gmail.com> My guess, though I'm not sure, is that google uses hashes... why? Because they're a *ahem* load faster than loops, and the reason is they replace the repetitive nature of a loop by using some type of formula. Exactly /how/ this is implemented, I'm not sure. A simple example of the speed difference: 11 * 1 = 11 The program spent 0.000810146331787 seconds. 11 * 1 = 11 The program spent 6.19888305664e-05 seconds. (btw, that means .000006... ) The difference? The first was a loop: 1 from time import time 2 start_time = time() 3 4 x = 0 5 while x < 11: 6 x +=1 7 8 print "11 * 1 = ", x 9 10 end_time = time() 11 print "The program spent", end_time - start_time, "seconds." And the second, a algebraic statement 14 start_time = time() 15 16 x = 11 / 1 17 print "11 * 1 = ", x 18 19 end_time = time() 20 print "The program spent", end_time - start_time, "seconds." It would be simple to replace the 11 with a variable supplied by something like variable = int(raw_input("Enter a number: ")) and you would come out with similar output. That's basically the reason a dictionary finds dictionary["foo"] faster than a for loop: the key, "foo", is transformed into some value (As I understand it, the hashtable refers to some memory location, i.e 0x08f or some such), and there, sitting in that location, is the value for the key "foo". so rather than comparing each value a list, it would be like having some formula to grab that value. I hope this wasn't too confusing, and if anyone has any corrections or clarifications, feel free to muck about. But yeah, a hash is probably the way you want to go (from what I know) -Wayne On Thu, Apr 10, 2008 at 5:03 AM, linuxian iandsd wrote: > also if you need to go for 20000 results I propose you use filters & > interactive menus which will help you tailor the query to the users desires > & thus limit the query results. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From kent37 at tds.net Thu Apr 10 14:20:39 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 Apr 2008 08:20:39 -0400 Subject: [Tutor] List comprehensions In-Reply-To: References: <47FD1BB4.5050108@tds.net> <47FD2B9C.10209@tds.net> Message-ID: <47FE0617.5030203@tds.net> Dinesh B Vadhia wrote: > Kent > > I'm using a Javascript autocomplete plugin for an online web > application/service. Each time a user inputs a character, the character > is sent to the backend Python program which searches for the character > in a list of >10,000 string items. Once it finds the character, the > backend will return that string and N other adjacent string items where > N can vary from 20 to 150. Each string item is sent back to the JS in > separate print statements. Hence, the for loop. Ok, this sounds a little closer to a real spec. What kind of search are you doing? Do you really just search for individual characters or are you looking for the entire string entered so far as a prefix? Is the list of 10,000 items sorted? Can it be? You need to look at your real problem and find an appropriate data structure, rather than showing us what you think is the solution and asking how to make it faster. For example, if what you have a sorted list of strings and you want to find the first string that starts with a given prefix and return the N adjacent strings, you could use the bisect module to do a binary search rather than a linear search. Binary search of 10,000 items will take 13-14 comparisons to find the correct location. Your linear search will take an average of 5,000 comparisons. You might also want to use a trie structure though I'm not sure if that will let you find adjacent items. http://www.cs.mcgill.ca/~cs251/OldCourses/1997/topic7/ http://jtauber.com/blog/2005/02/10/updated_python_trie_implementation/ > I haven't done any profiling yet as we are still building the system but > it seemed sensible that replacing the for loop with a built-in would > help. Maybe not? Not. An algorithm with poor "big O" performance should be *replaced*, not optimized. Kent From alan.gauld at btinternet.com Thu Apr 10 14:32:48 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Apr 2008 13:32:48 +0100 Subject: [Tutor] List comprehensions References: <47FD1BB4.5050108@tds.net><47FD2B9C.10209@tds.net> <47FE0617.5030203@tds.net> Message-ID: "Kent Johnson" wrote >> application/service. Each time a user inputs a character, the >> character >> is sent to the backend Python program which searches for the >> character >> in a list of >10,000 string items. Once it finds the character, >> the >> backend will return that string and N other adjacent string items >> where >> N can vary from 20 to 150. Each string item is sent back to the JS >> in >> separate print statements. Hence, the for loop. > > You need to look at your real problem and find an appropriate data > structure, rather than showing us what you think is the solution and > asking how to make it faster. One possibility is that the javascript fetches the list back on the first few characters and caches it on the browser, it can then do the search locally and only go back to the server if the user deletes enough characters to invalidate the cache. That would make a big difference to the overall speed by eliminating several network lookups. I am assuming the server lookup list does not change significantly over the duration of a form submission? Alan G From kent37 at tds.net Thu Apr 10 14:54:10 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 Apr 2008 08:54:10 -0400 Subject: [Tutor] List comprehensions In-Reply-To: References: <47FD1BB4.5050108@tds.net><47FD2B9C.10209@tds.net> <47FE0617.5030203@tds.net> Message-ID: <47FE0DF2.9020000@tds.net> Alan Gauld wrote: > One possibility is that the javascript fetches the list back on the > first few characters and caches it on the browser Here is an autocomplete widget I use that can do exactly that: http://www.dyve.net/jquery/?autocomplete Kent From bgailer at gmail.com Thu Apr 10 15:10:30 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 10 Apr 2008 09:10:30 -0400 Subject: [Tutor] List comprehensions In-Reply-To: References: <47FD1BB4.5050108@tds.net> <47FD2B9C.10209@tds.net> Message-ID: <47FE11C6.2020109@gmail.com> Dinesh B Vadhia wrote: > Kent > > I'm using a Javascript autocomplete plugin for an online web > application/service. Each time a user inputs a character, the > character is sent to the backend Python program which searches for the > character in a list of >10,000 string items. Once it finds the > character, the backend will return that string and N other adjacent > string items where N can vary from 20 to 150. So if I had these strings "ape", "bee", "cat", dog", "eel", "fly", "gnu", "hex", "imp", "jut", "kit", "lox" and N were 2 and the user entered "g" the program finds "dog" and sends back "cat", dog", "eel". OK so far or not? The user then enters "y", the program finds "fly" and sends back "eel", "fly", "gnu". OK so far or not? The user then enters "x", the program finds no match and sends back what?? > Each string item is sent back to the JS in separate print statements. IIRC you don't need separate print statements. Just put \n between the strings and print one big string. > Hence, the for loop. > > Now, N = 20 to 150 is not a lot (for a for loop) but this process is > performed each time the user enters a character. Plus, there will be > thousands (possibly more) users at a time. There is also the > searching of the >10,000 string items using the entered character. > All of this adds up in terms of performance. > > I haven't done any profiling yet as we are still building the system > but it seemed sensible that replacing the for loop with a built-in > would help. Maybe not? > > Hope that helps. > > Dinesh > > > ----- Original Message ----- > *From:* Kent Johnson > *To:* Dinesh B Vadhia > *Cc:* tutor at python.org > *Sent:* Wednesday, April 09, 2008 1:48 PM > *Subject:* Re: [Tutor] List comprehensions > > Dinesh B Vadhia wrote: > > Here is a for loop operating on a list of string items: > > > > data = ["string 1", "string 2", "string 3", "string 4", "string 5", > > "string 6", "string 7", "string 8", "string 9", "string 10", "string > 11"] > > > > result = "" > > for item in data: > > result = item > > print result > > > > I want to replace the for loop with another structure to improve > > performance (as the data list will contain >10,000 string items]. At > > each iteration of the for loop the result is printed (in fact, the > > result is sent from the server to a browser one result line at a time) > > Any savings you have from optimizing this loop will be completely > swamped by the network time. Why do you think this is a bottleneck? > > You could use > [ sys.stdout.write(some operation on item) for item in data ] > > but I consider this bad style and I seriously doubt you will see any > difference in performance. > > > The for loop will be called continuously and this is another reason to > > look for a potentially better structure preferably a built-in. > > What do you mean 'called continuously'? > > Kent > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 919-636-4239 Chapel Hill, NC From dineshbvadhia at hotmail.com Thu Apr 10 15:13:03 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Thu, 10 Apr 2008 06:13:03 -0700 Subject: [Tutor] Searching through large number of string items References: <47FD1BB4.5050108@tds.net> <47FD2B9C.10209@tds.net> <47FE0617.5030203@tds.net> Message-ID: The 10,000 string items are sorted. The way the autocomplete works is that when a user enters a char eg. 'f', the 'f' is sent to the server and returns strings with the char 'f'. You can limit the number of items sent back to the browser (say, limit to between 15 and 100). The string items containing 'f' are displayed. The user can then enter another char eg. 'a' to make 'fa'. The autocomplete plugin will search the cache to find all items containing 'fa' but may need to go back to the server to collect others. And, so on. Equally, the user could backspace the 'f' and enter 'k'. The 'k' will be sent to the server to find strings containing 'k', and so on. One way to solve this is with linear search which as you rightly pointed out has horrible performance (and it has!). I'll try the binary search and let you know. I'll also look at the trie structure. An alternative is to create an in-memory SQLite database of the string items. Any thoughts on that? Dinesh ----- Original Message ----- From: Kent Johnson To: Dinesh B Vadhia Cc: tutor at python.org Sent: Thursday, April 10, 2008 5:20 AM Subject: Re: [Tutor] List comprehensions Dinesh B Vadhia wrote: > Kent > > I'm using a Javascript autocomplete plugin for an online web > application/service. Each time a user inputs a character, the character > is sent to the backend Python program which searches for the character > in a list of >10,000 string items. Once it finds the character, the > backend will return that string and N other adjacent string items where > N can vary from 20 to 150. Each string item is sent back to the JS in > separate print statements. Hence, the for loop. Ok, this sounds a little closer to a real spec. What kind of search are you doing? Do you really just search for individual characters or are you looking for the entire string entered so far as a prefix? Is the list of 10,000 items sorted? Can it be? You need to look at your real problem and find an appropriate data structure, rather than showing us what you think is the solution and asking how to make it faster. For example, if what you have a sorted list of strings and you want to find the first string that starts with a given prefix and return the N adjacent strings, you could use the bisect module to do a binary search rather than a linear search. Binary search of 10,000 items will take 13-14 comparisons to find the correct location. Your linear search will take an average of 5,000 comparisons. You might also want to use a trie structure though I'm not sure if that will let you find adjacent items. http://www.cs.mcgill.ca/~cs251/OldCourses/1997/topic7/ http://jtauber.com/blog/2005/02/10/updated_python_trie_implementation/ > I haven't done any profiling yet as we are still building the system but > it seemed sensible that replacing the for loop with a built-in would > help. Maybe not? Not. An algorithm with poor "big O" performance should be *replaced*, not optimized. Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080410/240d8aaf/attachment-0001.htm From kent37 at tds.net Thu Apr 10 15:32:22 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 Apr 2008 09:32:22 -0400 Subject: [Tutor] Searching through large number of string items In-Reply-To: References: <47FD1BB4.5050108@tds.net> <47FD2B9C.10209@tds.net> <47FE0617.5030203@tds.net> Message-ID: <47FE16E6.3070301@tds.net> Dinesh B Vadhia wrote: > The 10,000 string items are sorted. > > The way the autocomplete works is that when a user enters a char eg. > 'f', the 'f' is sent to the server and returns strings with the char > 'f'. If it is all strings containing 'f' (not all strings starting with 'f') then the binary search will not work. A database might work better for that. You can get all strings containing some substring x with [ item for item in list if x in item ] Of course that is back to linear search. You mentioned before that you want to also show adjacent items? I don't know how to do that with a database either. Kent From cappy2112 at gmail.com Thu Apr 10 15:45:42 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Thu, 10 Apr 2008 06:45:42 -0700 Subject: [Tutor] Copy script Message-ID: <8249c4ac0804100645s674b24f3ndcb8f78091408551@mail.gmail.com> Message: 7 Date: Thu, 10 Apr 2008 01:46:49 +0100 From: "Alan Gauld" Subject: Re: [Tutor] Copy script To: tutor at python.org Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original >>I don;t see how the input file relates to the pdf files? >>Which part of the pdf file does the input numbers refer to? Kent, I believe the text file contains the name of the text files the author wants to copy The problem with the Windows console commands is I don't believe they have the ability to read files for input. Que Here is some code that should get you started. I don't see the name of the destination directory in your email, so you will have to edit the variable 'destpath' in the code below Indenting is likely to get changed during posting, so be aware of that. import shutil import os sourceDir='' for line in open('input.txt'): if not sourceDir and ':' in line: sourceDir = line[line.find(':')-1:] if 'pdf' in line.lower(): filename = line.split(' ')[-1] sourcePath = os.path.join(sourceDir, filename) shutil.copyfile(sourcePath, destPath) print'\nCopying %s' % sourcePath print'\nCopy done' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080410/d5d0d300/attachment.htm From geekomancerone at gmail.com Thu Apr 10 15:52:29 2008 From: geekomancerone at gmail.com (Michael Schultz) Date: Thu, 10 Apr 2008 08:52:29 -0500 Subject: [Tutor] Text editing Message-ID: <9a326b160804100652y20aa82c4g604b11b69417b126@mail.gmail.com> Hello everyone. I'm looking to build a cross-platform "writer's assistant", and I figured my first step would be to re-invent the wheel, er I mean built a simple rich-text editor as a base. I'm trying to figure out the simplest way to do so, and figured I'd ask if anyone knew some good resources that give examples I can study? Thanks a lot! ~Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080410/b8a18b84/attachment.htm From dineshbvadhia at hotmail.com Thu Apr 10 15:54:29 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Thu, 10 Apr 2008 06:54:29 -0700 Subject: [Tutor] Searching through large number of string items References: <47FD1BB4.5050108@tds.net> <47FD2B9C.10209@tds.net> <47FE0617.5030203@tds.net> <47FE16E6.3070301@tds.net> Message-ID: Ignore the 'adjacent items' remark. The rest is correct ie. looking for all strings containing a substring x. ----- Original Message ----- From: Kent Johnson To: Dinesh B Vadhia Cc: tutor at python.org Sent: Thursday, April 10, 2008 6:32 AM Subject: Re: [Tutor] Searching through large number of string items Dinesh B Vadhia wrote: > The 10,000 string items are sorted. > > The way the autocomplete works is that when a user enters a char eg. > 'f', the 'f' is sent to the server and returns strings with the char > 'f'. If it is all strings containing 'f' (not all strings starting with 'f') then the binary search will not work. A database might work better for that. You can get all strings containing some substring x with [ item for item in list if x in item ] Of course that is back to linear search. You mentioned before that you want to also show adjacent items? I don't know how to do that with a database either. Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080410/192a17e5/attachment.htm From GGraham at cistercian.org Thu Apr 10 16:02:31 2008 From: GGraham at cistercian.org (Greg Graham) Date: Thu, 10 Apr 2008 09:02:31 -0500 Subject: [Tutor] Searching through large number of string items In-Reply-To: References: <47FD1BB4.5050108@tds.net><47FD2B9C.10209@tds.net><47FE0617.5030203@tds.net> Message-ID: <4B07785C52C78449A6C036FB2F69BEBD0320B848@server1.cistercian.com> One idea has to do with the fact that there are only 26 (assuming Latin alphabet) possible first letters, so I would try splitting up the list of 10,000 into 26 lists in a dictionary indexed by the first letter. Just doing that is a big reduction of your search space. That way you won't be doing the same search every time for a particular first letter. It might even be worthwhile to split each of those into 26 sublists based on the second letter. Now you've chopped up your 10,000 words into 676 lists, each of which might be small enough to send to the client without further searching. (Too bad you won't have an even distribution across all letters. Then each list would only have 15 words in it.) You could also try using SQLite. I'm using right now in a Django application, and I'm very happy with the setup and performance, especially for read operations. With Django, I'm using their ORM, which is quite nice, so I'm not doing any SQL directly. I think there can be problems with SQLite when you attempt concurrent writes, but you wouldn't have that. It's hard to predict which would perform better, a tailor made domain specific solution written in Python, or a general purpose in-memory database written in C. I would start with which ever direction you are most comfortable, and if you can't get satisfactory performance, try the other route. Greg From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Dinesh B Vadhia Sent: Thursday, April 10, 2008 8:13 AM To: tutor at python.org Subject: Re: [Tutor] Searching through large number of string items The 10,000 string items are sorted. The way the autocomplete works is that when a user enters a char eg. 'f', the 'f' is sent to the server and returns strings with the char 'f'. You can limit the number of items sent back to the browser (say, limit to between 15 and 100). The string items containing 'f' are displayed. The user can then enter another char eg. 'a' to make 'fa'. The autocomplete plugin will search the cache to find all items containing 'fa' but may need to go back to the server to collect others. And, so on. Equally, the user could backspace the 'f' and enter 'k'. The 'k' will be sent to the server to find strings containing 'k', and so on. One way to solve this is with linear search which as you rightly pointed out has horrible performance (and it has!). I'll try the binary search and let you know. I'll also look at the trie structure. An alternative is to create an in-memory SQLite database of the string items. Any thoughts on that? Dinesh ----- Original Message ----- From: Kent Johnson To: Dinesh B Vadhia Cc: tutor at python.org Sent: Thursday, April 10, 2008 5:20 AM Subject: Re: [Tutor] List comprehensions Dinesh B Vadhia wrote: > Kent > > I'm using a Javascript autocomplete plugin for an online web > application/service. Each time a user inputs a character, the character > is sent to the backend Python program which searches for the character > in a list of >10,000 string items. Once it finds the character, the > backend will return that string and N other adjacent string items where > N can vary from 20 to 150. Each string item is sent back to the JS in > separate print statements. Hence, the for loop. Ok, this sounds a little closer to a real spec. What kind of search are you doing? Do you really just search for individual characters or are you looking for the entire string entered so far as a prefix? Is the list of 10,000 items sorted? Can it be? You need to look at your real problem and find an appropriate data structure, rather than showing us what you think is the solution and asking how to make it faster. For example, if what you have a sorted list of strings and you want to find the first string that starts with a given prefix and return the N adjacent strings, you could use the bisect module to do a binary search rather than a linear search. Binary search of 10,000 items will take 13-14 comparisons to find the correct location. Your linear search will take an average of 5,000 comparisons. You might also want to use a trie structure though I'm not sure if that will let you find adjacent items. http://www.cs.mcgill.ca/~cs251/OldCourses/1997/topic7/ http://jtauber.com/blog/2005/02/10/updated_python_trie_implementation/ > I haven't done any profiling yet as we are still building the system but > it seemed sensible that replacing the for loop with a built-in would > help. Maybe not? Not. An algorithm with poor "big O" performance should be *replaced*, not optimized. Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080410/e0423072/attachment-0001.htm From kent37 at tds.net Thu Apr 10 16:14:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 Apr 2008 10:14:40 -0400 Subject: [Tutor] Text editing In-Reply-To: <9a326b160804100652y20aa82c4g604b11b69417b126@mail.gmail.com> References: <9a326b160804100652y20aa82c4g604b11b69417b126@mail.gmail.com> Message-ID: <47FE20D0.2080807@tds.net> Michael Schultz wrote: > Hello everyone. I'm looking to build a cross-platform "writer's > assistant", and I figured my first step would be to re-invent the wheel, > er I mean built a simple rich-text editor as a base. > > I'm trying to figure out the simplest way to do so, and figured I'd ask > if anyone knew some good resources that give examples I can study? wxPython includes a rich text control, see the wx demos. Kent From kent37 at tds.net Thu Apr 10 16:41:56 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 Apr 2008 10:41:56 -0400 Subject: [Tutor] Searching through large number of string items In-Reply-To: References: <47FD1BB4.5050108@tds.net> <47FD2B9C.10209@tds.net> <47FE0617.5030203@tds.net> <47FE16E6.3070301@tds.net> Message-ID: <47FE2734.5020101@tds.net> Dinesh B Vadhia wrote: > Ignore the 'adjacent items' remark. The rest is correct ie. looking > for all strings containing a substring x. Perhaps this would help: http://hkn.eecs.berkeley.edu/~dyoo/python/suffix_trees/ A SubstringDict that maps each string to itself would do exactly what you want. I have no idea what the performance would be... Kent From pylinuxian at gmail.com Thu Apr 10 18:14:54 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Thu, 10 Apr 2008 16:14:54 +0000 Subject: [Tutor] queries from the web & random number Message-ID: I have been used to making queries to websites automatically & analizing the results. a few minutes ago ... i can no longer do that now a website is protected by a ramdom number that i have to enter before i can login. its a picture with numbers on it that i have to type in in the authentication form before login in. i use urllib2.install_opener(opener) to keep the kookies & work on other pages of the website using response=urllib2.urlopen(req) now i need to at least be able to download this very first picture that has the random number on it to my hard disk so that i can look at it & feed my script with that number automatically. is that possible ? its a picture thats generated on the fly i guess & it comes only at the login page. i mean launch script, look at the picture, feed taht number to my script from the prompt & hit enter & it would go on as usual. thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080410/49a976d6/attachment.htm From alan.gauld at btinternet.com Thu Apr 10 19:17:30 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Apr 2008 18:17:30 +0100 Subject: [Tutor] Copy script References: <8249c4ac0804100645s674b24f3ndcb8f78091408551@mail.gmail.com> Message-ID: "Tony Cappellini" wrote >>>I don;t see how the input file relates to the pdf files? >>>Which part of the pdf file does the input numbers refer to? > > Kent, I believe the text file contains the name Actually that was me :-) > The problem with the Windows console commands is I don't believe > they have > the ability to read files for input. Of course they do - they can use input redirection just like Unix. But the FOR /F option I mentioned is explicitly for iterating over the contents of a text file. And of course you can use backticks(`) to TYPE a file into a command, in place of a file list, say. The XP command line tools are much better than the early DOS stuff - although still nowhere near to Unix shells. Alan G. From alan.gauld at btinternet.com Thu Apr 10 19:24:39 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Apr 2008 18:24:39 +0100 Subject: [Tutor] queries from the web & random number References: Message-ID: "linuxian iandsd" wrote > now a website is protected by a ramdom number that i have to enter > before i > can login.its a picture with numbers on it that i have to type in in > the > authentication form before login in. This is added to web sites to specifically stop people screen scraping the site. Sometimes to stop comparison sites from stealing trade, other times to force users to see sponsors adverts. If you ignore the owners/authors wishes you will make yourself unpopular and very unlikely to get much support from them in future. Worth considering before you deliberately set out to circumvent their wishes > now i need to at least be able to download this very first picture > that has > the random number on it to my hard disk so that i can look at it & > feed my > script with that number automatically. is that possible ? Almost cerainly since its just an embedded image, although what you do once you've grabbed it is another matter... If its present it to the user for manual input not too bad, if its trying to auto-read the text out of the uimage, then good luck! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Apr 10 19:20:07 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Apr 2008 18:20:07 +0100 Subject: [Tutor] Text editing References: <9a326b160804100652y20aa82c4g604b11b69417b126@mail.gmail.com> Message-ID: "Michael Schultz" wrote > Hello everyone. I'm looking to build a cross-platform "writer's > assistant", > and I figured my first step would be to re-invent the wheel, er I > mean built > a simple rich-text editor as a base. > > I'm trying to figure out the simplest way to do so, and figured I'd > ask if > anyone knew some good resources that give examples I can study? Look at the code for IDLE. Look at the Scintilla widget and the Ala Mode code in wxPython. I assume you want to use a GUI toolkit. Fuinally decide whether you want a full GUI WYSIWYG editing interface or a command driven one (ala vi or emacs C- mode). The latter is esier to build but less popular with modern users. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From marc.tompkins at gmail.com Thu Apr 10 19:30:12 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 10 Apr 2008 10:30:12 -0700 Subject: [Tutor] queries from the web & random number In-Reply-To: References: Message-ID: <40af687b0804101030w7b35f4aco7fcf00c5e3ea1179@mail.gmail.com> On Thu, Apr 10, 2008 at 9:14 AM, linuxian iandsd wrote: > I have been used to making queries to websites automatically & analizing > the results. a few minutes ago ... i can no longer do that > now a website is protected by a ramdom number that i have to enter before > i can login. > its a picture with numbers on it that i have to type in in the > authentication form before login in. > I don't have any insight on solving your problem - but what you're talking about is called CAPTCHA, for Completely Automated Public Turing Test to Tell Computers and Humans Apart. It'll probably be easier to communicate if you call it by name - everybody will know what you mean. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080410/b6919e67/attachment.htm From sanhitam at yahoo.com Thu Apr 10 19:47:10 2008 From: sanhitam at yahoo.com (Sanhita Mallick) Date: Thu, 10 Apr 2008 10:47:10 -0700 (PDT) Subject: [Tutor] Graphs in Python Message-ID: <725136.71886.qm@web55603.mail.re4.yahoo.com> Hi. I am a newbie to Python. I am trying to implement a Python code for graph manipulation. My graphs are about 200-500 nodes big. Excepting for the short basic graph implementation info on Python.org, where can I find more in depth info about how to express graphs in python, and how to use them in a code? Also, does anyone know of a easy way of creating the dictionary for python for a 500-node graph, without typing each and every node? I found some application that recognize dot file Graphviz - but I am looking for a program that can let me "draw" a graph and then generate the lists automatically from the drawing. Thanks. -SM From kent37 at tds.net Thu Apr 10 20:06:19 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 Apr 2008 14:06:19 -0400 Subject: [Tutor] Graphs in Python In-Reply-To: <725136.71886.qm@web55603.mail.re4.yahoo.com> References: <725136.71886.qm@web55603.mail.re4.yahoo.com> Message-ID: <47FE571B.5030207@tds.net> Sanhita Mallick wrote: > Hi. > > I am a newbie to Python. I am trying to implement a > Python code for graph manipulation. My graphs are > about 200-500 nodes big. Excepting for the short basic > graph implementation info on Python.org, where can I > find more in depth info about how to express graphs in > python, and how to use them in a code? Many pointers here: http://www.velocityreviews.com/forums/t355467-tree-and-graph-structures-in-python.html Kent From pylinuxian at gmail.com Thu Apr 10 20:32:37 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Thu, 10 Apr 2008 18:32:37 +0000 Subject: [Tutor] queries from the web & random number In-Reply-To: <40af687b0804101030w7b35f4aco7fcf00c5e3ea1179@mail.gmail.com> References: <40af687b0804101030w7b35f4aco7fcf00c5e3ea1179@mail.gmail.com> Message-ID: I modified old script - added get_img=urllib2.urlopen('http://website.com/jcaptcha.jpg') > secret_img=open('/home/iandsd/secret_img.jpg','wb') > secret_img.write(get_img.read()) > secret_img.close() > and then to add the value to the dictionary : values['captcha']=raw_input("Enter the number you see on picture :") > data=urllib.urlencode(values) > req=urllib2.Request(url, data, headers) > > & i m on the road again. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080410/5435d5fe/attachment-0001.htm From govindgoyal at gmail.com Thu Apr 10 20:42:19 2008 From: govindgoyal at gmail.com (govind goyal) Date: Thu, 10 Apr 2008 11:42:19 -0700 Subject: [Tutor] python access of usb for winxp Message-ID: Hello, I want to retreive data to and fro USB device attached/connected to my WinXP PC. Is there any module or library available in python? I came across "pyusb" and downloaded some packages but I am not getting how to use or install those packages. Can anybody help me out in above stuffs? All help will be highly appreciated. Thanks and Best Regards, --Govind Goyal -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080410/ad8521e4/attachment.htm From cappy2112 at gmail.com Thu Apr 10 20:44:29 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Thu, 10 Apr 2008 11:44:29 -0700 Subject: [Tutor] Copy script Message-ID: <8249c4ac0804101144y251c18abj512b8c25392910cd@mail.gmail.com> >>Of course they do - they can use input redirection just like Unix. Oh,-I have forgotten about that. But why use clunky batch language when you can use Python? After all, he did post this to the python list. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080410/e67d3d22/attachment.htm From pylinuxian at gmail.com Thu Apr 10 21:05:39 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Thu, 10 Apr 2008 19:05:39 +0000 Subject: [Tutor] queries from the web & random number In-Reply-To: References: <40af687b0804101030w7b35f4aco7fcf00c5e3ea1179@mail.gmail.com> Message-ID: i was wondering if there was there any means of sending this number to the script thru the web. I mean have the script run from cron & i can remotely access the image read the code & enter the code in a form to be "submitted to my script" or another script i don't mind as long as it gets to final destination. I have already setup webpage with form & i have the image on it. i guess i have to setup some sort of server /client application to do this ... -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080410/13bb6621/attachment.htm From agent.krycek at gmail.com Thu Apr 10 22:22:47 2008 From: agent.krycek at gmail.com (Alex Krycek) Date: Thu, 10 Apr 2008 14:22:47 -0600 Subject: [Tutor] Python, CGI and CSS Message-ID: Hi, I've looked all over the internet but have not found an answer to my question. How do I apply an external stylesheet to the XHTML in a Python script? I tried to include the standard """ in with the rest of the printed XHTML. But that didn't work. I changed the href attribute to "/style1.css", then to "../style1.css" and finally to "http://localhost/cgi-bin/style1.css", all failed attempts. Just so you know, both sets of permissions for these two files have been set to 755. I tried other cgi scripts (still residing in the cgi-bin) and they did work. I checked the error log, and this is what I'm getting: (2)No such file or directory. When I took both files out of my cgi-bin, as a test, the CSS rules were implemented. I'm not sure why it stops working when located in the cgi-bin folder. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080410/b2d0607f/attachment.htm From steve at alchemy.com Thu Apr 10 22:27:51 2008 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 10 Apr 2008 13:27:51 -0700 Subject: [Tutor] Python, CGI and CSS In-Reply-To: References: Message-ID: <20080410202751.GA28456@dragon.alchemy.com> On Thu, Apr 10, 2008 at 02:22:47PM -0600, Alex Krycek wrote: > Hi, > > I've looked all over the internet but have not found an answer to my > question. How do I apply an external stylesheet to the XHTML in a Python > script? I tried to include the standard " type='text/css' href='style1.css' />"" in with the rest of the printed > XHTML. But that didn't work. I changed the href attribute to "/style1.css", > then to "../style1.css" and finally to "http://localhost/cgi-bin/style1.css", > all failed attempts. Just so you know, both sets of permissions for these > two files have been set to 755. I tried other cgi scripts (still residing in > the cgi-bin) and they did work. I checked the error log, and this is what > I'm getting: (2)No such file or directory. > > When I took both files out of my cgi-bin, as a test, the CSS rules were > implemented. I'm not sure why it stops working when located in the > cgi-bin folder. It's likely your web server is set up to *execute* (not deliver as text) files in your cgi-bin directory. > > Thanks! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From eric at ericwalstad.com Thu Apr 10 22:35:22 2008 From: eric at ericwalstad.com (Eric Walstad) Date: Thu, 10 Apr 2008 13:35:22 -0700 Subject: [Tutor] Python, CGI and CSS In-Reply-To: References: Message-ID: Hi Alex, On Thu, Apr 10, 2008 at 1:22 PM, Alex Krycek wrote: > Hi, > > I've looked all over the internet but have not found an answer to my > question. How do I apply an external stylesheet to the XHTML in a Python > script? I tried to include the standard " type='text/css' href='style1.css' />"" in with the rest of the printed > XHTML. Try writing your html file by hand, tweaking the href and/or server config and/or file permissions by hand until it *does* work. Once you have a working reference point, then make your Python script duplicate what you know works. > I > tried other cgi scripts (still residing in the cgi-bin) and they did work. View the HTML source of these working CGI scripts to see what the css link tag looks like. How does it differ from the css link tag output of your Python script? > I > checked the error log, and this is what I'm getting: (2)No such file or > directory. Paste the actual log file line here. > When I took both files out of my cgi-bin, as a test, the CSS rules were > implemented. I'm not sure why it stops working when located in the cgi-bin > folder. It feels like a permissions problem or a configuration problem with your web server. What webserver are you using? Have you followed any of the CGI tutorials? From agent.krycek at gmail.com Thu Apr 10 22:43:03 2008 From: agent.krycek at gmail.com (Alex Krycek) Date: Thu, 10 Apr 2008 14:43:03 -0600 Subject: [Tutor] Python, CGI and CSS In-Reply-To: References: Message-ID: Eric, I'm sorry, I never actually managed to get any stylesheets to work with my cgi scripts. The scripts that did work are just simple HTML. I'm using Apache 2.2.8 on a Mac OS X 10.4.11 system. When I get home I'll definitely look up the log file and paste it here. I'll also have to fool around with the permissions and httpd.conf file. I did look into CGI tutorials, but they didn't use Python code. They used something like: start_html(-title => $title, -head => style({type => 'text/css'} ) Thanks for the suggestions though. On 4/10/08, Eric Walstad wrote: > > Hi Alex, > > On Thu, Apr 10, 2008 at 1:22 PM, Alex Krycek > wrote: > > Hi, > > > > I've looked all over the internet but have not found an answer to my > > question. How do I apply an external stylesheet to the XHTML in a Python > > script? I tried to include the standard " > type='text/css' href='style1.css' />"" in with the rest of the printed > > XHTML. > > Try writing your html file by hand, tweaking the href and/or server > config and/or file permissions by hand until it *does* work. Once you > have a working reference point, then make your Python script duplicate > what you know works. > > > > > I > > tried other cgi scripts (still residing in the cgi-bin) and they did > work. > > View the HTML source of these working CGI scripts to see what the css > link tag looks like. How does it differ from the css link tag output > of your Python script? > > > > > I > > checked the error log, and this is what I'm getting: (2)No such file or > > directory. > > Paste the actual log file line here. > > > > > When I took both files out of my cgi-bin, as a test, the CSS rules were > > implemented. I'm not sure why it stops working when located in the > cgi-bin > > folder. > > It feels like a permissions problem or a configuration problem with > your web server. > > > What webserver are you using? > Have you followed any of the CGI tutorials? > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080410/ab9f78f4/attachment.htm From robertk at bcgsc.ca Thu Apr 10 22:34:27 2008 From: robertk at bcgsc.ca (Robert Kirkpatrick) Date: Thu, 10 Apr 2008 13:34:27 -0700 Subject: [Tutor] Conventions for code snippets for debugging and testing? Message-ID: Hi All, Just wondering if there are any basic conventions for including code snippets that are for testing / debugging only? For example, you could set a boolean variable called DEBUG, then have snippets of code like: if DEBUG: do stuff else: do otherstuff The use case I'm dealing with right now is to query the SVN commits for a weekly period and report on each user for that time period. If I'm testing though, I only want to cycle through a few users, not all of them. I'm thinking there has to be something slicker than that but maybe not... Thoughts? Rob From eric at ericwalstad.com Thu Apr 10 23:11:22 2008 From: eric at ericwalstad.com (Eric Walstad) Date: Thu, 10 Apr 2008 14:11:22 -0700 Subject: [Tutor] Python, CGI and CSS In-Reply-To: References: Message-ID: Hey Alex, On Thu, Apr 10, 2008 at 1:43 PM, Alex Krycek wrote: > Eric, > > I'm sorry, I never actually managed to get any stylesheets to work with my > cgi scripts. The scripts that did work are just simple HTML. I'm using > Apache 2.2.8 on a Mac OS X 10.4.11 system. If I understand your problem, you are expecting to see your stylesheet loaded but that is not happening. If that's what you want to fix, then I suggest you fix it in as simple a test case as possible. Try browsing directly to the css file with your web browser. When you have your web server configured correctly you should see the contents of your css displayed in the web browser. If you can't view your css file in your browser, then send us the apache log file line that shows the failed GET request and we can go from there. Keep the scripting and cgi stuff out of the equation until you get this working. Also, reread the apache FAQ. From eric at ericwalstad.com Thu Apr 10 23:21:05 2008 From: eric at ericwalstad.com (Eric Walstad) Date: Thu, 10 Apr 2008 14:21:05 -0700 Subject: [Tutor] Conventions for code snippets for debugging and testing? In-Reply-To: References: Message-ID: Hi Robert On Thu, Apr 10, 2008 at 1:34 PM, Robert Kirkpatrick wrote: > Hi All, > > Just wondering if there are any basic conventions for including code > snippets that are for testing / debugging only? > > For example, you could set a boolean variable called DEBUG, then have > snippets of code like: > > if DEBUG: > do stuff > else: > do otherstuff I'd do something like this: from settings import DEBUG def my_user_list() # assumes long_list is already populated (db, file, etc) if DEBUG: return long_list[:5] else: return long_list def process(user): # do the work on the user here pass def main(): # ... [process(user) for user in my_user_list()] The idea is to encapsulate the retrieval of the user list and let that encapsulation hide the DEBUG logic. It could be done with a function, like above, or with a MyUserList class. From kent37 at tds.net Thu Apr 10 23:22:16 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 Apr 2008 17:22:16 -0400 Subject: [Tutor] Python, CGI and CSS In-Reply-To: References: Message-ID: <47FE8508.1000604@tds.net> Alex Krycek wrote: > Eric, > > I'm sorry, I never actually managed to get any stylesheets to work with > my cgi scripts. The scripts that did work are just simple HTML. Where are the css files that work located? What URL is used to fetch them? If you put the css for your cgi into the same location and fetch with a similar URL it should work. Kent From kent37 at tds.net Thu Apr 10 23:24:52 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 Apr 2008 17:24:52 -0400 Subject: [Tutor] Conventions for code snippets for debugging and testing? In-Reply-To: References: Message-ID: <47FE85A4.1020402@tds.net> Robert Kirkpatrick wrote: > Hi All, > > Just wondering if there are any basic conventions for including code > snippets that are for testing / debugging only? > > For example, you could set a boolean variable called DEBUG, That is pretty common, with a boolean or an integer (for levels of debug info). > The use case I'm dealing with right now is to query the SVN commits for a > weekly period and report on each user for that time period. If I'm testing > though, I only want to cycle through a few users, not all of them. I would look at the structure of your code. Maybe there is a function that just runs one user that you could use for testing, or perhaps you could pass in a number that is a limit on how many users to process. Kent From kent37 at tds.net Thu Apr 10 23:46:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 Apr 2008 17:46:14 -0400 Subject: [Tutor] Conventions for code snippets for debugging and testing? In-Reply-To: References: Message-ID: <47FE8AA6.8050508@tds.net> Eric Walstad wrote: > I'd do something like this: > > from settings import DEBUG > > def my_user_list() > # assumes long_list is already populated (db, file, etc) > if DEBUG: > return long_list[:5] > else: > return long_list > > def process(user): > # do the work on the user here > pass > > def main(): > # ... > [process(user) for user in my_user_list()] > > The idea is to encapsulate the retrieval of the user list and let that > encapsulation hide the DEBUG logic. It could be done with a function, > like above, or with a MyUserList class. I would encapsulate the retrieval but not the DEBUG. My preference would be to have a separate main() in a test module that trims the user list. Then the DEBUG setting is not needed at all. Kent From dineshbvadhia at hotmail.com Fri Apr 11 00:24:41 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Thu, 10 Apr 2008 15:24:41 -0700 Subject: [Tutor] SQLite LIKE question Message-ID: I'm reading a text file into an in-memory pysqlite table. When I do a SELECT on the table, I get a 'u' in front of each returned row eg. > (u'QB VII',) > (u'Quackser Fortune Has a Cousin in the Bronx',) I've checked the data being INSERT'ed into the table and it has no 'u'. The second problem is that I'm using the LIKE operator to match a pattern against a string but am getting garbage results. For example, looking for the characters q='dog' in each string the SELECT statement is as follows: for row in con.execute("SELECT FROM WHERE LIKE '%q%' limit 25"): print row This doesn't work and I've tried other combinations without luck! Any thoughts on the correct syntax for the LIKE? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080410/607818ab/attachment.htm From alan.gauld at btinternet.com Fri Apr 11 00:55:45 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Apr 2008 23:55:45 +0100 Subject: [Tutor] python access of usb for winxp References: Message-ID: "govind goyal" wrote > I want to retreive data to and fro USB device attached/connected to > my > WinXP PC. It depends what kind of device it is. If it is a drive or flash card you can use the normal file access functions. If it is a printer or scanner then the usual APIs for those devices will work. You should only need to go down to the raw USB interface for very specialised devfices, and in that case you will need to understand enough about USB to use pyUSB So what kind of devices are they? And how would you access those devices if they weren't USB? Try that first! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Apr 11 01:05:50 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Apr 2008 00:05:50 +0100 Subject: [Tutor] Python, CGI and CSS References: Message-ID: "Alex Krycek" wrote > How do I apply an external stylesheet to the XHTML in a Python > script? Python doesn't really do anything with CSS that is handled by the browser. All Python can do is insert the correct HTML into the server response to the browser. > I tried to include the standard " type='text/css' href='style1.css' />"" in with the rest of the > printed > XHTML. But that didn't work. What if anything happened? And how did you test it? Did the CSS file actually exist in the location specified? > I changed the href attribute to "/style1.css", > then to "../style1.css" and finally to > "http://localhost/cgi-bin/style1.css", > all failed attempts. Just so you know, both sets of permissions for > these > two files have been set to 755. I tried other cgi scripts (still > residing in > the cgi-bin) and they did work. I checked the error log, and this is > what > I'm getting: (2)No such file or directory. So it says the file doesn't exist. Have you double checked that the css file is in the same folder as the CGI script? When you say you tried other CGI scripts and they worked, what does that mean? That they loaded the same CSS file? If its only the CSS that isn't working you can presumably save the web page from the browser as HTML? What does the HTML look like? Is it what you expected? What path is it specifying? > When I took both files out of my cgi-bin, as a test, the CSS rules > were > implemented. I'm not sure why it stops working when located in the > cgi-bin folder. Ok, You obviously understand that paragraph but to the rest of us it is wholly ambiguous. When you took which files out of cgi-bin? In what way did they work? What was different exactly that constituted "working"? What is the "it" that stops working? The system the CSS, the CGI script? All of the above? Sorry, but I need a bit more precision in the description to understand what tyhe problem is. It might help if you can include a directory tree listing of the significant files - cgi and css. Also the section of the generated HTML that imports the CSS file. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Apr 11 01:07:28 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Apr 2008 00:07:28 +0100 Subject: [Tutor] Python, CGI and CSS References: Message-ID: "Alex Krycek" wrote > I did look into CGI tutorials, but they didn't use Python code. They > used > something like: > start_html(-title => $title, > -head => style({type => 'text/css'} ) That looks like Perl. Try the CGI tutorial on the Python web site. That would be a good start. Alan G. From alan.gauld at btinternet.com Fri Apr 11 01:26:06 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Apr 2008 00:26:06 +0100 Subject: [Tutor] SQLite LIKE question References: Message-ID: "Dinesh B Vadhia" wrote > I'm reading a text file into an in-memory pysqlite table. > When I do a SELECT on the table, I get a 'u' in front of > each returned row eg. > > (u'QB VII',) The u is not part of the data its Python telling you that the string is Unicode. > The second problem is that I'm using the LIKE operator > to match a pattern against a string but am getting garbage > results. Can you be more specidic? Can you post the statement and the 'garbage'? > for row in con.execute( "SELECT FROM
WHERE LIKE '%q%' limit 25"): Is thios the actual string or have you put the placemarkers ( etc) in just for the post? You do realise that the things inside <> are intended to be replaced with the actual values from your database. Thus a realistic string would look like "SELECT Name FROM Person WHERE Name LIKE '%q%" Which would return all Names with q in them. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Apr 11 01:30:54 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Apr 2008 00:30:54 +0100 Subject: [Tutor] Conventions for code snippets for debugging and testing? References: Message-ID: "Robert Kirkpatrick" wrote > The use case I'm dealing with right now is to query the SVN commits > for a > weekly period and report on each user for that time period. If I'm > testing > though, I only want to cycle through a few users, not all of them. You could pass the values in as command line arguments which are otherwise defaulted. Then to run the debug version create a shell alias or even a shell script with the debig values and another with the production values. Or if there are several values store the values in a config file and pass the name of the config file in as an argument. Or you could use environment variables to point to the config file. Or you could store the values as individual environment vars and have a batch file set the values prior to debugging and another to reset them for production. Lots of options. There is nothing Python specific about any of this its how debug environments have been set up for decades. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From cprompt at triad.rr.com Fri Apr 11 02:42:10 2008 From: cprompt at triad.rr.com (Curtis Adkins) Date: Thu, 10 Apr 2008 20:42:10 -0400 Subject: [Tutor] Python, CGI and CSS In-Reply-To: References: Message-ID: <1207874530.28609.6.camel@wayne-manor> It seems that your link to the stylesheet is just pointing to the wrong place. Like the others said, check to make sure you are pointing to the right place of the CSS file by typing it into the web browser. If you use the link you gave : "http://localhost/cgi-bin/style1.css" what shows up? Anything? From this link it says that your style sheet is in your cgi-bin directory. On Thu, 2008-04-10 at 14:22 -0600, Alex Krycek wrote: > Hi, > > I've looked all over the internet but have not found an answer to my > question. How do I apply an external stylesheet to the XHTML in a > Python script? I tried to include the standard " type='text/css' href='style1.css' />"" in with the rest of the printed > XHTML. But that didn't work. I changed the href attribute to > "/style1.css", then to "../style1.css" and finally to > "http://localhost/cgi-bin/style1.css", all failed attempts. Just so > you know, both sets of permissions for these two files have been set > to 755. I tried other cgi scripts (still residing in the cgi-bin) and > they did work. I checked the error log, and this is what I'm getting: > (2)No such file or directory. > > When I took both files out of my cgi-bin, as a test, the CSS rules > were > implemented. I'm not sure why it stops working when located in the cgi-bin folder. > > Thanks! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From agent.krycek at gmail.com Fri Apr 11 05:05:49 2008 From: agent.krycek at gmail.com (Alex Krycek) Date: Thu, 10 Apr 2008 21:05:49 -0600 Subject: [Tutor] Python, CGI and CSS In-Reply-To: <47FE8508.1000604@tds.net> References: <47FE8508.1000604@tds.net> Message-ID: Thank you all for your help. I've finally figured it out. I took people's suggestions and typed in the path for the CSS file into my browser. Well, I received an internal service error. When I checked the error log, I had received the following: [Thu Apr 10 20:38:47 2008] [error] [client ::1] (8)Exec format error: exec of '/usr/local/apache2/cgi-bin/style1.css' failed If I understand this correctly, Apache was apparently trying to execute my CSS file. So I moved the CSS file into my /~username/Sites folder (I'm on a Mac), changed the href link in my Python script, and finally my CSS rules were applied to the selected XHTML. I read somewhere that it's not a good idea to have anything other than scripts in one's cgi-bin anyways. Thanks again! On Thu, Apr 10, 2008 at 3:22 PM, Kent Johnson wrote: > Alex Krycek wrote: > > > Eric, > > > > I'm sorry, I never actually managed to get any stylesheets to work with > > my cgi scripts. The scripts that did work are just simple HTML. > > > > Where are the css files that work located? What URL is used to fetch them? > If you put the css for your cgi into the same location and fetch with a > similar URL it should work. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080410/0a82bf7e/attachment.htm From mlangford.cs03 at gtalumni.org Fri Apr 11 08:38:51 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Fri, 11 Apr 2008 02:38:51 -0400 Subject: [Tutor] python access of usb for winxp In-Reply-To: References: Message-ID: <82b4f5810804102338m12246ae4w1b30446bc6560d2d@mail.gmail.com> Libusb on windows, which pyusb depends on, is somewhat lacking the last time I tried. Seems like libusb on win is abandoned. --Michael On Thu, Apr 10, 2008 at 2:42 PM, govind goyal wrote: > Hello, > I want to retreive data to and fro USB device attached/connected to my > WinXP PC. > Is there any module or library available in python? > I came across "pyusb" and downloaded some packages but I am not getting > how > to use or install those packages.Win > Can anybody help me out in above stuffs? > All help will be highly appreciated. > > Thanks and Best Regards, > --Govind Goyal > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080411/c6424d34/attachment.htm From dineshbvadhia at hotmail.com Fri Apr 11 09:10:58 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Fri, 11 Apr 2008 00:10:58 -0700 Subject: [Tutor] Fw: SQLite LIKE question Message-ID: Try again: I'm using the LIKE operator to match a pattern against a string using this SELECT statement: for row in con.execute("SELECT FROM
WHERE LIKE '%q%' limit 25"): .. where ,
, are placeholders! With q="dog" as a test example, I've tried '$q%', '%q%', '%q' and 'q%' and none of them return what I expect ie. all strings with the characters "dog" in them. Cheers! Dinesh ----- Original Message ----- From: Dinesh B Vadhia To: tutor at python.org Sent: Thursday, April 10, 2008 3:24 PM Subject: SQLite LIKE question I'm reading a text file into an in-memory pysqlite table. When I do a SELECT on the table, I get a 'u' in front of each returned row eg. > (u'QB VII',) > (u'Quackser Fortune Has a Cousin in the Bronx',) I've checked the data being INSERT'ed into the table and it has no 'u'. The second problem is that I'm using the LIKE operator to match a pattern against a string but am getting garbage results. For example, looking for the characters q='dog' in each string the SELECT statement is as follows: for row in con.execute("SELECT FROM
WHERE LIKE '%q%' limit 25"): print row This doesn't work and I've tried other combinations without luck! Any thoughts on the correct syntax for the LIKE? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080411/adb2d37f/attachment.htm From alan.gauld at btinternet.com Fri Apr 11 10:29:45 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Apr 2008 09:29:45 +0100 Subject: [Tutor] SQLite LIKE question References: Message-ID: "Dinesh B Vadhia" wrote > I'm using the LIKE operator to match a pattern against a string > using this SELECT statement: > > for row in con.execute(" > SELECT > FROM
> WHERE LIKE '%q%' > limit 25"): > With q="dog" as a test example, I've tried '$q%', '%q%', '%q' Ok, Thats the problem. The execute statement works somewhat like Python string formatting. Yopu don't put variable names in the string you put markers(which vary by databnase unfortunately!) In SqlLite they are question marks. You then follow the SQL statement with a list of values. Here is an example from my tutorial topic on using databases: book.execute('''DELETE FROM Address WHERE First LIKE ? AND Last LIKE ?''', (first,last) ) Notice the tuple at the end? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From simozack at yahoo.it Fri Apr 11 11:53:13 2008 From: simozack at yahoo.it (Simone) Date: Fri, 11 Apr 2008 11:53:13 +0200 Subject: [Tutor] SQLite LIKE question In-Reply-To: References: Message-ID: <47FF3509.409@yahoo.it> Dinesh B Vadhia ha scritto: > The second problem is that I'm using the LIKE operator to match a > pattern against a string but am getting garbage results. For example, > looking for the characters q='dog' in each string the SELECT statement > is as follows: > > for row in con.execute("SELECT FROM
WHERE LIKE > '%q%' limit 25"): > print row > > This doesn't work and I've tried other combinations without luck! Any > thoughts on the correct syntax for the LIKE? In Python the symbol '%' in a string is a special char: you use it, for instance, to place a variable inside a string. The command you need is something like this: query = "SELECT FROM
WHERE LIKE '%s'" % q for row in con.execute(query): print row where q is your variable and %s tells Python that the q variable has to be converted in a string during the string valorization. If you want that q contains the symbol '%', you have to escape it by inserting 2 '%'. In your example, q have to be 'dog%%' instead of 'dog%'. However, as Alan said, the method with the question mark to construct the query is more safe than this. Hope that helps, Simone Chiacchiera con i tuoi amici in tempo reale! http://it.yahoo.com/mail_it/foot/*http://it.messenger.yahoo.com From pylinuxian at gmail.com Fri Apr 11 12:10:01 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Fri, 11 Apr 2008 10:10:01 +0000 Subject: [Tutor] SQLite LIKE question In-Reply-To: <47FF3509.409@yahoo.it> References: <47FF3509.409@yahoo.it> Message-ID: I m not sure this is your case but i believe you are missing the "cur.fetchall()" command which does fetch data from sql db .... i suggest you put a print statement for every data you use in your program that way you know whats empty & whats not... here is example of MySQLdb process: con=MySQLdb.connect(host='xxxxx', user='xxxxx', passwd='xxxxx', db='xxxxxxxx' ) cur) cur=con.cursor() my_cmd="select %s from xxxx where fieldx= '%s' ; " % (var1, var2) cur.execute(my_cmd) #now the cmd you are missing : data=cur.fetchall() # & then comes the : for i in data: print i hope this helps -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080411/ad9851d6/attachment.htm From pylinuxian at gmail.com Fri Apr 11 12:12:05 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Fri, 11 Apr 2008 10:12:05 +0000 Subject: [Tutor] SQLite LIKE question In-Reply-To: References: <47FF3509.409@yahoo.it> Message-ID: i forgot to mention that you need to try your sql commands out of your script before trying them inside, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080411/111742bd/attachment.htm From steve at alchemy.com Fri Apr 11 12:22:25 2008 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 11 Apr 2008 03:22:25 -0700 Subject: [Tutor] SQLite LIKE question In-Reply-To: <47FF3509.409@yahoo.it> References: <47FF3509.409@yahoo.it> Message-ID: <47FF3BE1.8070300@alchemy.com> Simone wrote: > In Python the symbol '%' in a string is a special char: you use it, for > instance, to place a variable inside a string. For completeness, it's worth mentioning in passing that % is only special when you're doing string formatting. It's not otherwise special in strings. > However, as Alan said, the method with the question mark to construct > the query is more safe than this. Way way way way way safer. In fact, forget that you can even use string formatting to put values into SQL queries. At all. Unless you know precisely what you're doing. And even then don't do it. Really. That way lies madness. And more, larger, and more disastrous SQL database problems than possibly any other error. If your library supports specifying a SQL query string using placeholders (and supplying those values in a tuple which the database module will paste in on its own), it will know to properly quote or escape special characters in those data values. Some modules use ? as the place holder, others use %s (even for numeric values, interestingly enough). Check with your documentation. --steve From pylinuxian at gmail.com Fri Apr 11 12:28:43 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Fri, 11 Apr 2008 10:28:43 +0000 Subject: [Tutor] queries from the web & random number In-Reply-To: References: <40af687b0804101030w7b35f4aco7fcf00c5e3ea1179@mail.gmail.com> Message-ID: i see no body has replied to my question, probably you are thinking this guy is hijicking someones website ? well, i can assure you i am not. simply because i have a username/password for this site, plus, I have thier agreement to automate the process of utilizing thier database all i want from midnight to 6 am. to axplain to you my case, we sell products, & we need to access extranet of our provider, & my job is to prepare an internal database for my company every night so that staff uses it during the next day, this is very important to our business because it gives us a step ahead of others who have to work on database live during the day manualy & thus wasting preciouse time of employees, making the surches themselves, waiting for queries to complete, making some decisions based on that, .... computers do this better ... & our provider is happy to see that we have this technology. now why would he add CAPTCHA to his extranet ? well, i don't know & i believe thier IT stuff are trying to improve thier extranet for the better, & they have all the right to doing that, as i myself do shut our website & sql db server every night at 10pm, or use another port other than 80, i am free to protect my stuff as well as they are free too. this said, i believe there are other means to protecting content of websites other than CAPCHA simply by ip or by number of queries ... etc ... so don't make me look like tryin to hijack websites please. i hope you find some truth in this. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080411/328b7b2f/attachment.htm From dineshbvadhia at hotmail.com Fri Apr 11 14:13:03 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Fri, 11 Apr 2008 05:13:03 -0700 Subject: [Tutor] SQLite LIKE question Message-ID: Okay, I've got this now: > con = sqlite3.connect(":memory:") > cur = con.cursor() > cur.execute("""CREATE TABLE db.table(col.a integer, col.b text)""") > con.executemany("""INSERT INTO db.table(col.a, col.b) VALUES (?, ?)""", m) > con.commit() > for row in con.execute("""SELECT col.a, col.b FROM db.table"""): > print row > # when run, all rows are printed correctly but as unicode strings > q = "dog" > for row in con.execute("""SELECT col.b FROM db.table WHERE col.b LIKE ? LIMIT 25""", q): > print row .. And, I get the following error: Traceback (most recent call last): for row in con.execute("SELECT col.b FROM db.table WHERE col.b LIKE ? LIMIT 25", q): ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied. As Python/pysqlite stores the items in the db.table as unicode strings, I've also run the code with q=u"dog" but get the same error. Same with putting the q as a tuple ie. (q) in the Select statement. Btw, there are 73 instances of the substring 'dog' in db.table. Cheers Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080411/9545ac17/attachment.htm From mail at timgolden.me.uk Fri Apr 11 14:20:12 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 11 Apr 2008 13:20:12 +0100 Subject: [Tutor] SQLite LIKE question In-Reply-To: References: Message-ID: <47FF577C.7090904@timgolden.me.uk> Dinesh B Vadhia wrote: > Okay, I've got this now: > >> con = sqlite3.connect(":memory:") >> cur = con.cursor() >> cur.execute("""CREATE TABLE db.table(col.a integer, col.b text)""") >> con.executemany("""INSERT INTO db.table(col.a, col.b) VALUES (?, ?)""", m) >> con.commit() > >> for row in con.execute("""SELECT col.a, col.b FROM db.table"""): >> print row >> # when run, all rows are printed correctly but as unicode strings >> q = "dog" >> for row in con.execute("""SELECT col.b FROM db.table WHERE col.b LIKE ? LIMIT 25""", q): >> print row > > .. And, I get the following error: > > Traceback (most recent call last): > for row in con.execute("SELECT col.b FROM db.table WHERE col.b LIKE ? LIMIT 25", q): > ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied. Whenever you see this in a dbapi context, you can bet your socks that you're passing a single item (such as a string, q) rather than a list or tuple of items. Try passing [q] as the second parameter to that .execute function and see what happens! TJG From kent37 at tds.net Fri Apr 11 14:30:04 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 11 Apr 2008 08:30:04 -0400 Subject: [Tutor] queries from the web & random number In-Reply-To: References: <40af687b0804101030w7b35f4aco7fcf00c5e3ea1179@mail.gmail.com> Message-ID: <47FF59CC.60405@tds.net> linuxian iandsd wrote: > well, i can assure you i am not. simply because i have a > username/password for this site, plus, I have thier agreement to > automate the process of utilizing thier database all i want from > midnight to 6 am. Perhaps the supplier would give you an interface that doesn't have the captcha? Maybe even provide you with a dump of the database rather than having to screen-scrape it every night? Otherwise you will just have to simulate what the browser is doing. Kent From python at bdurham.com Fri Apr 11 14:37:44 2008 From: python at bdurham.com (Malcolm Greene) Date: Fri, 11 Apr 2008 08:37:44 -0400 Subject: [Tutor] How to normalize/compress whitespace in a string? Message-ID: <1207917464.6178.1247341705@webmail.messagingengine.com> Any suggestions for how to normalize and compress whitespace in a string? By normalize I mean convert tabs and soft spaces (extended ascii code 160) to spaces. By compress I mean replace all runs of 2 or more spaces (after the normalization step) to a single space. I know I can use regular expressions to accomplish the above, but thought that might be too heavy handed. Thank you! Malcolm From kent37 at tds.net Fri Apr 11 15:22:11 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 11 Apr 2008 09:22:11 -0400 Subject: [Tutor] How to normalize/compress whitespace in a string? In-Reply-To: <1207917464.6178.1247341705@webmail.messagingengine.com> References: <1207917464.6178.1247341705@webmail.messagingengine.com> Message-ID: <47FF6603.1020407@tds.net> Malcolm Greene wrote: > Any suggestions for how to normalize and compress whitespace in a > string? > > By normalize I mean convert tabs and soft spaces (extended ascii code > 160) to spaces. > > By compress I mean replace all runs of 2 or more spaces (after the > normalization step) to a single space. > > I know I can use regular expressions to accomplish the above, but > thought that might be too heavy handed. I would say it is appropriate. string.translate() can do the normalization but I would still use a regex to compress so you might as well do it all in a single re.sub(). Kent From dineshbvadhia at hotmail.com Fri Apr 11 15:33:27 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Fri, 11 Apr 2008 06:33:27 -0700 Subject: [Tutor] Old School Message-ID: I belong to the Old School where getting my head around OO is just one big pain. I write software by modularization executed as a set of functions - and it works (some call this functional programming!). Whenever I review Python books (eg. Lutz's excellent Programming Python, 3ed) the code is laid out with Def's followed by Classes (with their own Def's) which is as it should be. But, the Def's on their own (ie. not in Classes) are all of the form: > def abc(self): return or, > def xyz(self, ): return I don't use 'self' in my def's - should I? If so, why? Thanks! Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080411/0c44b643/attachment.htm From kent37 at tds.net Fri Apr 11 15:43:20 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 11 Apr 2008 09:43:20 -0400 Subject: [Tutor] Old School In-Reply-To: References: Message-ID: <47FF6AF8.6030600@tds.net> Dinesh B Vadhia wrote: > I belong to the Old School where getting my head around OO is just one > big pain. I write software by modularization executed as a set of > functions - and it works (some call this functional programming!). > Whenever I review Python books (eg. Lutz's excellent Programming Python, > 3ed) the code is laid out with Def's followed by Classes (with their own > Def's) which is as it should be. But, the Def's on their own (ie. not > in Classes) are all of the form: > > > def abc(self): > > return > > or, > > > def xyz(self, ): > > return > > I don't use 'self' in my def's - should I? If so, why? No. self is the first argument to a method - a function that is part of a class. That is the only place it should be used. My guess is that you are seeing defs for methods that are presented out of context. In general it doesn't make sense (and would not work correctly) to add an extra self parameter to standalone functions. Kent From mail at timgolden.me.uk Fri Apr 11 15:45:49 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 11 Apr 2008 14:45:49 +0100 Subject: [Tutor] Old School In-Reply-To: References: Message-ID: <47FF6B8D.6040309@timgolden.me.uk> Dinesh B Vadhia wrote: > I belong to the Old School where getting my head around OO is just one big pain. > I write software by modularization executed as a set of functions - > and it works The great thing about Python is that you can use Classes if you want, or not if you don't. I use them less them more as a rule, but it will depend on what your background is, what model seems best to fit the problem domain, and so on. The great thing is that Classes *aren't* second-class citizens in Python (as though added on as an afterthought), but nor is straight procedural prgramming. If you're happy writing code like this: def abc (): return [1, 2, 3] def xyz (list_of_stuff, n): return [x + n for x in list_of_stuff] # then do it. But don't feel that you can't mix that with, eg: class X (object): def __init__ (self, some_list): self.some_list = some_list def add_n_to_list (self, n): self.some_list = xyz (self.some_list, n) x123 = X (abc ()) print x123.some_list x123.add_n_to_list (3) print x123.some_list Entirely contrived, of course, but nothing wrong with it as far as it goes. TJG From kent37 at tds.net Fri Apr 11 16:08:52 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 11 Apr 2008 10:08:52 -0400 Subject: [Tutor] Old School In-Reply-To: References: Message-ID: <47FF70F4.50407@tds.net> Dinesh B Vadhia wrote: > I belong to the Old School where getting my head around OO is just one > big pain. > I write software by modularization executed as a set of > functions - and it works (some call this functional programming!). Some are wrong. That style of programming is correctly called procedural programming: http://en.wikipedia.org/wiki/Procedural_programming Functional programming "is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data." http://en.wikipedia.org/wiki/Functional_programming Many programs can be easily and naturally expressed in a procedural style, there is nothing wrong with using it. One of Python's strengths is that it supports several styles of programming. There are also situations where an OO style yields a simpler, more manageable design. This essay gives some reasons why you might want to learn about OO: http://personalpages.tds.net/~kent37/stories/00014.html Kent From alan.gauld at btinternet.com Fri Apr 11 19:44:49 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Apr 2008 18:44:49 +0100 Subject: [Tutor] SQLite LIKE question References: Message-ID: "Dinesh B Vadhia" wrote > As Python/pysqlite stores the items in the db.table as unicode > strings, I've also run the code with q=u"dog" but get the same > error. Same with putting the q as a tuple ie. (q) in the Select (q) is not a tuple, it is a variable surrounded by quotes. They are different. To pass a single element as a tuple add a comma: (q,) like so. Try that. Alan G. From alan.gauld at btinternet.com Fri Apr 11 19:49:10 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Apr 2008 18:49:10 +0100 Subject: [Tutor] How to normalize/compress whitespace in a string? References: <1207917464.6178.1247341705@webmail.messagingengine.com> Message-ID: "Malcolm Greene" wrote in message news:1207917464.6178.1247341705 at webmail.messagingengine.com... > Any suggestions for how to normalize and compress whitespace in a > string? > > By normalize I mean convert tabs and soft spaces (extended ascii > code > 160) to spaces. > > By compress I mean replace all runs of 2 or more spaces (after the > normalization step) to a single space. > > I know I can use regular expressions to accomplish the above, but > thought that might be too heavy handed. > > Thank you! > > Malcolm > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Fri Apr 11 20:31:02 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Apr 2008 19:31:02 +0100 Subject: [Tutor] How to normalize/compress whitespace in a string? References: <1207917464.6178.1247341705@webmail.messagingengine.com> Message-ID: "Alan Gauld" wrote > "Malcolm Greene" wrote in message Oops, sorry. I hit the send button by mistake while aiming for the File menu! >> Any suggestions for how to normalize and compress whitespace in a >> string? >> I know I can use regular expressions to accomplish the above, but >> thought that might be too heavy handed. regex is probably the most elegant way of doing this just because you can combine what would otherwise a lot of individual operations into a single complex operation which will probably be faster. Also the regex doesn't sound like it would be overly complex. Alan G From dineshbvadhia at hotmail.com Sat Apr 12 10:26:56 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sat, 12 Apr 2008 01:26:56 -0700 Subject: [Tutor] pysqlite and functions Message-ID: I'm using a pysqlite select statement within a def function and it's not working because (I suspect) the pysqlite variables are not being declared corrrectly to be used within a def function or the def function is not setup correctly. Here is the code followed by the errors: **** code **** con = sqlite3.connect(":memory:") # create database/table in memory cur = con.cursor() # note: can use the nonstandard execute, executemany to avoid using Cursor object query = "CREATE TABLE db.table(field.a INTEGER, field.b TEXT)" cur.execute(query) query = "INSERT INTO db.table(field.a, field.b) VALUES (?, ?)", data cur.executemany(query) def getResult(q, limit): query = "SELECT field.b FROM db.table WHERE field.b LIKE '%s' LIMIT '%s'" %(q, limit) for row in cur.execute(query): print row return # main program .. q = limit = getResult(q, limit) # call getResult with parameters q and limit .. **** end code **** The error recieved is: Traceback (most recent call last): for row in cur.execute(query): NameError: global name 'cur' is not defined Some notes: 1. The code works perfectly outside of a def function but I need to have it working within a def. 2. Clearly, everything inside getResults is private unless declared otherwise. As a quick and dirty to force it to work I declared > global con, curs, db.table .. but that results in the same error 3. Moving con and cur into the def statement results in the error: Traceback (most recent call last): for row in cur.execute(query): OperationalError: no such table: db.table 4. The def getResults is not seeing con, curs and db.table even when declared as global. 5. I wonder if this is something specific to pysqlite. Cheers! Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080412/27aec8cd/attachment-0001.htm From dineshbvadhia at hotmail.com Sat Apr 12 10:42:38 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sat, 12 Apr 2008 01:42:38 -0700 Subject: [Tutor] SQLite LIKE question Message-ID: Guys, I got it to work. The problem was to use pysqlite to search (in memory) a large number (>10,000) of string items containing the substring q (and to do it continuosly with different q's). The solution was to incase the substring q with % ie. '%q%'. The performance is excellent. The code is in my recent post (Subject: pysqlite and functions) with a new problem ie. the code works as-is but not within a def function. Dinesh .............................................................. Date: Fri, 11 Apr 2008 13:20:12 +0100 From: Tim Golden Subject: Re: [Tutor] SQLite LIKE question Cc: tutor at python.org Message-ID: <47FF577C.7090904 at timgolden.me.uk> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Dinesh B Vadhia wrote: > Okay, I've got this now: > >> con = sqlite3.connect(":memory:") >> cur = con.cursor() >> cur.execute("""CREATE TABLE db.table(col.a integer, col.b text)""") >> con.executemany("""INSERT INTO db.table(col.a, col.b) VALUES (?, ?)""", m) >> con.commit() > >> for row in con.execute("""SELECT col.a, col.b FROM db.table"""): >> print row >> # when run, all rows are printed correctly but as unicode strings >> q = "dog" >> for row in con.execute("""SELECT col.b FROM db.table WHERE col.b LIKE ? LIMIT 25""", q): >> print row > > .. And, I get the following error: > > Traceback (most recent call last): > for row in con.execute("SELECT col.b FROM db.table WHERE col.b LIKE ? LIMIT 25", q): > ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied. Whenever you see this in a dbapi context, you can bet your socks that you're passing a single item (such as a string, q) rather than a list or tuple of items. Try passing [q] as the second parameter to that .execute function and see what happens! TJG -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080412/fa306859/attachment.htm From queprime at gmail.com Sat Apr 12 12:44:16 2008 From: queprime at gmail.com (Que Prime) Date: Sat, 12 Apr 2008 03:44:16 -0700 Subject: [Tutor] Simple copy script Message-ID: <17285ccf0804120344o3d6e552dlbde52a69f5a918f@mail.gmail.com> I'm trying to copy files from one directory to another based on an input txt file containing the filename. Source directory = C:\test Destination directory = C:\output input.txt looks like: 12345.pdf 12344.pdf I having trouble getting my mind around a loop that would accomplish this. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080412/31f5e519/attachment.htm From onyxtic at gmail.com Sat Apr 12 13:12:46 2008 From: onyxtic at gmail.com (Evans Anyokwu) Date: Sat, 12 Apr 2008 12:12:46 +0100 Subject: [Tutor] Simple copy script In-Reply-To: <17285ccf0804120344o3d6e552dlbde52a69f5a918f@mail.gmail.com> References: <17285ccf0804120344o3d6e552dlbde52a69f5a918f@mail.gmail.com> Message-ID: Its hard to tell what you're doing wrong without the code. Sorry, my policy is not to write code for anyone until they have something to show. On Sat, Apr 12, 2008 at 11:44 AM, Que Prime wrote: > > I'm trying to copy files from one directory to another based on an input > txt file containing the filename. > > Source directory = C:\test > Destination directory = C:\output > > input.txt looks like: > > 12345.pdf > 12344.pdf > > > I having trouble getting my mind around a loop that would accomplish this. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080412/be9269a4/attachment.htm From pylinuxian at gmail.com Sat Apr 12 14:01:04 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Sat, 12 Apr 2008 12:01:04 +0000 Subject: [Tutor] Simple copy script In-Reply-To: References: <17285ccf0804120344o3d6e552dlbde52a69f5a918f@mail.gmail.com> Message-ID: right ! show us what you've done so far. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080412/06f2b2a7/attachment.htm From alan.gauld at btinternet.com Sat Apr 12 14:15:08 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Apr 2008 13:15:08 +0100 Subject: [Tutor] Simple copy script References: <17285ccf0804120344o3d6e552dlbde52a69f5a918f@mail.gmail.com> Message-ID: "Que Prime" wrote > I'm trying to copy files from one directory to another based on an > input txt > file containing the filename. > > Source directory = C:\test > Destination directory = C:\output > > input.txt looks like: > > 12345.pdf > 12344.pdf Try writing what you want to do in structured English first Open the file input.txt For each line in input.txt : copy the named file from source to destination Close the file input.txt Now can you write that ion Python? (You may want to check the shutil module for copying the files) If you can';t get it to work send us your code and any error messages you get. You will find more detailed info in the Using the OS topic of my tutor. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Apr 12 14:26:16 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Apr 2008 13:26:16 +0100 Subject: [Tutor] pysqlite and functions References: Message-ID: "Dinesh B Vadhia" wrote Your code has several strangenesses in it but I'll focus on your query for now... ################ con = sqlite3.connect(":memory:") # create database/table in memory cur = con.cursor() # note: can use the nonstandard execute, executemany to avoid using Cursor object query = "CREATE TABLE db.table(field.a INTEGER, field.b TEXT)" cur.execute(query) query = "INSERT INTO db.table(field.a, field.b) VALUES (?, ?)", data cur.executemany(query) ############# You don;t say where db or field are defined but on the assumption that this does work and you don;t get err9ors I'#ll ignore it for now. ########### def getResult(q, limit): query = "SELECT field.b FROM db.table WHERE field.b LIKE '%s' LIMIT '%s'" %(q, limit) for row in cur.execute(query): print row return #################### This should work provided you really do have the names consistent between the global variable cur and the name in the function. > The error recieved is: > > NameError: global name 'cur' is not defined > global con, curs, db.table Note that you have cur in the code you posted and cvur in the error message but you say curs here. Which is it? 3. Moving con and cur into the def statement results in the error: The def statement is really just the first line, is that what you mean? Or do you mean the function definition that follows the def? Don't move them inside the function definition but rather pass them in as parameters as you did with q, limit. However it shouldn't really be necessary, but it is better style and aids reuse > 4. The def getResults is not seeing con, curs and db.table > even when declared as global. Which suggests that either they are defined in another module or function or you have inconsistent names (maybe a case error?) > 5. I wonder if this is something specific to pysqlite. No, this is an error in your code somewhere. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dineshbvadhia at hotmail.com Sat Apr 12 17:11:29 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sat, 12 Apr 2008 08:11:29 -0700 Subject: [Tutor] in-memory pysqlite databases Message-ID: Say, you have already created a pysqlite database "testDB". In a Python program, you connect to the database as: > con = sqlite3.connect("testDB") > cur = con.cursor() To use a database in memory (ie. all the 'testDB' tables are held in memory) the pysqlite documentation says the declaration is: > con = sqlite3.connect(":memory:") > cur = con.cursor() But, this can't be right as you're not telling Python/pysqlite which database to keep in memory. I've tried ... > con = sqlite3.connect("testDB", ":memory:") > cur = con.cursor() .. but that didn't work. Any ideas? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080412/fd7df586/attachment.htm From maximo7274 at gmail.com Sat Apr 12 18:46:54 2008 From: maximo7274 at gmail.com (John Jojo) Date: Sat, 12 Apr 2008 12:46:54 -0400 Subject: [Tutor] hey, a bit of a noob at python ut a question about animation... Message-ID: <83d702900804120946j6227825euf055854633c2e109@mail.gmail.com> I am trying to make a simple animation, and this is what I have. from livewires import games, color games.init(screen_width = 1000, screen_height = 1000, fps = 50) class Animation(games.Sprite): files1 = ["stick1.jpg"] files2 = ["stick2.jpg"] def __init__(self): self.animate1() def animate1(self): act = games.Animation(images = Animation.files1, x = 500, y = 500, n_repeats = 5, repeat_interval = 5) def animate2(self): act = games.Animation(images = Animation.files2, x = 500, y = 500, dy = 1, lifetime = 5 * games.screen.fps, repeat_interval = 5, after_death = games.screen.quit) def main(): wall_image = games.load_image("class.jpg", transparent = False) games.screen.background = wall_image animater = Animation() games.screen.add(animater) games.screen.mainloop() main() I use the after_death item because it is used for the games.Message() command and I thought it would do the same thing here. It doesn't. So does anyone know the command to show after an animation is over??? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080412/18cab7a9/attachment.htm From bgailer at gmail.com Sat Apr 12 20:04:10 2008 From: bgailer at gmail.com (bob gailer) Date: Sat, 12 Apr 2008 14:04:10 -0400 Subject: [Tutor] hey, a bit of a noob at python ut a question about animation... In-Reply-To: <83d702900804120946j6227825euf055854633c2e109@mail.gmail.com> References: <83d702900804120946j6227825euf055854633c2e109@mail.gmail.com> Message-ID: <4800F99A.7030504@gmail.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080412/53be5bf5/attachment-0001.htm From bgailer at gmail.com Sat Apr 12 20:25:33 2008 From: bgailer at gmail.com (bob gailer) Date: Sat, 12 Apr 2008 14:25:33 -0400 Subject: [Tutor] in-memory pysqlite databases In-Reply-To: References: Message-ID: <4800FE9D.9000002@gmail.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080412/547393fe/attachment.htm From alan.gauld at btinternet.com Sat Apr 12 21:09:53 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Apr 2008 20:09:53 +0100 Subject: [Tutor] hey, a bit of a noob at python ut a question about animation... References: <83d702900804120946j6227825euf055854633c2e109@mail.gmail.com> Message-ID: "John Jojo" wrote > from livewires import games, color > ... > def main(): > wall_image = games.load_image("class.jpg", transparent = False) > games.screen.background = wall_image > animater = Animation() > games.screen.add(animater) > games.screen.mainloop() > main() > I use the after_death item because it is used for the > games.Message() > command and I thought it would do the same thing here. It doesn't. > So does > anyone know the command to show after an animation is over??? I suspect this has more to do with LiveWires than with standard Python. Youmay be better off asking on a Livewires forum if you can find such a thing. Othewise you may need to explain a bit more background so the non Livewires users here can help you. Alan G. From alan.gauld at btinternet.com Sat Apr 12 21:20:20 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Apr 2008 20:20:20 +0100 Subject: [Tutor] in-memory pysqlite databases References: Message-ID: "Dinesh B Vadhia" wrote > Say, you have already created a pysqlite database "testDB". > In a Python program, you connect to the database as: > con = sqlite3.connect("testDB") > cur = con.cursor() OK so far. > To use a database in memory (ie. all the 'testDB' tables > are held in memory) the pysqlite documentation says > the declaration is: > con = sqlite3.connect(":memory:") > cur = con.cursor() No it doesn't. It says to create and use a database in memory you use that syntax. It makes no claims about being able to use a file based database in memory. The normal way to prepopulate an in memory database is to have a function (possibly in another module) that creates the structure and loads the data. That way you can easily move the data to a file based solution if needed. > But, this can't be right as you're not telling > Python/pysqlite which database to keep in memory. You are creating a new database in memory. What would be nice is a function that could persist an in-memory database to disk. But I';m not aware of any such feature. HTH, Alan G From bhaaluu at gmail.com Sat Apr 12 22:03:49 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Sat, 12 Apr 2008 16:03:49 -0400 Subject: [Tutor] designing POOP In-Reply-To: References: <47ACBA8E.1020902@tds.net> <47ACCDB9.7000200@tds.net> <005001c86aa9$48bd1e30$c7fce004@jslaptop> Message-ID: On Sat, Feb 9, 2008 at 9:46 AM, Alan Gauld wrote: > > As I mentioned in an earlier mail it tends to oscillate in practice. > You start off looking at the problem to identify the basic classes. > Then you pick one or two and start designing those in detail and > that identifies lower level classes. When you reach the point of > being able to write some code you do so. The act of writing code > brings up issues that get reflected back up the design - maybe > even identifying new classes. Once you've written as much > code as you can you go back up to the problem level, using > your new found knowledge and design a bit more. Once you > know enough to start coding go back into code mode again. > > This constant iteration between top level class discovery and low > level class construction is what Grady Booch refers to in his book > as "Round Trip Gestalt Design" and in practice is how most > software other than the very biggest projects is built. I recently found the Grady Booch book: OBJECT ORIENTED DESIGN WITH APPLICATIONS. Benjamin Cummings, 1991. pg. 189: As Heinlein suggests, "When faced with a problem you do not understand, do any part of it you do understand, then look at it again". This is just another way of describing round-trip gestalt design. pg. 517: round-trip gestalt design A style of design that emphasizes the incremental and iterative development of a system, through the refinement of different yet consistent logical and physical views of the system as a whole; the process of object-oriented design is guided by the concepts of round-trip gestalt design: round-trip gestalt design is a recognition of that fact that the big picture of a design affects its details, and that the details often reflect the big picture. Happy Programming. -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From dineshbvadhia at hotmail.com Sat Apr 12 22:10:49 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sat, 12 Apr 2008 13:10:49 -0700 Subject: [Tutor] in-memory pysqlite databases References: <4800FE9D.9000002@gmail.com> Message-ID: Bob An in-memory database that is empty to start, loaded with data, and goes away when the connection goes away is exactly what I'm after. The code and the program for an in-memory database works perfectly. However, a web version using webpy doesn't work - the error message is that it cannot find the database table. After reading your note, it hit me that an execution thread is created by pysqlite and another thread by webpy and hence webpy is not seeing the table. What a pain! Dinesh ----- Original Message ----- From: bob gailer To: Dinesh B Vadhia Cc: tutor at python.org Sent: Saturday, April 12, 2008 11:25 AM Subject: Re: [Tutor] in-memory pysqlite databases Dinesh B Vadhia wrote: Say, you have already created a pysqlite database "testDB". In a Python program, you connect to the database as: > con = sqlite3.connect("testDB") > cur = con.cursor() To use a database in memory (ie. all the 'testDB' tables are held in memory) the pysqlite documentation says the declaration is: > con = sqlite3.connect(":memory:") > cur = con.cursor() But, this can't be right as you're not telling Python/pysqlite which database to keep in memory. The documentation says "Creating an in-memory database". That means (to me) a new database that is memory resident and as consequence is empty to start and goes away when the connection goes away. I don't see any easy way to load a file-based db into a memory-based one. Seems like you'd need to create all the tables in memory, then run select cursors to retrieve from the file-based db and insert the rows into the memory-based db tables Why do you want it in memory? [snip] -- Bob Gailer 919-636-4239 Chapel Hill, NC -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080412/538cc32f/attachment.htm From alan.gauld at btinternet.com Sun Apr 13 00:23:30 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Apr 2008 23:23:30 +0100 Subject: [Tutor] in-memory pysqlite databases References: <4800FE9D.9000002@gmail.com> Message-ID: "Dinesh B Vadhia" wrote > However, a web version using webpy doesn't work Now you didn't mention webpy before, that makes a big difference! > an execution thread is created by pysqlite and > another thread by webpy and hence webpy is not > seeing the table. Almost certainly the case but if you are using the web you can almost certainly afford to use a file based SqlLite database and that way the data can be shared. The network delays will more than overcome the slowdown of moving to the file based database. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dineshbvadhia at hotmail.com Sun Apr 13 12:15:41 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sun, 13 Apr 2008 03:15:41 -0700 Subject: [Tutor] in-memory pysqlite databases Message-ID: Why do you say: "Now you didn't mention webpy before, that makes a big difference!" ? As an aside, it really is a huge pain in the neck that, in general standard Python works (and works wonderfully) but as soon as you include external libraries (eg. Numpy, Scipy, webpy - and probably other web frameworks etc. etc.) things start to fall apart (badly!). And, from my experience with Python so far it is not of my incompetance (well, not most of the time!). Dinesh .............................................................................. Date: Sat, 12 Apr 2008 23:23:30 +0100 From: "Alan Gauld" Subject: Re: [Tutor] in-memory pysqlite databases To: tutor at python.org Message-ID: Content-Type: text/plain; format=flowed; charset="Windows-1252"; reply-type=original "Dinesh B Vadhia" wrote > However, a web version using webpy doesn't work Now you didn't mention webpy before, that makes a big difference! > an execution thread is created by pysqlite and > another thread by webpy and hence webpy is not > seeing the table. Almost certainly the case but if you are using the web you can almost certainly afford to use a file based SqlLite database and that way the data can be shared. The network delays will more than overcome the slowdown of moving to the file based database. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080413/e2cd266d/attachment.htm From sbigtymers3 at yahoo.com Sun Apr 13 01:06:53 2008 From: sbigtymers3 at yahoo.com (brebreman3) Date: Sat, 12 Apr 2008 16:06:53 -0700 (PDT) Subject: [Tutor] Ball in Box Message-ID: <16656670.post@talk.nabble.com> I have a program i am trying to create where the user clicks inside of a red parameter inside of the window. The user has an unlimited amount of clicks in order to create their own pool table. I would like for the ball to bounce inside of the pool table they just created and for it to fall inside of a hole that is shown on the pool table. I already have the users unlimited clicks and the red parameter of where the user can only click inside but I don't have a clue how to get the ball to bounce inside of the pool table and for the pocket to be created inside the pool table. Can someone pleeeaaaase help me? Thanks -- View this message in context: http://www.nabble.com/Ball-in-Box-tp16656670p16656670.html Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Sun Apr 13 15:53:11 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 13 Apr 2008 09:53:11 -0400 Subject: [Tutor] hey, a bit of a noob at python ut a question about animation... In-Reply-To: <83d702900804120946j6227825euf055854633c2e109@mail.gmail.com> References: <83d702900804120946j6227825euf055854633c2e109@mail.gmail.com> Message-ID: <48021047.30401@tds.net> John Jojo wrote: > I am trying to make a simple animation, and this is what I have. > > from livewires import games, color Please say which version of livewires you are using, the one from the livewires site is different from the one that comes with Dawson's book. > games.init(screen_width = 1000, screen_height = 1000, fps = 50) > def animate2(self): > act = games.Animation(images = Animation.files2, > x = 500, > y = 500, > dy = 1, > lifetime = 5 * games.screen.fps, > repeat_interval = 5, > after_death = games.screen.quit) You don't seem to do anything with this method - it is never called. > def main(): > wall_image = games.load_image("class.jpg", transparent = False) > games.screen.background = wall_image > animater = Animation() > games.screen.add(animater) > > games.screen.mainloop() > main() > I use the after_death item because it is used for the games.Message() > command and I thought it would do the same thing here. It doesn't. No, Animation and Message are different objects with different interfaces. You have to look at the __init__() method of the Animation class to see what parameters it supports. I don't think Animation supports calling a function when it finishes, you will have to find another way to stop the game. Kent From kent37 at tds.net Sun Apr 13 15:54:31 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 13 Apr 2008 09:54:31 -0400 Subject: [Tutor] Ball in Box In-Reply-To: <16656670.post@talk.nabble.com> References: <16656670.post@talk.nabble.com> Message-ID: <48021097.7040702@tds.net> brebreman3 wrote: > I don't have a clue how to get the ball to bounce inside of the > pool table and for the pocket to be created inside the pool table. How are you representing the balls? Do you know how to get them to move? What are you using to draw them? Kent From kent37 at tds.net Sun Apr 13 16:00:22 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 13 Apr 2008 10:00:22 -0400 Subject: [Tutor] in-memory pysqlite databases In-Reply-To: References: Message-ID: <480211F6.2060905@tds.net> Dinesh B Vadhia wrote: > And, from my > experience with Python so far it is not of my incompetance (well, not > most of the time!). Hmm. You are very much a beginner. Perhaps you will learn not to be so quick to blame your tools. When you have trouble, you would do well to ask, "What is it that I don't understand here?" Kent From alan.gauld at btinternet.com Sun Apr 13 16:41:20 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 13 Apr 2008 15:41:20 +0100 Subject: [Tutor] in-memory pysqlite databases References: Message-ID: "Dinesh B Vadhia" wrote > Why do you say: "Now you didn't mention webpy before, > that makes a big difference!" ? Because any time you change the operating environment different rules apply. That's not a Python thing that's true of all programming languages. If you operate in a particular environment (embedded systems, web, GUI, RDBMS etc) then a new set of constraints will apply. > as soon as you include external libraries > (eg. Numpy, Scipy, webpy - and probably other web > frameworks etc. etc.) things start to fall apart (badly!). It's not so much that they fall apart but they expect the user to understand the operating environment and model and the dependencies that they are based on. Again, this is true of most languages, once you leave the standard model behind you have to work with the library's constraints. To pick the webpy example, it is one of several Python web frameworks, but its not one I have used. I've used Zope(briefly! - too heavy for me), TurboGears (I like it a lot) and am currently toying with Django (which seems promising). But I've also used raw CGI and the Java JSP/Struts framework and frankly they are all broadly similar in concept. The differences in framework are minor compared to the differences between web programming and CLI programming. Of course in the Open Source world many of these Frameworks are less than perfectly documented. One of my primary selection criteria for any Framework but especially OpenvSource is that there must be good quality (and preferrably independantly written dead tree type) documentation. Without that you will be expected to learn by example and experiment rather than from a properly written specification, so you expect some pain. But then again, it diodn't cost you any $$$ so you pay in another way... Time is money etc. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Apr 13 16:48:49 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 13 Apr 2008 15:48:49 +0100 Subject: [Tutor] Ball in Box References: <16656670.post@talk.nabble.com> Message-ID: "brebreman3" wrote > I have a program i am trying to create where the user clicks inside > of a red > parameter inside of the window. The user has an unlimited amount of > clicks > in order to create their own pool table. I would like for the ball > to > bounce inside of the pool table they just created and for it to fall > inside > of a hole that is shown on the pool table. This will require a fairly good understanding of basic geometry. Is your math level good enough to understand how this would be modelled mathematically? If not you might find this quite tough to get working. You can probably find sample code on the net but if it doesn't work it will be hard to debug. OTOH if your math skill is good then this shouldn't be too hard. Can you tell us more about what you are using and what you find difficult? > I already have the users unlimited clicks and the red parameter What are you drawing this on? Is it a GUI? If so, which one and which widget? > inside but I don't have a clue how to get the ball to bounce > inside of the pool table and for the pocket to be created > inside the pool table. Do you know how to make a ball move? Forget the bouncing just get them to move in a staight line for a fixed distance. Then get them to stop when the meet the perimeter. Then calculate the angles and set them in motion again. Finally detect when they reach the hole. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dineshbvadhia at hotmail.com Sun Apr 13 20:52:28 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sun, 13 Apr 2008 11:52:28 -0700 Subject: [Tutor] in-memory pysqlite databases Message-ID: Alan Your last paragraph is the gist of my note ie. it's the documentation, documentation, documentation. In addition to Python, we use Numpy/Scipy/webpy at the server - all of them Python libraries written in Python and/or C - and have faced no end of problems with these libraries. We also use HTML/CSS/JavaScript/JQuery at the browser and so far we've had zero problems. Of course, these tools are fully documented including the dead tree type! Cheers Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080413/d73346e7/attachment-0001.htm From alan.gauld at btinternet.com Mon Apr 14 00:31:59 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 13 Apr 2008 23:31:59 +0100 Subject: [Tutor] in-memory pysqlite databases References: Message-ID: "Dinesh B Vadhia" wrote > Your last paragraph is the gist of my note ie. it's the > documentation, documentation, documentation. I agree it can be very variable in quality. One of the problems of Open Source is that there are more people who want to write code than there are who want to write documentation... > In addition to Python, we use Numpy/Scipy/webpy at > the server - all of them Python libraries written in Python > and/or C - and have faced no end of problems with > these libraries. All non standard items, all Open Source. > We also use HTML/CSS/JavaScript/JQuery at the browser All standard items for Browser work. Tools designed for the job. Have you tried using non standard browser code libraries like say the various graphing libraries for JavaScript? Or sound libraries, say? They are just as patchy in support. > Of course, these tools are fully documented including > the dead tree type! Exactly, but they are standard tools so need to be compared to core Python not the contributed software. Of course you could use Java on the server and then you could buy commercial libraries that do the same job as Numpy etc. But you have to pay hard $$$ for those. So you take your choice: persevere with Python and its libraries for its rapid development and hope the time savings outweigh the time spent working out how the libraries work or, pay out for the commercial products and hope the savings in quality(*) outweigh the expenditure. And also hope that the different tools work together because if they don't you can't go look at the source to fix it! Its all about making choices, but that's engineering - you choose the right trade off! (*)And of course that's a gamble too because there are many badly documented commercial libraries too! But at least you can complain to somebody! :-/ Alan G From sbigtymers3 at yahoo.com Mon Apr 14 00:40:31 2008 From: sbigtymers3 at yahoo.com (brebreman3) Date: Sun, 13 Apr 2008 15:40:31 -0700 (PDT) Subject: [Tutor] Ball in Box In-Reply-To: <48021097.7040702@tds.net> References: <16656670.post@talk.nabble.com> <48021097.7040702@tds.net> Message-ID: <16669033.post@talk.nabble.com> I have drawn the circles by the circ.draw and i have defined the radius of the circle. I do know how to also get them to move just I don't know how to do friction and get them to only bounce inside of the pool table that was created. Kent Johnson wrote: > > brebreman3 wrote: >> I don't have a clue how to get the ball to bounce inside of the >> pool table and for the pocket to be created inside the pool table. > > How are you representing the balls? Do you know how to get them to move? > What are you using to draw them? > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/Ball-in-Box-tp16656670p16669033.html Sent from the Python - tutor mailing list archive at Nabble.com. From bgailer at gmail.com Mon Apr 14 01:55:22 2008 From: bgailer at gmail.com (bob gailer) Date: Sun, 13 Apr 2008 19:55:22 -0400 Subject: [Tutor] in-memory pysqlite databases In-Reply-To: References: Message-ID: <48029D6A.4080801@gmail.com> Alan Gauld wrote: [snip] > (*)And of course that's a gamble too because there are > many badly documented commercial libraries too! > How true. > But at least you can complain to somebody! Oh yeah? Try complaining to MS! They built a wall to protect themselves from their customers. -- Bob Gailer 919-636-4239 Chapel Hill, NC From kent37 at tds.net Mon Apr 14 02:19:34 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 13 Apr 2008 20:19:34 -0400 Subject: [Tutor] Ball in Box In-Reply-To: <16669033.post@talk.nabble.com> References: <16656670.post@talk.nabble.com> <48021097.7040702@tds.net> <16669033.post@talk.nabble.com> Message-ID: <4802A316.6020308@tds.net> brebreman3 wrote: > I have drawn the circles by the circ.draw and i have defined the radius of > the circle. I do know how to also get them to move just I don't know how to > do friction and get them to only bounce inside of the pool table that was > created. Can you show us some code? You will have to check the position of the balls against the borders of the table. If a ball is at the edge of the table then reverse one component of its direction. Kent > > Kent Johnson wrote: >> brebreman3 wrote: >>> I don't have a clue how to get the ball to bounce inside of the >>> pool table and for the pocket to be created inside the pool table. >> How are you representing the balls? Do you know how to get them to move? >> What are you using to draw them? >> >> Kent >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > From andreas at kostyrka.org Mon Apr 14 02:23:17 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 14 Apr 2008 02:23:17 +0200 Subject: [Tutor] in-memory pysqlite databases In-Reply-To: References: Message-ID: <1208132597.6891.13.camel@andi-lap.lan> Am Sonntag, den 13.04.2008, 23:31 +0100 schrieb Alan Gauld: > "Dinesh B Vadhia" wrote > > > Your last paragraph is the gist of my note ie. it's the > > documentation, documentation, documentation. > > I agree it can be very variable in quality. > One of the problems of Open Source is that there are more > people who want to write code than there are who want to > write documentation... > > > In addition to Python, we use Numpy/Scipy/webpy at > > the server - all of them Python libraries written in Python > > and/or C - and have faced no end of problems with > > these libraries. > > All non standard items, all Open Source. > > > We also use HTML/CSS/JavaScript/JQuery at the browser > > All standard items for Browser work. Tools designed for the job. > Have you tried using non standard browser code libraries > like say the various graphing libraries for JavaScript? Or > sound libraries, say? They are just as patchy in support. > > > Of course, these tools are fully documented including > > the dead tree type! > > Exactly, but they are standard tools so need to be > compared to core Python not the contributed software. > Of course you could use Java on the server and then > you could buy commercial libraries that do the same > job as Numpy etc. But you have to pay hard $$$ for > those. So you take your choice: persevere with Python > and its libraries for its rapid development and hope the > time savings outweigh the time spent working out how > the libraries work or, pay out for the commercial products > and hope the savings in quality(*) outweigh the > expenditure. And also hope that the different tools work > together because if they don't you can't go look at > the source to fix it! Its all about making choices, but > that's engineering - you choose the right trade off! And don't forget that even with the best documented Java/C++ library you will be coding way slower. OTOH, Python has relative strong introspective powers, it's seldom that I'm incapable of figuring how to use a library from trying it out interactivly. OTOH, reading the docs and/or source code later often points out that I did things potentially not in the best or recommended way. ;) > > (*)And of course that's a gamble too because there are > many badly documented commercial libraries too! > But at least you can complain to somebody! :-/ Yeah, although this most often means being ignored by somebody that has some of my money/my budget/my customer's money. While it is often frustrating to have no or little response to problems with open source stuff, at least one has the option to try to fix it yourself. Admittingly that does not work for typical commercial operations aka Java sweatshops in practice, as they tend to hire not good enough developers to make that a workable proposition. I've seen contractors that did not do anything in 3 months (well, they did some simple string replaces on constants in the code) being hired as employees, probably because they were the only ones not killing the hiring talk immediatly ;) > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080414/60ce0287/attachment.pgp From queprime at gmail.com Mon Apr 14 09:08:52 2008 From: queprime at gmail.com (Que Prime) Date: Mon, 14 Apr 2008 00:08:52 -0700 Subject: [Tutor] Fwd: Simple copy script In-Reply-To: References: <17285ccf0804120344o3d6e552dlbde52a69f5a918f@mail.gmail.com> Message-ID: <17285ccf0804140008j3d8272e9n7e951774f2cec754@mail.gmail.com> This is what I came up with after writing it out and reading the corresponding functions. I feel I'm close but something is still awry. #file copy based on input file containing filenames to be copied ############################## import os import shutil os.chdir('c:\\test') infile = open("input.txt","r") for line in infile: shutil.copy(line, 'outfolder') #print line 'copied' infile.close() ############################# ---------- Forwarded message ---------- From: Alan Gauld Date: Sat, Apr 12, 2008 at 5:15 AM Subject: Re: [Tutor] Simple copy script To: tutor at python.org "Que Prime" wrote > I'm trying to copy files from one directory to another based on an > input txt > file containing the filename. > > Source directory = C:\test > Destination directory = C:\output > > input.txt looks like: > > 12345.pdf > 12344.pdf Try writing what you want to do in structured English first Open the file input.txt For each line in input.txt : copy the named file from source to destination Close the file input.txt Now can you write that ion Python? (You may want to check the shutil module for copying the files) If you can';t get it to work send us your code and any error messages you get. You will find more detailed info in the Using the OS topic of my tutor. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080414/64d5fd45/attachment.htm From andreas at kostyrka.org Mon Apr 14 09:29:58 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 14 Apr 2008 09:29:58 +0200 Subject: [Tutor] Fwd: Simple copy script In-Reply-To: <17285ccf0804140008j3d8272e9n7e951774f2cec754@mail.gmail.com> References: <17285ccf0804120344o3d6e552dlbde52a69f5a918f@mail.gmail.com> <17285ccf0804140008j3d8272e9n7e951774f2cec754@mail.gmail.com> Message-ID: <1208158198.6891.23.camel@andi-lap.lan> line.strip() for line in file: => line will contain '\n' at the end of the string. Andreas Am Montag, den 14.04.2008, 00:08 -0700 schrieb Que Prime: > > This is what I came up with after writing it out and reading the > corresponding functions. I feel I'm close but something is still > awry. > > > #file copy based on input file containing filenames to be copied > > ############################## > import os > import shutil > > os.chdir('c:\\test') > infile = open("input.txt","r") > > for line in infile: > shutil.copy(line, 'outfolder') > #print line 'copied' > infile.close() > > ############################# > > ---------- Forwarded message ---------- > From: Alan Gauld > Date: Sat, Apr 12, 2008 at 5:15 AM > Subject: Re: [Tutor] Simple copy script > To: tutor at python.org > > > "Que Prime" wrote > > > > I'm trying to copy files from one directory to another based on an > > input txt > > file containing the filename. > > > > Source directory = C:\test > > Destination directory = C:\output > > > > input.txt looks like: > > > > 12345.pdf > > 12344.pdf > > > Try writing what you want to do in structured English first > > Open the file input.txt > For each line in input.txt : > copy the named file from source to destination > Close the file input.txt > > Now can you write that ion Python? (You may want to check > the shutil module for copying the files) > > If you can';t get it to work send us your code and any error > messages you get. > > You will find more detailed info in the Using the OS > topic of my tutor. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080414/4a76e090/attachment.pgp From alan.gauld at btinternet.com Mon Apr 14 09:42:23 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 Apr 2008 08:42:23 +0100 Subject: [Tutor] Simple copy script References: <17285ccf0804120344o3d6e552dlbde52a69f5a918f@mail.gmail.com> <17285ccf0804140008j3d8272e9n7e951774f2cec754@mail.gmail.com> Message-ID: "Que Prime" wrote > This is what I came up with after writing it out and reading the > corresponding functions. I feel I'm close but something is still > awry. You need to give us more information. What is still awry? Do you get any errors or is it not copyng all files? Or any of them? Here are some possibilities: Do all the files you are copying exist? - Are you 100% sure? Does the 'outfile' folder exist? Does it exist inside C:\test? To try and fix things: Add some print lines to print: 1) The current folder( use os.getcwd() ) 2) Each filename 3) A directory listing of outfile after copying the files Finally a couple of comments: > #file copy based on input file containing filenames to be copied > > ############################## > import os > import shutil > > os.chdir('c:\\test') > infile = open("input.txt","r") > > for line in infile: You can miss out the open() line by putting it into the for loop: for line in open('input.txt','r'): > shutil.copy(line, 'outfolder') You may want to strip() the line first just in case any extra whitespace has been added in the file > #print line 'copied' > infile.close() HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dineshbvadhia at hotmail.com Mon Apr 14 10:31:41 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Mon, 14 Apr 2008 01:31:41 -0700 Subject: [Tutor] encode unicode strings from pysqlite Message-ID: Here is a program that SELECT's from a pysqlite database table and encode's the returned unicode strings: import sys import os import sqlite3 con = sqlite3.connect("testDB.db") cur = con.cursor() a = u'99 Cycling Swords' b = a.encode('utf-8') print b q = '%wor%' limit = 25 query = "SELECT fieldB FROM testDB WHERE fieldB LIKE '%s' LIMIT '%s'" %(q, limit) for row in cur.execute(query): r = str(row) print r.encode('utf-8') The print b results in: 99 Cycling Swords ... which is what I want. But, the print r.encode('utf-8') leaves the strings as unicode strings eg. u'99 Cycling Swords' Any ideas what might be going on? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080414/39b9cbfc/attachment.htm From kent37 at tds.net Mon Apr 14 12:42:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 Apr 2008 06:42:36 -0400 Subject: [Tutor] encode unicode strings from pysqlite In-Reply-To: References: Message-ID: <4803351C.6020007@tds.net> Dinesh B Vadhia wrote: > Here is a program that SELECT's from a pysqlite database table and > encode's the returned unicode strings: > query = "SELECT fieldB FROM testDB WHERE fieldB LIKE '%s' LIMIT '%s'" > %(q, limit) > for row in cur.execute(query): Here row is a list containing a single unicode string. When you convert a list to a string, it converts the list elements to strings using the repr() function. The repr() of a unicode string includes the u'' as part of the result. In [64]: row = [u'99 Cycling Swords'] In [65]: str(row) Out[65]: "[u'99 Cycling Swords']" Notice that the above is a string that includes u' as part of the string. What you need to do is pick out the actual data and encode just that to a string. In [62]: row[0].encode('utf-8') Out[62]: '99 Cycling Swords' Kent From mail2ashish.sharma at gmail.com Mon Apr 14 14:02:44 2008 From: mail2ashish.sharma at gmail.com (Ashish Sharma) Date: Mon, 14 Apr 2008 17:32:44 +0530 Subject: [Tutor] Font capture from webpages Message-ID: <72cd25f60804140502o35d55e17hd45b14ec6c631d1d@mail.gmail.com> Hi , I want to find the font style,Font size written in webpage without looking into source code. Can Any one tell if there is API avalable for this in python . Thanks in Advance. Ashish Sharma From dineshbvadhia at hotmail.com Mon Apr 14 14:10:56 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Mon, 14 Apr 2008 05:10:56 -0700 Subject: [Tutor] encode unicode strings from pysqlite References: <4803351C.6020007@tds.net> Message-ID: Hi! Kent. The row[0].encode('utf-8') works perfectly within a standalone program. But didn't work within webpy until I realized that maybe webpy is storing the row as a dictionary (which it does) and that you have to get the string by the key (ie. 'fieldB'). That worked and also webpy encodes the unicode string at the same time. Here are the details: # standard Python: testDB.py con = sqlite3.connect("testDB.db") cur = con.cursor() query = "SELECT fieldB FROM testDB WHERE fieldB LIKE '%s' LIMIT '%s'" %(q, limit) for row in cur.execute(query): # row is a list print row[0].encode('utf-8') # works perfectly! # webpy: testDB2.py web.config.db_parameters = dict(dbn='sqlite', db="testDB.db") for row in web.select('testDB', what='fieldB', where='fieldB LIKE $q', limit=limit, vars={'q':q}): r = row['fieldB'] # get encode'd unicode through dict key value print r # works perfectly! ----- Original Message ----- From: Kent Johnson To: Dinesh B Vadhia Cc: tutor at python.org Sent: Monday, April 14, 2008 3:42 AM Subject: Re: [Tutor] encode unicode strings from pysqlite Dinesh B Vadhia wrote: > Here is a program that SELECT's from a pysqlite database table and > encode's the returned unicode strings: > query = "SELECT fieldB FROM testDB WHERE fieldB LIKE '%s' LIMIT '%s'" > %(q, limit) > for row in cur.execute(query): Here row is a list containing a single unicode string. When you convert a list to a string, it converts the list elements to strings using the repr() function. The repr() of a unicode string includes the u'' as part of the result. In [64]: row = [u'99 Cycling Swords'] In [65]: str(row) Out[65]: "[u'99 Cycling Swords']" Notice that the above is a string that includes u' as part of the string. What you need to do is pick out the actual data and encode just that to a string. In [62]: row[0].encode('utf-8') Out[62]: '99 Cycling Swords' Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080414/59e200db/attachment.htm From srilyk at gmail.com Mon Apr 14 14:13:12 2008 From: srilyk at gmail.com (W W) Date: Mon, 14 Apr 2008 07:13:12 -0500 Subject: [Tutor] Font capture from webpages In-Reply-To: <72cd25f60804140502o35d55e17hd45b14ec6c631d1d@mail.gmail.com> References: <72cd25f60804140502o35d55e17hd45b14ec6c631d1d@mail.gmail.com> Message-ID: <333efb450804140513m2f9b50e8x3d20346056d64c5f@mail.gmail.com> beautiful soup would do it. It's still looking into the source, though. On Mon, Apr 14, 2008 at 7:02 AM, Ashish Sharma wrote: > Hi , > > I want to find the font style,Font size written in webpage without > looking into source code. > > Can Any one tell if there is API avalable for this in python . > > Thanks in Advance. > Ashish Sharma > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From kent37 at tds.net Mon Apr 14 14:22:18 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 Apr 2008 08:22:18 -0400 Subject: [Tutor] Font capture from webpages In-Reply-To: <72cd25f60804140502o35d55e17hd45b14ec6c631d1d@mail.gmail.com> References: <72cd25f60804140502o35d55e17hd45b14ec6c631d1d@mail.gmail.com> Message-ID: <48034C7A.1050000@tds.net> Ashish Sharma wrote: > Hi , > > I want to find the font style,Font size written in webpage without > looking into source code. Do you mean you don't want to look at the HTML/CSS for the page? If not, I guess you will have to somehow query the browser. Tools for that will be specific to the browser/OS you are using. Kent From bhaaluu at gmail.com Mon Apr 14 16:32:16 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 14 Apr 2008 10:32:16 -0400 Subject: [Tutor] Python Programming Tools Message-ID: A (mainly Java) programmer on a LUG mailing list asks: What is a good IDE [for Python] that has Python tools for: library management, code completion, debugging, documentation, help Since I'm not familiar with Java at all, I'm not sure how many of the things he is asking for, are even relevant for Python? I'm presuming he is working with a team, and is developing complex programs. What do _you use? -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From muchanek at gmail.com Mon Apr 14 16:39:06 2008 From: muchanek at gmail.com (kinuthia muchane) Date: Mon, 14 Apr 2008 17:39:06 +0300 Subject: [Tutor] Tutor Digest, Vol 50, Issue 43 In-Reply-To: References: Message-ID: <1208183946.5776.55.camel@www.kinuthia.com> > > Message: 1 > Date: Mon, 14 Apr 2008 01:31:41 -0700 > From: "Dinesh B Vadhia" > Subject: [Tutor] encode unicode strings from pysqlite > To: > Message-ID: > Content-Type: text/plain; charset="iso-8859-1" > > Here is a program that SELECT's from a pysqlite database table and encode's the returned unicode strings: > > import sys > import os > import sqlite3 > > con = sqlite3.connect("testDB.db") > cur = con.cursor() > > a = u'99 Cycling Swords' > b = a.encode('utf-8') > print b > > q = '%wor%' > limit = 25 > query = "SELECT fieldB FROM testDB WHERE fieldB LIKE '%s' LIMIT '%s'" %(q, limit) > for row in cur.execute(query): > r = str(row) > print r.encode('utf-8') Why not change this to: > for row in cur.execute(query): > for item in row: > print item.encode('utf-8') which will return a string ? Kinuthia. From jordangreenberg at gmail.com Mon Apr 14 16:49:02 2008 From: jordangreenberg at gmail.com (Jordan Greenberg) Date: Mon, 14 Apr 2008 10:49:02 -0400 Subject: [Tutor] Python Programming Tools In-Reply-To: References: Message-ID: <48036EDE.3080105@gmail.com> bhaaluu wrote: > A (mainly Java) programmer on a LUG mailing list asks: > > What is a good IDE [for Python] that has Python tools for: > > library management, > code completion, > debugging, > documentation, > help > > Since I'm not familiar with Java at all, I'm not sure how many > of the things he is asking for, are even relevant for Python? > I'm presuming he is working with a team, and is developing > complex programs. > > What do _you use? Personally, I use Emacs for more or less everything. As far as a more complete IDE solution goes, PyDev for the Eclipse platform is pretty popular. If you're willing to spend some $$$, then PyDev Extensions (also for Eclipse) are good, or ActiveState's Komodo IDE. They seem to be the gold standard. -Jordan Greenberg From brnstrmrs at gmail.com Mon Apr 14 18:55:07 2008 From: brnstrmrs at gmail.com (Brain Stormer) Date: Mon, 14 Apr 2008 12:55:07 -0400 Subject: [Tutor] input and output files from terminal Message-ID: <24bc7f6c0804140955t5a352243w19490dd2dfbf6c26@mail.gmail.com> I have a python program which works fine when run using idle but I would like call the program from the terminal. python test.py -i inputfile -o outputfile I tried with raw_input but that only works in idle. Can this be achieved? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080414/2af3bda7/attachment.htm From v2punkt0 at googlemail.com Mon Apr 14 19:14:11 2008 From: v2punkt0 at googlemail.com (v2punkt0 at googlemail.com) Date: Mon, 14 Apr 2008 19:14:11 +0200 Subject: [Tutor] input and output files from terminal In-Reply-To: <24bc7f6c0804140955t5a352243w19490dd2dfbf6c26@mail.gmail.com> References: <24bc7f6c0804140955t5a352243w19490dd2dfbf6c26@mail.gmail.com> Message-ID: <20080414171411.GB3325@simplex> look at the OptParse module, with this u can easily realize such things. http://docs.python.org/lib/module-optparse.html On Mon, Apr 14, 2008 at 12:55:07PM -0400, Brain Stormer wrote: > I have a python program which works fine when run using idle but I would > like call the program from the terminal. > > python test.py -i inputfile -o outputfile > > I tried with raw_input but that only works in idle. Can this be achieved? > Thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From pylinuxian at gmail.com Mon Apr 14 19:18:50 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Mon, 14 Apr 2008 17:18:50 +0000 Subject: [Tutor] input and output files from terminal In-Reply-To: <20080414171411.GB3325@simplex> References: <24bc7f6c0804140955t5a352243w19490dd2dfbf6c26@mail.gmail.com> <20080414171411.GB3325@simplex> Message-ID: i think you need to try : cat input.txt | /usr/bin/python test.py >output.txt > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080414/e06c756c/attachment.htm From pylinuxian at gmail.com Mon Apr 14 19:16:54 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Mon, 14 Apr 2008 17:16:54 +0000 Subject: [Tutor] Font capture from webpages In-Reply-To: References: <72cd25f60804140502o35d55e17hd45b14ec6c631d1d@mail.gmail.com> <48034C7A.1050000@tds.net> Message-ID: > I want to find the font style,Font size written in webpage without looking > > into source code. > > > your best bet would be your eyes. otherwise python will need to parse the source code to tell. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080414/cf790b8c/attachment.htm From bhaaluu at gmail.com Mon Apr 14 19:32:23 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 14 Apr 2008 13:32:23 -0400 Subject: [Tutor] input and output files from terminal In-Reply-To: <24bc7f6c0804140955t5a352243w19490dd2dfbf6c26@mail.gmail.com> References: <24bc7f6c0804140955t5a352243w19490dd2dfbf6c26@mail.gmail.com> Message-ID: On Mon, Apr 14, 2008 at 12:55 PM, Brain Stormer wrote: > I have a python program which works fine when run using idle but I would > like call the program from the terminal. > > python test.py -i inputfile -o outputfile > > I tried with raw_input but that only works in idle. Can this be achieved? > Thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Please see: http://www.faqs.org/docs/diveintopython/kgp_commandline.html >From the book: Dive into Python. Source code examples from the book: http://diveintopython.org/download/diveintopython-examples-4.1.zip Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From python at bdurham.com Mon Apr 14 19:38:09 2008 From: python at bdurham.com (Malcolm Greene) Date: Mon, 14 Apr 2008 13:38:09 -0400 Subject: [Tutor] Pythonic way to extract delimited substrings In-Reply-To: <24bc7f6c0804140955t5a352243w19490dd2dfbf6c26@mail.gmail.com> References: <24bc7f6c0804140955t5a352243w19490dd2dfbf6c26@mail.gmail.com> Message-ID: <1208194689.19177.1247813209@webmail.messagingengine.com> Suggestions on the best way to extract delimited substrings strings from a larger string? Background: I have a long multi-line string with expressions delimited with '<(' and ')>' markers. I would like to extract these substrings and process them in a loop. Because the left and right delimiters are different from each other *and* multi-char strings, it would appear that the .split() method would not be an appropriate tool for this work. I know how to do this task with regular expressions, but I'm always cautious about using a bazooka when a hammer will suffice. What strategy would you recommend? 1. Write a simple parsing function using string primitives (find, slicing) 2. Use regular expressions 3. Use a 3rd party string processing module Thanks! Malcolm From python at bdurham.com Mon Apr 14 19:55:09 2008 From: python at bdurham.com (Malcolm Greene) Date: Mon, 14 Apr 2008 13:55:09 -0400 Subject: [Tutor] Remove specific chars from a string Message-ID: <1208195709.22453.1247815769@webmail.messagingengine.com> What is the Pythonic way to remove specific chars from a string? The .translate( table[, deletechars]) method seems the most 'politically correct' and also the most complicated. My ideas: 1. For each char to be removed, do a .replace( char_to_delete, '' ) 2. Do a .split( str_of_chars_to_delete ) followed by a ''.join() 3. Use a regular expression 4. Other? Thanks! Malcolm From brnstrmrs at gmail.com Mon Apr 14 19:55:31 2008 From: brnstrmrs at gmail.com (Brain Stormer) Date: Mon, 14 Apr 2008 13:55:31 -0400 Subject: [Tutor] input and output files from terminal In-Reply-To: <20080414171411.GB3325@simplex> References: <24bc7f6c0804140955t5a352243w19490dd2dfbf6c26@mail.gmail.com> <20080414171411.GB3325@simplex> Message-ID: <24bc7f6c0804141055x24ca3ec8g665f3038b3e62b03@mail.gmail.com> I used the optparse module since that is exactly what I wanted. Here is my code: import sys from optparse import OptionParser import os parser = OptionParser() parser.add_option("-i", "--input", dest="infile", help="input FILE to convert", metavar="FILE") parser.add_option("-o", "--output", dest="outfile", help="output FILE to convert to", metavar="FILE") (options, args) = parser.parse_args() if not os.path.isfile(options.infile): print "Input files does not exit...Quitting" sys.exit() elif os.path.isfile(options.outfile): print "Output file exists, Remove it first" sys.exit() Thanks everyone. On Mon, Apr 14, 2008 at 1:14 PM, wrote: > look at the OptParse module, with this u can easily realize such things. > http://docs.python.org/lib/module-optparse.html > > > On Mon, Apr 14, 2008 at 12:55:07PM -0400, Brain Stormer wrote: > > I have a python program which works fine when run using idle but I would > > like call the program from the terminal. > > > > python test.py -i inputfile -o outputfile > > > > I tried with raw_input but that only works in idle. Can this be > achieved? > > Thanks > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080414/dc718f51/attachment.htm From alan.gauld at btinternet.com Mon Apr 14 20:49:37 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 Apr 2008 19:49:37 +0100 Subject: [Tutor] Font capture from webpages References: <72cd25f60804140502o35d55e17hd45b14ec6c631d1d@mail.gmail.com> Message-ID: "Ashish Sharma" wrote > I want to find the font style,Font size written in webpage without > looking into source code. Do you mean you need to find the actual font used in the browser regardless of the settings in the HTML/CSS source? On Windows you can probably do that by querying the OLE/DDE interface but it will be messy. On browsers like Lynx or Links it will be determined by the users resource file settings. It seems like a very strange thing to want to do. HTML and CSS allow a lot of scope for the browser to interpret things like fonmts locally. For example if a page specifies Helvetica it could wind up being displayed on one browser as Helvetica and on another (on the same computer!) as Arial or even Courier... > Can Any one tell if there is API avalable for this in python . Not in Python as such. You have a choice of ways of parsing the HTML but querying the browser will need to go via things like COM or DDE I suspect. (And I have no idea what you'd do on Linux or MacOS!) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Apr 14 20:53:16 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 Apr 2008 19:53:16 +0100 Subject: [Tutor] Python Programming Tools References: <48036EDE.3080105@gmail.com> Message-ID: "Jordan Greenberg" wrote > > What is a good IDE [for Python] that has Python tools for: > > > > library management, > > code completion, > > debugging, > > documentation, > > help Depending on what he wants in the way of "Library Management" then Pythonwin will give him all of that for free on Windows. > > Since I'm not familiar with Java at all, I'm not sure how many > > of the things he is asking for, are even relevant for Python? They are all relevant but might have a slightly different meaning... > complete IDE solution goes, PyDev for the Eclipse platform is pretty > popular. If you're willing to spend some $$$, then PyDev Extensions > (also for Eclipse) are good, or ActiveState's Komodo IDE. They seem > to > be the gold standard. I'd second that particularly since a Java programmer has about a 50% chance of already using Eclipse so its an easy continuation of what he already knows. Platform independant but very resource hungry. But if he uses it already thats not a problem. Alan G. From alan.gauld at btinternet.com Mon Apr 14 20:57:22 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 Apr 2008 19:57:22 +0100 Subject: [Tutor] input and output files from terminal References: <24bc7f6c0804140955t5a352243w19490dd2dfbf6c26@mail.gmail.com> Message-ID: "Brain Stormer" wrote >I have a python program which works fine when run using idle but I >would > like call the program from the terminal. > > python test.py -i inputfile -o outputfile Easier to use file redirection: python test.py < inputfile > outputfile The -i flag in particular might conflict with Pythons own -i option. > I tried with raw_input but that only works in idle. What makes you think that? raw_input is the normal way to get input from stdin. Can you explain what you did and what the result was? Perhaps with a short code example? Try this for example: #################### name = raw_input('What's your name? ') print "hello", name #################### That can be run in IDLE or in a command window or using file redirection as described above. Tell us how you get on... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Mon Apr 14 21:02:42 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 Apr 2008 15:02:42 -0400 Subject: [Tutor] Pythonic way to extract delimited substrings In-Reply-To: <1208194689.19177.1247813209@webmail.messagingengine.com> References: <24bc7f6c0804140955t5a352243w19490dd2dfbf6c26@mail.gmail.com> <1208194689.19177.1247813209@webmail.messagingengine.com> Message-ID: <4803AA52.1010305@tds.net> Malcolm Greene wrote: > Suggestions on the best way to extract delimited substrings strings from > a larger string? > > Background: I have a long multi-line string with expressions delimited > with '<(' and ')>' markers. I would like to extract these substrings and > process them in a loop. > What strategy would you recommend? If you just want to get the text between <( and )>, re.findall() or re.finditer() is probably the simplest way to do it. If it is more complicated than that (e.g. nesting, escape chars) then I would probably look at pyparsing. Kent From kent37 at tds.net Mon Apr 14 21:04:29 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 Apr 2008 15:04:29 -0400 Subject: [Tutor] Remove specific chars from a string In-Reply-To: <1208195709.22453.1247815769@webmail.messagingengine.com> References: <1208195709.22453.1247815769@webmail.messagingengine.com> Message-ID: <4803AABD.7080205@tds.net> Malcolm Greene wrote: > What is the Pythonic way to remove specific chars from a string? The > .translate( table[, deletechars]) method seems the most 'politically > correct' and also the most complicated. Most 'correct' and also by far the fastest. This recipe makes it a bit easier to use: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303342 Kent From alan.gauld at btinternet.com Mon Apr 14 21:01:46 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 Apr 2008 20:01:46 +0100 Subject: [Tutor] Pythonic way to extract delimited substrings References: <24bc7f6c0804140955t5a352243w19490dd2dfbf6c26@mail.gmail.com> <1208194689.19177.1247813209@webmail.messagingengine.com> Message-ID: "Malcolm Greene" wrote in > Background: I have a long multi-line string with expressions > delimited > with '<(' and ')>' markers. I would like to extract these substrings > and > process them in a loop. > > I know how to do this task with regular expressions, but I'm always > cautious about using a bazooka when a hammer will suffice. Sounds like an ideal candidate for regex and findall to me. If you have to stop a tank a bazooka may be the right tool... Alan G. From alan.gauld at btinternet.com Mon Apr 14 21:00:20 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 Apr 2008 20:00:20 +0100 Subject: [Tutor] Remove specific chars from a string References: <1208195709.22453.1247815769@webmail.messagingengine.com> Message-ID: "Malcolm Greene" wrote > What is the Pythonic way to remove specific chars from a string? The > .translate( table[, deletechars]) method seems the most 'politically > correct' and also the most complicated. Assuming you have lots of different characters and not just one to remove, then: either translate() or > 3. Use a regular expression HTH, Alan G. From rdm at rcblue.com Mon Apr 14 21:57:00 2008 From: rdm at rcblue.com (Dick Moores) Date: Mon, 14 Apr 2008 12:57:00 -0700 Subject: [Tutor] Remove specific chars from a string In-Reply-To: <4803AABD.7080205@tds.net> References: <1208195709.22453.1247815769@webmail.messagingengine.com> <4803AABD.7080205@tds.net> Message-ID: <20080414195747.B95731E4005@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080414/2c66e3d8/attachment.htm From kent37 at tds.net Mon Apr 14 22:39:42 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 Apr 2008 16:39:42 -0400 Subject: [Tutor] Remove specific chars from a string In-Reply-To: <20080414195747.B95731E4005@bag.python.org> References: <1208195709.22453.1247815769@webmail.messagingengine.com> <4803AABD.7080205@tds.net> <20080414195747.B95731E4005@bag.python.org> Message-ID: <4803C10E.8060709@tds.net> Dick Moores wrote: > def sigDigits(n): > """ > Strips any real decimal (as string) to just its significant digits, > then returns its length, the number of significant digits. > Examples: "-345" -> "345" -> 3; > "3.000" -> "3000" -> 4 > "0.0001234" -> "1234" -> 4; > "10.0001234" -> "100001234" -> 9 > "7.2345e+543" -> "72345" -> 5 > """ > s = str(n).lstrip("-+0") > s = s.lstrip(".") > s = s.lstrip("0") > s = s.lstrip(".") Why the repeated strips? Couldn't this all just be done with lstrip('-+0.') ? How many significant digits are in 123000? Kent From python at bdurham.com Mon Apr 14 22:46:13 2008 From: python at bdurham.com (python at bdurham.com) Date: Mon, 14 Apr 2008 16:46:13 -0400 Subject: [Tutor] Best practice: Use % operator or locale.format? Message-ID: <1208205973.21609.1247850107@webmail.messagingengine.com> Does the % operator always respect locale or should one use locale.format() instead? Are there guidelines where one should use one string formatting technique vs. another? Thanks! Malcolm From rdm at rcblue.com Mon Apr 14 23:29:16 2008 From: rdm at rcblue.com (Dick Moores) Date: Mon, 14 Apr 2008 14:29:16 -0700 Subject: [Tutor] Remove specific chars from a string In-Reply-To: <4803C10E.8060709@tds.net> References: <1208195709.22453.1247815769@webmail.messagingengine.com> <4803AABD.7080205@tds.net> <20080414195747.B95731E4005@bag.python.org> <4803C10E.8060709@tds.net> Message-ID: <20080414212941.8F7D41E4013@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080414/721e263c/attachment.htm From timmichelsen at gmx-topmail.de Tue Apr 15 00:29:53 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Tue, 15 Apr 2008 00:29:53 +0200 Subject: [Tutor] setting program configuration for all files and modules of a program Message-ID: Hello, I am building a simple GUI for a calculation program. I am using config files (*.cfg) and reading them in with ConfigParser. This works well because I have nearly all code in 1 text file. But I would like to modularize my code and separate the GUI code from the functional code that provides the calculation operations. This will help to expand the functionality at a later stage. I want to achieve this through splitting the code into different modules. The problem is now that I would always have to write the configration file specific code in each module that uses the configration settings (see code below). How can I provide the settings stored in the configuration file throughout my program to all functions without needing to initiate the ConfigParser object in each module? I through of having a special module "settings.py" which I could use to read in the configuration from the file and then import this in each module. Is there a more decent and elegant way? What is the state of the art in storing and parsing configuraions in python programs? Kind regards, Timmie ##### CODE ##### import sys import locale import ConfigParser import gettext ## Path to configuration file configuration_file_name = './config/program_settings.cfg' # name of the configuration file ## read configuration from config file try: program_config = ConfigParser.ConfigParser() program_config.readfp(open(configuration_file_name)) except IOError, (errno, strerror): error_msg_exception = _("I/O error(%s): %s") % (errno, strerror) error_msg_no_config = _("No configuration file with name "), configuration_file_name, _("found in the program directory. Please copy your configuration there. Values will be replaced by defaults.") print error_msg_exception print error_msg_no_config easygui.msgbox(error_msg_no_config) #pass output = program_config.get('output', 'file_extension') ##### From ricaraoz at gmail.com Fri Apr 11 16:22:39 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 11 Apr 2008 11:22:39 -0300 Subject: [Tutor] Conventions for code snippets for debugging and testing? In-Reply-To: References: Message-ID: <47FF742F.1010708@bigfoot.com> Robert Kirkpatrick wrote: > Hi All, > > Just wondering if there are any basic conventions for including code > snippets that are for testing / debugging only? > > For example, you could set a boolean variable called DEBUG, then have > snippets of code like: > > if DEBUG: > do stuff > else: > do otherstuff > > The use case I'm dealing with right now is to query the SVN commits for a > weekly period and report on each user for that time period. If I'm testing > though, I only want to cycle through a few users, not all of them. > > I'm thinking there has to be something slicker than that but maybe not... > > Thoughts? > > Rob > Check the logging standard module. I use it this way (from the manual) : import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='/tmp/myapp.log', filemode='w') logging.debug('A debug message') logging.info('Some information') logging.warning('A shot across the bows') I put the logging.debug('dbg messg') at the appropriate places. When I'm done then I replaces the logging.basicConfig(level=logging.CRITICAL or just 100 so as not to log anything and that's it. You have 6 preset levels, but you can define as many levels you want. Level Numeric value CRITICAL 50 ERROR 40 WARNING 30 INFO 20 DEBUG 10 NOTSET 0 Once you have your logging set you use a tail program to watch your log and see what's going on. HTH From alan.gauld at btinternet.com Tue Apr 15 01:19:10 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Apr 2008 00:19:10 +0100 Subject: [Tutor] setting program configuration for all files and modules ofa program References: Message-ID: "Tim Michelsen" wrote > But I would like to modularize my code and separate the GUI code > from > the functional code that provides the calculation operations. This > will > help to expand the functionality at a later stage. I want to achieve > this through splitting the code into different modules. A good plan > How can I provide the settings stored in the configuration file > throughout my program to all functions without needing to initiate > the > ConfigParser object in each module? > > I through of having a special module "settings.py" which I could use > to > read in the configuration from the file and then import this in each > module. Yes, thats the way I'd recommend. > Is there a more decent and elegant way? Why do you feel that is "indecent" or inelegant? Another option is to have the config settiongs in a normal Python module and just import it. That is less appealing if the config file is shared with a non python program, but if its all Python then that's a much simpler approach... PS. Why all the parens around the error strings in your code? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From timmichelsen at gmx-topmail.de Tue Apr 15 01:26:51 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Tue, 15 Apr 2008 01:26:51 +0200 Subject: [Tutor] cut all decimal places with zeros Message-ID: Hello, how can I suppress the decimal places for (only those) numbers whos decimal places are zero (0)? Example: #### CODE #### In [1]: m = 2.0 In [2]: n = 2.56789080 In [3]: n_format = '%.4f' %n In [4]: n_format Out[4]: '2.5679' In [5]: m_format = '%.4f' %m In [6]: m_format Out[6]: '2.0000' ### END #### I would like to have the "m_format" to be formatted like "2" and the n_format like "2.5679". How can I achive this? A g with "2.4" should return "2.4" and not "2.4000". Basically, I am looking for a way to eliminate the decimal places that are zero (0). I tried this humble function before appling the formatting and it works well with the numbers: ### CODE ### def cut_decimals(float): """ input: floating number output: number as string with zero decimals removed """ #print float-int(float) #print '%.4f' %float if float-int(float) != 0: number = '%.4f' %float number = number.replace('0.','X.') number = number.replace('0','') number = number.replace('X.','0.') else: number = '%.0f' %float return number n = 2.0 m = 2.5678908 g = 2.4 h = 1.45 i = 0.67 numbers = [n, m, g, h, i] for i in numbers: i_f = cut_decimals(i) print i_f ### END ### ### OUTPUT ### %run ./test_number.py 2 2.5679 2.4 1.45 0.67 ### END ### Is there any more efficient solution using string formatting only? Thanks in adavance. Kind regards, Timmie From timmichelsen at gmx-topmail.de Tue Apr 15 01:45:21 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Tue, 15 Apr 2008 01:45:21 +0200 Subject: [Tutor] setting program configuration for all files and modules ofa program In-Reply-To: References: Message-ID: > Yes, thats the way I'd recommend. >> Is there a more decent and elegant way? I don't know. I was just asking how other programmers achive this efficiently. > Another option is to have the config settiongs in a normal > Python module and just import it. That is less appealing if > the config file is shared with a non python program, but if > its all Python then that's a much simpler approach... I think that the cfg-files are much more readable for others. > PS. > Why all the parens around the error strings in your code? I am using gettext: _ = gettest.gettest Got this from the documentation. Thanks for your reply! Timmie From mfin at comcast.net Tue Apr 15 02:12:47 2008 From: mfin at comcast.net (Michael Finlayson) Date: Mon, 14 Apr 2008 20:12:47 -0400 Subject: [Tutor] Open url in browser window Message-ID: <000001c89e8d$71a8e2d0$54faa870$@net> Hi all, This is a serious newbie question. I started this morning. I need to do two simple things (simple on a PC anyway), and I would like to ask the group if it is even possible on a Mac before I go through learning Python. I am a partner in an online training company. All training is delivered via the web. Thus far, our training is accessed via an executable launcher in Windows. We have been asked to create such a launching interface for a Mac based client. We use this approach for several reasons. For the security of our training and the security of our clients computers, we do not allow students to know where the training is on the web (to prevent unauthorized access), or visit any other websites. No surfing while training! We do this by opening a browser window of a specific size with no url line, no menus, nothing except scroll bars, if necessary. Also, to discourage trainees from skipping out of the training to launch other applications, we also disable the tab key and control/alt/delete. Are either or both of these possible on a Mac using Python? Again, we need to: 1. Control the default browser parameters (like you can setup popup windows in javascript with the onClick="MM_openBrWindow command) 2. Control of the user?s keyboard. Obviously, these are both temporary and functionality is restored upon exiting the training. Thank you for your input. Michael Finlayson No virus found in this outgoing message. Checked by AVG. Version: 7.5.519 / Virus Database: 269.22.13/1376 - Release Date: 4/13/2008 1:45 PM -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080414/115114e7/attachment.htm From kent37 at tds.net Tue Apr 15 03:43:35 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 Apr 2008 21:43:35 -0400 Subject: [Tutor] cut all decimal places with zeros In-Reply-To: References: Message-ID: <48040847.7020105@tds.net> Tim Michelsen wrote: > Hello, > how can I suppress the decimal places for (only those) numbers whos > decimal places are zero (0)? I don't know how to do this with just string formatting but I think ('%.4f' % n).rstrip('.0') will do what you want. Kent From kent37 at tds.net Tue Apr 15 03:46:10 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 Apr 2008 21:46:10 -0400 Subject: [Tutor] setting program configuration for all files and modules of a program In-Reply-To: References: Message-ID: <480408E2.5000208@tds.net> Tim Michelsen wrote: > What is the state of the art in storing and parsing configuraions in > python programs? It is pretty common to have a configuration module that is imported wherever the configuration is needed. This is simple but it is essentially global state and shares some of the disadvantages of globals; in particular it couples all your code to the settings module and makes testing more difficult. The alternative is to pass a configuration object to whatever needs it. This eliminates the coupling but is more painful to implement. Kent From alan.gauld at btinternet.com Tue Apr 15 11:08:59 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Apr 2008 10:08:59 +0100 Subject: [Tutor] setting program configuration for all files and modules ofa program References: Message-ID: "Tim Michelsen" wrote in >> Another option is to have the config settiongs in a normal >> Python module and just import it. > I think that the cfg-files are much more readable for others. More readable than: # Section Heading variable = value It looks pretty easy to read to me! :-) If its very complex you can use dictionaries: SectionFoo = { firstName : theValue second : anotherValue } Which is still pretty easy for the casual reader/maintainer and allows access like: import myconfig foo2 = myconfig.SectionFoo['second'] Just a thought. Alan G. From reachmsn at hotmail.com Tue Apr 15 11:12:09 2008 From: reachmsn at hotmail.com (Anshu Raval) Date: Tue, 15 Apr 2008 14:42:09 +0530 Subject: [Tutor] Recursion doubt Message-ID: Hi, At the url http://www.python.org/doc/essays/graphs.html there is some code by Guido Van Rossum for computing paths through a graph - I have pasted it below for reference - Let's write a simple function to determine a path between two nodes. It takes a graph and the start and end nodes as arguments. It will return a list of nodes (including the start and end nodes) comprising the path. When no path can be found, it returns None. The same node will not occur more than once on the path returned (i.e. it won't contain cycles). The algorithm uses an important technique called backtracking: it tries each possibility in turn until it finds a solution. def find_path(graph, start, end, path=[]): path = path + [start] if start == end: return path if not graph.has_key(start): return None for node in graph[start]: if node not in path: newpath = find_path(graph, node, end, path) if newpath: return newpath return None *** He then says------------------------ It is simple to change this function to return a list of all paths (without cycles) instead of the first path it finds: def find_all_paths(graph, start, end, path=[]): path = path + [start] if start == end: return [path] if not graph.has_key(start): return [] paths = [] for node in graph[start]: if node not in path: newpaths = find_all_paths(graph, node, end, path) for newpath in newpaths: paths.append(newpath) return paths *** I couldn't understand how it was simple to change the function find paths to find all paths. How would you think about writing this second function recursively. Especially the part about if start==end: return [path]. I feel you would give square brackets around path here after first writing the inductive part ... for node in graph[start] .... and then by trial and error put square brackets around path in the Basis part. Can someone please explain how to write this code. Thanks! _________________________________________________________________ Video: Get a glimpse of the latest in Cricket, Bollywood, News and Fashion. Only on MSN videos. http://video.msn.com/?mkt=en-in -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080415/6acb0338/attachment-0001.htm From alan.gauld at btinternet.com Tue Apr 15 11:25:30 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Apr 2008 10:25:30 +0100 Subject: [Tutor] Open url in browser window References: <000001c89e8d$71a8e2d0$54faa870$@net> Message-ID: "Michael Finlayson" wrote > I would like to ask the group if it is even possible > on a Mac before I go through learning Python. This has less to do with Python than with Macs Which browser are you thinking of using? Mac users have a variety with Safari the most common along with Firefox and IE for Mac. But Opera and several others also exist. I think Safari and IE are installed by default. But any or all of them could be removed by the user. (For example I removed IE since its not very good on a MAC IMHO!) Or do you install your own browser within your application? > We use this approach for several reasons. > For the security of our training and the security > of our clients computers, The latter claim is a bit spurious, if they weren't secure before launching your app they are unlikely to be more secure during the running of it! Especially if there are processes running in the background or orther users logged in - MacOS is a true multi user/multi tasking OS after all, there may be several simultaneous users on any machine. > We do this by opening a browser window of > a specific size with no url line, no menus, nothing except > scroll bars, if necessary. That will be totally browser dependant. > Also, to discourage trainees from skipping out of > the training to launch other applications, we also > disable the tab key and control/alt/delete. Thee are equivalents on a mac. I assume you also make your app full screen and remove menus etc? ie use kiosk view? That is presumably possible on MacOS but recall that the menu bar in MacOS is not attached to the app window. > Are either or both of these possible on a Mac > using Python? If its possible on a Mac its almost certainly possible via Python. The programming language isn't your issue here, its what does MacOS and the browser support? > 1. Control the default browser parameters > (like you can setup popup windows in javascript > with the onClick="MM_openBrWindow command) Depends on the browser. > 2. Control of the user?s keyboard. Yes that should be possible but it might involve a lot of work catching all the possible exit codes on a Mac. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From oltarasenko at gmail.com Tue Apr 15 17:20:53 2008 From: oltarasenko at gmail.com (Oleg Oltar) Date: Tue, 15 Apr 2008 18:20:53 +0300 Subject: [Tutor] Error with incorrect encoding Message-ID: I am trying to parse an html page. Have following error while doing that src = sel.get_html_source() links = re.findall(r'', src) for link in links: print link ====================================================================== ERROR: test_new (__main__.NewTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "", line 19, in test_new UnicodeEncode Error: 'ascii' codec can't encode character u'\xae' in position 90: ordinal not in range(128) ---------------------------------------------------------------------- Ran 1 test in 6.345s -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080415/91c85a1a/attachment.htm From kent37 at tds.net Tue Apr 15 18:43:39 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 15 Apr 2008 12:43:39 -0400 Subject: [Tutor] Error with incorrect encoding In-Reply-To: References: Message-ID: <4804DB3B.90908@tds.net> Oleg Oltar wrote: > I am trying to parse an html page. Have following error while doing that > > > src = sel.get_html_source() > links = re.findall(r'', src) > for link in links: > print link Presumably get_html_source() is returning unicode? So link is a unicode string. To print, unicode must be encoded somehow. By default Python will try to encode as ascii, which causes the failure you are seeing. Try print link.encode('xxx') where 'xxx' is the value of sys.stdout.encoding, most likely either 'utf-8' or 'windows-1252' depending on your platform. Kent From timmichelsen at gmx-topmail.de Tue Apr 15 21:16:19 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Tue, 15 Apr 2008 21:16:19 +0200 Subject: [Tutor] setting program configuration for all files and modules ofa program In-Reply-To: References: Message-ID: >>> Another option is to have the config settiongs in a normal >>> Python module and just import it. > >> I think that the cfg-files are much more readable for others. > > More readable than: > > # Section Heading > variable = value > > It looks pretty easy to read to me! :-) > > If its very complex you can use dictionaries: > > SectionFoo = { > firstName : theValue > second : anotherValue > } > > Which is still pretty easy for the casual reader/maintainer > and allows access like: > > import myconfig > foo2 = myconfig.SectionFoo['second'] This seems like reinventing what the ConfigParser mdoule [1] already does. I think I will read the config file once and the provide the parameters with a settings.py module throughout the program and the modules. Sounds like doing it twice. But to my optinion Config Parser offers the following advantage: - Readable - All are strings => no strange 'mysetting' is needed. Thanks for your help. Kind regards, Timmie [1]http://docs.python.org/lib/module-ConfigParser.html From alan.gauld at btinternet.com Tue Apr 15 22:21:58 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Apr 2008 21:21:58 +0100 Subject: [Tutor] setting program configuration for all files and modules ofa program References: Message-ID: "Tim Michelsen" wrote >> import myconfig >> foo2 = myconfig.SectionFoo['second'] > This seems like reinventing what the ConfigParser > mdoule [1] already does. But with the advantage that its pure python, no parsing needed so its both faster and avouds any string to int type conversions > But to my optinion Config Parser offers the following advantage: > - Readable > - All are strings => no strange 'mysetting' is needed. I'm not sure what you mean. The Python variables and dictionary is all strings too. mysetting is just a string... But the choice is yours, you can use config parser to parse a config file into variables in a settings module or you can create the settings directly in the settings module. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Apr 15 22:31:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 15 Apr 2008 16:31:27 -0400 Subject: [Tutor] setting program configuration for all files and modules ofa program In-Reply-To: References: Message-ID: <4805109F.3010500@tds.net> Alan Gauld wrote: >> But to my optinion Config Parser offers the following advantage: >> - Readable >> - All are strings => no strange 'mysetting' is needed. > > I'm not sure what you mean. The Python variables and dictionary > is all strings too. mysetting is just a string... He means, with ConfigParser strings don't need to be quoted, giving perhaps a cleaner and more friendly syntax. Kent From rdm at rcblue.com Tue Apr 15 22:55:53 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 15 Apr 2008 13:55:53 -0700 Subject: [Tutor] datetime module problem Message-ID: <20080415205654.C2C531E4023@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080415/6bcfadd1/attachment.htm From bgailer at gmail.com Tue Apr 15 23:29:08 2008 From: bgailer at gmail.com (bob gailer) Date: Tue, 15 Apr 2008 17:29:08 -0400 Subject: [Tutor] datetime module problem In-Reply-To: <20080415205654.C2C531E4023@bag.python.org> References: <20080415205654.C2C531E4023@bag.python.org> Message-ID: <48051E24.3060007@gmail.com> Dick Moores wrote: > I'm really struggling with the datetime module. Trying for a script > that will calculate the number of days between any two dates, I've > come up with this: > > import datetime > date1 = raw_input("Enter date1 as year-month-day: ") > year1, month1, day1 = date1.split('-') > date1 = datetime.date(int(year1), int(month1), int(day1)) > date2 = raw_input("Enter date2 as year-month-day: ") > year2, month2, day2 = date2.split('-') > date2 = datetime.date(int(year2), int(month2), int(day2)) > print "date2 - date1 is", date2 - date1 > > Here's one run: > Enter date1 as year-month-day: 2003-4-15 > Enter date2 as year-month-day: 2008-4-15 > date2 - date1 is 1827 days, 0:00:00 > > How can I get rid of that "0:00:00"? > > And there must be a better way. What is it? You might read the datetime documentation. And then notice that date2 - date1 is a timedelta object. And then look that up to see its attributes (which inculdes days) And then try print (date2 - date1).days -- Bob Gailer 919-636-4239 Chapel Hill, NC From kent37 at tds.net Tue Apr 15 23:37:18 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 15 Apr 2008 17:37:18 -0400 Subject: [Tutor] datetime module problem In-Reply-To: <20080415205654.C2C531E4023@bag.python.org> References: <20080415205654.C2C531E4023@bag.python.org> Message-ID: <4805200E.8010106@tds.net> Dick Moores wrote: > I'm really struggling with the datetime module. Trying for a script that > will calculate the number of days between any two dates How about this: from datetime import datetime date1 = raw_input("Enter date1 as year-month-day: ") date1 = datetime.strptime(date1, '%Y-%m-%d') date2 = raw_input("Enter date2 as year-month-day: ") date2 = datetime.strptime(date2, '%Y-%m-%d') print "date2 - date1 is", (date2 - date1).days, 'days' Kent From alan.gauld at btinternet.com Wed Apr 16 00:44:43 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Apr 2008 23:44:43 +0100 Subject: [Tutor] setting program configuration for all files and modules ofa program References: <4805109F.3010500@tds.net> Message-ID: "Kent Johnson" wrote >> I'm not sure what you mean. The Python variables and dictionary >> is all strings too. mysetting is just a string... > > He means, with ConfigParser strings don't need to be quoted, giving > perhaps a cleaner and more friendly syntax. Ah, I see, yes that's a valid point. The whole issue of security is worth considering too. If the config file is not controlled then it is open to abuse since it allows a lot more than the simple set of name/value assignments that ConfigParser does. (I meant to mention that earlier) Alan G. From timmichelsen at gmx-topmail.de Wed Apr 16 00:48:22 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Wed, 16 Apr 2008 00:48:22 +0200 Subject: [Tutor] setting program configuration for all files and modules ofa program In-Reply-To: <4805109F.3010500@tds.net> References: <4805109F.3010500@tds.net> Message-ID: >>> But to my optinion Config Parser offers the following advantage: >>> - Readable >>> - All are strings => no strange 'mysetting' is needed. >> I'm not sure what you mean. The Python variables and dictionary >> is all strings too. mysetting is just a string... > > He means, with ConfigParser strings don't need to be quoted, giving > perhaps a cleaner and more friendly syntax. Yes, Kent that's what I wanted to express. Thanks for clarifying. My target here are users that do not develop python. From ricaraoz at gmail.com Tue Apr 15 16:42:23 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 15 Apr 2008 11:42:23 -0300 Subject: [Tutor] Remove specific chars from a string In-Reply-To: <4803AABD.7080205@tds.net> References: <1208195709.22453.1247815769@webmail.messagingengine.com> <4803AABD.7080205@tds.net> Message-ID: <4804BECF.2000901@bigfoot.com> > Malcolm Greene wrote: >> What is the Pythonic way to remove specific chars from a string? The >> .translate( table[, deletechars]) method seems the most 'politically >> correct' and also the most complicated. Why complicated? import string myStr = 'some text from which you want to delete some chars' resultStr = s.translate(string.maketrans('', ''), 'nem') print resultStr Output : so txt fro which you wat to dlt so chars You just have to use maketrans with empty strings. If string is deprecated then I guess some other way of creating translation tables will be provided. HTH From timmichelsen at gmx-topmail.de Wed Apr 16 01:20:07 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Wed, 16 Apr 2008 01:20:07 +0200 Subject: [Tutor] cut all decimal places with zeros In-Reply-To: <48040847.7020105@tds.net> References: <48040847.7020105@tds.net> Message-ID: >> how can I suppress the decimal places for (only those) numbers whos >> decimal places are zero (0)? > > I don't know how to do this with just string formatting but I think > ('%.4f' % n).rstrip('.0') > will do what you want. No. I tested with n = 10.0 You code returns '1' My code returns '10' Here again: ### CODE ### def cut_decimals(float): """ input: floating number output: number as string with zero decimals removed """ #print float-int(float) #print '%.4f' %float if float-int(float) != 0: number = '%.4f' %float number = number.replace('0.','X.') number = number.replace('0','') number = number.replace('X.','0.') else: number = '%.0f' %float return number #### END ### Regards, Timmie From rdm at rcblue.com Wed Apr 16 01:31:23 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 15 Apr 2008 16:31:23 -0700 Subject: [Tutor] datetime module problem In-Reply-To: <4805200E.8010106@tds.net> References: <20080415205654.C2C531E4023@bag.python.org> <4805200E.8010106@tds.net> Message-ID: <20080415233331.E4ABB1E4013@bag.python.org> At 02:37 PM 4/15/2008, Kent Johnson wrote: >Dick Moores wrote: >>I'm really struggling with the datetime module. Trying for a script >>that will calculate the number of days between any two dates > >How about this: > >from datetime import datetime >date1 = raw_input("Enter date1 as year-month-day: ") >date1 = datetime.strptime(date1, '%Y-%m-%d') >date2 = raw_input("Enter date2 as year-month-day: ") >date2 = datetime.strptime(date2, '%Y-%m-%d') >print "date2 - date1 is", (date2 - date1).days, 'days' > >Kent Yes, thanks, Kent. I finally tracked down that table for the format string, at . Been experimenting with it. Realized that the format string could be the more familiar American '%m/%d/%Y', or '%m/%d/%y'. The docs are so hard for me to understand, that I'm even feeling pleased with myself for this: from datetime import datetime date1 = raw_input("Enter date1 as year-month-day: ") date1 = datetime.strptime(date1, '%m/%d/%Y') today = datetime.now() print "today - date1 is", (today - date1).days, 'days' Dick ================================ UliPad <>: http://code.google.com/p/ulipad/ From john at fouhy.net Wed Apr 16 01:45:33 2008 From: john at fouhy.net (John Fouhy) Date: Wed, 16 Apr 2008 11:45:33 +1200 Subject: [Tutor] cut all decimal places with zeros In-Reply-To: References: <48040847.7020105@tds.net> Message-ID: <5e58f2e40804151645w22cdac5bh8c15847c0ff5006e@mail.gmail.com> On 16/04/2008, Tim Michelsen wrote: > Kent wrote: > > I don't know how to do this with just string formatting but I think > > ('%.4f' % n).rstrip('.0') > > will do what you want. > > No. > I tested with > n = 10.0 > You code returns '1' > > My code returns '10' Good catch. Try: ('%.4f' % n).rstrip('0').rstrip('.') You can read about the rstrip function by starting the python interpreter, then typing help(''.rstrip) This will explain that rstrip will strip off any charcters in the argument from the right of the string you call it on. So '10.0'.rstrip('.0') will remove any '.' or '0' from the right, leaving '1'. '10.0'.rstrip('0') will remove '0' only, leaving '10.'. Thus '10.0'.rstrip('0').rstrip('.') will remove the '0's, then remove the '.'s, leaving '10'. -- John. From john at fouhy.net Wed Apr 16 01:52:12 2008 From: john at fouhy.net (John Fouhy) Date: Wed, 16 Apr 2008 11:52:12 +1200 Subject: [Tutor] Remove specific chars from a string In-Reply-To: <4804BECF.2000901@bigfoot.com> References: <1208195709.22453.1247815769@webmail.messagingengine.com> <4803AABD.7080205@tds.net> <4804BECF.2000901@bigfoot.com> Message-ID: <5e58f2e40804151652k763e3813pfbfc02b28417dc5c@mail.gmail.com> On 16/04/2008, Ricardo Ar?oz wrote: > You just have to use maketrans with empty strings. If string is > deprecated then I guess some other way of creating translation tables > will be provided. Most string.* functions are deprecated, because they've been moved to methods of strings. (e.g. string.capitalize(s) --> s.capitalize()) But that doesn't work for a couple of functions, like maketrans, so those functions are not deprecated. -- John. From bgailer at gmail.com Wed Apr 16 02:57:13 2008 From: bgailer at gmail.com (bob gailer) Date: Tue, 15 Apr 2008 20:57:13 -0400 Subject: [Tutor] Test - please ignore Message-ID: <48054EE9.1080908@gmail.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080415/0ec92b7c/attachment.htm From gtxy20 at gmail.com Wed Apr 16 03:51:02 2008 From: gtxy20 at gmail.com (GTXY20) Date: Tue, 15 Apr 2008 21:51:02 -0400 Subject: [Tutor] Nested dictionary with defaultdict Message-ID: <39cb7e5d0804151851h7c46970l3e73c65417c2b309@mail.gmail.com> Hi tutors, I currently have a dictionary like the following: {'1': ['220', '220', '220''], '2': ['220', '238', '238', '238', '238'], '3': ['220', '238'], '4': ['220', '220'], '5': ['220', '220', '238'], '6': ['238', '238'], '7': ['220']} I am trying to create a dictionary that would list the current key and a count of the iterations of values within the value list like so: {'1': {'220' : 3}, '2': {'220' : 1}, 2: {238 : 4}, '3': {'220' : 1}, 3: { '238' : 1}, '4': {220 : 2}, '5': {'220: 2}, '5': {238 : 1}, '6': {'238' : 2}, '7': {'220' : 1}} Now I am pretty sure that I need to loop through the first dictionary and create a defaultdict from the values for each key in that dictionary but at this point I am having difficulty coming up with the loop. I am looking for a satrting point or any suggestions. Many thanks in advance. GTXY20 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080415/a5dbe9e0/attachment.htm From marc.tompkins at gmail.com Wed Apr 16 04:03:44 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 15 Apr 2008 19:03:44 -0700 Subject: [Tutor] Hoping to benefit from someone's experience... Message-ID: <40af687b0804151903s5577b339gb92bbc92dae8a899@mail.gmail.com> Does anyone out have experience with: - manipulating RTF files? - or writing OpenOffice macros in Python? I need to pre-process approximately 10,000 medical reports so they can be imported into an EMR. (They were originally saved as Word .docs; I'd like to give hearty thanks to the authors of "ooconvert" ( http://sourceforge.net/projects/ooconvert/), which enabled me to do a batch conversion with much less effort than I was expecting...) Anyway, the files as they now exist each contain a single section, with a header and footer on each page. The EMR's import function wants to see a slug of summary information as the first thing on the first page, which means that the header needs to be suppressed; however, I expect that the users will want to reprint these things in the future, so I don't want to delete the header entirely. In short, what I want to do is insert a new section at the top of the file. My tasks are: - figure out which codes I need to insert to create a new section with no header and then re-enable it at the end - figure out where in the file to do the inserting (I thought I already had this worked out, but apparently not quite) THEN - figure out how to find the correct insertion point programmatically - either agnostically, by finding a particular pattern of symbols that occur in the right location, or by actually parsing the RTF hierarchy to figure out where the meta-document ends and the document begins. The agnostic solution would be much easier - and this is a one-off, so I'm not building for the ages here - but it really looks like homogeneous tag soup to me. I have, of course, tried inserting the section myself and then compared the before-and-after files... but all I've got so far is a headache... (Not quite true - I think I'm close - but I'm getting angrier with Microsoft with every moment I spend looking at this stuff. Hyper-optimized Perl is a freakin' marvel of clarity next to this... ) {\footerr \ltrpar \pard\plain \ltrpar\s22\qc \li0\ri0\nowidctlpar\tqc\tx4153\tqr\tx8306\wrapdefault\faauto\rin0\lin0\itap0 \rtlch\fcs1 \af0\afs20\alang1025 \ltrch\fcs0 \fs24\lang3081\langfe255\cgrid\langnp3081\langfenp255 {\rtlch\fcs1 \af0 \ltrch\fcs0 \f1\fs16\insrsid5703726 \par } \pard \ltrpar\s22\qc \li0\ri0\nowidctlpar\tqc\tx4153\tqr\tx8306\wrapdefault\faauto\rin0\lin0\itap0\pararsid5703726 {\rtlch\fcs1 \af0\afs24 \ltrch\fcs0 \fs16\lang3081\langfe1033\loch\af1\hich\af43\langfenp1033\insrsid5703726 GAAAAAAAHHH! It occurs to me that there might be another way - maybe I can automate OpenOffice to open each file and insert the blank section and some dummy text, and then, in Python, find the dummy text and replace it with the summary slug? Maybe even do the whole job with a macro? And never have to poke through RTF again? So I was juggling the RTF spec (the RTFM?), a text editor, Word (so I can make sure the thing still looks right), and the import utility - when it suddenly struck me that someone out there may have done this before. (And yes, I've definitely Googled, but my Google-fu may be weak today.) If anyone has insight into RTF Zen, or has some tips on batch macros in oO, I'd be obliged... Marc -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080415/1c779f54/attachment.htm From john at fouhy.net Wed Apr 16 04:10:24 2008 From: john at fouhy.net (John Fouhy) Date: Wed, 16 Apr 2008 14:10:24 +1200 Subject: [Tutor] Hoping to benefit from someone's experience... In-Reply-To: <40af687b0804151903s5577b339gb92bbc92dae8a899@mail.gmail.com> References: <40af687b0804151903s5577b339gb92bbc92dae8a899@mail.gmail.com> Message-ID: <5e58f2e40804151910w1e984c86t54688a6c90a56be1@mail.gmail.com> On 16/04/2008, Marc Tompkins wrote: > Does anyone out have experience with: > - manipulating RTF files? Is this any help to you: http://pyrtf.sourceforge.net/ ? -- John. From kent37 at tds.net Wed Apr 16 04:17:08 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 15 Apr 2008 22:17:08 -0400 Subject: [Tutor] Nested dictionary with defaultdict In-Reply-To: <39cb7e5d0804151851h7c46970l3e73c65417c2b309@mail.gmail.com> References: <39cb7e5d0804151851h7c46970l3e73c65417c2b309@mail.gmail.com> Message-ID: <480561A4.1090208@tds.net> GTXY20 wrote: > > Hi tutors, > > I currently have a dictionary like the following: > > {'1': ['220', '220', '220''], '2': ['220', '238', '238', '238', '238'], > '3': ['220', '238'], '4': ['220', '220'], '5': ['220', '220', '238'], > '6': ['238', '238'], '7': ['220']} > > I am trying to create a dictionary that would list the current key and a > count of the iterations of values within the value list like so: > > {'1': {'220' : 3}, '2': {'220' : 1}, 2: {238 : 4}, '3': {'220' : 1}, 3: > { '238' : 1}, '4': {220 : 2}, '5': {'220: 2}, '5': {238 : 1}, '6': > {'238' : 2}, '7': {'220' : 1}} ?? Do you really want keys of '2' and 2? How can you have two keys '5'? I guess maybe you want {'1': {'220' : 3}, '2': {'220' : 1, 238 : 4}, '3': {'220' : 1, '238' : 1}, '4': {220 : 2}, '5': {'220: 2, 238 : 1}, '6': {'238' : 2}, '7': {'220' : 1}} > Now I am pretty sure that I need to loop through the first dictionary > and create a defaultdict from the values for each key in that dictionary > but at this point I am having difficulty coming up with the loop. > > I am looking for a satrting point or any suggestions. Do you know how to turn ['220', '238', '238', '238', '238'] into {'220' : 1, '238' : 4} ? If so, then put that code in a loop over the key, value pairs of the dict. Kent From python at bdurham.com Wed Apr 16 04:18:43 2008 From: python at bdurham.com (python at bdurham.com) Date: Tue, 15 Apr 2008 22:18:43 -0400 Subject: [Tutor] Hoping to benefit from someone's experience... In-Reply-To: <40af687b0804151903s5577b339gb92bbc92dae8a899@mail.gmail.com> References: <40af687b0804151903s5577b339gb92bbc92dae8a899@mail.gmail.com> Message-ID: <1208312323.15504.1248115007@webmail.messagingengine.com> Mark, Here's how we work with RTF: We create a Word document formatted exactly like we want with special markers (unique text) inserted in places where we want to programmatically add text. We save this document to RTF (this RTF becomes our template file), remove all the carriage returns and line feeds, and then replace our marker text with the text we want to insert. Each new version of Word introduces new RTF codes and markup patterns. Recommendation: Find a very old version of Word (Word 95) to generate your RTF 'templates'. The older versions of Word generate much simpler RTF that is forward compatible. Good luck! Malcolm From john at fouhy.net Wed Apr 16 04:19:54 2008 From: john at fouhy.net (John Fouhy) Date: Wed, 16 Apr 2008 14:19:54 +1200 Subject: [Tutor] Nested dictionary with defaultdict In-Reply-To: <39cb7e5d0804151851h7c46970l3e73c65417c2b309@mail.gmail.com> References: <39cb7e5d0804151851h7c46970l3e73c65417c2b309@mail.gmail.com> Message-ID: <5e58f2e40804151919mb13d7d3h5d4d00ca728f9b86@mail.gmail.com> On 16/04/2008, GTXY20 wrote: > I currently have a dictionary like the following: > > {'1': ['220', '220', '220''], '2': ['220', '238', '238', '238', '238'], '3': > ['220', '238'], '4': ['220', '220'], '5': ['220', '220', '238'], '6': > ['238', '238'], '7': ['220']} > > I am trying to create a dictionary that would list the current key and a > count of the iterations of values within the value list like so: > > {'1': {'220' : 3}, '2': {'220' : 1}, 2: {238 : 4}, '3': {'220' : 1}, 3: { > '238' : 1}, '4': {220 : 2}, '5': {'220: 2}, '5': {238 : 1}, '6': {'238' : > 2}, '7': {'220' : 1}} [...] > I am looking for a satrting point or any suggestions. Can you write a function that will take a list and return a dictionary with the counts of elements in the list? i.e. something like: >>> def countValues(valueList): ... # your code goes here ... >>> countValues(['220', '238', '238', '238', '238']) {'238': 4, '220': 1} P.S. Your sample output is not a valid dictionary... -- John. From gtxy20 at gmail.com Wed Apr 16 04:52:43 2008 From: gtxy20 at gmail.com (GTXY20) Date: Tue, 15 Apr 2008 22:52:43 -0400 Subject: [Tutor] Nested dictionary with defaultdict In-Reply-To: <480561A4.1090208@tds.net> References: <39cb7e5d0804151851h7c46970l3e73c65417c2b309@mail.gmail.com> <480561A4.1090208@tds.net> Message-ID: <39cb7e5d0804151952i1cb9abc5n198358377017fcff@mail.gmail.com> Hi Kent, Yes I think so I think I am almost there with this: from collections import defaultdict d = {'1': ['220', '220', '220''], '2': ['220', '238', '238', '238', '238'], '3': ['220', '238'], '4': ['220', '220'], '5': ['220', '220', '238'], '6': ['238', '238'], '7': ['220']} for f, b in d.items(): h = defaultdict(int) for j in b: h[j]+=1 print ('%s, %s' % (f, h)) However, not exactly happy with the printed output as soon as I complete I will repost what I come up with. Thanks so much. M. On Tue, Apr 15, 2008 at 10:17 PM, Kent Johnson wrote: > GTXY20 wrote: > > > > > Hi tutors, > > > > I currently have a dictionary like the following: > > > > {'1': ['220', '220', '220''], '2': ['220', '238', '238', '238', '238'], > > '3': ['220', '238'], '4': ['220', '220'], '5': ['220', '220', '238'], '6': > > ['238', '238'], '7': ['220']} > > > > I am trying to create a dictionary that would list the current key and a > > count of the iterations of values within the value list like so: > > > > {'1': {'220' : 3}, '2': {'220' : 1}, 2: {238 : 4}, '3': {'220' : 1}, 3: > > { '238' : 1}, '4': {220 : 2}, '5': {'220: 2}, '5': {238 : 1}, '6': {'238' : > > 2}, '7': {'220' : 1}} > > > > ?? Do you really want keys of '2' and 2? How can you have two keys '5'? I > guess maybe you want > {'1': {'220' : 3}, '2': {'220' : 1, 238 : 4}, '3': {'220' : 1, '238' : 1}, > '4': {220 : 2}, '5': {'220: 2, 238 : 1}, '6': {'238' : 2}, '7': {'220' : 1}} > > > Now I am pretty sure that I need to loop through the first dictionary and > > create a defaultdict from the values for each key in that dictionary but at > > this point I am having difficulty coming up with the loop. > > > > I am looking for a satrting point or any suggestions. > > > > Do you know how to turn > ['220', '238', '238', '238', '238'] > into > {'220' : 1, '238' : 4} > ? > > If so, then put that code in a loop over the key, value pairs of the dict. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080415/0261bd8f/attachment.htm From kepalapening at gmail.com Wed Apr 16 05:06:44 2008 From: kepalapening at gmail.com (Kepala Pening) Date: Wed, 16 Apr 2008 11:06:44 +0800 Subject: [Tutor] Nested dictionary with defaultdict Message-ID: <20080416.030644.421.1@SELINAPPORTABLE> count = lambda x: [{y: x.count(y)} for y in set(x)] y = {} for key, val in myDict.items(): y[key] = count(val) print y {'1': [{'220': 3}], '3': [{'238': 1}, {'220': 1}], '2': [{'238': 4}, {'220': 1}], '5': [{'238': 1}, {'220': 2}], '4': [{'220': 2}], '7': [{'220': 1}], '6': [{'238': 2}]} ----- Original Message ----- From: GTXY20 To: tutor at python.org Date: Tue, 15 Apr 2008 21:51:02 -0400 Subject: [Tutor] Nested dictionary with defaultdict Hi tutors, I currently have a dictionary like the following: {'1': ['220', '220', '220''], '2': ['220', '238', '238', '238', '238'], '3': ['220', '238'], '4': ['220', '220'], '5': ['220', '220', '238'], '6': ['238', '238'], '7': ['220']} I am trying to create a dictionary that would list the current key and a count of the iterations of values within the value list like so: {'1': {'220' : 3}, '2': {'220' : 1}, 2: {238 : 4}, '3': {'220' : 1}, 3: { '238' : 1}, '4': {220 : 2}, '5': {'220: 2}, '5': {238 : 1}, '6': {'238' : 2}, '7': {'220' : 1}} Now I am pretty sure that I need to loop through the first dictionary and create a defaultdict from the values for each key in that dictionary but at this point I am having difficulty coming up with the loop. I am looking for a satrting point or any suggestions. Many thanks in advance. GTXY20 From gtxy20 at gmail.com Wed Apr 16 05:39:04 2008 From: gtxy20 at gmail.com (GTXY20) Date: Tue, 15 Apr 2008 23:39:04 -0400 Subject: [Tutor] Nested dictionary with defaultdict In-Reply-To: <5e58f2e40804151919mb13d7d3h5d4d00ca728f9b86@mail.gmail.com> References: <39cb7e5d0804151851h7c46970l3e73c65417c2b309@mail.gmail.com> <5e58f2e40804151919mb13d7d3h5d4d00ca728f9b86@mail.gmail.com> Message-ID: <39cb7e5d0804152039i53ad05e0oe34cdf85bc79fa75@mail.gmail.com> Thanks John and Kent for the guidance. This following ends up working perfect for me - instead of print to the console I will just write this to a text file. I will also wrap it in a function. from collections import defaultdict d = {'1': ['220', '220', '220''], '2': ['220', '238', '238', '238', '238'], '3': ['220', '238'], '4': ['220', '220'], '5': ['220', '220', '238'], '6': ['238', '238'], '7': ['220']} for f, b in d.items(): h = defaultdict(int) for j in b: h[j]+=1 for k,v in sorted (h.items()): print ('%s, (%s:%s)' % (f, k, v)) M. On Tue, Apr 15, 2008 at 10:19 PM, John Fouhy wrote: > On 16/04/2008, GTXY20 wrote: > > I currently have a dictionary like the following: > > > > {'1': ['220', '220', '220''], '2': ['220', '238', '238', '238', '238'], > '3': > > ['220', '238'], '4': ['220', '220'], '5': ['220', '220', '238'], '6': > > ['238', '238'], '7': ['220']} > > > > I am trying to create a dictionary that would list the current key and a > > count of the iterations of values within the value list like so: > > > > {'1': {'220' : 3}, '2': {'220' : 1}, 2: {238 : 4}, '3': {'220' : 1}, 3: > { > > '238' : 1}, '4': {220 : 2}, '5': {'220: 2}, '5': {238 : 1}, '6': {'238' > : > > 2}, '7': {'220' : 1}} > [...] > > I am looking for a satrting point or any suggestions. > > Can you write a function that will take a list and return a dictionary > with the counts of elements in the list? > > i.e. something like: > > >>> def countValues(valueList): > ... # your code goes here > ... > >>> countValues(['220', '238', '238', '238', '238']) > {'238': 4, '220': 1} > > P.S. Your sample output is not a valid dictionary... > > -- > John. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080415/f9f6dbc1/attachment.htm From marc.tompkins at gmail.com Wed Apr 16 05:31:56 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 15 Apr 2008 20:31:56 -0700 Subject: [Tutor] Hoping to benefit from someone's experience... In-Reply-To: <1208312323.15504.1248115007@webmail.messagingengine.com> References: <40af687b0804151903s5577b339gb92bbc92dae8a899@mail.gmail.com> <1208312323.15504.1248115007@webmail.messagingengine.com> Message-ID: <40af687b0804152031h6c9ad724ma50ef0d7ce809531@mail.gmail.com> On Tue, Apr 15, 2008 at 7:18 PM, wrote: > Recommendation: Find a very old version of Word (Word 95) to generate > your RTF 'templates'. The older versions of Word generate much simpler > RTF that is forward compatible. > Excellent advice! Unfortunately, my case is a bit different... All incoming files (from the transcribing company) will be coming in as RTF and formatted properly - or at least they will if my instructions were clearly understood. In any case, future files are not my problem. My problem is transcriptions from the past year or so, maybe more - the practice moved to a new software package, and it remains to be seen how much history they want/need to load into the new EMR. (It's not a primary-care practice, so there's a lot of patient-base turnover.) The files I have to deal with were generated by Word 2003, and now have been converted to RTF by OpenOffice 2.4. I just need to shove a (mostly) blank page in at the beginning, with a slug of summary info, so that the import utility can digest the file. I've done it by hand on a few files now - open in Word*, - insert a section/page break at the top of the document - go to the second header and uncheck "Same as Previous" - go to the first header and delete it - close the header and enter the slug info (doctor is easy, as the files are separated into folders by doctor, but patient ID and date need to be determined for each file) - save - feed it to the import utility *Although I have OpenOffice installed, and I used it - in Ubuntu - for the batch conversion, I haven't yet checked to see whether this task is simpler or more complicated in Writer. ** I just did. Viva open source and all, but they've got a loooong way to catch up in ease of use - at least for this task... Since I have 10,000 or so files to do, the job screams for automation, and Python is my favorite tool. So hope springs eternal... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080415/b0b8862c/attachment-0001.htm From marc.tompkins at gmail.com Wed Apr 16 05:50:54 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 15 Apr 2008 20:50:54 -0700 Subject: [Tutor] Hoping to benefit from someone's experience... In-Reply-To: <5e58f2e40804151910w1e984c86t54688a6c90a56be1@mail.gmail.com> References: <40af687b0804151903s5577b339gb92bbc92dae8a899@mail.gmail.com> <5e58f2e40804151910w1e984c86t54688a6c90a56be1@mail.gmail.com> Message-ID: <40af687b0804152050w2f05e645pe0e85bc3b69ac8d@mail.gmail.com> On Tue, Apr 15, 2008 at 7:10 PM, John Fouhy wrote: > Is this any help to you: http://pyrtf.sourceforge.net/ > Not so much, because it only produces RTF - it doesn't help me pick apart the stuff I've already got. (It did cross my mind to try to create in pyRTF the same structure that I'm trying to code by hand... but from my quick overview, pyRTF doesn't appear to deal with "sections" in the same way Word does. Maybe I'm missing something, but I didn't see it.) This, though: http://sourceforge.net/projects/pyrtflib/, parses the file and extracts content from it; it just doesn't seem to pay much attention to the non-content tags it picks through. I think I'm going to have to figure out a way to make the "agnostic" method work. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080415/c09b1999/attachment.htm From rabidpoobear at gmail.com Wed Apr 16 05:51:14 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 15 Apr 2008 22:51:14 -0500 Subject: [Tutor] [Fwd: Re: Hoping to benefit from someone's experience...] Message-ID: <480577B2.8020903@gmail.com> Sorry, forgot to cc the list. -------------- next part -------------- An embedded message was scrubbed... From: "Marc Tompkins" Subject: Re: [Tutor] Hoping to benefit from someone's experience... Date: Tue, 15 Apr 2008 20:31:56 -0700 Size: 8722 Url: http://mail.python.org/pipermail/tutor/attachments/20080415/887775bb/attachment.eml From marc.tompkins at gmail.com Wed Apr 16 06:15:02 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 15 Apr 2008 21:15:02 -0700 Subject: [Tutor] Hoping to benefit from someone's experience... In-Reply-To: <4805779D.6090202@gmail.com> References: <40af687b0804151903s5577b339gb92bbc92dae8a899@mail.gmail.com> <1208312323.15504.1248115007@webmail.messagingengine.com> <40af687b0804152031h6c9ad724ma50ef0d7ce809531@mail.gmail.com> <4805779D.6090202@gmail.com> Message-ID: <40af687b0804152115x77f083d3o55a8b3777e4b5574@mail.gmail.com> On Tue, Apr 15, 2008 at 8:50 PM, Luke Paireepinart wrote: > Sorry, forgot to cc the list. > Actually, you cc'd the list with my previous post instead of your response to it. Here's what you sent me: > I don't know if this is the best way, but given that other guy's > suggestion about RTF, > why not create a new document formatted how you want, > then use ooconvert to throw all of your files into text files. > Then you don't have to deal with parsing the original files, and you can > use the data from the text files and then generate new RTFs? > You can see how the result is... just make sure you don't overwrite your > original RTFs! > -Luke I _have_ been thinking about this... but I don't think it's going to fly. Apart from the header and footer (which would be a snap to re-create), the reports include a good deal of formatting, without which they're nearly impossible to comprehend. (Bulleted lists, numbered lists, S.O.A.P. quadrants, reviews of systems with the name of each system bolded for emphasis...) From a publishing or stylistic point of view, they're a freaking nightmare, but this is medicine, not literature! Furthermore, the formatting varies from document to document... basically, this would require reviewing each of the 10K documents to make sure it still makes sense after its travels - and, almost as important, still resembles the printed document sitting in a file cabinet somewhere. I've been very impressed by how well OO saved the formatting during conversion from .doc to .rtf... but I don't want to push my luck too far. I'm sorry if it seems I'm just shooting everything down - it's just that I had done a good bit of thinking about my problem before I wrote my original question. Moving away from the RTF horn of my dilemma, does anyone have any experience writing OO macros? Or know of any sites with more than ten lines of documentation? I'm studying ooconvert itself, but that's only getting me so far. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080415/2ed6dbad/attachment.htm From alan.gauld at btinternet.com Wed Apr 16 08:33:56 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Apr 2008 07:33:56 +0100 Subject: [Tutor] Hoping to benefit from someone's experience... References: <40af687b0804151903s5577b339gb92bbc92dae8a899@mail.gmail.com><1208312323.15504.1248115007@webmail.messagingengine.com><40af687b0804152031h6c9ad724ma50ef0d7ce809531@mail.gmail.com><4805779D.6090202@gmail.com> <40af687b0804152115x77f083d3o55a8b3777e4b5574@mail.gmail.com> Message-ID: "Marc Tompkins" wrote > Moving away from the RTF horn of my dilemma, does anyone have any > experience > writing OO macros? Or know of any sites with more than ten lines of > documentation? I'm studying ooconvert itself, but that's only > getting me so > far. Have you considered driving Word instead of OOo? That way you leave the documents in their original format and make the mods using COM from Python. Python and COM are not super friendly but they are not impossible either. And if you can record some Macros in Word and save them as functions you should be able to call those macros from a python script that just orchestrates the macros. Alternatively learn enough VBScript to do it all in Word itself.... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From python at bdurham.com Wed Apr 16 13:33:35 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 16 Apr 2008 07:33:35 -0400 Subject: [Tutor] Remove specific chars from a string In-Reply-To: <4804BECF.2000901@bigfoot.com> References: <1208195709.22453.1247815769@webmail.messagingengine.com> <4803AABD.7080205@tds.net> <4804BECF.2000901@bigfoot.com> Message-ID: <1208345615.2472.1248178745@webmail.messagingengine.com> Ricardo, Thanks for the tip on how to use maketrans. I was trying to over-complicate things on my side. The string module lives in 3.0 ... only the duplicate methods have been removed. Regards, Malcolm From bgailer at gmail.com Wed Apr 16 17:41:14 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 16 Apr 2008 11:41:14 -0400 Subject: [Tutor] Help with tutor@python.org Message-ID: <48061E1A.2030500@gmail.com> I just changed my email address. Now when I post to tutor at python.org the posts do not show up. I have checked the mailman settings; they look OK. Have you any guidance? Did this post show up on the list? -- Bob Gailer 919-636-4239 Chapel Hill, NC From bgailer at gmail.com Wed Apr 16 19:23:45 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 16 Apr 2008 13:23:45 -0400 Subject: [Tutor] Help with tutor@python.org In-Reply-To: <48062D5A.6070008@linguasos.org> References: <48061E1A.2030500@gmail.com> <48062D5A.6070008@linguasos.org> Message-ID: <48063621.9010203@gmail.com> Thanks to all. My posts do show up. Now how to get them sent to me??? -- Bob Gailer 919-636-4239 Chapel Hill, NC From marc.tompkins at gmail.com Wed Apr 16 19:48:14 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 16 Apr 2008 10:48:14 -0700 Subject: [Tutor] Hoping to benefit from someone's experience... In-Reply-To: References: <40af687b0804151903s5577b339gb92bbc92dae8a899@mail.gmail.com> <1208312323.15504.1248115007@webmail.messagingengine.com> <40af687b0804152031h6c9ad724ma50ef0d7ce809531@mail.gmail.com> <4805779D.6090202@gmail.com> <40af687b0804152115x77f083d3o55a8b3777e4b5574@mail.gmail.com> Message-ID: <40af687b0804161048o63517b61y983734e68bb1b3ca@mail.gmail.com> Again with the forgetting to cc the list... On Tue, Apr 15, 2008 at 11:33 PM, Alan Gauld wrote: > Alternatively learn enough VBScript to do it all in Word itself.... That's exactly what I'm doing now. After mentioning in a previous email that formatting is important, I took a closer look at the documents that OO had converted... and they weren't as good as I thought at first. No disgrace to OO; the fact that anybody outside of Microsoft has ever managed to make even a little bit of sense out of the .doc format is a testimony to human ingenuity and stubbornness - but it's just not good enough. So, despite my enthusiasm for Python and the fact that VBScript repulses me, I think I need to start fresh and do it the Redmond way. If I were building something for long-term use rather than a one-time conversion, I would figure out how to drive Word from Python, but under the circumstances I'll hack something quick and dirty in VBS. (Does anyone remember VBA?) It's funny - years ago I used to use Visual Studio and _enjoy_ it. I'm spoiled now, I guess. By the way, there was a recent XKCD that I liked: http://xkcd.com/409/ -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080416/60641930/attachment.htm From kent37 at tds.net Wed Apr 16 20:07:24 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 16 Apr 2008 14:07:24 -0400 Subject: [Tutor] Hoping to benefit from someone's experience... In-Reply-To: <40af687b0804161048o63517b61y983734e68bb1b3ca@mail.gmail.com> References: <40af687b0804151903s5577b339gb92bbc92dae8a899@mail.gmail.com> <1208312323.15504.1248115007@webmail.messagingengine.com> <40af687b0804152031h6c9ad724ma50ef0d7ce809531@mail.gmail.com> <4805779D.6090202@gmail.com> <40af687b0804152115x77f083d3o55a8b3777e4b5574@mail.gmail.com> <40af687b0804161048o63517b61y983734e68bb1b3ca@mail.gmail.com> Message-ID: <4806405C.6050002@tds.net> Marc Tompkins wrote: > It's funny - years ago I used to use Visual Studio and _enjoy_ it. I'm > spoiled now, I guess. Python does that to you. The only disadvantage I know to learning Python is that you won't want to code in anything else ever again :-) Kent From jeff at san-dc.com Wed Apr 16 20:35:21 2008 From: jeff at san-dc.com (Jeff Johnson) Date: Wed, 16 Apr 2008 11:35:21 -0700 Subject: [Tutor] Hoping to benefit from someone's experience... In-Reply-To: <4806405C.6050002@tds.net> References: <40af687b0804151903s5577b339gb92bbc92dae8a899@mail.gmail.com> <1208312323.15504.1248115007@webmail.messagingengine.com> <40af687b0804152031h6c9ad724ma50ef0d7ce809531@mail.gmail.com> <4805779D.6090202@gmail.com> <40af687b0804152115x77f083d3o55a8b3777e4b5574@mail.gmail.com> <40af687b0804161048o63517b61y983734e68bb1b3ca@mail.gmail.com> <4806405C.6050002@tds.net> Message-ID: <480646E9.9060607@san-dc.com> I have done most major languages over the last thirty years of which FoxPro has been the last 16 years. I thought FoxPro was the greatest until Python. Now I code in FoxPro and Python and I wish I could just use Python. It's fun to code, everything works and it is a complete package without needing to incorporate a bunch of api's or third party applications. Jeff Jeff Johnson jeff at san-dc.com SanDC, Inc. 623-582-0323 Fax 623-869-0675 Kent Johnson wrote: > Marc Tompkins wrote: >> It's funny - years ago I used to use Visual Studio and _enjoy_ it. I'm >> spoiled now, I guess. > > Python does that to you. The only disadvantage I know to learning Python > is that you won't want to code in anything else ever again :-) > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From pylinuxian at gmail.com Thu Apr 17 10:31:15 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Thu, 17 Apr 2008 08:31:15 +0000 Subject: [Tutor] Hoping to benefit from someone's experience... In-Reply-To: <480646E9.9060607@san-dc.com> References: <40af687b0804151903s5577b339gb92bbc92dae8a899@mail.gmail.com> <1208312323.15504.1248115007@webmail.messagingengine.com> <40af687b0804152031h6c9ad724ma50ef0d7ce809531@mail.gmail.com> <4805779D.6090202@gmail.com> <40af687b0804152115x77f083d3o55a8b3777e4b5574@mail.gmail.com> <40af687b0804161048o63517b61y983734e68bb1b3ca@mail.gmail.com> <4806405C.6050002@tds.net> <480646E9.9060607@san-dc.com> Message-ID: just a thought ... there must be some way of using OpenOffice to convert your ORIGINAL word documents into HTML files ... then as html is a very nice & structured language that you can manipulate & modify with ease just by adding some tags inside where you want or wish .... this is also only if you have some rich content like tables inside your documents ... if thats not your case, you can use OpenOffice tou extract just text ... hope this helps -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080417/8e3bd0f1/attachment.htm From kimgaang at aol.com Thu Apr 17 09:40:11 2008 From: kimgaang at aol.com (Michael Kim) Date: Thu, 17 Apr 2008 03:40:11 -0400 Subject: [Tutor] HELP!!!!! Message-ID: <4806FEDB.2020703@aol.com> Hi I am having a really hard time making my tictactoe program work. I was wondering if you could could check it out and help me with the error. Thanks blank = " " def asknumber(question, low, high): response = None while response not in range(low, high): response = int(raw_input(question)) return response def askquestion(question): response = None while response not in ("y", "n"): response = raw_input (question).lower() return response def pieces(): whosefirst=askquestion("Do you want to go first? (y/n): ") if whosefirst == "y": human = X X="X" computer = O O="O" else: computer = X human = O return computer, human def newboard(): board = [] box = 9 for square in range(box): blank = " " board.append(blank) return board def createboard(board): print "\n\t", board[0], "|", board[1], "|", board[2] print "\t", "---------" print "\t", board[3], "|", board[4], "|", board[5] print "\t", "---------" print "\t", board[6], "|", board[7], "|", board[8], "\n" def allowedmove(board): moves=[] for square in range(box): if board[square] == blank: moves.append(square) return moves def winner(board): movestowin=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)) for row in movestowin: if board[row[0]] == board[row[1]] ==board[row[2]] !=blank: winner=board[row[0]] return winner if blank not in board: tie = "tie" return tie return None def humanmove (board, human): allowed = allowedmove(board) move = None while move not in allowed: move = asknumber("It is your turn. Pick 0-8:", 0, box) if move not in allowed: print "\nPick again.\n" return move def computermove (board, computer, human): board = board[:] winnermoves = (4, 0, 2, 6, 8, 1, 3, 5, 7) for move in allowedmoves(board): board[move] = computer if winner (board) == computer: print move return move board[move] = blank for move in allowedmoves(board): board[move] = human if winner(board) == human: print move return move board[move] = blank for move in winnermoves: if move in allwedmoves(board): print move return move def whoseturn(turn): if turn == X: return O else: return X def whowon(iwon, computer, human): if iwon !=tie: print iwon, "you win!" else: print "a tie" def main(): computer, human = pieces() turn = X board = newboard() createboard(board) while not winner(board): if turn == human: move = humanmove(board, human) board[move] = human else: move = computermove(board, computer, human) board[move] = computer createboard(board) turn = whoseturn(turn) iwon = winner(board) whowon(iwon, computer, human) main() From kent37 at tds.net Thu Apr 17 12:27:55 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Apr 2008 06:27:55 -0400 Subject: [Tutor] Nested dictionary with defaultdict In-Reply-To: <20080416.030644.421.1@SELINAPPORTABLE> References: <20080416.030644.421.1@SELINAPPORTABLE> Message-ID: <4807262B.8060609@tds.net> Kepala Pening wrote: > count = lambda x: [{y: x.count(y)} for y in set(x)] At least for long enough lists, this is likely to be more expensive than the approach using defaultdict. Your count() function iterates the list (1+m) times, where m is the number of distinct words - once to create the set, and once for each call to x.count(). The complexity of your count() is O(m*n) where n is len(x). OTOH the defaultdict method is O(n). The loops in your solution are all in C code which may give some performance improvement but I expect that would be overshadowed by the factor of m as m and n get large. Kent > y = {} > for key, val in myDict.items(): > y[key] = count(val) > > print y > > {'1': [{'220': 3}], '3': [{'238': 1}, {'220': 1}], '2': [{'238': 4}, {'220': > 1}], '5': [{'238': 1}, {'220': 2}], '4': [{'220': 2}], '7': [{'220': 1}], > '6': [{'238': 2}]} From kent37 at tds.net Thu Apr 17 12:28:30 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Apr 2008 06:28:30 -0400 Subject: [Tutor] HELP!!!!! In-Reply-To: <4806FEDB.2020703@aol.com> References: <4806FEDB.2020703@aol.com> Message-ID: <4807264E.6000505@tds.net> Michael Kim wrote: > Hi I am having a really hard time making my tictactoe program work. I > was wondering if you could could check it out and help me with the > error. Thanks What is the error? Kent From rdm at rcblue.com Thu Apr 17 13:38:16 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 17 Apr 2008 04:38:16 -0700 Subject: [Tutor] datetime module problem In-Reply-To: <20080415233331.E4ABB1E4013@bag.python.org> References: <20080415205654.C2C531E4023@bag.python.org> <4805200E.8010106@tds.net> <20080415233331.E4ABB1E4013@bag.python.org> Message-ID: <20080417113824.9C7991E4007@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080417/1f23f565/attachment.htm From bala.biophysics at gmail.com Thu Apr 17 13:42:21 2008 From: bala.biophysics at gmail.com (Bala subramanian) Date: Thu, 17 Apr 2008 17:12:21 +0530 Subject: [Tutor] python assignments Message-ID: <288df32a0804170442n7b98df32qdad2865d38abfcbc@mail.gmail.com> Dear friends, I covered few introductory books on python. B4 going for an advanced book, i want to take up small, small assignments and try to solve with python. Can someone please suggest me any url where i can have assignments and solutions. Thanks, Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080417/34e69b55/attachment.htm From kent37 at tds.net Thu Apr 17 14:10:32 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Apr 2008 08:10:32 -0400 Subject: [Tutor] datetime module problem In-Reply-To: <20080417113824.9C7991E4007@bag.python.org> References: <20080415205654.C2C531E4023@bag.python.org> <4805200E.8010106@tds.net> <20080415233331.E4ABB1E4013@bag.python.org> <20080417113824.9C7991E4007@bag.python.org> Message-ID: <48073E38.9060408@tds.net> Dick Moores wrote: > from datetime import datetime > > print "Enter 2 dates, first the earlier date, then the later date." > def getDate(): > date = raw_input("Enter date as month/day/year, or enter nothing for > today: ") > if date == "": > date = datetime.now() > print "Today's date entered" > else: > date = datetime.strptime(date, '%m/%d/%Y') > return date > > print "What's the earlier date?" > date1 = getDate() > print > print "What's the later date?" > date2 = getDate() > print > print "The difference between the dates is", (date2 - date1).days, 'days' > > However, when the earlier date (date1) is today's date entered by just > pressing Enter, the result is always 1 day too small. And I don't see > how to correct this, other than by adding the 1 (and I'd have to give up > using a function, I think). I still don't really get datetime. Help? It's a rounding error. In [3]: from datetime import datetime In [4]: n=datetime.now() In [5]: n Out[5]: datetime.datetime(2008, 4, 17, 8, 2, 15, 278631) Notice n has a time component. In [8]: y=datetime.strptime('4/18/2008', '%m/%d/%Y') In [14]: y Out[14]: datetime.datetime(2008, 4, 18, 0, 0) y represents midnight on the given date. In [9]: y-n Out[9]: datetime.timedelta(0, 57464, 721369) So y-n is a fractional day, not a whole day. You could either create n with hours=minutes=0, or round the difference up to the next whole number of days. Kent From kent37 at tds.net Thu Apr 17 14:12:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Apr 2008 08:12:27 -0400 Subject: [Tutor] python assignments In-Reply-To: <288df32a0804170442n7b98df32qdad2865d38abfcbc@mail.gmail.com> References: <288df32a0804170442n7b98df32qdad2865d38abfcbc@mail.gmail.com> Message-ID: <48073EAB.2010907@tds.net> Bala subramanian wrote: > Dear friends, > > I covered few introductory books on python. B4 going for an advanced > book, i want to take up small, small assignments and try to solve with > python. Can someone please suggest me any url where i can have > assignments and solutions. Here are some ideas: http://personalpages.tds.net/~kent37/stories/00021.html#e21puzzles-and-problems Kent From rdm at rcblue.com Thu Apr 17 15:05:08 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 17 Apr 2008 06:05:08 -0700 Subject: [Tutor] datetime module problem In-Reply-To: <48073E38.9060408@tds.net> References: <20080415205654.C2C531E4023@bag.python.org> <4805200E.8010106@tds.net> <20080415233331.E4ABB1E4013@bag.python.org> <20080417113824.9C7991E4007@bag.python.org> <48073E38.9060408@tds.net> Message-ID: <20080417130516.D27501E4016@bag.python.org> At 05:10 AM 4/17/2008, Kent Johnson wrote: >Dick Moores wrote: > >>from datetime import datetime >>print "Enter 2 dates, first the earlier date, then the later date." >>def getDate(): >> date = raw_input("Enter date as month/day/year, or enter >> nothing for today: ") >> if date == "": >> date = datetime.now() >> print "Today's date entered" >> else: >> date = datetime.strptime(date, '%m/%d/%Y') >> return date >> >>print "What's the earlier date?" >>date1 = getDate() >>print >>print "What's the later date?" >>date2 = getDate() >>print >>print "The difference between the dates is", (date2 - date1).days, 'days' >>However, when the earlier date (date1) is today's date entered by >>just pressing Enter, the result is always 1 day too small. And I >>don't see how to correct this, other than by adding the 1 (and I'd >>have to give up using a function, I think). I still don't really >>get datetime. Help? > >It's a rounding error. > >In [3]: from datetime import datetime >In [4]: n=datetime.now() >In [5]: n >Out[5]: datetime.datetime(2008, 4, 17, 8, 2, 15, 278631) > >Notice n has a time component. > >In [8]: y=datetime.strptime('4/18/2008', '%m/%d/%Y') >In [14]: y >Out[14]: datetime.datetime(2008, 4, 18, 0, 0) > >y represents midnight on the given date. > >In [9]: y-n >Out[9]: datetime.timedelta(0, 57464, 721369) > >So y-n is a fractional day, not a whole day. > >You could either create n with hours=minutes=0, or round the >difference up to the next whole number of days. Kent, Man, I don't think I've ever been so frustrated with Python as I am with it's datetime module. I had guessed correctly at WHY I was getting that error, but I have no idea how to implement either of your suggestions as to how to eliminate it. Could you please spell them both out? Here's my script again: Thanks, Dick ================================ UliPad <>: http://code.google.com/p/ulipad/ From pylinuxian at gmail.com Thu Apr 17 15:09:22 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Thu, 17 Apr 2008 13:09:22 +0000 Subject: [Tutor] python assignments In-Reply-To: <48073EAB.2010907@tds.net> References: <288df32a0804170442n7b98df32qdad2865d38abfcbc@mail.gmail.com> <48073EAB.2010907@tds.net> Message-ID: http://www.pythonchallenge.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080417/b645cc01/attachment-0001.htm From kent37 at tds.net Thu Apr 17 15:29:11 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Apr 2008 09:29:11 -0400 Subject: [Tutor] datetime module problem In-Reply-To: <20080417130516.D27501E4016@bag.python.org> References: <20080415205654.C2C531E4023@bag.python.org> <4805200E.8010106@tds.net> <20080415233331.E4ABB1E4013@bag.python.org> <20080417113824.9C7991E4007@bag.python.org> <48073E38.9060408@tds.net> <20080417130516.D27501E4016@bag.python.org> Message-ID: <480750A7.8050604@tds.net> Dick Moores wrote: >> You could either create n with hours=minutes=0, or round the >> difference up to the next whole number of days. > > I have no idea how to implement either of > your suggestions as to how to eliminate it. Could you please spell > them both out? 1. In [17]: n=datetime.today() In [18]: n=datetime(n.year, n.month, n.day) In [19]: n Out[19]: datetime.datetime(2008, 4, 17, 0, 0) 2. In [20]: diff=y-n In [21]: diff Out[21]: datetime.timedelta(0, 57464, 721369) In [22]: days = diff.days In [23]: if diff.seconds or diff.microseconds: ....: days += 1 ....: ....: In [24]: days Out[24]: 1 Kent From pylinuxian at gmail.com Thu Apr 17 15:48:59 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Thu, 17 Apr 2008 13:48:59 +0000 Subject: [Tutor] Error with incorrect encoding In-Reply-To: <4804DB3B.90908@tds.net> References: <4804DB3B.90908@tds.net> Message-ID: Kent was right, >>> print u'\xae'.encode('utf-8') > (R) > but i think you are using the wrong source file, i mean don't copy & paste it from your browsers 'VIEW SOURCE' button. use python native urllib to get the file. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080417/3bb0a785/attachment.htm From brnstrmrs at gmail.com Thu Apr 17 15:57:46 2008 From: brnstrmrs at gmail.com (Brain Stormer) Date: Thu, 17 Apr 2008 09:57:46 -0400 Subject: [Tutor] input and output files from terminal In-Reply-To: References: <24bc7f6c0804140955t5a352243w19490dd2dfbf6c26@mail.gmail.com> Message-ID: <24bc7f6c0804170657t16cd1487gfb482a5aadc1d3c3@mail.gmail.com> Actually, Let me take that back with the raw_input comment since it is not the idle issue but I didn't want to the program to be interactive so I didn't want to wait for someone to put the information and press enter. Thanks for the file direction method but how do I get the names of the files so I can use it inside my program. On Mon, Apr 14, 2008 at 2:57 PM, Alan Gauld wrote: > > "Brain Stormer" wrote > > >I have a python program which works fine when run using idle but I > >would > > like call the program from the terminal. > > > > python test.py -i inputfile -o outputfile > > Easier to use file redirection: > > python test.py < inputfile > outputfile > > The -i flag in particular might conflict with Pythons own -i option. > > > I tried with raw_input but that only works in idle. > > What makes you think that? > raw_input is the normal way to get input from stdin. > > Can you explain what you did and what the result was? > Perhaps with a short code example? > > Try this for example: > > #################### > > name = raw_input('What's your name? ') > print "hello", name > > #################### > > That can be run in IDLE or in a command window > or using file redirection as described above. > > Tell us how you get on... > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080417/2ed872e6/attachment.htm From python at bdurham.com Thu Apr 17 16:43:58 2008 From: python at bdurham.com (python at bdurham.com) Date: Thu, 17 Apr 2008 10:43:58 -0400 Subject: [Tutor] Best practice for installing new packages (eggs) Message-ID: <1208443438.11218.1248422187@webmail.messagingengine.com> I would like to take a look at the wxOptParse package. This is my first time installing a package (vs. a module) so I'm looking for feedback on what installation technique I should use and where (in terms of folder paths) one would normally install 3rd party packages. For example, is are there conventions for where to put core packages, experimental packages, and packages that one is building themselves? Also, is it safe to assume that installing a 3rd party package won't (unexpectedly) affect other parts of my Python environment. I'm running Python 2.5.2 on Windows XP Pro SP2. Here are the 3 installation options that wxOptParse provides: Choose one of the following methods. In all cases you probably need to run as root. Egg Download ------------ # easy_install.py wxoptparse Egg File --------- # easy_install.py wxOptParse-x.y.z-py2.4.egg Easy Install Zip ---------------- # easy_install.py wxOptParse-x.y.z.zip Normal Python Install ---------------------- # unzip wxOptParse-x.y.z.zip # cd wxOptParse-x.y.z # python setup.py install Also note the following run instructions: If you want to run your program you should be able to type: wxoptparse myprogram.py Under Windows you may need to add "c:\Python2.4\scripts" to your path (or whatever directory python is installed) in order to run wxoptparse. The standard Python installer does not appear to do this for you. Thank you! Malcolm From bgailer at gmail.com Thu Apr 17 16:56:31 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 17 Apr 2008 10:56:31 -0400 Subject: [Tutor] HELP!!!!! In-Reply-To: <4806FEDB.2020703@aol.com> References: <4806FEDB.2020703@aol.com> Message-ID: <4807651F.9070702@gmail.com> Michael Kim wrote: > Hi I am having a really hard time making my tictactoe program work. I > was wondering if you could could check it out and help me with the > error. Thanks > As Kent pointed out, we need to see the error you are getting in order to help. That usually shows up as a traceback. When I run your program I get: File "j:/python/tictactoe.py", line 53 movestowin=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)) ^ IndentationError: expected an indented block There are numerous other problems in your code. As you fix one error the next will be revealed. For example when I fix the indentation error I next get: File "J:\python\tictactoe.py", line 124, in main() File "J:\python\tictactoe.py", line 105, in main computer, human = pieces() File "J:\python\tictactoe.py", line 20, in pieces human = X UnboundLocalError: local variable 'X' referenced before assignment Do you understand that variables must be assigned before reference? Python does not know what X is. So please report the specific error. Also try to determine what it means before reporting it. > > blank = " " > > > > def asknumber(question, low, high): > response = None > while response not in range(low, high): > response = int(raw_input(question)) > return response > > def askquestion(question): > response = None > while response not in ("y", "n"): > response = raw_input (question).lower() > return response > > def pieces(): > whosefirst=askquestion("Do you want to go first? (y/n): ") > if whosefirst == "y": > human = X > X is undefined (here and below) > X="X" > computer = O > O is undefined (here and below) > O="O" > else: > computer = X > human = O > return computer, human > > def newboard(): > board = [] > box = 9 > for square in range(box): > blank = " " > board.append(blank) > return board > > def createboard(board): > print "\n\t", board[0], "|", board[1], "|", board[2] > print "\t", "---------" > print "\t", board[3], "|", board[4], "|", board[5] > print "\t", "---------" > print "\t", board[6], "|", board[7], "|", board[8], "\n" > > def allowedmove(board): > moves=[] > for square in range(box): > if board[square] == blank: > moves.append(square) > return moves > > def winner(board): > > movestowin=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)) > for row in movestowin: > if board[row[0]] == board[row[1]] ==board[row[2]] !=blank: > winner=board[row[0]] > return winner > if blank not in board: > tie = "tie" > return tie > return None > > def humanmove (board, human): > allowed = allowedmove(board) > move = None > while move not in allowed: > move = asknumber("It is your turn. Pick 0-8:", 0, box) > if move not in allowed: > print "\nPick again.\n" > return move > > def computermove (board, computer, human): > board = board[:] > winnermoves = (4, 0, 2, 6, 8, 1, 3, 5, 7) > for move in allowedmoves(board): > board[move] = computer > if winner (board) == computer: > print move > return move > board[move] = blank > for move in allowedmoves(board): > board[move] = human > if winner(board) == human: > print move > return move > board[move] = blank > for move in winnermoves: > if move in allwedmoves(board): > print move > return move > > def whoseturn(turn): > if turn == X: > return O > else: > return X > > def whowon(iwon, computer, human): > if iwon !=tie: > print iwon, "you win!" > else: > print "a tie" > > def main(): > computer, human = pieces() > turn = X > board = newboard() > createboard(board) > > while not winner(board): > if turn == human: > move = humanmove(board, human) > board[move] = human > else: > move = computermove(board, computer, human) > board[move] = computer > createboard(board) > turn = whoseturn(turn) > > iwon = winner(board) > whowon(iwon, computer, human) > > > main() > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 919-636-4239 Chapel Hill, NC From cbc at unc.edu Thu Apr 17 17:07:21 2008 From: cbc at unc.edu (Chris Calloway) Date: Thu, 17 Apr 2008 11:07:21 -0400 Subject: [Tutor] HELP!!!!! In-Reply-To: <4806FEDB.2020703@aol.com> References: <4806FEDB.2020703@aol.com> Message-ID: <480767A9.6060206@unc.edu> On 4/17/2008 3:40 AM, Michael Kim wrote: > Hi I am having a really hard time making my tictactoe program work. I > was wondering if you could could check it out and help me with the > error. Thanks Heh. First, there are two obvious indentation errors you can find yourself. This may be a byproduct of having pasted your program into an email. Email programs will often incorrectly reformat Python code so that the indentation no longer works. To send long code listings to an email list, use a pastebin like: http://python.pastebin.com/ and send us the link of your pasted code. So after you fix the indentation errors, we get this: >>> main() Do you want to go first? (y/n): y Traceback (most recent call last): File "", line 1, in ? File "", line 2, in main File "", line 4, in pieces UnboundLocalError: local variable 'X' referenced before assignment >>> And if you look just where the traceback is telling you (line 4 of function pieces): >>> def pieces(): ... whosefirst=askquestion("Do you want to go first? (y/n): ") ... if whosefirst == "y": ... human = X You see that you did indeed do exactly what the traceback told you. You referenced a local variable named X before anything was assigned to X. Good luck with your homework! -- Sincerely, Chris Calloway http://www.secoora.org office: 332 Chapman Hall phone: (919) 599-3530 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From alan.gauld at btinternet.com Thu Apr 17 18:40:23 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Apr 2008 17:40:23 +0100 Subject: [Tutor] input and output files from terminal References: <24bc7f6c0804140955t5a352243w19490dd2dfbf6c26@mail.gmail.com> <24bc7f6c0804170657t16cd1487gfb482a5aadc1d3c3@mail.gmail.com> Message-ID: "Brain Stormer" wrote > Thanks for the file direction method but how do I get the names of > the files > so I can use it inside my program. I'm not sure I understand. Thepoint of using redirection is that your code doesn't need to know anything about the files, it just reads/writes to/from stdin/stdout. The OS connects the bits together at runtime. >> Easier to use file redirection: >> >> python test.py < inputfile > outputfile So you can provide any name you like for inputfile and outputfile when you execute the program. If you want the program to read/write to a specific file then use the standard open()/read/write functions Or am I missing something? Alan G. From alan.gauld at btinternet.com Thu Apr 17 18:44:31 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Apr 2008 17:44:31 +0100 Subject: [Tutor] Error with incorrect encoding References: Message-ID: I don't know the cause of the error here but I will say that parsing HTML with regular expressions is fraught with difficulty unless you know that the HTML will be suitably formatted in advance. You may be better off using one of the HTML parsing modules such as HTMLParser or even the more powerful BeautifulSoup. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld "Oleg Oltar" wrote in message news:b4fc2ad80804150820y7ae54b6dw8c7fea4981821fd2 at mail.gmail.com... >I am trying to parse an html page. Have following error while doing >that > > > src = sel.get_html_source() > links = re.findall(r'', src) > for link in links: > print link > > > > ====================================================================== > ERROR: test_new (__main__.NewTest) > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "", line 19, in test_new > UnicodeEncode Error: 'ascii' codec can't encode character u'\xae' > in > position 90: ordinal not in range(128) > > ---------------------------------------------------------------------- > Ran 1 test in 6.345s > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Thu Apr 17 18:51:04 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Apr 2008 17:51:04 +0100 Subject: [Tutor] HELP!!!!! References: <4806FEDB.2020703@aol.com> Message-ID: "Michael Kim" wrote > Hi I am having a really hard time making my tictactoe program work. > I > was wondering if you could could check it out and help me with the > error. Thanks Like to give us a clue as to what the error is? And include the error message if there is one please. However, at a quick glance: > def pieces(): > whosefirst=askquestion("Do you want to go first? (y/n): ") > if whosefirst == "y": > human = X I would expect that to fail since you haven't defined the variable X yet. You need to put the line below above the assignment... > X="X" > computer = O > O="O" > else: > computer = X > human = O Similarly here, X and O are not defined anywhere. This is as far -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauldas I read... From alan.gauld at btinternet.com Thu Apr 17 18:53:34 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Apr 2008 17:53:34 +0100 Subject: [Tutor] python assignments References: <288df32a0804170442n7b98df32qdad2865d38abfcbc@mail.gmail.com> Message-ID: "Bala subramanian" wrote > someone please suggest me any url where i can have assignments and > solutions. The old Useless Python website had a whole bundle of these. And of course you should try the Python Challenge web game. Alan G From rdm at rcblue.com Thu Apr 17 19:58:00 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 17 Apr 2008 10:58:00 -0700 Subject: [Tutor] python assignments In-Reply-To: <288df32a0804170442n7b98df32qdad2865d38abfcbc@mail.gmail.co m> References: <288df32a0804170442n7b98df32qdad2865d38abfcbc@mail.gmail.com> Message-ID: <20080417175811.EB5A31E401B@bag.python.org> At 04:42 AM 4/17/2008, you wrote: >Dear friends, > >I covered few introductory books on python. B4 going for an advanced >book, i want to take up small, small assignments and try to solve >with python. Can someone please suggest me any url where i can have >assignments and solutions. http://projecteuler.net/index.php?section=problems Dick Moores ================================ UliPad <>: http://code.google.com/p/ulipad/ From rdm at rcblue.com Thu Apr 17 22:20:32 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 17 Apr 2008 13:20:32 -0700 Subject: [Tutor] datetime module problem In-Reply-To: <480750A7.8050604@tds.net> References: <20080415205654.C2C531E4023@bag.python.org> <4805200E.8010106@tds.net> <20080415233331.E4ABB1E4013@bag.python.org> <20080417113824.9C7991E4007@bag.python.org> <48073E38.9060408@tds.net> <20080417130516.D27501E4016@bag.python.org> <480750A7.8050604@tds.net> Message-ID: <20080417202042.C8E3C1E4007@bag.python.org> At 06:29 AM 4/17/2008, Kent Johnson wrote: >Dick Moores wrote: > >>>You could either create n with hours=minutes=0, or round the >>>difference up to the next whole number of days. >>I have no idea how to implement either of your suggestions as to >>how to eliminate it. Could you please spell them both out? > >1. > >In [17]: n=datetime.today() >In [18]: n=datetime(n.year, n.month, n.day) >In [19]: n >Out[19]: datetime.datetime(2008, 4, 17, 0, 0) > >2. > >In [20]: diff=y-n >In [21]: diff >Out[21]: datetime.timedelta(0, 57464, 721369) >In [22]: days = diff.days >In [23]: if diff.seconds or diff.microseconds: > ....: days += 1 > ....: > ....: >In [24]: days >Out[24]: 1 Thanks, Kent. So here's where I am now: The script calculates correctly, but note the output, lines 34, 39, 49, 53. Please show me how to print these in the form 4/17/2007. I've tried everything I could think of. Dick ================================ UliPad <>: http://code.google.com/p/ulipad/ From kent37 at tds.net Thu Apr 17 22:35:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Apr 2008 16:35:40 -0400 Subject: [Tutor] datetime module problem In-Reply-To: <20080417202042.C8E3C1E4007@bag.python.org> References: <20080415205654.C2C531E4023@bag.python.org> <4805200E.8010106@tds.net> <20080415233331.E4ABB1E4013@bag.python.org> <20080417113824.9C7991E4007@bag.python.org> <48073E38.9060408@tds.net> <20080417130516.D27501E4016@bag.python.org> <480750A7.8050604@tds.net> <20080417202042.C8E3C1E4007@bag.python.org> Message-ID: <4807B49C.7010207@tds.net> Dick Moores wrote: > The script calculates correctly, but note the output, lines 34, 39, > 49, 53. Please show me how to print these in the form 4/17/2007. I've > tried everything I could think of. Come to think of it, you should be using datetime.date everywhere instead of datetime.datetime; you are always trying to get rid of the time part of datetime. Then look at date.strftime() or datetime.strftime() to format the output. Use the same format string as for strptime(). Kent From Mike.Hansen at atmel.com Thu Apr 17 22:29:29 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Thu, 17 Apr 2008 14:29:29 -0600 Subject: [Tutor] datetime module problem In-Reply-To: <20080417202042.C8E3C1E4007@bag.python.org> References: <20080415205654.C2C531E4023@bag.python.org><4805200E.8010106@tds.net><20080415233331.E4ABB1E4013@bag.python.org><20080417113824.9C7991E4007@bag.python.org><48073E38.9060408@tds.net><20080417130516.D27501E4016@bag.python.org><480750A7.8050604@tds.net> <20080417202042.C8E3C1E4007@bag.python.org> Message-ID: <7941B2693F32294AAF16C26B679A258D01E8B968@csomb01.corp.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Dick Moores > Sent: Thursday, April 17, 2008 2:21 PM > To: Python Tutor List > Subject: Re: [Tutor] datetime module problem > > At 06:29 AM 4/17/2008, Kent Johnson wrote: > >Dick Moores wrote: > > > >>>You could either create n with hours=minutes=0, or round the > >>>difference up to the next whole number of days. > >>I have no idea how to implement either of your suggestions as to > >>how to eliminate it. Could you please spell them both out? > > > >1. > > > >In [17]: n=datetime.today() > >In [18]: n=datetime(n.year, n.month, n.day) > >In [19]: n > >Out[19]: datetime.datetime(2008, 4, 17, 0, 0) > > > >2. > > > >In [20]: diff=y-n > >In [21]: diff > >Out[21]: datetime.timedelta(0, 57464, 721369) > >In [22]: days = diff.days > >In [23]: if diff.seconds or diff.microseconds: > > ....: days += 1 > > ....: > > ....: > >In [24]: days > >Out[24]: 1 > > Thanks, Kent. So here's where I am now: > > > The script calculates correctly, but note the output, lines 34, 39, > 49, 53. Please show me how to print these in the form 4/17/2007. I've > tried everything I could think of. > > Dick > In [23]: import datetime In [24]: x = datetime.datetime.now() In [25]: x Out[25]: datetime.datetime(2008, 4, 17, 14, 24, 18, 447000) In [26]: x.month Out[26]: 4 In [27]: x.day Out[27]: 17 In [28]: x.year Out[28]: 2008 In [30]: print "%s/%s/%s" %(x.month, x.day, x.year, ) 4/17/2008 Does that help? There's probably another way to do it, but this seems to work. Mike From dave6502 at googlemail.com Thu Apr 17 23:07:53 2008 From: dave6502 at googlemail.com (dave selby) Date: Thu, 17 Apr 2008 22:07:53 +0100 Subject: [Tutor] Need suggestion / advice - controlling remote server Message-ID: Hi all, I am after some advice / suggestions. I have written web interface for viewing CCTV images http://code.google.com/p/kmotion/wiki/ScreenShots its called 'kmotion'. Underneath its all Python daemons. It usually runs stand alone on headless servers. Now I am about to write a KDE interface in Python & QT4 for config & local viewing. The question is how to communicate with the remote kmotion servers Python daemons. I could access the images via port 80, no prob but I need the KDE interface to change configs etc and restart services. I am thinking of getting the KDE interface to ssh in and do the changes via shell commands, ie change config files, restarts deamons etc, should work OK. Is this acceptable ? How would you guys do it ? Thanks in advance Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From rdm at rcblue.com Fri Apr 18 00:13:03 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 17 Apr 2008 15:13:03 -0700 Subject: [Tutor] datetime module problem In-Reply-To: <7941B2693F32294AAF16C26B679A258D01E8B968@csomb01.corp.atme l.com> References: <20080415205654.C2C531E4023@bag.python.org> <4805200E.8010106@tds.net> <20080415233331.E4ABB1E4013@bag.python.org> <20080417113824.9C7991E4007@bag.python.org> <48073E38.9060408@tds.net> <20080417130516.D27501E4016@bag.python.org> <480750A7.8050604@tds.net> <20080417202042.C8E3C1E4007@bag.python.org> <7941B2693F32294AAF16C26B679A258D01E8B968@csomb01.corp.atmel.com> Message-ID: <20080417221325.0A4E51E4024@bag.python.org> At 01:29 PM 4/17/2008, Hansen, Mike wrote: > > > > -----Original Message----- > > From: tutor-bounces at python.org > > [mailto:tutor-bounces at python.org] On Behalf Of Dick Moores > > Sent: Thursday, April 17, 2008 2:21 PM > > To: Python Tutor List > > Subject: Re: [Tutor] datetime module problem > > > > At 06:29 AM 4/17/2008, Kent Johnson wrote: > > >Dick Moores wrote: > > > > > >>>You could either create n with hours=minutes=0, or round the > > >>>difference up to the next whole number of days. > > >>I have no idea how to implement either of your suggestions as to > > >>how to eliminate it. Could you please spell them both out? > > > > > >1. > > > > > >In [17]: n=datetime.today() > > >In [18]: n=datetime(n.year, n.month, n.day) > > >In [19]: n > > >Out[19]: datetime.datetime(2008, 4, 17, 0, 0) > > > > > >2. > > > > > >In [20]: diff=y-n > > >In [21]: diff > > >Out[21]: datetime.timedelta(0, 57464, 721369) > > >In [22]: days = diff.days > > >In [23]: if diff.seconds or diff.microseconds: > > > ....: days += 1 > > > ....: > > > ....: > > >In [24]: days > > >Out[24]: 1 > > > > Thanks, Kent. So here's where I am now: > > > > > > The script calculates correctly, but note the output, lines 34, 39, > > 49, 53. Please show me how to print these in the form 4/17/2007. I've > > tried everything I could think of. > > > > Dick > > > > >In [23]: import datetime > >In [24]: x = datetime.datetime.now() > >In [25]: x >Out[25]: datetime.datetime(2008, 4, 17, 14, 24, 18, 447000) > >In [26]: x.month >Out[26]: 4 > >In [27]: x.day >Out[27]: 17 > >In [28]: x.year >Out[28]: 2008 > >In [30]: print "%s/%s/%s" %(x.month, x.day, x.year, ) >4/17/2008 > >Does that help? There's probably another way to do it, but this seems to >work. Yes, I'd finally done that (honest), so that will take care of lines 39, 49, but not 34, 53 of . Thanks, Dick ================================ UliPad <>: http://code.google.com/p/ulipad/ From alan.gauld at btinternet.com Fri Apr 18 01:54:20 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 18 Apr 2008 00:54:20 +0100 Subject: [Tutor] Need suggestion / advice - controlling remote server References: Message-ID: "dave selby" wrote > The question is how to communicate with the remote kmotion servers > Python daemons. I could access the images via port 80, no prob but I > need the KDE interface to change configs etc and restart services. You should still be able to do thast via a web interface. Restarts are probably the trickiest becauyse you need to be able to pick up again with the admin interface after the restart. But its not that tricky. > ...getting the KDE interface to ssh in and do the changes That will work too, but a web admin is probably easier for users since you don't need to maintain a thick client on the desktop. Alan G From rdm at rcblue.com Fri Apr 18 04:49:50 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 17 Apr 2008 19:49:50 -0700 Subject: [Tutor] datetime module problem In-Reply-To: <20080417221325.0A4E51E4024@bag.python.org> References: <20080415205654.C2C531E4023@bag.python.org> <4805200E.8010106@tds.net> <20080415233331.E4ABB1E4013@bag.python.org> <20080417113824.9C7991E4007@bag.python.org> <48073E38.9060408@tds.net> <20080417130516.D27501E4016@bag.python.org> <480750A7.8050604@tds.net> <20080417202042.C8E3C1E4007@bag.python.org> <7941B2693F32294AAF16C26B679A258D01E8B968@csomb01.corp.atmel.com> <20080417221325.0A4E51E4024@bag.python.org> Message-ID: <20080418025238.56F651E4007@bag.python.org> Got it, I think. The crucial lines are 22, 27. Thanks all, Dick ================================ UliPad <>: http://code.google.com/p/ulipad/ From pine508 at hotmail.com Fri Apr 18 05:20:36 2008 From: pine508 at hotmail.com (Che M) Date: Thu, 17 Apr 2008 23:20:36 -0400 Subject: [Tutor] web programming tutorials? Message-ID: [I thought I sent a similar msg to this list 2 days ago, but now I'm not sure it went through, so sorry if I've doubled] Can someone point me to a start-from-dead-scratch tutorial about the basics of web programming? I've been learning wxPython for GUI programming, but web programming (that is, making web applications) seems like another world entirely. I'm aware of *names*--Django, Pylons, CherryPy, TurboGears, Zope, Webpy, etc.--but I have a poor sense of what all this means, and so I am sort of 'pre-Python' in my understanding. I've scanned the archives of this list, but so far haven't found pointers to tutorials that assume very little knowledge. I was kind of hoping Alan Gauld's project would be updated for the tempting but not yet existent section on web programming. Any word on that, Alan? In lieu of that, can anyone recommend books/online tutorials/words of advice? Thanks, Che _________________________________________________________________ Pack up or back up?use SkyDrive to transfer files or keep extra copies. Learn how. http://www.windowslive.com/skydrive/overview.html?ocid=TXT_TAGLM_WL_Refresh_skydrive_packup_042008 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080417/3322eed3/attachment.htm From oltarasenko at gmail.com Fri Apr 18 08:37:06 2008 From: oltarasenko at gmail.com (Oleg Oltar) Date: Fri, 18 Apr 2008 09:37:06 +0300 Subject: [Tutor] web programming tutorials? In-Reply-To: References: Message-ID: OK. take a look on the pages: 1. http://www.djangobook.com/ 2. Official docs on http://www.djangoproject.com/ 3. Dive into python (http://diveintopython.org/) 4. And the last one (but the best) showmedo: http://showmedo.com/ On Fri, Apr 18, 2008 at 6:20 AM, Che M wrote: > [I thought I sent a similar msg to this list 2 days ago, but now I'm not > sure it went through, so sorry if I've doubled] > > Can someone point me to a start-from-dead-scratch tutorial about the > basics of web programming? I've been learning wxPython for GUI programming, > but web programming (that is, making web applications) seems like another > world entirely. I'm aware of *names*--Django, Pylons, CherryPy, TurboGears, > Zope, Webpy, etc.--but I have a poor sense of what all this means, and so I > am sort of 'pre-Python' in my understanding. I've scanned the archives of > this list, but so far haven't found pointers to tutorials that assume very > little knowledge. > > I was kind of hoping Alan Gauld's project would be updated for the > tempting but not yet existent section on web programming. Any word on that, > Alan? In lieu of that, can anyone recommend books/online tutorials/words of > advice? > > Thanks, > Che > > > ------------------------------ > Pack up or back up?use SkyDrive to transfer files or keep extra copies. Learn > how. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080418/1b783d1a/attachment.htm From norman at khine.net Fri Apr 18 08:44:28 2008 From: norman at khine.net (Norman Khine) Date: Fri, 18 Apr 2008 08:44:28 +0200 Subject: [Tutor] web programming tutorials? In-Reply-To: References: Message-ID: <4808434C.3090202@khine.net> Hi Che, I started with python web programming using Zope, but this was because I needed a quick CMS application for a small project I did and Zope's CMF fitted the bill nicely. Now I use itools (http://ikaaro.org/itools) it is relatively easy to setup and is 99% python (the parser is now in C) the latest version has two packages, the core itools is a python library and ikaaro is the CMS. Here are the docs, http://download.ikaaro.org/doc/itools/index.html Hope this helps. Good luck. Che M wrote: > [I thought I sent a similar msg to this list 2 days ago, but now I'm not > sure it went through, so sorry if I've doubled] > > Can someone point me to a start-from-dead-scratch tutorial about the > basics of web programming? I've been learning wxPython for GUI > programming, but web programming (that is, making web applications) > seems like another world entirely. I'm aware of *names*--Django, > Pylons, CherryPy, TurboGears, Zope, Webpy, etc.--but I have a poor sense > of what all this means, and so I am sort of 'pre-Python' in my > understanding. I've scanned the archives of this list, but so far > haven't found pointers to tutorials that assume very little knowledge. > > I was kind of hoping Alan Gauld's project would be updated for the > tempting but not yet existent section on web programming. Any word on > that, Alan? In lieu of that, can anyone recommend books/online > tutorials/words of advice? > > Thanks, > Che > > > ------------------------------------------------------------------------ > Pack up or back up?use SkyDrive to transfer files or keep extra copies. > Learn how. > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Norman Khine 24 rue de la Madeleine, 30000, N?mes, France tel +33 (0) 466 267 064 e-fax +44 7006 009 324 %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] ) From oltarasenko at gmail.com Fri Apr 18 09:50:39 2008 From: oltarasenko at gmail.com (Oleg Oltar) Date: Fri, 18 Apr 2008 10:50:39 +0300 Subject: [Tutor] web programming tutorials? In-Reply-To: <4808434C.3090202@khine.net> References: <4808434C.3090202@khine.net> Message-ID: Hi Che! Use django, don't use Zope and everything will be fine. Django is a new very powerful web framework. Many cool web applications was created using django! e.g. you can take a look on our project: www.mydeco.com Use django and let the Power be with you :) Thanks, Oleg On Fri, Apr 18, 2008 at 9:44 AM, Norman Khine wrote: > Hi Che, > I started with python web programming using Zope, but this was because I > needed a quick CMS application for a small project I did and Zope's CMF > fitted the bill nicely. > > Now I use itools (http://ikaaro.org/itools) it is relatively easy to > setup and is 99% python (the parser is now in C) the latest version has > two packages, the core itools is a python library and ikaaro is the CMS. > > Here are the docs, http://download.ikaaro.org/doc/itools/index.html > > Hope this helps. > Good luck. > > Che M wrote: > > [I thought I sent a similar msg to this list 2 days ago, but now I'm not > > sure it went through, so sorry if I've doubled] > > > > Can someone point me to a start-from-dead-scratch tutorial about the > > basics of web programming? I've been learning wxPython for GUI > > programming, but web programming (that is, making web applications) > > seems like another world entirely. I'm aware of *names*--Django, > > Pylons, CherryPy, TurboGears, Zope, Webpy, etc.--but I have a poor sense > > of what all this means, and so I am sort of 'pre-Python' in my > > understanding. I've scanned the archives of this list, but so far > > haven't found pointers to tutorials that assume very little knowledge. > > > > I was kind of hoping Alan Gauld's project would be updated for the > > tempting but not yet existent section on web programming. Any word on > > that, Alan? In lieu of that, can anyone recommend books/online > > tutorials/words of advice? > > > > Thanks, > > Che > > > > > > ------------------------------------------------------------------------ > > Pack up or back up?use SkyDrive to transfer files or keep extra copies. > > Learn how. > > < > http://www.windowslive.com/skydrive/overview.html?ocid=TXT_TAGLM_WL_Refresh_skydrive_packup_042008 > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- > Norman Khine > 24 rue de la Madeleine, 30000, N?mes, France > tel +33 (0) 466 267 064 e-fax +44 7006 009 324 > > %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-83)%26) > for c in ",adym,*)&uzq^zqf" ] ) > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080418/f00b32af/attachment.htm From alan.gauld at btinternet.com Fri Apr 18 09:53:31 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 18 Apr 2008 08:53:31 +0100 Subject: [Tutor] web programming tutorials? References: Message-ID: "Che M" wrote in message news:BAY105-W222C2E87BE08DEB36E3B4BE0E40 at phx.gbl... > I was kind of hoping Alan Gauld's project would be updated > for the tempting but not yet existent section on web programming. I have been working on two web programming topics (one client side, one server side) for over a year now. UInfortunately I'm in the middle of a classic death march project at work and just don't have any spare time to work on the tutorial topics. I wioll send you the introductory material that explains the theory and a bit about parsing HTML, but for the server side I don't have anything worth readiong yet. That having been said one problem you face is that although all of the server side frameworks share a lot of concepts they all do things very differently. You really need to understand the most basic CGI mechanism first but then just pick a framework and work through its tutorials. To understand CGI there are a lot of web tutorial, although not in Python. But once you understand the concepts - which are pretty suimple - you can read the Python CGI HowTo article and then move on to a framework. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Apr 18 10:04:49 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 18 Apr 2008 09:04:49 +0100 Subject: [Tutor] web programming tutorials? References: <4808434C.3090202@khine.net> Message-ID: "Norman Khine" wrote > Now I use itools (http://ikaaro.org/itools) it is relatively easy to > setup and is 99% python (the parser is now in C) the latest version > has > two packages, the core itools is a python library and ikaaro is the > CMS. I had a look at this since I hadn't come across it before. They hide any discussion of the web framework side very well. I found the download link and an administrators guide but nothing like a beginners tutorial or even a description of how it all works. Did I miss something? Alan G From oltarasenko at gmail.com Fri Apr 18 10:06:33 2008 From: oltarasenko at gmail.com (Oleg Oltar) Date: Fri, 18 Apr 2008 11:06:33 +0300 Subject: [Tutor] web programming tutorials? In-Reply-To: References: Message-ID: Introduction into CGI in Russian http://www.intuit.ru/department/internet/cgi/ Please give alternative link on English variant On Fri, Apr 18, 2008 at 10:53 AM, Alan Gauld wrote: > > "Che M" wrote in message > news:BAY105-W222C2E87BE08DEB36E3B4BE0E40 at phx.gbl... > > > I was kind of hoping Alan Gauld's project would be updated > > for the tempting but not yet existent section on web programming. > > I have been working on two web programming topics > (one client side, one server side) for over a year now. > > UInfortunately I'm in the middle of a classic death march project > at work and just don't have any spare time to work on the tutorial > topics. > > I wioll send you the introductory material that explains the > theory and a bit about parsing HTML, but for the server side > I don't have anything worth readiong yet. > > That having been said one problem you face is that although > all of the server side frameworks share a lot of concepts > they all do things very differently. You really need to > understand the most basic CGI mechanism first but > then just pick a framework and work through its tutorials. > > To understand CGI there are a lot of web tutorial, although > not in Python. But once you understand the concepts > - which are pretty suimple - you can read the Python CGI > HowTo article and then move on to a framework. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080418/d448e201/attachment.htm From norman at khine.net Fri Apr 18 10:26:25 2008 From: norman at khine.net (Norman Khine) Date: Fri, 18 Apr 2008 10:26:25 +0200 Subject: [Tutor] web programming tutorials? In-Reply-To: References: <4808434C.3090202@khine.net> Message-ID: <48085B31.7080004@khine.net> yes i have to admit documentation is not all there, but there is a chapter for the web, http://download.ikaaro.org/doc/itools/chapter--web.html which gives basic understandings of how it works. Alan Gauld wrote: > "Norman Khine" wrote > >> Now I use itools (http://ikaaro.org/itools) it is relatively easy to >> setup and is 99% python (the parser is now in C) the latest version >> has >> two packages, the core itools is a python library and ikaaro is the >> CMS. > > I had a look at this since I hadn't come across it before. > They hide any discussion of the web framework side very well. > I found the download link and an administrators guide but nothing > like a beginners tutorial or even a description of how it all works. > > Did I miss something? > > Alan G > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From muchanek at gmail.com Fri Apr 18 10:35:33 2008 From: muchanek at gmail.com (kinuthia muchane) Date: Fri, 18 Apr 2008 11:35:33 +0300 Subject: [Tutor] Tutor Digest, Vol 50, Issue 56 In-Reply-To: References: Message-ID: <1208507733.5786.2.camel@www.kinuthia.com> > > ------------------------------ > > Message: 3 > Date: Thu, 17 Apr 2008 10:58:00 -0700 > From: Dick Moores > Subject: Re: [Tutor] python assignments > To: Python Tutor List > Message-ID: <20080417175811.EB5A31E401B at bag.python.org> > Content-Type: text/plain; charset="us-ascii"; format=flowed > > At 04:42 AM 4/17/2008, you wrote: > >Dear friends, > > > >I covered few introductory books on python. B4 going for an advanced > >book, i want to take up small, small assignments and try to solve > >with python. Can someone please suggest me any url where i can have > >assignments and solutions. > > http://projecteuler.net/index.php?section=problems Hi, this link is not loading. > > Dick Moores > From sander.sweers at gmail.com Fri Apr 18 11:17:43 2008 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 18 Apr 2008 11:17:43 +0200 Subject: [Tutor] datetime module problem In-Reply-To: <20080418025238.56F651E4007@bag.python.org> References: <20080415205654.C2C531E4023@bag.python.org> <20080415233331.E4ABB1E4013@bag.python.org> <20080417113824.9C7991E4007@bag.python.org> <48073E38.9060408@tds.net> <20080417130516.D27501E4016@bag.python.org> <480750A7.8050604@tds.net> <20080417202042.C8E3C1E4007@bag.python.org> <7941B2693F32294AAF16C26B679A258D01E8B968@csomb01.corp.atmel.com> <20080417221325.0A4E51E4024@bag.python.org> <20080418025238.56F651E4007@bag.python.org> Message-ID: On Fri, Apr 18, 2008 at 4:49 AM, Dick Moores wrote: > Got it, I think. Here is a my somewhat simplified version of your daysDelta script. It uses less variables but I am not sure if it is faster? http://py77.python.pastebin.com/m14e4010 One thing you might want to do is look at catching wrong input. For example when you enter nodate instead of 4/10/2008 it will raise a ValueError. I'll give a hint, look at try and except. Greets Sander From bgailer at gmail.com Fri Apr 18 14:20:26 2008 From: bgailer at gmail.com (bob gailer) Date: Fri, 18 Apr 2008 08:20:26 -0400 Subject: [Tutor] web programming tutorials? In-Reply-To: <4808434C.3090202@khine.net> References: <4808434C.3090202@khine.net> Message-ID: <4808920A.1010502@gmail.com> Norman Khine wrote: > Hi Che, > I started with python web programming using Zope, but this was because I > needed a quick CMS application for a small project I did and Zope's CMF > fitted the bill nicely. > > Now I use itools (http://ikaaro.org/itools) it is relatively easy to > setup and is 99% python (the parser is now in C) the latest version has > two packages, the core itools is a python library and ikaaro is the CMS. > > Here are the docs, http://download.ikaaro.org/doc/itools/index.html > > Having never heard of itools I decided to take a look at the itools.web examples. I was OK with 13.1 Hello world. Then I hit 13.2 Traversal. The text on the page leaves me hopelessly lost. Is there any other explanation? -- Bob Gailer 919-636-4239 Chapel Hill, NC From kent37 at tds.net Fri Apr 18 14:29:08 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 18 Apr 2008 08:29:08 -0400 Subject: [Tutor] web programming tutorials? In-Reply-To: References: Message-ID: <1c2a2c590804180529s6e8ff5dy3c8061bfa50e8518@mail.gmail.com> On Thu, Apr 17, 2008 at 11:20 PM, Che M wrote: > Can someone point me to a start-from-dead-scratch tutorial about the > basics of web programming? > You might be interested in the book "Foundations of Python Network Programming". http://www.complete.org/publications/pynet/ It gives a bit lower-level introduction to what is going on with network programming than you will get from a Django or Zope tutorial. Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080418/f14911f4/attachment.htm From rdm at rcblue.com Fri Apr 18 16:37:32 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 18 Apr 2008 07:37:32 -0700 Subject: [Tutor] datetime module problem In-Reply-To: References: <20080415205654.C2C531E4023@bag.python.org> <20080415233331.E4ABB1E4013@bag.python.org> <20080417113824.9C7991E4007@bag.python.org> <48073E38.9060408@tds.net> <20080417130516.D27501E4016@bag.python.org> <480750A7.8050604@tds.net> <20080417202042.C8E3C1E4007@bag.python.org> <7941B2693F32294AAF16C26B679A258D01E8B968@csomb01.corp.atmel.com> <20080417221325.0A4E51E4024@bag.python.org> <20080418025238.56F651E4007@bag.python.org> Message-ID: <20080418143742.99AD51E4007@bag.python.org> At 02:17 AM 4/18/2008, Sander Sweers wrote: >On Fri, Apr 18, 2008 at 4:49 AM, Dick Moores wrote: > > Got it, I think. > >Here is a my somewhat simplified version of your daysDelta script. It >uses less variables but I am not sure if it is faster? >http://py77.python.pastebin.com/m14e4010 Thanks for the improvement. >One thing you might want to do is look at catching wrong input. For >example when you enter nodate instead of 4/10/2008 it will raise a >ValueError. I'll give a hint, look at try and except. Yes, I know how to do that, and will. Dick ================================ UliPad <>: http://code.google.com/p/ulipad/ From monjissvel at googlemail.com Fri Apr 18 14:19:47 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Fri, 18 Apr 2008 12:19:47 +0000 Subject: [Tutor] urllib2.urlopen(url) Message-ID: Hi, can i stop urllib2.urlopen() from following redirects automatically ? one more question i had in mind, the function urllib2.urlopen.geturl() does get me what i want but does it do the download of the page i was redirected to ? or just downloads the initial page that actually does the redirect ? thanks in advance Monika Jissvel -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080418/e490b199/attachment.htm From rdm at rcblue.com Fri Apr 18 16:48:13 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 18 Apr 2008 07:48:13 -0700 Subject: [Tutor] Tutor Digest, Vol 50, Issue 56 In-Reply-To: <1208507733.5786.2.camel@www.kinuthia.com> References: <1208507733.5786.2.camel@www.kinuthia.com> Message-ID: <20080418144831.BCC5C1E4007@bag.python.org> At 01:35 AM 4/18/2008, kinuthia muchane wrote: > > > > ------------------------------ > > > > Message: 3 > > Date: Thu, 17 Apr 2008 10:58:00 -0700 > > From: Dick Moores > > Subject: Re: [Tutor] python assignments > > To: Python Tutor List > > Message-ID: <20080417175811.EB5A31E401B at bag.python.org> > > Content-Type: text/plain; charset="us-ascii"; format=flowed > > > > At 04:42 AM 4/17/2008, you wrote: > > >Dear friends, > > > > > >I covered few introductory books on python. B4 going for an advanced > > >book, i want to take up small, small assignments and try to solve > > >with python. Can someone please suggest me any url where i can have > > >assignments and solutions. > > > > http://projecteuler.net/index.php?section=problems > >Hi, this link is not loading. > > > > Dick Moores > > No problem right now. Dick ================================ UliPad <>: http://code.google.com/p/ulipad/ From Mike.Hansen at atmel.com Fri Apr 18 17:01:18 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Fri, 18 Apr 2008 09:01:18 -0600 Subject: [Tutor] web programming tutorials? In-Reply-To: References: Message-ID: <7941B2693F32294AAF16C26B679A258D01E8BDF4@csomb01.corp.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Che M > Sent: Thursday, April 17, 2008 9:21 PM > To: tutor at python.org > Subject: [Tutor] web programming tutorials? > > [I thought I sent a similar msg to this list 2 days ago, but > now I'm not sure it went through, so sorry if I've doubled] > > Can someone point me to a start-from-dead-scratch tutorial > about the basics of web programming? I've been learning > wxPython for GUI programming, but web programming (that is, > making web applications) seems like another world entirely. > I'm aware of *names*--Django, Pylons, CherryPy, TurboGears, > Zope, Webpy, etc.--but I have a poor sense of what all this > means, and so I am sort of 'pre-Python' in my understanding. > I've scanned the archives of this list, but so far haven't > found pointers to tutorials that assume very little knowledge. > > I was kind of hoping Alan Gauld's project would be updated > for the tempting but not yet existent section on web > programming. Any word on that, Alan? In lieu of that, can > anyone recommend books/online tutorials/words of advice? > > Thanks, > Che > IMHO, I think before anyone jumps into using a framework, they should understand the basics of cgi programming. Maybe do just a small exercise with simple form processing. After that exercise, then move on to one of the frameworks that make a lot of that grunt work easier. Jumping into a framework right away is like trying to run before you can crawl. There's a lot going on with the many frameworks(URL mapping, templates, ORM, persistence...). When you have some basic understanding of web programming, it might help you figure out why something isn't working properly in the framework. I'm curious about other tutor list member's thoughts on this. Am I out to lunch on this viewpoint? Anyway, here's a link to a python cgi tutorial: http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python/ Mike From cbc at unc.edu Fri Apr 18 17:04:01 2008 From: cbc at unc.edu (Chris Calloway) Date: Fri, 18 Apr 2008 11:04:01 -0400 Subject: [Tutor] web programming tutorials? In-Reply-To: <4808920A.1010502@gmail.com> References: <4808434C.3090202@khine.net> <4808920A.1010502@gmail.com> Message-ID: <4808B861.9030803@unc.edu> On 4/18/2008 8:20 AM, bob gailer wrote: > Norman Khine wrote: >> Here are the docs, http://download.ikaaro.org/doc/itools/index.html >> >> > Having never heard of itools I decided to take a look at the itools.web > examples. I was OK with 13.1 Hello world. Then I hit 13.2 Traversal. The > text on the page leaves me hopelessly lost. Is there any other explanation? Bob, Traversal (and acquisition) is (and are) standard Zope 2 terminology. They are described, among other places, on page 226 of the Zope Book: http://www.zope.org/Documentation/Books/ZopeBook/2_6Edition/ZopeBook-2_6.pdf Here's an illustrated version of the same explanation: http://plope.com/Books/2_7Edition/BasicScripting.stx#2-6 Zope picked this up from some storied academic paper somewhere I've since misplaced. Several other Python frameworks subsequently picked it up. Here's a paper from the 1996 Python Workshop 5 described how traveral was implemented in what was then called the Python Object Publisher, commissioned by what was then called the Python Software Activity (PSA) which later became the PSF, code-named "Bobo," and later known as the Zope Object Publisher: http://www.python.org/workshops/1996-11/papers/PythonObjectPublisher.html And thus is how all your bobobase came to belong to us. -- Sincerely, Chris Calloway http://www.secoora.org office: 332 Chapman Hall phone: (919) 599-3530 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From kent37 at tds.net Fri Apr 18 17:33:31 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 18 Apr 2008 11:33:31 -0400 Subject: [Tutor] Fwd: urllib2.urlopen(url) In-Reply-To: <1c2a2c590804180822t2ffebd51y2564dcbb7ae56b6c@mail.gmail.com> References: <1c2a2c590804180822t2ffebd51y2564dcbb7ae56b6c@mail.gmail.com> Message-ID: <1c2a2c590804180833y7e8336e0mde0542e271d86934@mail.gmail.com> On Fri, Apr 18, 2008 at 8:19 AM, Monika Jisswel wrote: > Hi, > > can i stop urllib2.urlopen() from following redirects automatically ? There doesn't seem to be an easy way to do this. Probably the simplest way is to create a subclass of HTTPRedirectHandler that does nothing and build an opener that uses that. > > > one more question i had in mind, the function urllib2.urlopen.geturl() > does get me what i want but does it do the download of the page i was > redirected to ? or just downloads the initial page that actually does the > redirect ? > It gets the page you were redirected to. If you want access to the redirect code, see the note about Universal Feed Parser here: http://personalpages.tds.net/~kent37/kk/00010.html#e10other-resources Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080418/01f022c9/attachment.htm From python at bdurham.com Fri Apr 18 18:08:29 2008 From: python at bdurham.com (python at bdurham.com) Date: Fri, 18 Apr 2008 12:08:29 -0400 Subject: [Tutor] When to use __new__ vs. __init__ ? Message-ID: <1208534909.26459.1248637981@webmail.messagingengine.com> Any guidelines on when to use __new__ vs. __init__ when sub-classing? Thanks! Malcolm From eric at abrahamsen.com Fri Apr 18 18:43:46 2008 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Fri, 18 Apr 2008 09:43:46 -0700 Subject: [Tutor] web programming tutorials? In-Reply-To: <7941B2693F32294AAF16C26B679A258D01E8BDF4@csomb01.corp.atmel.com> References: <7941B2693F32294AAF16C26B679A258D01E8BDF4@csomb01.corp.atmel.com> Message-ID: On Apr 18, 2008, at 8:01 AM, Hansen, Mike wrote: > IMHO, I think before anyone jumps into using a framework, they should > understand the basics of cgi programming. Maybe do just a small > exercise with simple form processing. After that exercise, then move > on to one of the frameworks that make a lot of that grunt work easier. > Jumping into a framework right away is like trying to run before you > can crawl. There's a lot going on with the many frameworks(URL > mapping, templates, ORM, persistence...). When you have some basic > understanding of web programming, it might help you figure out why > something isn't working properly in the framework. I'm curious about > other tutor list member's thoughts on this. Am I out to lunch on this > viewpoint? I think that's exactly right, and I'd add that if you don't know the bits and bobs of the HTTP protocol, it can also make it difficult to pick up the frameworks. Django was fine for me but I found CherryPy/ Paste/other low-level frameworks very confusing until I realized I didn't really understand how they fit into and handle the mechanisms of HTTP. Doing some background reading helped me see the fundamental similarities between them. Eric From kent37 at tds.net Fri Apr 18 19:18:06 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 18 Apr 2008 13:18:06 -0400 Subject: [Tutor] When to use __new__ vs. __init__ ? In-Reply-To: <1208534909.26459.1248637981@webmail.messagingengine.com> References: <1208534909.26459.1248637981@webmail.messagingengine.com> Message-ID: <1c2a2c590804181018o31aebc82pd4473e3a6b10a79a@mail.gmail.com> On Fri, Apr 18, 2008 at 12:08 PM, wrote: > Any guidelines on when to use __new__ vs. __init__ when sub-classing? > Generally use __init__(). The only use-case for __new__() that I can think of is when you subclass immutable classes like str or int you generally have to use __new__() because __init__() is too late. Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080418/f57ec730/attachment.htm From python at bdurham.com Fri Apr 18 19:26:35 2008 From: python at bdurham.com (python at bdurham.com) Date: Fri, 18 Apr 2008 13:26:35 -0400 Subject: [Tutor] When to use __new__ vs. __init__ ? In-Reply-To: <1c2a2c590804181018o31aebc82pd4473e3a6b10a79a@mail.gmail.com> References: <1208534909.26459.1248637981@webmail.messagingengine.com> <1c2a2c590804181018o31aebc82pd4473e3a6b10a79a@mail.gmail.com> Message-ID: <1208539595.7996.1248651713@webmail.messagingengine.com> Thanks Kent! Malcolm From malaclypse2 at gmail.com Fri Apr 18 19:36:51 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 18 Apr 2008 13:36:51 -0400 Subject: [Tutor] When to use __new__ vs. __init__ ? In-Reply-To: <1208534909.26459.1248637981@webmail.messagingengine.com> References: <1208534909.26459.1248637981@webmail.messagingengine.com> Message-ID: <16651e80804181036g6b199f44n61e0c7989477212a@mail.gmail.com> On Fri, Apr 18, 2008 at 12:08 PM, wrote: > Any guidelines on when to use __new__ vs. __init__ when sub-classing? Use __new__ when you need to control the creation of a new instance. Use __init__ when you need to control initialization of a new instance. __new__ is the first step of instance creation. It's called first, and is responsible for returning a new instance of your class. In contrast, __init__ doesn't return anything; it's only responsible for initializing the instance after it's been created. In general, you shouldn't need to override __new__ unless you're subclassing an immutable type like str, int, unicode or tuple. Some references: The description of new style classes goes into some depth about how instance creation works, including examples of overriding __new__ and __init__. http://www.python.org/download/releases/2.2/descrintro/ The reference manual has a section on class customization, but I don't think it goes into enough depth to really answer your question: http://docs.python.org/ref/customization.html -- Jerry From juhasecke at googlemail.com Fri Apr 18 20:41:39 2008 From: juhasecke at googlemail.com (Jan Ulrich Hasecke) Date: Fri, 18 Apr 2008 20:41:39 +0200 Subject: [Tutor] web programming tutorials? In-Reply-To: References: Message-ID: <26ba0efc0804181141ld55754ah1b8b860009bc8249@mail.gmail.com> Hi Che, try out Grok. Grok is a convention-over-configuration-framework for Zope and an excellent start into this framework. You'll find a really cool tutorial of Grok here: http://grok.zope.org/documentation/book/ juh From cbc at unc.edu Fri Apr 18 21:03:42 2008 From: cbc at unc.edu (Chris Calloway) Date: Fri, 18 Apr 2008 15:03:42 -0400 Subject: [Tutor] web programming tutorials? In-Reply-To: <7941B2693F32294AAF16C26B679A258D01E8BDF4@csomb01.corp.atmel.com> References: <7941B2693F32294AAF16C26B679A258D01E8BDF4@csomb01.corp.atmel.com> Message-ID: <4808F08E.8030509@unc.edu> On 4/18/2008 11:01 AM, Hansen, Mike wrote: > I'm curious about > other tutor list member's thoughts on this. Am I out to lunch on this > viewpoint? +1 (In favor of your viewpoint, that is. Not in favor of you being out to lunch on this. :) In the Zope community I see evidence all the time from noobs that tells me, oh, you don't know how HTTP requests and responses work, do you? Honestly, I don't know how anyone could work well with a web framework without knowing these things. But many people try. :) Python makes it so easy to try. Even with CGI programming, there are some things you need to know about this first. Actually, more so. It's almost like web noobs should start with socket programming. :) There is a Firefox extension called LiveHTTPHeaders that can be illustrative to HTTP noobs. You can see all the requests and response headers without any programming: http://livehttpheaders.mozdev.org/ The httplib module allows you to experiment with this in Python programming once you understand a little about what to put in a request by watching a few with LiveHTTPHeaders: http://docs.python.org/lib/httplib-examples.html This little $10 book is also indispensable for those on such a learning curve: http://www.amazon.com/HTTP-Pocket-Reference-Hypertext-Transfer/dp/1565928628/ -- Sincerely, Chris Calloway http://www.secoora.org office: 332 Chapman Hall phone: (919) 599-3530 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From monjissvel at googlemail.com Fri Apr 18 21:37:25 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Fri, 18 Apr 2008 19:37:25 +0000 Subject: [Tutor] web programming tutorials? In-Reply-To: <4808F08E.8030509@unc.edu> References: <7941B2693F32294AAF16C26B679A258D01E8BDF4@csomb01.corp.atmel.com> <4808F08E.8030509@unc.edu> Message-ID: Hi, reading theses emails i have a question : ikaaro or zope - what's best ? which one is the most used ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080418/e3cdf62f/attachment.htm From juhasecke at googlemail.com Fri Apr 18 21:46:52 2008 From: juhasecke at googlemail.com (Jan Ulrich Hasecke) Date: Fri, 18 Apr 2008 21:46:52 +0200 Subject: [Tutor] web programming tutorials? In-Reply-To: References: <7941B2693F32294AAF16C26B679A258D01E8BDF4@csomb01.corp.atmel.com> <4808F08E.8030509@unc.edu> Message-ID: <79C03F21-26E6-47DA-BEED-77F4AA802257@googlemail.com> Am 18.04.2008 um 21:37 schrieb Monika Jisswel: > Hi, > > reading theses emails i have a question : > ikaaro or zope - what's best ? which one is the most used ? > Zope is in production since 1996 and has a huge community, it is a very advanced framework. One of the best CMS is built on top of Zope: http://plone.org juh -- Business: http://hasecke.com --- Private: http://hasecke.eu --- Blog: http://www.sudelbuch.de --- History: www.generationenprojekt.de --- Europe: www.wikitution.org -------------- next part -------------- A non-text attachment was scrubbed... Name: PGP.sig Type: application/pgp-signature Size: 186 bytes Desc: Signierter Teil der Nachricht Url : http://mail.python.org/pipermail/tutor/attachments/20080418/2ab409f7/attachment.pgp From monjissvel at googlemail.com Fri Apr 18 22:00:22 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Fri, 18 Apr 2008 20:00:22 +0000 Subject: [Tutor] web programming tutorials? In-Reply-To: <79C03F21-26E6-47DA-BEED-77F4AA802257@googlemail.com> References: <7941B2693F32294AAF16C26B679A258D01E8BDF4@csomb01.corp.atmel.com> <4808F08E.8030509@unc.edu> <79C03F21-26E6-47DA-BEED-77F4AA802257@googlemail.com> Message-ID: > > and has a huge community, it is a very advanced framework. > Ok but I still need more votes for zope to be convinced, Just in case Zope won the majority of the voices ... How much time would it take one to learn & become productive in zope ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080418/10d1b9f4/attachment.htm From pine508 at hotmail.com Fri Apr 18 22:23:32 2008 From: pine508 at hotmail.com (Che M) Date: Fri, 18 Apr 2008 16:23:32 -0400 Subject: [Tutor] web programming tutorials? In-Reply-To: <79C03F21-26E6-47DA-BEED-77F4AA802257@googlemail.com> References: <7941B2693F32294AAF16C26B679A258D01E8BDF4@csomb01.corp.atmel.com> <4808F08E.8030509@unc.edu> <79C03F21-26E6-47DA-BEED-77F4AA802257@googlemail.com> Message-ID: Thank you, everyone, for all the responses! I will wade through them and try to get some understanding and then will no doubt come back with some questions in some days. Much appreciated. -Che _________________________________________________________________ More immediate than e-mail? Get instant access with Windows Live Messenger. http://www.windowslive.com/messenger/overview.html?ocid=TXT_TAGLM_WL_Refresh_instantaccess_042008 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080418/bddbecf1/attachment.htm From kdgorospe at gmail.com Fri Apr 18 23:22:00 2008 From: kdgorospe at gmail.com (Kelvin Gorospe) Date: Fri, 18 Apr 2008 11:22:00 -1000 Subject: [Tutor] Reading Multiple Files in Sequence Message-ID: Hi everyone, I'm new to Python AND programming and would appreciate any help anybody has to offer. I have several .csv files that contains temperature data taken at several different locations. Each line in the csv file is a list such as this: timestamp at location 1, temperature at location 1, timestamp at location 2, temperature at location 2, etc. The attached script opens one file and creates an output file that lists all the timestamps and temperatures for location 1. However, what I'd like to do, is have a script that SEVERAL csv files (each one containing one month of temperature data) and create an output file for EACH location (approximately 50 of them). So in the end, I'll have 50 txt files showing time stamps and temperatures for a single location over all months of data collection. Thanks in advance for your help. -Kelvin -- Kelvin D. Gorospe Hawai'i Institute of Marine Biology University of Hawai'i at Manoa Department of Zoology, PhD Student Lab: (808) 236-7456 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080418/b8ac616b/attachment-0001.htm From kdgorospe at gmail.com Fri Apr 18 23:23:50 2008 From: kdgorospe at gmail.com (Kelvin Gorospe) Date: Fri, 18 Apr 2008 11:23:50 -1000 Subject: [Tutor] Reading Multiple Files in Sequence In-Reply-To: References: Message-ID: Sorry, I need to stop doing this... Attached is the script that I forgot to attach in my last email to the list. Thanks again, K On Fri, Apr 18, 2008 at 11:22 AM, Kelvin Gorospe wrote: > Hi everyone, > > I'm new to Python AND programming and would appreciate any help anybody > has to offer. I have several .csv files that contains temperature data taken > at several different locations. Each line in the csv file is a list such as > this: timestamp at location 1, temperature at location 1, timestamp at > location 2, temperature at location 2, etc. > > The attached script opens one file and creates an output file that lists > all the timestamps and temperatures for location 1. However, what I'd like > to do, is have a script that SEVERAL csv files (each one containing one > month of temperature data) and create an output file for EACH location > (approximately 50 of them). So in the end, I'll have 50 txt files showing > time stamps and temperatures for a single location over all months of data > collection. > > Thanks in advance for your help. > > -Kelvin > > > > -- > Kelvin D. Gorospe > Hawai'i Institute of Marine Biology > University of Hawai'i at Manoa > Department of Zoology, PhD Student > Lab: (808) 236-7456 -- Kelvin D. Gorospe Hawai'i Institute of Marine Biology University of Hawai'i at Manoa Department of Zoology, PhD Student Lab: (808) 236-7456 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080418/10acc1f7/attachment.htm -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: tempshelp.txt Url: http://mail.python.org/pipermail/tutor/attachments/20080418/10acc1f7/attachment.txt From pylinuxian at gmail.com Fri Apr 18 23:49:03 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Fri, 18 Apr 2008 21:49:03 +0000 Subject: [Tutor] Reading Multiple Files in Sequence In-Reply-To: References: Message-ID: if you only want to start a loop to parse all files in a directory try something like this: import glob > > n=0 > for file in > glob.glob('/Users/Kelvin/TEMPDATASET/CLEANEDFIELDDATA/WEST/*'): > n=n+1 > new_output_file='/Users/Kelvin/TEMPDATASET/PCA/'+ str(n) + '.txt' > output = open(new_output_file,'w') > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080418/b3775216/attachment.htm From Mike.Hansen at atmel.com Sat Apr 19 00:23:06 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Fri, 18 Apr 2008 16:23:06 -0600 Subject: [Tutor] Reading Multiple Files in Sequence In-Reply-To: References: Message-ID: <7941B2693F32294AAF16C26B679A258D01EE9600@csomb01.corp.atmel.com> > [mailto:tutor-bounces at python.org] On Behalf Of Kelvin Gorospe > > Sorry, I need to stop doing this... Attached is the script > that I forgot to attach in my last email to the list. Thanks again, K > > > On Fri, Apr 18, 2008 at 11:22 AM, Kelvin Gorospe > wrote: > > > Hi everyone, > > I'm new to Python AND programming and would appreciate > any help anybody has to offer. I have several .csv files that > contains temperature data taken at several different > locations. Each line in the csv file is a list such as this: > timestamp at location 1, temperature at location 1, timestamp > at location 2, temperature at location 2, etc. > > The attached script opens one file and creates an > output file that lists all the timestamps and temperatures > for location 1. However, what I'd like to do, is have a > script that SEVERAL csv files (each one containing one month > of temperature data) and create an output file for EACH > location (approximately 50 of them). So in the end, I'll > have 50 txt files showing time stamps and temperatures for a > single location over all months of data collection. > > Thanks in advance for your help. > > -Kelvin Hmmmm..... first, I'd use the CSV module instead of manually parsing the csv files. Although it might be ok in your application, sometimes you can get killed by CSV files that have commas as part of the data. Example: zone 1, 90, "Hansen, Mike", "555 Elm Street, MayBerry", 555-5555 Just splitting on commas will give you unexpected results since it will catch the stuff between the quotes. The CSV module handles this. Second, if you want to grab all csv files in a directory, you can use the glob module. Then you can iterate and read each csv file. Finally, the tricky part. There are a few ways of collecting the data for each location. If there isn't a huge amount of data, then you could load it into a in-memory data structure like a dictionary with each key being the location and the value being a list of tuples or a list of class instances, or a dictionary of dictionaries. Example of dictionary with a list of tuples: { "location1" : [ (200804181611, 55), (200804171625, 42) , ...], "location2" : [ (200804150800, 35)] } Then you could iterate over each dictionary key and write out your text file for that location. Another way would be to load the data into a database. Python 2.5 comes with SQLite. You could create one database table with columns for location, time, and temp. Then you can query the database for each location. I wouldn't open a file for each location while parsing the CSV files. To me it seems ugly to have up to 50 files open at once. I'm sure there are other ways that some of the more experienced tutor list members can suggest. Mike From cbc at unc.edu Sat Apr 19 00:50:32 2008 From: cbc at unc.edu (Chris Calloway) Date: Fri, 18 Apr 2008 18:50:32 -0400 Subject: [Tutor] web programming tutorials? In-Reply-To: References: <7941B2693F32294AAF16C26B679A258D01E8BDF4@csomb01.corp.atmel.com> <4808F08E.8030509@unc.edu> <79C03F21-26E6-47DA-BEED-77F4AA802257@googlemail.com> Message-ID: <480925B8.1060400@unc.edu> On 4/18/2008 4:00 PM, Monika Jisswel wrote: > Ok but I still need more votes for zope to be convinced, Well, arguing about what is the best python web framework is kind of fruitless. Everybody has an opinion. But no one is qualified to pronounce a comparison on all of them. The "votes" you would get would be reflective of the number of devotees of particular frameworks. And not all frameworks are comparable. They have all sorts of niches from simple to advanced covering different use cases. Heck, Zope 2 isn't even a framework. It's an application server. And Zope 3 isn't even a framework. It's a component architecture. And Plone isn't even a framework. It's a CMS product. Experience is your guide. Experience from others: you look at who is using what to solve your *use case*. And then experience from yourself: you evaluate the options for your use case by using them for yourself. There is some old Python saw I think attributed to GVR that goes something like, "Why would anyone learn anyone else's Python web framework when it is so easy to write your own Python web framework?" And of course the answer is, to get to the other side. Your question twofold. First, "What's best?" And I would have to ask, "Best what?" Then, "Which is most used, Zope or ikaaro?" And the answer would be Zope by a mile. But possibly only because a lot of people haven't tried ikaaro and Zope has been around about ten years longer with a huge accumulated mind-share. > Just in case Zope won the majority of the voices ... How much time would it > take one to learn & become productive in zope ? If you have to ask... (you can't afford). It depends on what you want to do. The base use case for Zope 2 has one of the lowest barriers to entry of any web application server ever. The trouble is learning enough to extend that base use case to your use case. Then the learning curve can be very steep. Whole frameworks on top of Zope have been built for that reason. Which is why people head for simpler web frameworks for other use cases. I find that the complexity and learning curve of a technology *may* have some relation to its power and flexibility. Or not. In the case of Zope, it is definitely related to *stuff I don't have to build that I want in order to be productive.* That is, to get to the other side. When I look at a lot of other web technologies, they spend most of their learning curve showing you how to build things that already come pre-built in Zope. That alone is very much in keeping with the Zen of Python in a "batteries included" kind of way. And these things are usually built the right way in Zope by people much wiser than me and in ways other technologies only borrow from when they get wise enough themselves to borrow from Zope. It's like Python in that I spend less time programming and more time just getting things done. But like the Python Standard Library, you don't learn it in a week. You learn it bit by bit. And then there's the stuff in Zope the other technologies never even get around showing you how to build, like awesome super-fine-grained easily-extensible security done right and awesome super-flexible easily-extensible workflow done right. Stuff that come "out of the box" with Zope would often be considered some very advanced cutting edge application in some other mere web framework. You may not need these things. Lesser web frameworky kinda thingies have their sweet spot use cases which only require a certain amount of functionality that you might be able to get your head around in a shorter amount of time. But if you have to ask why Zope, you probably should not get into it. Seriously. -- Sincerely, Chris Calloway http://www.secoora.org office: 332 Chapman Hall phone: (919) 599-3530 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From carroll at tjc.com Sat Apr 19 02:38:27 2008 From: carroll at tjc.com (Terry Carroll) Date: Fri, 18 Apr 2008 17:38:27 -0700 (PDT) Subject: [Tutor] web programming tutorials? In-Reply-To: Message-ID: On Fri, 18 Apr 2008, Che M wrote: > Thank you, everyone, for all the responses! I will wade through them > and try to get some understanding and then will no doubt come back with > some questions in some days. Much appreciated. -Che Che, I've done several superficial web programs over the years, and I'm inclined to agree with those who suggest trying some imple CGI programs first to understand how it works under the covers. That being said, for an upcoming personal project, I'm going to be using at least CherryPy and perhaps some other Turbogears components, and perhaps even Turbogears itself. To that end, I've found the Turbogear parts of the book "Professional Python Frameworks: Web 2.0 Programming with Django and Turbogears" ( http://www.wrox.com/WileyCDA/WroxTitle/productCd-0470138092.html ) to be very helpful in understanding Turbogears. This may just be a point of personal preference, but I found it a better explanation than the Turbogears book "rapid Web Applications with Turogears" referred to at http://turbogears.org/. You may wish to try a few simple web programs, and then look at whether a framework (whether small like CherryPy or big like Turbogears, Zope or Django) would be appropriate for you. From alan.gauld at btinternet.com Sat Apr 19 13:52:34 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Apr 2008 12:52:34 +0100 Subject: [Tutor] web programming tutorials? References: <7941B2693F32294AAF16C26B679A258D01E8BDF4@csomb01.corp.atmel.com><4808F08E.8030509@unc.edu> Message-ID: "Monika Jisswel" wrote > reading theses emails i have a question : > ikaaro or zope - what's best ? which one is the most used ? They are very different animals as far as I can rtell. In terms of usage there is nom doubt Zope is more poular, you can tell that by the fact that there are several commercial books published by mainstream publishers about Zope. I know from experiejce that a publisher won't go to print unless they are confident they can sell at least several thousand copies. Howeever Zope is a very big comprehesive web environment, much bigger than is needed for the majority of web projects. My guess is that the most popeular web frameworks just now are Django and TurboGears(*), both of which are much simpler than Zope but offer much of its convenience. As I understand it ikaaro is more directly targetted at the Django type user community than Zope. Zope is great if youneed to build a big complex web site with many visitors each performing complex transactions. (*)TurboGears is really a package of other framework components, most notably CherryPy which has its own independant community and so could therefore be argued to be most popular if you aggregate TurboGears and CherryPy users. But comparing Zope with ikaaro is not really a sensible comparison. Its like comparing Microsoft Access with IBM DB2 as databases. They have totally different audiences. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sierra_mtnview at sbcglobal.net Sat Apr 19 17:45:25 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 19 Apr 2008 08:45:25 -0700 Subject: [Tutor] Setting the PC Clock to Correct Time Message-ID: <480A1395.4010906@sbcglobal.net> I have a Python program that runs 24/7, but is activated around dusk and de-activated from its task around dawn. My clock drifts about 4 sec/day. Is there some function that will fetch the correct time from the internet and reset the clock? I'd like to reset the clock each time the program is activated at dusk. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "Philosophy is questions that may never be answered. Religion is answers that may never be questioned" -- Anon Web Page: From titleistfour at gmail.com Sat Apr 19 18:20:39 2008 From: titleistfour at gmail.com (jay) Date: Sat, 19 Apr 2008 11:20:39 -0500 Subject: [Tutor] Setting the PC Clock to Correct Time In-Reply-To: <480A1395.4010906@sbcglobal.net> References: <480A1395.4010906@sbcglobal.net> Message-ID: <7c25bb490804190920m37662a9bt72328ea41641638@mail.gmail.com> Wayne, Is this a Linux box? If so, you might consider setting up NTP to sync to an outside time source. We do that here and it works quite well, even accounting for drifting. If this is a Windows machine, I believe those are already synced with the PDC, if joined to a Domain, but I might be wrong. Jason On Sat, Apr 19, 2008 at 10:45 AM, Wayne Watson wrote: > I have a Python program that runs 24/7, but is activated around dusk and > de-activated from its task around dawn. My clock drifts about 4 sec/day. > Is there some function that will fetch the correct time from the > internet and reset the clock? I'd like to reset the clock each time the > program is activated at dusk. > > -- > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > "Philosophy is questions that may never be > answered. Religion is answers that may never > be questioned" -- Anon > > Web Page: > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080419/4a9b8ae7/attachment.htm From cfuller084 at thinkingplanet.net Sat Apr 19 18:24:05 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sat, 19 Apr 2008 11:24:05 -0500 Subject: [Tutor] Setting the PC Clock to Correct Time In-Reply-To: <480A1395.4010906@sbcglobal.net> References: <480A1395.4010906@sbcglobal.net> Message-ID: <200804191124.05588.cfuller084@thinkingplanet.net> On Saturday 19 April 2008 10:45, Wayne Watson wrote: > I have a Python program that runs 24/7, but is activated around dusk and > de-activated from its task around dawn. My clock drifts about 4 sec/day. > Is there some function that will fetch the correct time from the > internet and reset the clock? I'd like to reset the clock each time the > program is activated at dusk. You need an NTP (network time protocol) client. You may have one built in to your operating system. Check out http://www.pool.ntp.org/ for tips on how to get started. Cheers From cfuller084 at thinkingplanet.net Sat Apr 19 19:40:10 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sat, 19 Apr 2008 12:40:10 -0500 Subject: [Tutor] Setting the PC Clock to Correct Time In-Reply-To: <480A1395.4010906@sbcglobal.net> References: <480A1395.4010906@sbcglobal.net> Message-ID: <200804191240.10906.cfuller084@thinkingplanet.net> I just checked my laptop (XP Pro), and you can set the time server (or use the default), but it only updates once a week. So your computer's time could be off by thirty seconds by the time of the next synchronization. It might be enough, but you also need to be aware so you aren't confused into thinking it isn't working when its off by four seconds the next day. I used to have my linux desktop synchronize every six hours. The full blown NTP client runs more or less continuously, and can keep you within milliseconds of the standard. Cheers On Saturday 19 April 2008 10:45, Wayne Watson wrote: > I have a Python program that runs 24/7, but is activated around dusk and > de-activated from its task around dawn. My clock drifts about 4 sec/day. > Is there some function that will fetch the correct time from the > internet and reset the clock? I'd like to reset the clock each time the > program is activated at dusk. From muchanek at gmail.com Sat Apr 19 21:12:25 2008 From: muchanek at gmail.com (kinuthia muchane) Date: Sat, 19 Apr 2008 22:12:25 +0300 Subject: [Tutor] Executing from Python prompt In-Reply-To: References: Message-ID: <1208632345.5802.14.camel@www.kinuthia.com> Hi, I do not know what I am doing wrong. When I run the following code from the Python prompt it executes without a murmur. But when I save it as a .py file and try to execute it from the shell, it just returns the prompt...actually it is all scripts that return a value which are behaving in this manner. def factorial(n): if n <= 1: return 1 else: return n * factorial(n-1) factorial(some number here) The same happens when I use IDLE. Thanks! Kinuthia... From marc.tompkins at gmail.com Sat Apr 19 21:45:34 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sat, 19 Apr 2008 12:45:34 -0700 Subject: [Tutor] Hoping to benefit from someone's experience... In-Reply-To: References: <40af687b0804151903s5577b339gb92bbc92dae8a899@mail.gmail.com> <1208312323.15504.1248115007@webmail.messagingengine.com> <40af687b0804152031h6c9ad724ma50ef0d7ce809531@mail.gmail.com> <4805779D.6090202@gmail.com> <40af687b0804152115x77f083d3o55a8b3777e4b5574@mail.gmail.com> <40af687b0804161048o63517b61y983734e68bb1b3ca@mail.gmail.com> <4806405C.6050002@tds.net> <480646E9.9060607@san-dc.com> Message-ID: <40af687b0804191245y24c1f76xc3f46bdae85e0db1@mail.gmail.com> Just as a followup - I ended up using a Python script to recurse through the folders of files and, for each file found, extract the doctor/date/medical record number from the filename, then run a Word macro on the file to insert the header slug. If anyone ever needs to do something similar, or just wants to laugh at what a hack this turned out to be, I've attached a text file containing the Python and the macro. (The UIDs and names have all been sanitized for my protection.) Bear in mind that this was a one-off; if I end up re-using this I will clean it up, put things in classes, load UIDs from an external file, etc. Background: In the folder "U:\transcripts.doc" there are folders called "Recent" and "Archive" for each of about twelve providers; I need only Able, Baker, Doe, Roe, Smith and Jones - that's why I put the folder names in a tuple instead of simply processing the root folder. Inside of each folder there are subfolders for individual patients, but also many patient documents in the main folder. File names are supposed to follow the format "Last,First-MRN-01Jan2008-Able.doc", but there are many variations on this theme - "Last,First-01Jan2008-MRN-Able.doc" "Last,First-MRN-01Jan2008-Able-Echo.doc" "Last,First-MRN-01Jan2008-Echo-Able.doc" "Last,First-01Jan2008-MRN-Echo-Able.doc" "Last,First-01Jan2008-MRN-Able-Echo.doc" etc. Last,First - the patient's name. Irrelevant to my purpose. MRN - medical record number Echo - most of these files are consultations, but the ones labeled "Echo" are echocardiogram reports. For these I need to set Category and Description to "Echo"; otherwise it's "Consultation External"/"Consultation". The doctor is supposed to dictate the MRN, and the transcriptionist puts it in the filename - but there are many cases where the MRN is missing. These can look like: "Last,First-XXX-01Jan2008-Able.doc" "Last,First--01Jan2008-Able.doc" "Last,First-01Jan2008-Able.doc" so I needed several different filters The date needs to be passed in MM/DD/YYYY format; I found that the easiest way to figure out which field was the date was to try/except strftime(). I'm sure there's a more elegant way using regexp, but I was in quick-and-dirty mode. As you might expect, most of the time is spent in Word. It would probably be faster if I set Visible = False, but for some reason the macro fails (silently) when I do that, so I just minimize Word instead to cut down on screen refreshes. Also, drive U is a Samba share, so there's network latency to take into account. Even so, 10,231 files took less than 15 minutes to convert, which I can live with. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080419/e4e8e4af/attachment-0001.htm -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: rtfConversion.txt Url: http://mail.python.org/pipermail/tutor/attachments/20080419/e4e8e4af/attachment-0001.txt From bgailer at gmail.com Sat Apr 19 22:06:22 2008 From: bgailer at gmail.com (bob gailer) Date: Sat, 19 Apr 2008 16:06:22 -0400 Subject: [Tutor] Executing from Python prompt In-Reply-To: <1208632345.5802.14.camel@www.kinuthia.com> References: <1208632345.5802.14.camel@www.kinuthia.com> Message-ID: <480A50BE.8050607@gmail.com> kinuthia muchane wrote: > Hi, > > I do not know what I am doing wrong. When I run the following code from > the Python prompt it executes without a murmur. But when I save it as > a .py file and try to execute it from the shell, it just returns the > prompt...actually it is all scripts that return a value which are > behaving in this manner. > > > def factorial(n): > if n <= 1: > return 1 > else: > return n * factorial(n-1) > > factorial(some number here) > > print factorial(some number here) When you enter an expression at the interactive prompt you see the value. Not true when you run a program. Expression values must be printed. So you are doing nothing wrong. -- Bob Gailer 919-636-4239 Chapel Hill, NC From alan.gauld at btinternet.com Sat Apr 19 23:14:11 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Apr 2008 22:14:11 +0100 Subject: [Tutor] Setting the PC Clock to Correct Time References: <480A1395.4010906@sbcglobal.net> Message-ID: "Wayne Watson" wrote Is there some function that will fetch the correct time from the internet and reset the clock? I'd like to reset the clock each time the program is activated at dusk. That should be standard in your S. If its Windows you do it via the Internet Time tab on the Date & Time applet. Do you have that set, it should prevent drift by more than a couple of seconds or so in total. You can do the same in MacOS or Linux. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Apr 19 23:21:22 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Apr 2008 22:21:22 +0100 Subject: [Tutor] Executing from Python prompt References: <1208632345.5802.14.camel@www.kinuthia.com> Message-ID: "kinuthia muchane" wrote > I do not know what I am doing wrong. When I run the following code > from > the Python prompt it executes without a murmur. But when I save it > as > a .py file and try to execute it from the shell, it just returns the > prompt...actually it is all scripts that return a value which are > behaving in this manner. The >>> prompt evaluates expressions and prionts the value. The interpreter on the other hand does not automatically print values you ghave to explicitly tell it to print using the print statement. So in your case just add the print command in front of the function call and all will be well. > factorial(some number here) print factorial(n) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From devsfan1830 at gmail.com Sat Apr 19 21:44:55 2008 From: devsfan1830 at gmail.com (James Duffy) Date: Sat, 19 Apr 2008 15:44:55 -0400 Subject: [Tutor] Need help with sockets Message-ID: <000001c8a255$d8980360$89c80a20$@com> For a part of a program, I need to send a text string to another machine in a IM style app. I've done this in C# but never in python. The server is in C# so I just need a client side program that can listen for and display incoming messages as well as send messages. Ive managed to make a socket and connect but I don't know how to setup a listen thread and a sender function. Can someone help? Below is C# code for the listener/send function of my client that id made. I basically hafta turn this into python. This method runs inside a thread. void RunClient() { TcpClient myClient; // instantiate TcpClient for sending data to server try { Output to screen: Attempting connection\r\n" // Step 1: Create TcpClient myClient = new TcpClient(); // Step 2: Connect to server myClient.Connect(address.Text,int.Parse(port.Text)); // Step 3: Create a Network Stream associated with TcpClient myNetStream = myClient.GetStream(); // Step 4: Create objects for writing and reading across stream myWriter = new BinaryWriter(myNetStream); myReader = new BinaryReader(myNetStream); // loop until server signals termination do { // Step 5: Processing phase try { // read message from server message = myReader.ReadString(); inbound.Text +="\r\n" + message; } // handle exception if error in reading server data catch (Exception) { System.Environment.Exit( System.Environment.ExitCode); } } while (message != "SERVER>>> TERMINATE"); status.Text += "\r\nClosing connection.\r\n"; // Step 6: Close connection myWriter.Close(); myReader.Close(); myNetStream.Close(); myClient.Close(); Application.Exit(); } // handle exception if error in establishing connection Catch (Exception error) { MessageBox.Show(error.ToString()); } } -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080419/b43ce12f/attachment.htm From joskerc at gmail.com Sun Apr 20 03:21:03 2008 From: joskerc at gmail.com (Jos Kerc) Date: Sun, 20 Apr 2008 03:21:03 +0200 Subject: [Tutor] Recursion doubt In-Reply-To: References: Message-ID: Hi, you are tackling 3 "heavy" subjects in just 1 go! graphs :a triving math society would approve your choice. But you might start with the *slightly* less difficult challenge: trees. I do not know your math/programming background, so the following link can perhaps enlighten you: http://www.brpreiss.com/books/opus7/ Trees, graphs, queues and what more implemented in several languages. Python included. Also, most CS starters have chapters devoted to (some of) them. (E.g. http://www.greenteapress.com/thinkpython/) Backtracking & recursion will surely be topics too. Reading them will help getting a handle on it The 3 chosen topics are advanced or even rather advanced even for most of CS people. To return to your question... Basically, find_path takes a node connected to 'start', if not at the 'end', make the current node 'start' and see if find_path does return a path. As soon as a path is foud find_path quits searching. You can look at find_all as a master routine that keeps calling find_path until find_path gives up. If the search space has not been exhausted (here there are still other nodes connected to 'start') take a suitable candidate call find_path from there until no more paths from there can be found. Repeat until no more suitable candidates. As you have gone through the whole search space, all paths from 'start' to 'end' were found. Recursion makes backtracking easier: the program/routine will by itself keep track of the steps taken & where to go back if a search fails. Backtracking is the powerful technique of remembering the steps already taken & to retrace them till the first non-explored sidetrack when needed. Choosing the next non-explored sidetrack though can be complex involving other searches, ... It all depends on what you look for, how the data is represented. A related topic that will help you understand things is breadth-first & depth-first searches on trees. (in this case find_path executes a depth-first search on the graph - represented as a dictionary & find_all combines the 2 searches, first the depth search & when it quits, the breadth search takes over.) Greetz On 4/15/08, Anshu Raval wrote: > > Hi, > At the url *http://www.python.org/doc/essays/graphs.html*there is some > code by Guido Van Rossum for computing paths through a graph - I have > pasted it below for reference - > > Let's write a simple function to determine a path between two nodes. > It takes a graph and the start and end nodes as arguments. It will > return a list of nodes (including the start and end nodes) comprising > the path. When no path can be found, it returns None. The same node > will not occur more than once on the path returned (i.e. it won't > contain cycles). The algorithm uses an important technique called > backtracking: it tries each possibility in turn until it finds a > solution. > > def find_path(graph, start, end, path=[]): > path = path + [start] > if start == end: > return path > if not graph.has_key(start): > return None > for node in graph[start]: > if node not in path: > newpath = find_path(graph, node, end, path) > if newpath: return newpath > return None > > *** He then says------------------------ > > It is simple to change this function to return a list of all paths > (without cycles) instead of the first path it finds: > > def find_all_paths(graph, start, end, path=[]): > path = path + [start] > if start == end: > return [path] > if not graph.has_key(start): > return [] > paths = [] > for node in graph[start]: > if node not in path: > newpaths = find_all_paths(graph, node, end, path) > for newpath in newpaths: > paths.append(newpath) > return paths > > *** I couldn't understand how it was simple to change the function > find paths to find all paths. How would you think about writing this > second function recursively. Especially the part about if start==end: > return [path]. I feel you would give square brackets around path here > after first writing the inductive part ... for node in > graph[start] .... > and then by trial and error put square brackets around path in the > Basis part. Can someone please explain how to write this code. Thanks! > > > > > ------------------------------ > Planning marriage in 2008! Join Shaadi.com matrimony FREE! Try it now! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080420/0413e200/attachment-0001.htm From rdm at rcblue.com Sun Apr 20 03:58:58 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 19 Apr 2008 18:58:58 -0700 Subject: [Tutor] Setting the PC Clock to Correct Time In-Reply-To: <200804191240.10906.cfuller084@thinkingplanet.net> References: <480A1395.4010906@sbcglobal.net> <200804191240.10906.cfuller084@thinkingplanet.net> Message-ID: <20080420020600.EB5E41E4005@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080419/afdc30d3/attachment.htm From alan.gauld at btinternet.com Sun Apr 20 08:18:32 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 Apr 2008 07:18:32 +0100 Subject: [Tutor] Need help with sockets References: <000001c8a255$d8980360$89c80a20$@com> Message-ID: "James Duffy" wrote > C# so I just need a client side program that can listen for and > display > incoming messages as well as send messages. Ive managed to make a > socket and > connect but I don't know how to setup a listen thread and a sender > function. Tale a look at the Network Programming topic in my tutorial. It has an example of a client sending to a server and listening for the responses. Its not threaded though so you'll need to look elsewhere for the threading code. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From muchanek at gmail.com Sun Apr 20 09:42:15 2008 From: muchanek at gmail.com (kinuthia muchane) Date: Sun, 20 Apr 2008 10:42:15 +0300 Subject: [Tutor] Executing from Python prompt In-Reply-To: <480A50BE.8050607@gmail.com> References: <1208632345.5802.14.camel@www.kinuthia.com> <480A50BE.8050607@gmail.com> Message-ID: <1208677335.5712.3.camel@www.kinuthia.com> On Sat, 2008-04-19 at 16:06 -0400, bob gailer wrote: > kinuthia muchane wrote: > > Hi, > > > > I do not know what I am doing wrong. When I run the following code from > > the Python prompt it executes without a murmur. But when I save it as > > a .py file and try to execute it from the shell, it just returns the > > prompt...actually it is all scripts that return a value which are > > behaving in this manner. > > > > > > def factorial(n): > > if n <= 1: > > return 1 > > else: > > return n * factorial(n-1) > > > > factorial(some number here) > > > > > print factorial(some number here) > > When you enter an expression at the interactive prompt you see the > value. Not true when you run a program. Expression values must be > printed. So you are doing nothing wrong. Thanks, Bob, it worked the first time. It was staring me in the face the whole time! Thanks once again. Kinuthia... From muchanek at gmail.com Sun Apr 20 10:00:57 2008 From: muchanek at gmail.com (kinuthia muchane) Date: Sun, 20 Apr 2008 11:00:57 +0300 Subject: [Tutor] Tutor Digest, Vol 50, Issue 63 In-Reply-To: References: Message-ID: <1208678457.5712.6.camel@www.kinuthia.com> > "kinuthia muchane" wrote > > > I do not know what I am doing wrong. When I run the following code > > from > > the Python prompt it executes without a murmur. But when I save it > > as > > a .py file and try to execute it from the shell, it just returns the > > prompt...actually it is all scripts that return a value which are > > behaving in this manner. > > The >>> prompt evaluates expressions and prionts the value. > The interpreter on the other hand does not automatically print > values you ghave to explicitly tell it to print using the print > statement. > > So in your case just add the print command in front of the > function call and all will be well. > > > factorial(some number here) > > print factorial(n) > > HTH, > > > -- > Alan Gauld Thanks, that worked. Kinuthia... From mwalsh at groktech.org Sun Apr 20 10:05:45 2008 From: mwalsh at groktech.org (Martin Walsh) Date: Sun, 20 Apr 2008 03:05:45 -0500 Subject: [Tutor] urllib2.urlopen(url) Message-ID: <480AF959.5090804@groktech.org> Monika Jisswel wrote: > Hi, > > can i stop urllib2.urlopen() from following redirects automatically ? It doesn't answer your question directly, but if you care more about the initial request/response than the content at the other end of a redirect -- you can use httplib. It might look something like this: """ import urlparse import httplib url = urlparse.urlsplit('http://google.com/search?q=python') host = url[1] path = urlparse.urlunsplit(('', '')+url[2:]) con = httplib.HTTPConnection(host) con.request('GET', path) response = con.getresponse() print 'status:', response.status print 'reason:', response.reason print 'document:', response.read() """ You lose many advantages of the higher-level urllib2, as it does much of the mundane work for you -- parsing urls, choosing http or https transparently, etc -- but I think httplib is still appropriate if your needs are simple. More information here: http://docs.python.org/lib/module-httplib.html HTH, Marty > thanks in advance > > Monika Jissvel > From monjissvel at googlemail.com Sun Apr 20 13:49:41 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Sun, 20 Apr 2008 11:49:41 +0000 Subject: [Tutor] urllib2.urlopen(url) In-Reply-To: <480AF959.5090804@groktech.org> References: <480AF959.5090804@groktech.org> Message-ID: Hi Martin, print 'status:', response.status > print 'reason:', response.reason > print 'document:', response.read() > This is definitly what i was looking for and did not know in which module to look. Thank you so much for the code illusration. Monika. 2008/4/20, Martin Walsh : > > Monika Jisswel wrote: > > Hi, > > > > can i stop urllib2.urlopen() from following redirects automatically ? > > > It doesn't answer your question directly, but if you care more about the > initial request/response than the content at the other end of a redirect > -- you can use httplib. It might look something like this: > > """ > import urlparse > import httplib > > url = urlparse.urlsplit('http://google.com/search?q=python') > host = url[1] > path = urlparse.urlunsplit(('', '')+url[2:]) > > con = httplib.HTTPConnection(host) > con.request('GET', path) > response = con.getresponse() > > print 'status:', response.status > print 'reason:', response.reason > print 'document:', response.read() > """ > > You lose many advantages of the higher-level urllib2, as it does much of > the mundane work for you -- parsing urls, choosing http or https > transparently, etc -- but I think httplib is still appropriate if your > needs are simple. > > More information here: > http://docs.python.org/lib/module-httplib.html > > HTH, > Marty > > > > thanks in advance > > > > Monika Jissvel > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080420/7e2fdd6e/attachment.htm From monjissvel at googlemail.com Sun Apr 20 14:23:04 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Sun, 20 Apr 2008 12:23:04 +0000 Subject: [Tutor] web programming tutorials? In-Reply-To: References: <7941B2693F32294AAF16C26B679A258D01E8BDF4@csomb01.corp.atmel.com> <4808F08E.8030509@unc.edu> Message-ID: Hi, Ok, so if you were to go back in time ... which pythonic web-tool /framework would you put more time in studying ? keep in mind that you still have no experience and you need something to get you started in web technology, second thing to take into account is that it doesn't have to be a learning tool only but something you can use for real projects once you've become experienced in it. I am asking this question because of this huge number of tools/frameworks/projects all over the web that let no choice but get confused & maybe lost. my choice to go python was because i could feel its power from the first applications I could develop, then were able to modify (in no time), expand (with no single problem & in no time) ... I want to feel the same experience again in web development . Monika. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080420/f6d00802/attachment.htm From alan.gauld at btinternet.com Sun Apr 20 15:55:42 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 Apr 2008 14:55:42 +0100 Subject: [Tutor] web programming tutorials? References: <7941B2693F32294AAF16C26B679A258D01E8BDF4@csomb01.corp.atmel.com><4808F08E.8030509@unc.edu> Message-ID: "Monika Jisswel" wrote > confused & maybe lost. my choice to go python was because i could > feel its > power from the first applications I could develop, then were able to > modify > (in no time), expand (with no single problem & in no time) ... I > want to > feel the same experience again in web development . I sympathise but feel you will be dissapointed. The web is almost by its nature a mess. It is a hodge podge of ideas glued onto what was originally intended as a simple documentation repository. Berners-Lee never expected http/html to become the main application framework of the 21st century. We have got to where we are with web technology by a triumph of innovation over good engineering. The result is a bunch of technologies and frameworks that often don't work well together and are either insecure, unreliable or both. There are moves afoot to addresss most of these things (Web services, new http versions, xhtml etc) but none of these are mature yet and even fewer are in widespread use. The result is that you can choose whichever framework you like and it will serve you fairly well, but with limitations. So in shhort there is no equivalent to Python application programming for the web. This probably shouldn't surprise us, the web is only 15 years old, computing is about 60 years old. Python was created with about 45 years of research behind it, the web is still being invented. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From amonroe at columbus.rr.com Sun Apr 20 17:51:06 2008 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun, 20 Apr 2008 11:51:06 -0400 Subject: [Tutor] String made of list elements' nth characters? Message-ID: <57-783088892.20080420115106@columbus.rr.com> Given a list of 6-letter words: ['abject','poetry','keypad'] How do I derive this list: ['apk', 'boe', 'jey'] (The original list's first letters, second letters, third letters, etc.) I have a text file of 15280 six-letter words and I want to robotically generate 6x6 word squares. My first attempt returns the right results, but _not in string form_. There's bound to be a really simple approach that I'm just not remembering. def checksolution(sol): maybes = [] for x in range(len(sol)): maybes.append( [y[x] for y in sol] ) print maybes solution=['abject','poetry','keypad'] checksolution(solution) [['a', 'p', 'k'], ['b', 'o', 'e'], ['j', 'e', 'y']] Alan From amonroe at columbus.rr.com Sun Apr 20 18:01:00 2008 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun, 20 Apr 2008 12:01:00 -0400 Subject: [Tutor] String made of list elements' nth characters? In-Reply-To: <57-783088892.20080420115106@columbus.rr.com> References: <57-783088892.20080420115106@columbus.rr.com> Message-ID: <163-782494187.20080420120100@columbus.rr.com> > Given a list of 6-letter words: > ['abject','poetry','keypad'] > How do I derive this list: > ['apk', 'boe', 'jey'] > (The original list's first letters, second letters, third letters, > etc.) > I have a text file of 15280 six-letter words and I want to robotically > generate 6x6 word squares. > My first attempt returns the right results, but _not in string form_. > There's bound to be a really simple approach that I'm just not > remembering. Per usual, I figured out a working approach right after posting. Could probably be optimized, but it works: def checksolution(sol): maybes = [] big = ''.join(solution) for x in range(len(sol)): maybes.append( big[x::6] ) print maybes solution=['abject','poetry','keypad'] checksolution(solution) ['apk', 'boe', 'jey'] Alan From kent37 at tds.net Sun Apr 20 18:27:45 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 20 Apr 2008 12:27:45 -0400 Subject: [Tutor] String made of list elements' nth characters? In-Reply-To: <163-782494187.20080420120100@columbus.rr.com> References: <57-783088892.20080420115106@columbus.rr.com> <163-782494187.20080420120100@columbus.rr.com> Message-ID: <480B6F01.6080006@tds.net> R. Alan Monroe wrote: > def checksolution(sol): > maybes = [] > big = ''.join(solution) > for x in range(len(sol)): > maybes.append( big[x::6] ) > print maybes > > solution=['abject','poetry','keypad'] > checksolution(solution) > > ['apk', 'boe', 'jey'] That's nice. Why do you use len(sol) instead of len(sol[0])? You only print the first three items. Here is another way to do it: In [8]: solution=['abject','poetry','keypad'] In [9]: [''.join(x) for x in zip(*solution)] Out[9]: ['apk', 'boe', 'jey', 'etp', 'cra', 'tyd'] Kent From amonroe at columbus.rr.com Sun Apr 20 18:39:18 2008 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun, 20 Apr 2008 12:39:18 -0400 Subject: [Tutor] String made of list elements' nth characters? In-Reply-To: <480B6F01.6080006@tds.net> References: <57-783088892.20080420115106@columbus.rr.com> <163-782494187.20080420120100@columbus.rr.com> <480B6F01.6080006@tds.net> Message-ID: <78-780196443.20080420123918@columbus.rr.com> > R. Alan Monroe wrote: >> def checksolution(sol): >> maybes = [] >> big = ''.join(solution) >> for x in range(len(sol)): >> maybes.append( big[x::6] ) >> print maybes >> >> solution=['abject','poetry','keypad'] >> checksolution(solution) >> >> ['apk', 'boe', 'jey'] > That's nice. Why do you use len(sol) instead of len(sol[0])? You only > print the first three items. Here is another way to do it: > In [8]: solution=['abject','poetry','keypad'] > In [9]: [''.join(x) for x in zip(*solution)] > Out[9]: ['apk', 'boe', 'jey', 'etp', 'cra', 'tyd'] If there are no valid words beginning with 'apk', 'boe', or 'jey' (there aren't) I know immediately that this word square can't possibly be completed, so no need to evaluate the remaining three. (I create a dict with all possible prefixes to speed up validity checks too.) In case it's not clear, a word square is basically a 6x6 crossword puzzle with no blacked out cells. Valid words are form on all the acrosses and all the downs simultaneously. Playing this game is what inspired me to experiment with it: http://boardgamegeek.com/game/8032 Alan From alan.gauld at btinternet.com Sun Apr 20 23:41:46 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 Apr 2008 22:41:46 +0100 Subject: [Tutor] String made of list elements' nth characters? References: <57-783088892.20080420115106@columbus.rr.com> Message-ID: "R. Alan Monroe" wrote > Given a list of 6-letter words: > ['abject','poetry','keypad'] > > How do I derive this list: > ['apk', 'boe', 'jey'] >>> a = ['abject', 'poetry', 'keypad'] >>> zip( a[0],a[1],a[2]) [('a', 'p', 'k'), ('b', 'o', 'e'), ('j', 'e', 'y'), ('e', 't', 'p'), ('c', 'r', 'a'), ('t', 'y', 'd')] >>> [''.join(t) for t in zip(a[0],a[1],a[2])] ['apk', 'boe', 'jey', 'etp', 'cra', 'tyd'] >>> Does that give you any ideas? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From katcipis at inf.ufsc.br Mon Apr 21 03:40:11 2008 From: katcipis at inf.ufsc.br (Tiago Katcipis) Date: Sun, 20 Apr 2008 22:40:11 -0300 Subject: [Tutor] Little problem with math module Message-ID: <480BF07B.80300@inf.ufsc.br> im not understanding why is this a problem...i have this simple function def newton_divergente(x): return math.pow(x, 1.0/3.0) but when x = -20 it returns this error return math.pow(x, 1.0/3.0) ValueError: math domain error but why is that? is it impossible to calculate -20 ^ (1/3) ? here on my calculator i get the result -6,666666667, but python seens to dont now the answer, why? am i doing something wrong? =/ thanks to everyone who tries do help best regards katcipis From kent37 at tds.net Mon Apr 21 04:23:19 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 20 Apr 2008 22:23:19 -0400 Subject: [Tutor] Little problem with math module In-Reply-To: <480BF07B.80300@inf.ufsc.br> References: <480BF07B.80300@inf.ufsc.br> Message-ID: <480BFA97.3000009@tds.net> Tiago Katcipis wrote: > im not understanding why is this a problem...i have this simple function > > def newton_divergente(x): > return math.pow(x, 1.0/3.0) > > but when x = -20 it returns this error > > return math.pow(x, 1.0/3.0) > ValueError: math domain error > > but why is that? is it impossible to calculate -20 ^ (1/3) ? > > here on my calculator i get the result -6,666666667, but python seens to > dont now the answer, why? am i doing something wrong? =/ Your calculator is not doing so well either since In [15]: -6.666666667**3 Out[15]: -296.29629634074081 but this seems to work: In [13]: -20**(1./3.) Out[13]: -2.7144176165949063 Kent From john at fouhy.net Mon Apr 21 04:40:57 2008 From: john at fouhy.net (John Fouhy) Date: Mon, 21 Apr 2008 14:40:57 +1200 Subject: [Tutor] Little problem with math module In-Reply-To: <480BF07B.80300@inf.ufsc.br> References: <480BF07B.80300@inf.ufsc.br> Message-ID: <5e58f2e40804201940s4f1ff9fdgf6038ec6d8429a83@mail.gmail.com> On 21/04/2008, Tiago Katcipis wrote: > im not understanding why is this a problem...i have this simple function > > def newton_divergente(x): > return math.pow(x, 1.0/3.0) > > but when x = -20 it returns this error > > return math.pow(x, 1.0/3.0) > ValueError: math domain error > > but why is that? is it impossible to calculate -20 ^ (1/3) ? > > here on my calculator i get the result -6,666666667, but python seens to > dont now the answer, why? am i doing something wrong? =/ -6.66.. looks more like -20 * (1.0/3.0), rather than -20 ** (1.0/3.0). That said, it's an interesting error. It must be an artefact of the method python uses to calculate roots, but I don't know what this error is. This is also interesting: >>> math.pow(-20, 1.0/3.0) nan >>> -20 ** (1.0/3.0) -2.7144176165949063 (nan stands for "not a number") And, one more for good luck: >>> -1 ** (1.0/2.0) -1.0 Hmm, that's not quite right! Python supports a complex datatype, but evidently the math.* functions don't extend to producing complex outputs when necessary. At a guess, the algorithm for calculating math.pow(x,y) says something like "If x is negative there might not be a real solution, so we won't try to find it". Whereas the algorithm for x**y just plows ahead -- and if the input is bad, the output might be too (GIGO). If you're going to be working with complex numbers, you might be better off looking at scipy or some other module that provides more mathematical grunt. -- John. From john at fouhy.net Mon Apr 21 04:52:54 2008 From: john at fouhy.net (John Fouhy) Date: Mon, 21 Apr 2008 14:52:54 +1200 Subject: [Tutor] Little problem with math module In-Reply-To: <5e58f2e40804201940s4f1ff9fdgf6038ec6d8429a83@mail.gmail.com> References: <480BF07B.80300@inf.ufsc.br> <5e58f2e40804201940s4f1ff9fdgf6038ec6d8429a83@mail.gmail.com> Message-ID: <5e58f2e40804201952v4246b9cet81869c2499425c7e@mail.gmail.com> On 21/04/2008, John Fouhy wrote: > >>> -1 ** (1.0/2.0) > -1.0 Replying to myself: It turns out that all is not what it seems. Let's try again: >>> (-1)**0.5 Traceback (most recent call last): File "", line 1, in ValueError: negative number cannot be raised to a fractional power So, to revise my answer, for math.pow(x,y) or x**y, python will refuse negative values of x. This might not be mathematically perfect, but you get what you pay for, I guess. Furthermore, python evaluates "-x**y" as "-(x**y)" which is why it seemed to give correct answers. -- John. From katcipis at inf.ufsc.br Mon Apr 21 05:31:24 2008 From: katcipis at inf.ufsc.br (Tiago Katcipis) Date: Mon, 21 Apr 2008 00:31:24 -0300 Subject: [Tutor] Little problem with math module In-Reply-To: <480BF07B.80300@inf.ufsc.br> References: <480BF07B.80300@inf.ufsc.br> Message-ID: <480C0A8C.3000102@inf.ufsc.br> ops, now i realize the mistake i was making. Thanks for the help people Tiago Katcipis escreveu: > im not understanding why is this a problem...i have this simple function > > def newton_divergente(x): > return math.pow(x, 1.0/3.0) > > but when x = -20 it returns this error > > return math.pow(x, 1.0/3.0) > ValueError: math domain error > > but why is that? is it impossible to calculate -20 ^ (1/3) ? > > here on my calculator i get the result -6,666666667, but python seens to > dont now the answer, why? am i doing something wrong? =/ > > thanks to everyone who tries do help > > best regards > > katcipis > > From katcipis at inf.ufsc.br Mon Apr 21 05:42:13 2008 From: katcipis at inf.ufsc.br (Tiago Katcipis) Date: Mon, 21 Apr 2008 00:42:13 -0300 Subject: [Tutor] Little problem with math module In-Reply-To: <480BF07B.80300@inf.ufsc.br> References: <480BF07B.80300@inf.ufsc.br> Message-ID: <480C0D15.307@inf.ufsc.br> well i made a mistake again :P. i have the function x ^ 1/3, i first remembered that negative numbers do not have a square, but in this case negative numbers are ok...because it aint 1/2 ...its 1/3. Can anyone give a hint of how i can calculate it without using pow ou **? none of them work properly Tiago Katcipis escreveu: > im not understanding why is this a problem...i have this simple function > > def newton_divergente(x): > return math.pow(x, 1.0/3.0) > > but when x = -20 it returns this error > > return math.pow(x, 1.0/3.0) > ValueError: math domain error > > but why is that? is it impossible to calculate -20 ^ (1/3) ? > > here on my calculator i get the result -6,666666667, but python seens to > dont now the answer, why? am i doing something wrong? =/ > > thanks to everyone who tries do help > > best regards > > katcipis > > From alan.gauld at btinternet.com Mon Apr 21 09:07:10 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 21 Apr 2008 08:07:10 +0100 Subject: [Tutor] Little problem with math module References: <480BF07B.80300@inf.ufsc.br> Message-ID: "Tiago Katcipis" wrote > def newton_divergente(x): > return math.pow(x, 1.0/3.0) > > but when x = -20 it returns this error > > return math.pow(x, 1.0/3.0) > ValueError: math domain error > > but why is that? is it impossible to calculate -20 ^ (1/3) ? It may be your use of the pow() function: >>> pow(20, 0.3333333) 2.7144173455393048 >>> pow(-20, 0.3333333) Traceback (most recent call last): File "", line 1, in ValueError: negative number cannot be raised to a fractional power >>> -20**0.3333333 -2.7144173455393048 >>> So the exponentiation operator seems happy but pow isn't. Very strange and potentially a bug in pow()? Unless someone knows a reason for it? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ryandmo at gmail.com Mon Apr 21 09:39:33 2008 From: ryandmo at gmail.com (ryan d'mello) Date: Mon, 21 Apr 2008 13:09:33 +0530 Subject: [Tutor] Python WSDL Generation Tools Message-ID: <5d38c3430804210039u73c68ed3oa7fdace161d15271@mail.gmail.com> Hi all, I am using SOAPpy for generating web services .I have also written a client in python for accessing that web service ,and it works fine.Now when i try to make a java client to access the web service created in python ,the java client ask me for a wsdl file which is not present . So i want to know if there is any way in which i can generate the wsdl file from existing python module. thanks in advance.any help will be appreciated. regards. Joseph. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080421/aeb07c86/attachment.htm From gallo.j at gmail.com Mon Apr 21 10:04:48 2008 From: gallo.j at gmail.com (joe gallo) Date: Mon, 21 Apr 2008 01:04:48 -0700 Subject: [Tutor] Little problem with math module In-Reply-To: References: <480BF07B.80300@inf.ufsc.br> Message-ID: <4b6381420804210104p2fc6bbdjc2601f0b02e38538@mail.gmail.com> On Mon, Apr 21, 2008 at 12:07 AM, Alan Gauld wrote: > > >>> pow(20, 0.3333333) > 2.7144173455393048 > >>> pow(-20, 0.3333333) > Traceback (most recent call last): > File "", line 1, in > ValueError: negative number cannot be raised to a fractional power > >>> -20**0.3333333 > -2.7144173455393048 > >>> > > So the exponentiation operator seems happy but pow isn't. > > Very strange and potentially a bug in pow()? > Unless someone knows a reason for it? I think you're confusing the order of operations. math.pow(-20, (1.0/3.0)) and -20**(1.0/3.0) are not equivalent Whereas, as john mentioned, -20**(1.0/3.0) is actually -(20**(1.0/3.0)), math.pow(-20, (1.0/3.0)) is (-20)**(1.0/3.0) The behavior of ** is appropriate since http://docs.python.org/ref/summary.html shows that exponentiation has higher precedence over positive, negative. Also, I found this from http://www.python.org/download/releases/2.0/: *Raise ZeroDivisionError when raising zero to a negative number, e.g. 0.0 ** > -2.0. Note that math.pow is unrelated to the builtin power operator and the > result of math.pow(0.0, -2.0) will vary by platform. On Linux, it raises a > ValueError.* which is related to why some people would get nan and others a ValueError. And, just to clarify (although i doubt there was any confusion over it), -20**(1/3) = -1 * (20**0) = -1 due to integer division magic. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080421/1547f449/attachment.htm From kent37 at tds.net Mon Apr 21 12:14:13 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 21 Apr 2008 06:14:13 -0400 Subject: [Tutor] Python WSDL Generation Tools In-Reply-To: <5d38c3430804210039u73c68ed3oa7fdace161d15271@mail.gmail.com> References: <5d38c3430804210039u73c68ed3oa7fdace161d15271@mail.gmail.com> Message-ID: <480C68F5.6060602@tds.net> ryan d'mello wrote: > Hi all, > > I am using SOAPpy for generating web services .I have also written a > client in python for accessing that web service ,and it works fine.Now > when i try to make a java client to access the web service created in > python ,the java client ask me for a wsdl file which is not present . > > So i want to know if there is any way in which i can generate the wsdl > file from existing python module. I found this: http://osdir.com/ml/python.pywebsvcs.general/2006-07/msg00015.html I seems to require that you specify parameter types in the docstrings to the methods you expose. Kent From sanelson at gmail.com Mon Apr 21 14:35:49 2008 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Mon, 21 Apr 2008 13:35:49 +0100 Subject: [Tutor] HTML Parsing Message-ID: Hi, I want to write a little script that parses an apache mod_status page. I want it to return simple the number of page requests a second and the number of connections. It seems this is very complicated... I can do it in a shell one-liner: curl 10.1.2.201/server-status 2>&1 | grep -i request | grep dt | { IFS='> ' read _ rps _; IFS='> ' read _ currRequests _ _ _ _ idleWorkers _; echo $rps $currRequests $idleWorkers ; } But that's horrid. So is: $ eval `printf '
3 requests currently being processed, 17 idle workers
\n
2.82 requests/sec - 28.1 kB/second - 10.0 kB/request
\n' | sed -nr '/
/ { N; s@
([0-9]*)[^,]*,([0-9]*).*
([0-9.]*).*@workers=$((\1+\2));requests=\3 at p; }'` $ echo "workers: $workers reqs/secs $requests" workers: 20 reqs/sec 2.82 The page looks like this: Apache Status

Apache Server Status for 10.1.2.201

Server Version: Apache/2.0.46 (Red Hat)
Server Built: Aug 1 2006 09:25:45

Current Time: Monday, 21-Apr-2008 14:29:44 BST
Restart Time: Monday, 21-Apr-2008 13:32:46 BST
Parent Server Generation: 0
Server uptime: 56 minutes 58 seconds
Total accesses: 10661 - Total Traffic: 101.5 MB
CPU Usage: u6.03 s2.15 cu0 cs0 - .239% CPU load
3.12 requests/sec - 30.4 kB/second - 9.7 kB/request
9 requests currently being processed, 11 idle workers
How can/should I do this? S. From andreas at kostyrka.org Mon Apr 21 15:34:00 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 21 Apr 2008 15:34:00 +0200 Subject: [Tutor] HTML Parsing In-Reply-To: References: Message-ID: <1208784840.14651.2.camel@andi-lap.lan> As usual there are a number of ways. But I basically see two steps here: 1.) capture all dt elements. If you want to stick with the standard library, htmllib would be the module. Else you can use e.g. BeautifulSoup or something comparable. 2.) Check all dt contents either via regex, or with a .startswith and string manipulations. Andreas Am Montag, den 21.04.2008, 13:35 +0100 schrieb Stephen Nelson-Smith: > Hi, > > I want to write a little script that parses an apache mod_status page. > > I want it to return simple the number of page requests a second and > the number of connections. > > It seems this is very complicated... I can do it in a shell one-liner: > > curl 10.1.2.201/server-status 2>&1 | grep -i request | grep dt | { > IFS='> ' read _ rps _; IFS='> ' read _ currRequests _ _ _ _ > idleWorkers _; echo $rps $currRequests $idleWorkers ; } > > But that's horrid. > > So is: > > $ eval `printf '
3 requests currently being processed, 17 idle > workers
\n
2.82 requests/sec - 28.1 kB/second - 10.0 > kB/request
\n' | sed -nr '/
/ { N; > s@
([0-9]*)[^,]*,([0-9]*).*
([0-9.]*).*@workers=$((\1+\2));requests=\3 at p; > }'` > $ echo "workers: $workers reqs/secs $requests" > workers: 20 reqs/sec 2.82 > > The page looks like this: > > > > Apache Status > >

Apache Server Status for 10.1.2.201

> >
Server Version: Apache/2.0.46 (Red Hat)
>
Server Built: Aug 1 2006 09:25:45 >

>
Current Time: Monday, 21-Apr-2008 14:29:44 BST
>
Restart Time: Monday, 21-Apr-2008 13:32:46 BST
>
Parent Server Generation: 0
>
Server uptime: 56 minutes 58 seconds
>
Total accesses: 10661 - Total Traffic: 101.5 MB
>
CPU Usage: u6.03 s2.15 cu0 cs0 - .239% CPU load
>
3.12 requests/sec - 30.4 kB/second - 9.7 kB/request
>
9 requests currently being processed, 11 idle workers
> > > How can/should I do this? > > S. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080421/b22cca84/attachment.pgp From sanelson at gmail.com Mon Apr 21 15:40:09 2008 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Mon, 21 Apr 2008 14:40:09 +0100 Subject: [Tutor] HTML Parsing In-Reply-To: <1208784840.14651.2.camel@andi-lap.lan> References: <1208784840.14651.2.camel@andi-lap.lan> Message-ID: On 4/21/08, Andreas Kostyrka wrote: > As usual there are a number of ways. > > But I basically see two steps here: > > 1.) capture all dt elements. If you want to stick with the standard > library, htmllib would be the module. Else you can use e.g. > BeautifulSoup or something comparable. I want to stick with standard library. How do you capture
elements? S. From andreas at kostyrka.org Mon Apr 21 16:19:15 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 21 Apr 2008 16:19:15 +0200 Subject: [Tutor] HTML Parsing In-Reply-To: References: <1208784840.14651.2.camel@andi-lap.lan> Message-ID: <1208787555.14651.5.camel@andi-lap.lan> Just from memory, you need to subclass the HTMLParser class, and provide start_dt and end_dt methods, plus one to capture the text inbetween. Read the docs on htmllib (www.python.org | Documentation | module docs), and see if you can manage if not, come back with questions ;) Andreas Am Montag, den 21.04.2008, 14:40 +0100 schrieb Stephen Nelson-Smith: > On 4/21/08, Andreas Kostyrka wrote: > > As usual there are a number of ways. > > > > But I basically see two steps here: > > > > 1.) capture all dt elements. If you want to stick with the standard > > library, htmllib would be the module. Else you can use e.g. > > BeautifulSoup or something comparable. > > I want to stick with standard library. > > How do you capture
elements? > > S. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080421/97f94caa/attachment.pgp From muchanek at gmail.com Mon Apr 21 16:30:30 2008 From: muchanek at gmail.com (kinuthia muchane) Date: Mon, 21 Apr 2008 17:30:30 +0300 Subject: [Tutor] Computing factorial... Message-ID: <1208788230.5954.29.camel@www.kinuthia.com> Hi, I wanted to calculate the factorial of a given number without using recursion. I came up with the following code, although it is not very elegant it works. def factorial(*args): product = args[0] for item in args[1:]: product *= item return product number = int(raw_input('Enter value of number to compute factorial ')) seq = range(1,number + 1) if number <= 0: print -1 else: print factorial(*seq) When I change that code a bit to (In fact, this is what I started with, it almost drove me crazy trying to figure out what was wrong!) : def factorial(*args): temp = args[0] for item in args[1:]: product = temp * item return product number = int(raw_input('Enter value of number to compute factorial ')) seq = range(1,number + 1) if number <= 0: print -1 else: print factorial(*seq) ... it just echoes back the number you were prompted to enter. My confusion is, aren't the variables 'temp' and 'product' storing the same value ie "args[0]". So why would they return different values, the one with "temp" giving a wrong answer? Thanks! Kinuthia... From rdm at rcblue.com Mon Apr 21 17:17:15 2008 From: rdm at rcblue.com (Dick Moores) Date: Mon, 21 Apr 2008 08:17:15 -0700 Subject: [Tutor] Little problem with math module In-Reply-To: <5e58f2e40804201940s4f1ff9fdgf6038ec6d8429a83@mail.gmail.co m> References: <480BF07B.80300@inf.ufsc.br> <5e58f2e40804201940s4f1ff9fdgf6038ec6d8429a83@mail.gmail.com> Message-ID: <20080421151933.D949A1E4033@bag.python.org> At 07:40 PM 4/20/2008, John Fouhy wrote: >If you're going to be working with complex numbers, you might be >better off looking at scipy or some other module that provides more >mathematical grunt. Try mpMath () With version 0.7: >>> from mpmath import power, mpf >>> print power(-20,(1.0/3.0)) (1.35720880829745 + 2.3507546124512j) Or, to a precision of, say, 43: >>> mp.dps = 43 >>> print power(-20,(1.0/3.0)) (1.357208808297453347178047801626363199806658 + 2.350754612451197324056065041655768179779947j) Dick Moores ================================ UliPad <>: http://code.google.com/p/ulipad/ From bgailer at gmail.com Mon Apr 21 17:24:06 2008 From: bgailer at gmail.com (bob gailer) Date: Mon, 21 Apr 2008 11:24:06 -0400 Subject: [Tutor] Computing factorial... In-Reply-To: <1208788230.5954.29.camel@www.kinuthia.com> References: <1208788230.5954.29.camel@www.kinuthia.com> Message-ID: <480CB196.3040903@gmail.com> kinuthia muchane wrote: > Hi, > > I wanted to calculate the factorial of a given number without using > recursion. I came up with the following code, although it is not very > elegant it works. > > def factorial(*args): > > product = args[0] > for item in args[1:]: > product *= item > return product > > number = int(raw_input('Enter value of number to compute factorial ')) > seq = range(1,number + 1) > > if number <= 0: > print -1 > > else: > print factorial(*seq) > > When I change that code a bit to (In fact, this is what I started with, > it almost drove me crazy trying to figure out what was wrong!) : > > def factorial(*args): > > temp = args[0] > for item in args[1:]: > product = temp * item > return product > > number = int(raw_input('Enter value of number to compute factorial ')) > seq = range(1,number + 1) > > if number <= 0: > print -1 > > else: > print factorial(*seq) > > ... it just echoes back the number you were prompted to enter. > My confusion is, aren't the variables 'temp' and 'product' storing the > same value ie "args[0]". So why would they return different values, the > one with "temp" giving a wrong answer? > > The program never changes temp. So temp will always be 1. Is that not obvious? Or are you expecting that product and temp both refer to the same object? Which would be true if the object were a mutable such as a list or a dict or a class instance. But is NOT the case for immutables such as numbers and strings. -- Bob Gailer 919-636-4239 Chapel Hill, NC From bgailer at gmail.com Mon Apr 21 17:35:54 2008 From: bgailer at gmail.com (bob gailer) Date: Mon, 21 Apr 2008 11:35:54 -0400 Subject: [Tutor] HTML Parsing In-Reply-To: References: Message-ID: <480CB45A.6000102@gmail.com> Stephen Nelson-Smith wrote: > Hi, > > I want to write a little script that parses an apache mod_status page. > > I want it to return simple the number of page requests a second and > the number of connections. > > It seems this is very complicated... I can do it in a shell one-liner: > > curl 10.1.2.201/server-status 2>&1 | grep -i request | grep dt | { > IFS='> ' read _ rps _; IFS='> ' read _ currRequests _ _ _ _ > idleWorkers _; echo $rps $currRequests $idleWorkers ; } > > But that's horrid. > > So is: > > $ eval `printf '
3 requests currently being processed, 17 idle > workers
\n
2.82 requests/sec - 28.1 kB/second - 10.0 > kB/request
\n' | sed -nr '/
/ { N; > s@
([0-9]*)[^,]*,([0-9]*).*
([0-9.]*).*@workers=$((\1+\2));requests=\3 at p; > }'` > $ echo "workers: $workers reqs/secs $requests" > workers: 20 reqs/sec 2.82 > > The page looks like this: > > > > Apache Status > >

Apache Server Status for 10.1.2.201

> >
Server Version: Apache/2.0.46 (Red Hat)
>
Server Built: Aug 1 2006 09:25:45 >

>
Current Time: Monday, 21-Apr-2008 14:29:44 BST
>
Restart Time: Monday, 21-Apr-2008 13:32:46 BST
>
Parent Server Generation: 0
>
Server uptime: 56 minutes 58 seconds
>
Total accesses: 10661 - Total Traffic: 101.5 MB
>
CPU Usage: u6.03 s2.15 cu0 cs0 - .239% CPU load
>
3.12 requests/sec - 30.4 kB/second - 9.7 kB/request
>
9 requests currently being processed, 11 idle workers
> > > How can/should I do this? > > S. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > I don't know how you get the page HTML, but let's assume each line is in an iterable, named html. It seems very straightforward to code: for lineno, line in enumerate(html): x = line.find("requests/sec") if x >= 0: no_requests_sec = line[3:x] break for lineno, line in enumerate(html[lineno+1:]): x = line.find("requests currently being processed") if x >= 0: no_connections = line[3:x] That makes certain assumptions about the file format, such as the matching text and knowing that connections follows requests/sec, and does not assume that connections is the first line after requests/sec. -- Bob Gailer 919-636-4239 Chapel Hill, NC From Mike.Hansen at atmel.com Mon Apr 21 17:52:40 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Mon, 21 Apr 2008 09:52:40 -0600 Subject: [Tutor] Hoping to benefit from someone's experience... In-Reply-To: <40af687b0804191245y24c1f76xc3f46bdae85e0db1@mail.gmail.com> References: <40af687b0804151903s5577b339gb92bbc92dae8a899@mail.gmail.com><1208312323.15504.1248115007@webmail.messagingengine.com><40af687b0804152031h6c9ad724ma50ef0d7ce809531@mail.gmail.com><4805779D.6090202@gmail.com><40af687b0804152115x77f083d3o55a8b3777e4b5574@mail.gmail.com><40af687b0804161048o63517b61y983734e68bb1b3ca@mail.gmail.com><4806405C.6050002@tds.net> <480646E9.9060607@san-dc.com> <40af687b0804191245y24c1f76xc3f46bdae85e0db1@mail.gmail.com> Message-ID: <7941B2693F32294AAF16C26B679A258D01EE9BBB@csomb01.corp.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Marc Tompkins > Sent: Saturday, April 19, 2008 1:46 PM > To: tutor at python.org > Subject: Re: [Tutor] Hoping to benefit from someone's experience... > > > As you might expect, most of the time is spent in Word. It > would probably be faster if I set Visible = False, but for > some reason the macro fails (silently) when I do that, so I > just minimize Word instead to cut down on screen refreshes. > Also, drive U is a Samba share, so there's network latency to > take into account. Even so, 10,231 files took less than 15 > minutes to convert, which I can live with. > This isn't Python related, but it might help those who do Word macros. I think you can use Applications.ScreenUpdating = False at the beginning of your macro. The macro will run a bit faster. It's essentially hiding all the updating to the document(s). You should set it back at the end of your macro: Application.ScreenUpdating = True. Mike From pylinuxian at gmail.com Mon Apr 21 18:02:33 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Mon, 21 Apr 2008 16:02:33 +0000 Subject: [Tutor] HTML Parsing In-Reply-To: <480CB45A.6000102@gmail.com> References: <480CB45A.6000102@gmail.com> Message-ID: Another horrid solution > #!/usr/bin/python > # line number does not change so we use that # the data we're looking for does not have a (unique) close tag (htmllib > ????) > > import re, urllib2 > file=urllib2.urlopen('http://10.1.2.201/server-status') > n=0 > for line in file: > n=n+1 > if n==16: > print re.sub('requests.*','',line)[4:].strip() > elif n==17: > print re.sub('requests.*','',line)[4:].strip() > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080421/eda74bce/attachment.htm From rdm at rcblue.com Mon Apr 21 18:12:23 2008 From: rdm at rcblue.com (Dick Moores) Date: Mon, 21 Apr 2008 09:12:23 -0700 Subject: [Tutor] Little problem with math module In-Reply-To: <20080421151933.D949A1E4033@bag.python.org> References: <480BF07B.80300@inf.ufsc.br> <5e58f2e40804201940s4f1ff9fdgf6038ec6d8429a83@mail.gmail.com> <20080421151933.D949A1E4033@bag.python.org> Message-ID: <20080421161311.9B7A91E400D@bag.python.org> At 08:17 AM 4/21/2008, Dick Moores wrote: >At 07:40 PM 4/20/2008, John Fouhy wrote: > >If you're going to be working with complex numbers, you might be > >better off looking at scipy or some other module that provides more > >mathematical grunt. > >Try mpMath () > >With version 0.7: > > >>> from mpmath import power, mpf > >>> print power(-20,(1.0/3.0)) >(1.35720880829745 + 2.3507546124512j) I needn't have imported mpf >>> from mpmath import power >>> print power(-20,(1.0/3.0)) (1.35720880829745 + 2.3507546124512j) Dick >Or, to a precision of, say, 43: > > >>> mp.dps = 43 > >>> print power(-20,(1.0/3.0)) >(1.357208808297453347178047801626363199806658 + >2.350754612451197324056065041655768179779947j) > >Dick Moores ================================ UliPad <>: http://code.google.com/p/ulipad/ From bgailer at gmail.com Mon Apr 21 19:07:05 2008 From: bgailer at gmail.com (bob gailer) Date: Mon, 21 Apr 2008 13:07:05 -0400 Subject: [Tutor] HTML Parsing In-Reply-To: References: <480CB45A.6000102@gmail.com> Message-ID: <480CC9B9.7000704@gmail.com> Stephen Nelson-Smith wrote: > Hi, > > >> for lineno, line in enumerate(html): >> > > -Epython2.2hasnoenumerate() > > I used enumerate for a marginal (unproven) performance enhancement. > Can we code around this? for lineno in range(len(html)): x = html[lineno].find("requests/sec") if x >= 0: no_requests_sec = html[lineno].[3:x] break for lineno in range(lineno, len(html)): x = html[lineno].find("requests currently being processed") if x >= 0: no_connections = html[lineno][3:x] break -- Bob Gailer 919-636-4239 Chapel Hill, NC From jeff at drinktomi.com Mon Apr 21 19:26:06 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Mon, 21 Apr 2008 10:26:06 -0700 Subject: [Tutor] Hoping to benefit from someone's experience... In-Reply-To: References: <40af687b0804151903s5577b339gb92bbc92dae8a899@mail.gmail.com><1208312323.15504.1248115007@webmail.messagingengine.com><40af687b0804152031h6c9ad724ma50ef0d7ce809531@mail.gmail.com><4805779D.6090202@gmail.com> <40af687b0804152115x77f083d3o55a8b3777e4b5574@mail.gmail.com> Message-ID: <448BC301-67A1-4FFA-BFDF-C3633421E5D6@drinktomi.com> On Apr 15, 2008, at 11:33 PM, Alan Gauld wrote: > Have you considered driving Word instead of OOo? > That way you leave the documents in their original format > and make the mods using COM from Python. I've used this approach before, and I whole heartedly suggest that you look into it. The Win32 extensions for Python make talking to office applications via COM nearly effortless. -jeff From sanelson at gmail.com Mon Apr 21 17:50:27 2008 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Mon, 21 Apr 2008 16:50:27 +0100 Subject: [Tutor] HTML Parsing In-Reply-To: <480CB45A.6000102@gmail.com> References: <480CB45A.6000102@gmail.com> Message-ID: Hi, > for lineno, line in enumerate(html): -Epython2.2hasnoenumerate() Can we code around this? > x = line.find("requests/sec") > if x >= 0: > no_requests_sec = line[3:x] > break > for lineno, line in enumerate(html[lineno+1:]): > x = line.find("requests currently being processed") > if x >= 0: > no_connections = line[3:x] That all looks ok. S. From jeff at drinktomi.com Mon Apr 21 19:35:09 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Mon, 21 Apr 2008 10:35:09 -0700 Subject: [Tutor] HTML Parsing In-Reply-To: References: <1208784840.14651.2.camel@andi-lap.lan> Message-ID: On Apr 21, 2008, at 6:40 AM, Stephen Nelson-Smith wrote: > On 4/21/08, Andreas Kostyrka wrote: > I want to stick with standard library. > > How do you capture
elements? from xml.etree import ElementTree document = """ foo and bar
foo
bar
""" dt_elements = ElementTree.XML(document).findall('dt') -jeff From alan.gauld at btinternet.com Mon Apr 21 19:50:51 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 21 Apr 2008 17:50:51 +0000 (GMT) Subject: [Tutor] Little problem with math module Message-ID: <88445.90218.qm@web86709.mail.ukl.yahoo.com> On Mon, Apr 21, 2008 at 12:07 AM, Alan Gauld wrote: >>> pow(-20, 0.3333333) Traceback (most recent call last): File "", line 1, in ValueError: negative number cannot be raised to a fractional power >>> -20**0.3333333 -2.7144173455393048 >>> I think you're confusing the order of operations. math.pow(-20, (1.0/3.0)) and -20**(1.0/3.0) are not equivalent Whereas, as john mentioned, -20**(1.0/3.0) is actually -(20**(1.0/3.0)), math.pow(-20, (1.0/3.0)) is (-20)**(1.0/3.0) Yes, quite correct, I posted my reply before the others had posted theirs although it showed up afterwards(at least on gmane) > exponentiation has higher precedence over positive, negative. Yep, I hadn't realized that, although it does make sense when you think about it :-) > Note that math.pow is unrelated to the builtin power operator > and the result of math.pow(0.0, -2.0) will vary by platform. This is interesting, I had assumed that pow simply called **. Does anyone know why they made it different? Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080421/c7947b40/attachment.htm From andreas at kostyrka.org Mon Apr 21 20:10:25 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 21 Apr 2008 20:10:25 +0200 Subject: [Tutor] HTML Parsing In-Reply-To: References: <1208784840.14651.2.camel@andi-lap.lan> Message-ID: <1208801425.14651.26.camel@andi-lap.lan> If you have a correct XML document. In practice this is rather a big IF. Andreas Am Montag, den 21.04.2008, 10:35 -0700 schrieb Jeff Younker: > On Apr 21, 2008, at 6:40 AM, Stephen Nelson-Smith wrote: > > > On 4/21/08, Andreas Kostyrka wrote: > > I want to stick with standard library. > > > > How do you capture
elements? > > > from xml.etree import ElementTree > > document = """ > > > foo and bar > > >
foo
>
bar
> > > """ > > dt_elements = ElementTree.XML(document).findall('dt') > > -jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080421/0572719d/attachment.pgp From katcipis at inf.ufsc.br Mon Apr 21 20:25:08 2008 From: katcipis at inf.ufsc.br (Tiago Katcipis) Date: Mon, 21 Apr 2008 15:25:08 -0300 Subject: [Tutor] Little problem with math module In-Reply-To: <88445.90218.qm@web86709.mail.ukl.yahoo.com> References: <88445.90218.qm@web86709.mail.ukl.yahoo.com> Message-ID: <480CDC04.2080108@inf.ufsc.br> i will change the subject but this one is interessenting. i have this test code import funcoes import bissecao import falsa_posicao import falsa_posicaom import newton_simples import math INTERVALO = [0,1] ERRO_DET = math.pow(10, -16) ITER = funcoes.calcular_num_iteracoes(INTERVALO[0], INTERVALO[1], ERRO_DET) print 'Por bissecao: ' print 'Numero de iteracoes necessarios = ', ITER resultado, erro = bissecao.obter_alpha(INTERVALO, funcoes.convergente_simples, ERRO_DET, ITER) print 'Alpha = ', resultado print 'Erro = ', erro print '' and i have this function on bissecao import math import funcoes def obter_alpha(intervalo, funcao, erro_passado = 0.0, limite = 20): a = intervalo[0] b = intervalo[1] fa = funcao(a) fb = funcao(b) erro = erro_passado * 10.0 contador = 0 xm = 0.0 if( (fa * fb) < 0 ): while(contador < limite): contador += 1 xm = (a + b) / 2.0 fm = funcao(xm) if(fm == 0): return xm, 0.0 if( (fm * fa) < 0.0): b = xm else: a = xm erro = funcoes.calcular_erro(a, b) if(erro < erro_passado): return xm, erro print 'Iteracao ', contador, ' alpha = ', xm print 'Erro ', contador, ' = ', erro return xm, erro else: print 'Funcao nao eh continua' my problem is, INSIDE the funcion...the variable erro is correct, but when i return it to the test...and the test prints it....comes out 0.0. Its disturbing...i didnt found a way of solving this. the out of the test is like this Erro 50 = 1.50914019446e-15 Iteracao 51 alpha = 0.588532743982 Erro 51 = 7.54570097231e-16 Alpha = 0.588532743982 Erro = 0.0 it would print more things but it is desnecessary, inside the function erro has a value like 7.54570097231e-16, but when it is returned it goes out like 0.0. What can i do to prevent this from happening? the whole thing is at https://svn.inf.ufsc.br/katcipis/python/trunk/Funcoes/src/ just log as user "guest" without a password ALAN GAULD escreveu: > On Mon, Apr 21, 2008 at 12:07 AM, Alan Gauld > > wrote: > > > >>> pow(-20, 0.3333333) > Traceback (most recent call last): > File "", line 1, in > ValueError: negative number cannot be raised to a fractional power > >>> -20**0.3333333 > -2.7144173455393048 > >>> > > I think you're confusing the order of operations. > > math.pow(-20, (1.0/3.0)) and -20**(1.0/3.0) are not equivalent > > Whereas, as john mentioned, -20**(1.0/3.0) is actually > -(20**(1.0/3.0)), math.pow(-20, (1.0/3.0)) is (-20)**(1.0/3.0) > > Yes, quite correct, I posted my reply before the others had > posted theirs although it showed up afterwards(at least on gmane) > > > exponentiation has higher precedence over positive, negative. > > Yep, I hadn't realized that, although it does make sense when you > think about it :-) > > /> Note that math.pow is unrelated to the builtin power operator / > /> and the result of math.pow(0.0, -2.0) will vary by platform. / > > /This is interesting, I had assumed that pow simply called **./ > Does anyone know why they made it different? > > Alan G. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From andreas at kostyrka.org Mon Apr 21 20:29:43 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 21 Apr 2008 20:29:43 +0200 Subject: [Tutor] HTML Parsing In-Reply-To: References: <1208784840.14651.2.camel@andi-lap.lan> <1208787555.14651.5.camel@andi-lap.lan> Message-ID: <1208802583.14651.30.camel@andi-lap.lan> eeck. Not that I advocate parsing files by line, but if you need to do it: lines = list(file)[16:] or lines_iter = iter(file) zip(lines_iter, xrange(16)) for line in lines_iter: Andreas Am Montag, den 21.04.2008, 14:42 +0000 schrieb linuxian iandsd: > Another horrid solution > > #!/usr/bin/python > # line number does not change so we use that > # the data we're looking for does not have a (unique) close > tag (htmllib ????) > > import re, urllib2 > file=urllib2.urlopen('http://10.1.2.201/server-status') > n=0 > for line in file: > n=n+1 > if n==16: > print re.sub('requests.*','',line)[4:].strip() > elif n==17: > print re.sub('requests.*','',line)[4:].strip() > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20080421/23e53f62/attachment.pgp From sanhitam at yahoo.com Mon Apr 21 20:40:22 2008 From: sanhitam at yahoo.com (Sanhita Mallick) Date: Mon, 21 Apr 2008 11:40:22 -0700 (PDT) Subject: [Tutor] Arguments ina separate file Message-ID: <147800.97005.qm@web55610.mail.re4.yahoo.com> Hi. I have a big list of arguments, which I would like to keep in a separate file. How do I pass arguments that are in a separate file? Thanks. San From timmichelsen at gmx-topmail.de Mon Apr 21 20:58:04 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Mon, 21 Apr 2008 20:58:04 +0200 Subject: [Tutor] Arguments ina separate file In-Reply-To: <147800.97005.qm@web55610.mail.re4.yahoo.com> References: <147800.97005.qm@web55610.mail.re4.yahoo.com> Message-ID: > I have a big list of arguments, which I would like to > keep in a separate file. How do I pass arguments that > are in a separate file? do you mean like setting? do something like this write them in the file myargs.py import myargs call_my_function(myargs.argument1, myargs.argument2) see also my recent thread on settings called "setting program configuration for all files and modules of a program" Regards, Timmie From pylinuxian at gmail.com Mon Apr 21 21:46:23 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Mon, 21 Apr 2008 19:46:23 +0000 Subject: [Tutor] Arguments ina separate file In-Reply-To: References: <147800.97005.qm@web55610.mail.re4.yahoo.com> Message-ID: > > import myargs this one is clever -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080421/e86e0b7f/attachment.htm From timmichelsen at gmx-topmail.de Mon Apr 21 23:21:18 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Mon, 21 Apr 2008 23:21:18 +0200 Subject: [Tutor] Arguments ina separate file In-Reply-To: References: <147800.97005.qm@web55610.mail.re4.yahoo.com> Message-ID: > import myargs > > > this one is clever just see here: setting program configuration for all files and modules of a program http://permalink.gmane.org/gmane.comp.python.tutor/47549 and the respective answers. Good luck. From kent37 at tds.net Tue Apr 22 00:51:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 21 Apr 2008 18:51:36 -0400 Subject: [Tutor] HTML Parsing In-Reply-To: References: Message-ID: <480D1A78.8000209@tds.net> Stephen Nelson-Smith wrote: > Hi, > > I want to write a little script that parses an apache mod_status page. > > I want it to return simple the number of page requests a second and > the number of connections. > The page looks like this: > > > > Apache Status > >

Apache Server Status for 10.1.2.201

> >
Server Version: Apache/2.0.46 (Red Hat)
>
Server Built: Aug 1 2006 09:25:45 >

>
Current Time: Monday, 21-Apr-2008 14:29:44 BST
>
Restart Time: Monday, 21-Apr-2008 13:32:46 BST
>
Parent Server Generation: 0
>
Server uptime: 56 minutes 58 seconds
>
Total accesses: 10661 - Total Traffic: 101.5 MB
>
CPU Usage: u6.03 s2.15 cu0 cs0 - .239% CPU load
>
3.12 requests/sec - 30.4 kB/second - 9.7 kB/request
>
9 requests currently being processed, 11 idle workers
> > > How can/should I do this? For data this predictable, simple regex matching will probably work fine. If 'data' is the above text, then this seems to get what you want: In [17]: import re In [18]: re.search(r'[\d.]+ requests/sec', data).group() Out[18]: '3.12 requests/sec' In [19]: re.search(r'\d+ requests currently being processed', data).group() Out[19]: '9 requests currently being processed' Kent From python at bdurham.com Tue Apr 22 01:14:31 2008 From: python at bdurham.com (python at bdurham.com) Date: Mon, 21 Apr 2008 19:14:31 -0400 Subject: [Tutor] Why next vs. __next__ ? In-Reply-To: <480d016e$1@news.mel.dft.com.au> References: <87wsmrdka8.fsf@mulj.homelinux.net> <480d016e$1@news.mel.dft.com.au> Message-ID: <1208819671.24431.1249125487@webmail.messagingengine.com> Is there a reason why generators have a special method named "next" vs. "__next__"? All other Python's special names have the double underscore prefix/suffix. http://docs.python.org/ref/specialnames.html Are there other special names like "next" that don't have the double underscore delimiters? Thanks! Malcolm From mlangford.cs03 at gtalumni.org Tue Apr 22 01:23:13 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Mon, 21 Apr 2008 19:23:13 -0400 Subject: [Tutor] Hoping to benefit from someone's experience... In-Reply-To: <40af687b0804161048o63517b61y983734e68bb1b3ca@mail.gmail.com> References: <40af687b0804151903s5577b339gb92bbc92dae8a899@mail.gmail.com> <1208312323.15504.1248115007@webmail.messagingengine.com> <40af687b0804152031h6c9ad724ma50ef0d7ce809531@mail.gmail.com> <4805779D.6090202@gmail.com> <40af687b0804152115x77f083d3o55a8b3777e4b5574@mail.gmail.com> <40af687b0804161048o63517b61y983734e68bb1b3ca@mail.gmail.com> Message-ID: <82b4f5810804211623u7354bd76g43820e1fb11b2980@mail.gmail.com> Office VBA is pretty much the same objects as the Office COM object. You use the same for both, so probably can do it in python very close to the same speed as vba --Michael On Wed, Apr 16, 2008 at 1:48 PM, Marc Tompkins wrote: > Again with the forgetting to cc the list... > On Tue, Apr 15, 2008 at 11:33 PM, Alan Gauld > wrote: > > > Alternatively learn enough VBScript to do it all in Word itself.... > > > That's exactly what I'm doing now. After mentioning in a previous email > that formatting is important, I took a closer look at the documents that OO > had converted... and they weren't as good as I thought at first. No > disgrace to OO; the fact that anybody outside of Microsoft has ever managed > to make even a little bit of sense out of the .doc format is a testimony to > human ingenuity and stubbornness - but it's just not good enough. So, > despite my enthusiasm for Python and the fact that VBScript repulses me, I > think I need to start fresh and do it the Redmond way. If I were building > something for long-term use rather than a one-time conversion, I would > figure out how to drive Word from Python, but under the circumstances I'll > hack something quick and dirty in VBS. (Does anyone remember VBA?) > > > > It's funny - years ago I used to use Visual Studio and _enjoy_ it. I'm > spoiled now, I guess. By the way, there was a recent XKCD that I liked: > http://xkcd.com/409/ > > > -- > www.fsrtechnologies.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Tue Apr 22 02:33:56 2008 From: python at bdurham.com (python at bdurham.com) Date: Mon, 21 Apr 2008 20:33:56 -0400 Subject: [Tutor] When to use % vs. locale.format()? Message-ID: <1208824436.4555.1249135079@webmail.messagingengine.com> Are there any best practices guidelines that discuss when one should use % vs. locale.format? The locale.format() seems closer to the new new Python 3.0 print-as-a-function vs. statement ... with the added benefit of localized output. Malcolm From keridee at jayco.net Wed Apr 23 05:14:03 2008 From: keridee at jayco.net (tiger12506) Date: Tue, 22 Apr 2008 22:14:03 -0500 Subject: [Tutor] Little problem with math module References: <88445.90218.qm@web86709.mail.ukl.yahoo.com> <480CDC04.2080108@inf.ufsc.br> Message-ID: <00a101c8a4f0$15d53620$0702a8c0@home> > my problem is, INSIDE the funcion...the variable erro is correct, but > when i return it to the test...and the test prints it....comes out 0.0. > Its disturbing...i didnt found a way of solving this. err is defined in the function so it thinks it's a local variable. You can set it to change only the global variable by putting global err as the line right after your function def. From kent37 at tds.net Tue Apr 22 04:15:30 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 21 Apr 2008 22:15:30 -0400 Subject: [Tutor] Why next vs. __next__ ? In-Reply-To: <1208819671.24431.1249125487@webmail.messagingengine.com> References: <87wsmrdka8.fsf@mulj.homelinux.net> <480d016e$1@news.mel.dft.com.au> <1208819671.24431.1249125487@webmail.messagingengine.com> Message-ID: <480D4A42.9020101@tds.net> python at bdurham.com wrote: > Is there a reason why generators have a special method named "next" vs. > "__next__"? > > All other Python's special names have the double underscore > prefix/suffix. > http://docs.python.org/ref/specialnames.html It's actually considered a mistake. The original rationale is spelled out in PEP 234 - see the Resolved Issues section: http://www.python.org/dev/peps/pep-0234/ It is being renamed to __next__() in Python 3.0 and there will be a builtin next() method that calls it. Instead of iterator.next() you will call next(iterator). http://www.python.org/dev/peps/pep-3114/ Kent From kent37 at tds.net Tue Apr 22 04:17:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 21 Apr 2008 22:17:14 -0400 Subject: [Tutor] When to use % vs. locale.format()? In-Reply-To: <1208824436.4555.1249135079@webmail.messagingengine.com> References: <1208824436.4555.1249135079@webmail.messagingengine.com> Message-ID: <480D4AAA.7060205@tds.net> python at bdurham.com wrote: > Are there any best practices guidelines that discuss when one should use > % vs. locale.format? You might want to try comp.lang.python if you don't get an answer here. Kent From keridee at jayco.net Wed Apr 23 05:23:10 2008 From: keridee at jayco.net (tiger12506) Date: Tue, 22 Apr 2008 22:23:10 -0500 Subject: [Tutor] Why next vs. __next__ ? References: <87wsmrdka8.fsf@mulj.homelinux.net><480d016e$1@news.mel.dft.com.au><1208819671.24431.1249125487@webmail.messagingengine.com> <480D4A42.9020101@tds.net> Message-ID: <00d101c8a4f1$5b524110$0702a8c0@home> > It's actually considered a mistake. > > The original rationale is spelled out in PEP 234 - see the Resolved Issues > section: > http://www.python.org/dev/peps/pep-0234/ > > It is being renamed to __next__() in Python 3.0 and there will be a > builtin next() method that calls it. Instead of iterator.next() you will It's not a method if it's global to the namespace. Or so I've been told. A built-in function. > call next(iterator). > http://www.python.org/dev/peps/pep-3114/ Which makes a lot more sense because then it follows the convention of: int(MyObject) == MyObject.__int__() str(MyObject) == MyObject.__str__() float(MyObject) == MyObject.__float__() etc. like all of the other special method names From kent37 at tds.net Tue Apr 22 04:33:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 21 Apr 2008 22:33:14 -0400 Subject: [Tutor] Little problem with math module In-Reply-To: <00a101c8a4f0$15d53620$0702a8c0@home> References: <88445.90218.qm@web86709.mail.ukl.yahoo.com> <480CDC04.2080108@inf.ufsc.br> <00a101c8a4f0$15d53620$0702a8c0@home> Message-ID: <480D4E6A.3010501@tds.net> tiger12506 wrote: >> my problem is, INSIDE the funcion...the variable erro is correct, but >> when i return it to the test...and the test prints it....comes out 0.0. >> Its disturbing...i didnt found a way of solving this. > > err is defined in the function so it thinks it's a local variable. My reading is that erro is returned from the function and assigned to a 'new' erro at the point of call. You > can set it to change only the global variable by putting > > global err > > as the line right after your function def. No, because the caller is in a different module. Kent From keridee at jayco.net Wed Apr 23 05:38:48 2008 From: keridee at jayco.net (tiger12506) Date: Tue, 22 Apr 2008 22:38:48 -0500 Subject: [Tutor] Little problem with math module References: <88445.90218.qm@web86709.mail.ukl.yahoo.com> <480CDC04.2080108@inf.ufsc.br><00a101c8a4f0$15d53620$0702a8c0@home> <480D4E6A.3010501@tds.net> Message-ID: <000601c8a4f3$8b5598b0$0702a8c0@home> Hmm. I didn't read particularly closely, but it seemed that there were two different versions going on. The first examples more like what he wanted to happen, and the last example what he tried and didn't get to work. Since it's in a different module he can get around it by using global erro and then using modulename.erro when he uses the actual value. ----- Original Message ----- From: "Kent Johnson" Cc: Sent: Monday, April 21, 2008 9:33 PM Subject: Re: [Tutor] Little problem with math module > tiger12506 wrote: >>> my problem is, INSIDE the funcion...the variable erro is correct, but >>> when i return it to the test...and the test prints it....comes out 0.0. >>> Its disturbing...i didnt found a way of solving this. >> >> err is defined in the function so it thinks it's a local variable. > > My reading is that erro is returned from the function and assigned to a > 'new' erro at the point of call. > > You >> can set it to change only the global variable by putting >> >> global err >> >> as the line right after your function def. > > No, because the caller is in a different module. > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From wescpy at gmail.com Tue Apr 22 06:35:39 2008 From: wescpy at gmail.com (wesley chun) Date: Mon, 21 Apr 2008 21:35:39 -0700 Subject: [Tutor] Python WSDL Generation Tools In-Reply-To: <5d38c3430804210039u73c68ed3oa7fdace161d15271@mail.gmail.com> References: <5d38c3430804210039u73c68ed3oa7fdace161d15271@mail.gmail.com> Message-ID: <78b3a9580804212135g53925e8djcb5dbd4bd40ad2ba@mail.gmail.com> > I am using SOAPpy for generating web services .I have also written a client > in python for accessing that web service ,and it works fine.Now when i try > to make a java client to access the web service created in python ,the java > client ask me for a wsdl file which is not present . > > So i want to know if there is any way in which i can generate the wsdl file > from existing python module. yes, it appears that such a file is supposed to be available via the server. i'm using SOAPpy as well but only for client stuff. when i connect, i use an invocation like this: proxy = SOAPpy.WSDL.Proxy("https://customer...com/public/SOAP%20Gateway%20files/hsan.wsdl") anyway, you may wish to start looking at various places such as: http://www.diveintopython.org/soap_web_services/wsdl.html http://www.diveintopython.org/soap_web_services/introspection.html http://pywebsvcs.sourceforge.net/apidocs/wstools/ http://pywebsvcs.sourceforge.net/apidocs/SOAPpy/ hope this helps, and let us know what worked for you! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From sanelson at gmail.com Tue Apr 22 10:59:13 2008 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Tue, 22 Apr 2008 09:59:13 +0100 Subject: [Tutor] HTML Parsing In-Reply-To: <480D1A78.8000209@tds.net> References: <480D1A78.8000209@tds.net> Message-ID: Hello, > For data this predictable, simple regex matching will probably work fine. I thought that too... Anyway - here's what I've come up with: #!/usr/bin/python import urllib, sgmllib, re mod_status = urllib.urlopen("http://10.1.2.201/server-status") status_info = mod_status.read() mod_status.close() class StatusParser(sgmllib.SGMLParser): def parse(self, string): self.feed(string) self.close() def __init__(self, verbose=0): sgmllib.SGMLParser.__init__(self, verbose) self.information = [] self.inside_dt_element = False def start_dt(self, attributes): self.inside_dt_element = True def end_dt(self): self.inside_dt_element = False def handle_data(self, data): if self.inside_dt_element: self.information.append(data) def get_data(self): return self.information status_parser = StatusParser() status_parser.parse(status_info) rps_pattern = re.compile( '(\d+\.\d+) requests/sec' ) connections_pattern = re.compile( '(\d+) requests\D*(\d+) idle.*' ) for line in status_parser.get_data(): rps_match = rps_pattern.search( line ) connections_match = connections_pattern.search( line ) if rps_match: rps = float(rps_match.group(1)) elif connections_match: connections = int(connections_match.group(1)) + int(connections_match.group(2)) rps_threshold = 10 connections_threshold = 100 if rps > rps_threshold: print "CRITICAL: %s Requests per second" % rps else: print "OK: %s Requests per second" % rps if connections > connections_threshold: print "CRITICAL: %s Simultaneous Connections" % connections else: print "OK: %s Simultaneous Connections" % connections Comments and criticism please. S. From kent37 at tds.net Tue Apr 22 11:35:49 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 22 Apr 2008 05:35:49 -0400 Subject: [Tutor] HTML Parsing In-Reply-To: References: <480D1A78.8000209@tds.net> Message-ID: <480DB175.7090701@tds.net> Stephen Nelson-Smith wrote: > Comments and criticism please. The SGML parser seems like overkill. Can't you just apply the regexes directly to status_info? If the format may change, or you need to interpret entities, etc then the parser is helpful. In this case I don't see how it is needed. Kent From sanelson at gmail.com Tue Apr 22 12:06:05 2008 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Tue, 22 Apr 2008 11:06:05 +0100 Subject: [Tutor] Sending Mail Message-ID: smtpserver = 'relay.clara.net' RECIPIENTS = ['sanelson at gmail.com'] SENDER = 'alerts at atalanta-systems.com' message = """Subject: HTTPD ALERT: %s requests %s connections Please investigate ASAP.""" % (rps, connections) session = smtplib.SMTP(smtpserver) smtpresult = session.sendmail(SENDER, RECIPIENTS, message) if smtpresult: errstr = "" for recip in smtpresult.keys(): errstr = """Could not delivery mail to: %s Server said: %s %s %s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr) raise smtplib.SMTPException, errstr This sends emails.... But gmail says it came from "unknown sender" I see an envelope-from in the headers. What am I missing? S. From pylinuxian at gmail.com Tue Apr 22 13:12:34 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Tue, 22 Apr 2008 11:12:34 +0000 Subject: [Tutor] Sending Mail In-Reply-To: References: Message-ID: i can send email w/ no problem using this : import smtplib smtp = smtplib.SMTP() smtp.connect('smtp_server_here') smtp.login('user_name', 'password') smtp.sendmail(strFrom, strTo, msgRoot.as_string()) smtp.quit() -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Apr 22 14:36:29 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 22 Apr 2008 08:36:29 -0400 Subject: [Tutor] Sending Mail In-Reply-To: References: Message-ID: <1c2a2c590804220536j5c82c7b9saf804a610b9a14ce@mail.gmail.com> On Tue, Apr 22, 2008 at 6:06 AM, Stephen Nelson-Smith wrote: > smtpserver = 'relay.clara.net' > > RECIPIENTS = ['sanelson at gmail.com'] > SENDER = 'alerts at atalanta-systems.com' > message = """Subject: HTTPD ALERT: %s requests %s connections > Please investigate ASAP.""" % (rps, connections) > > This sends emails.... > > But gmail says it came from "unknown sender" You have to include the From and To headers in the message body as well as passing them to sendmail(). See the example here: http://docs.python.org/lib/SMTP-example.html Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas at kostyrka.org Tue Apr 22 17:00:32 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 22 Apr 2008 17:00:32 +0200 Subject: [Tutor] Little problem with math module In-Reply-To: <88445.90218.qm@web86709.mail.ukl.yahoo.com> References: <88445.90218.qm@web86709.mail.ukl.yahoo.com> Message-ID: <1208876432.6717.21.camel@andi-lap.lan> Hmmm, the power function has basically two definitions: a ** n for integer n, pow is defined for all a in R. for real n, pow is defined only for non-negative a. If you think how a**x is derived (as a generalization from a**(p/q)), that makes sense. Basically, a ** (p/q), p > 0, q > 0, gcd(p, q) = 1, is defined as the q-th root of a ** p. Now for all even q, there is no result in R, only q results in C. Now, trying to remember my highschool math, a**x, x in R is defined basically by interpolation of the the a**x, x in Q function. As a**x with x in Q is only defined as a real function for a >= 0, so is a**x, x in R. In practice a ** x can be also derived from the exp and ln functions: (which are basically exp(x) = e ** x, and ln is the logarithm to the base e, funnily, the math module calls that log, which is often used by mathematicians for the logarithm to base 10, at least in German) math.exp(x * math.log(a)) == a ** x (this can be expressed with any base, but for deeper reasons it's usually e=2.7182... that is used for a base) Ok, hope that I didn't put my foot in my mouth, considering that high school is over a decade in that past for me ;) At least it's probably offtopic for the python tutor list :) Andreas Am Montag, den 21.04.2008, 17:50 +0000 schrieb ALAN GAULD: > On Mon, Apr 21, 2008 at 12:07 AM, Alan Gauld > wrote: > > > >>> pow(-20, 0.3333333) > Traceback (most recent call last): > File "", line 1, in > ValueError: negative number cannot be raised to a fractional power > >>> -20**0.3333333 > -2.7144173455393048 > >>> > > > I think you're confusing the order of operations. > > math.pow(-20, (1.0/3.0)) and -20**(1.0/3.0) are not equivalent > > Whereas, as john mentioned, -20**(1.0/3.0) is actually > -(20**(1.0/3.0)), math.pow(-20, (1.0/3.0)) is (-20)**(1.0/3.0) > > > Yes, quite correct, I posted my reply before the others had > posted theirs although it showed up afterwards(at least on gmane) > > > exponentiation has higher precedence over positive, negative. > > Yep, I hadn't realized that, although it does make sense when you > think about it :-) > > > Note that math.pow is unrelated to the builtin power operator > > and the result of math.pow(0.0, -2.0) will vary by platform. > > This is interesting, I had assumed that pow simply called **. > Does anyone know why they made it different? > > Alan G. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From inthefridge at gmail.com Tue Apr 22 19:48:06 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Tue, 22 Apr 2008 11:48:06 -0600 Subject: [Tutor] XMLRPC Message-ID: I am looking for a way to run commands remotely on another computer. I was thinking of doing this with XMLRPC. All the machines I have are behind a private network so I don't have the security implications of them being public. I need to run actual system level commands on the box themselves. What I need it to do is accept a certain level of parameters and the run a command according to that. Is this even possible? -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From pylinuxian at gmail.com Tue Apr 22 20:13:57 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Tue, 22 Apr 2008 18:13:57 +0000 Subject: [Tutor] XMLRPC In-Reply-To: References: Message-ID: > > looking for a way to run commands remotely on another computer. > I can run pretty much complicated commands on remote servers using only ssh. I also run programs on remote server (when inside lan) using cgi module, works perfectly. maybe if you describe your problem i can provide you with some code. -------------- next part -------------- An HTML attachment was scrubbed... URL: From inthefridge at gmail.com Tue Apr 22 20:39:07 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Tue, 22 Apr 2008 12:39:07 -0600 Subject: [Tutor] XMLRPC In-Reply-To: References: Message-ID: I am just trying to automate series of commands while keeping a low security profile. Most of the stuff we do now is through SSH and Pyexpect. I would like to see if there is a way of just triggering commands without requiring us to SSH into the server to get them to run. We currently ssh into a box and use expect to trigger a script that sets up Xen Virtual machines. All I really need it to do is hit the box and trigger a command...then give me the status once its done. The script does this now, but only as a log file in the same server. On Tue, Apr 22, 2008 at 12:13 PM, linuxian iandsd wrote: > looking for a way to run commands remotely on another computer. > > > > I can run pretty much complicated commands on remote servers using only > ssh. > I also run programs on remote server (when inside lan) using cgi module, > works perfectly. > > maybe if you describe your problem i can provide you with some code. > > -- Spencer Parker _______________________________________________________ "if you can't go to heaven, may you at least die in Ireland." _______________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From swartmumba at yahoo.com Wed Apr 23 01:18:49 2008 From: swartmumba at yahoo.com (SwartMumba snake) Date: Tue, 22 Apr 2008 16:18:49 -0700 (PDT) Subject: [Tutor] mod python Message-ID: <79222.94477.qm@web44815.mail.sp1.yahoo.com> An HTML attachment was scrubbed... URL: From clsdaniel at gmail.com Wed Apr 23 02:40:46 2008 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Tue, 22 Apr 2008 17:40:46 -0700 Subject: [Tutor] mod python In-Reply-To: <79222.94477.qm@web44815.mail.sp1.yahoo.com> References: <79222.94477.qm@web44815.mail.sp1.yahoo.com> Message-ID: <4fae7dfa0804221740ra28d532uf76c1cd5e60f3acd@mail.gmail.com> Hello, I think this is a problem with mod_python and Apache configuration, you should checkout mod_python configuration for Apache+Windows. Most likely your problem is the mod_python library file, use this instead (more appropiate for windows): "LoadModule python_module modules/mod_python.dll" I suggest you to consult the Apache configuration documentation on Windows. Regards, Carlos On Tue, Apr 22, 2008 at 4:18 PM, SwartMumba snake wrote: > Hello Python Mailing List > > I am trying to set up mod python 3.3.1. I have python 2.5.1, apache 2.2 > server, and my os is Vista. The problem is that after I install mod python, > there is no mod_python.so in the apache modules directory. Thus the > "LoadModule python_module modules/mod_python.so" call does not work. > > What should I do. > > Thanks. > > ________________________________ > Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it > now. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From whatpot at gmail.com Wed Apr 23 08:26:38 2008 From: whatpot at gmail.com (Vaibhav.bhawsar) Date: Wed, 23 Apr 2008 02:26:38 -0400 Subject: [Tutor] knowing when a list is updated by a thread In-Reply-To: <17d58cc40804222322i27d0b4cdn1379be903ef7c2d6@mail.gmail.com> References: <17d58cc40804222322i27d0b4cdn1379be903ef7c2d6@mail.gmail.com> Message-ID: <17d58cc40804222326o4db02141sde44028f956227c3@mail.gmail.com> i have this code to print every new element in a list only when the list length changes (while the list is updated by a thread running elsewhere)...I was wondering if there is a pythonic way to do this? how does one know when there is a new element in the list? prevlength = 0 while geoCode.running: places = geoCode.getResults() #returns a list with most up to date elements..the list grows as the thread that updates it if len(places) > prevlength: print places[prevlength] prevlength = len(places) thank you! -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Wed Apr 23 09:47:53 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 23 Apr 2008 00:47:53 -0700 Subject: [Tutor] Another mention on xkcd... Message-ID: <40af687b0804230047g763b65f5id4f4b302b0e0ade4@mail.gmail.com> I don't know whether there are any other xkcd fans here, but I am, and I was very happy to see Python mentioned again... http://xkcd.com/413/ Sometimes it really does seem that easy. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From reachmsn at hotmail.com Wed Apr 23 09:55:07 2008 From: reachmsn at hotmail.com (Anshu Raval) Date: Wed, 23 Apr 2008 13:25:07 +0530 Subject: [Tutor] Recursion doubt In-Reply-To: References: Message-ID: Hi, Thank you so much for your response. I followed the 2 reasonings you gave, -- You can look at find_all as a master routine that keeps calling find_path until find_path gives up. If the search space has not been exhausted (here there are still other nodes connected to 'start') take a suitable candidate call find_path from there until no more paths from there can be found. Repeat until no more suitable candidates. ----- (in this case find_path executes a depth-first search on the graph - represented as a dictionary & find_all combines the 2 searches, first the depth search & when it quits, the breadth search takes over.) -------- But my question would again be how do you know to put square brackets around path in if start == end: return [path] in find_all_paths. I am still puzzled by this. Thanks & Regards, Anshu Date: Sun, 20 Apr 2008 03:21:03 +0200From: joskerc at gmail.comTo: reachmsn at hotmail.comSubject: Re: [Tutor] Recursion doubtCC: tutor at python.org Hi, you are tackling 3 "heavy" subjects in just 1 go! graphs :a triving math society would approve your choice. But you might start with the *slightly* less difficult challenge: trees. I do not know your math/programming background, so the following link can perhaps enlighten you: http://www.brpreiss.com/books/opus7/ Trees, graphs, queues and what more implemented in several languages. Python included. Also, most CS starters have chapters devoted to (some of) them. (E.g. http://www.greenteapress.com/thinkpython/) Backtracking & recursion will surely be topics too. Reading them will help getting a handle on it The 3 chosen topics are advanced or even rather advanced even for most of CS people. To return to your question... Basically, find_path takes a node connected to 'start', if not at the 'end', make the current node 'start' and see if find_path does return a path. As soon as a path is foud find_path quits searching. You can look at find_all as a master routine that keeps calling find_path until find_path gives up. If the search space has not been exhausted (here there are still other nodes connected to 'start') take a suitable candidate call find_path from there until no more paths from there can be found. Repeat until no more suitable candidates. As you have gone through the whole search space, all paths from 'start' to 'end' were found. Recursion makes backtracking easier: the program/routine will by itself keep track of the steps taken & where to go back if a search fails. Backtracking is the powerful technique of remembering the steps already taken & to retrace them till the first non-explored sidetrack when needed. Choosing the next non-explored sidetrack though can be complex involving other searches, ... It all depends on what you look for, how the data is represented. A related topic that will help you understand things is breadth-first & depth-first searches on trees. (in this case find_path executes a depth-first search on the graph - represented as a dictionary & find_all combines the 2 searches, first the depth search & when it quits, the breadth search takes over.) Greetz On 4/15/08, Anshu Raval wrote: Hi, At the url http://www.python.org/doc/essays/graphs.html there is some code by Guido Van Rossum for computing paths through a graph - I have pasted it below for reference - Let's write a simple function to determine a path between two nodes. It takes a graph and the start and end nodes as arguments. It will return a list of nodes (including the start and end nodes) comprising the path. When no path can be found, it returns None. The same node will not occur more than once on the path returned (i.e. it won't contain cycles). The algorithm uses an important technique called backtracking: it tries each possibility in turn until it finds a solution. def find_path(graph, start, end, path=[]): path = path + [start] if start == end: return path if not graph.has_key(start): return None for node in graph[start]: if node not in path: newpath = find_path(graph, node, end, path) if newpath: return newpath return None *** He then says------------------------ It is simple to change this function to return a list of all paths (without cycles) instead of the first path it finds: def find_all_paths(graph, start, end, path=[]): path = path + [start] if start == end: return [path] if not graph.has_key(start): return [] paths = [] for node in graph[start]: if node not in path: newpaths = find_all_paths(graph, node, end, path) for newpath in newpaths: paths.append(newpath) return paths *** I couldn't understand how it was simple to change the function find paths to find all paths. How would you think about writing this second function recursively. Especially the part about if start==end: return [path]. I feel you would give square brackets around path here after first writing the inductive part ... for node in graph[start] .... and then by trial and error put square brackets around path in the Basis part. Can someone please explain how to write this code. Thanks! Planning marriage in 2008! Join Shaadi.com matrimony FREE! Try it now!_______________________________________________Tutor maillist - Tutor at python.orghttp://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Technology : Catch up on updates on the latest Gadgets, Reviews, Gaming and Tips to use technology etc. http://computing.in.msn.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From bhawsar.vaibhav at gmail.com Wed Apr 23 08:22:40 2008 From: bhawsar.vaibhav at gmail.com (Vaibhav.bhawsar) Date: Wed, 23 Apr 2008 02:22:40 -0400 Subject: [Tutor] knowing when a list is updated by a thread Message-ID: <17d58cc40804222322i27d0b4cdn1379be903ef7c2d6@mail.gmail.com> i have this code to print every new element in a list only when the list length changes (while the list is updated by a thread running elsewhere)...I was wondering if there is a pythonic way to do this? how does one know when there is a new element in the list? prevlength = 0 while geoCode.running: places = geoCode.getResults() #returns a list with most up to date elements..the list grows as the thread that updates it if len(places) > prevlength: print places[prevlength] prevlength = len(places) thank you! -- Vaibhav Bhawsar -------------- next part -------------- An HTML attachment was scrubbed... URL: From pylinuxian at gmail.com Wed Apr 23 13:19:46 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Wed, 23 Apr 2008 11:19:46 +0000 Subject: [Tutor] knowing when a list is updated by a thread In-Reply-To: <17d58cc40804222326o4db02141sde44028f956227c3@mail.gmail.com> References: <17d58cc40804222322i27d0b4cdn1379be903ef7c2d6@mail.gmail.com> <17d58cc40804222326o4db02141sde44028f956227c3@mail.gmail.com> Message-ID: if i only wanted the last element ofthe list, i would change the "geoCode.getResults()' to return to me both the complete list & the new elements in the list. it should be pretty easy from there. if what you need is to sort the list & see whether a value have changed or not then you will be better off working with dictionaries. On Wed, Apr 23, 2008 at 6:26 AM, Vaibhav.bhawsar wrote: > i have this code to print every new element in a list only when the list > length changes (while the list is updated by a thread running elsewhere)...I > was wondering if there is a pythonic way to do this? how does one know when > there is a new element in the list? > > prevlength = 0 > while geoCode.running: > places = geoCode.getResults() #returns a list with most up to date > elements..the list grows as the thread that updates it > if len(places) > prevlength: > print places[prevlength] > prevlength = len(places) > > > thank you! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Apr 23 14:07:47 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 23 Apr 2008 08:07:47 -0400 Subject: [Tutor] knowing when a list is updated by a thread In-Reply-To: <17d58cc40804222326o4db02141sde44028f956227c3@mail.gmail.com> References: <17d58cc40804222322i27d0b4cdn1379be903ef7c2d6@mail.gmail.com> <17d58cc40804222326o4db02141sde44028f956227c3@mail.gmail.com> Message-ID: <480F2693.80109@tds.net> Vaibhav.bhawsar wrote: > i have this code to print every new element in a list only when the list > length changes (while the list is updated by a thread running > elsewhere)...I was wondering if there is a pythonic way to do this? how > does one know when there is a new element in the list? > > prevlength = 0 > while geoCode.running: > places = geoCode.getResults() #returns a list with most up to > date elements..the list grows as the thread that updates it > if len(places) > prevlength: > print places[prevlength] > prevlength = len(places) Ouch. This loop will chew up CPU time unless there is some kind of delay in getResults(). If the intent of the loop is to print every new value placed in the list, there is no guarantee that it will work. If you are using the list to communicate results between two threads you should see if queue.Queue meets your needs. It is thread safe and has blocking access so you don't have to use a busy loop. Otherwise you could use a threading.Condition to communicate between the threads. Kent From kent37 at tds.net Wed Apr 23 14:10:00 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 23 Apr 2008 08:10:00 -0400 Subject: [Tutor] Recursion doubt In-Reply-To: References: Message-ID: <480F2718.8070109@tds.net> Anshu Raval wrote: > But my question would again be how do you know to put square brackets > around path in > if start == end: > return [path] > in find_all_paths. I am still puzzled by this. find_all_paths() returns a *list* of paths, even when the result is a single path. Without the brackets, it would sometimes return a list and sometimes a single path. Kent From bgailer at gmail.com Wed Apr 23 15:46:45 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 23 Apr 2008 09:46:45 -0400 Subject: [Tutor] knowing when a list is updated by a thread In-Reply-To: <480F2693.80109@tds.net> References: <17d58cc40804222322i27d0b4cdn1379be903ef7c2d6@mail.gmail.com> <17d58cc40804222326o4db02141sde44028f956227c3@mail.gmail.com> <480F2693.80109@tds.net> Message-ID: <480F3DC5.2010704@gmail.com> Kent Johnson wrote: > Vaibhav.bhawsar wrote: >> i have this code to print every new element in a list only when the >> list length changes (while the list is updated by a thread running >> elsewhere)...I was wondering if there is a pythonic way to do this? >> how does one know when there is a new element in the list? >> >> prevlength = 0 >> while geoCode.running: >> places = geoCode.getResults() #returns a list with most up to >> date elements..the list grows as the thread that updates it >> if len(places) > prevlength: >> print places[prevlength] >> prevlength = len(places) > > Ouch. This loop will chew up CPU time unless there is some kind of > delay in getResults(). If the intent of the loop is to print every new > value placed in the list, there is no guarantee that it will work. > > If you are using the list to communicate results between two threads > you should see if queue.Queue meets your needs. It is thread safe and > has blocking access so you don't have to use a busy loop. > Evey time someone recommends Queue I think "oh boy this will really help me". Then I go to the Library Reference, read the Queue docs and think "oh boy who can help me understand this". Even the sample code is confusing. Is there some other documentation or example? -- Bob Gailer 919-636-4239 Chapel Hill, NC From Mike.Hansen at atmel.com Wed Apr 23 15:52:31 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Wed, 23 Apr 2008 07:52:31 -0600 Subject: [Tutor] knowing when a list is updated by a thread In-Reply-To: <480F3DC5.2010704@gmail.com> References: <17d58cc40804222322i27d0b4cdn1379be903ef7c2d6@mail.gmail.com> <17d58cc40804222326o4db02141sde44028f956227c3@mail.gmail.com><480F2693.80109@tds.net> <480F3DC5.2010704@gmail.com> Message-ID: <7941B2693F32294AAF16C26B679A258D01F6F1EE@csomb01.corp.atmel.com> > Evey time someone recommends Queue I think "oh boy this will > really help > me". Then I go to the Library Reference, read the Queue docs > and think > "oh boy who can help me understand this". Even the sample code is > confusing. > > Is there some other documentation or example? > > > -- > Bob Gailer http://effbot.org/zone/librarybook-index.htm That might help. It looks like it has some example code. Look at the Threads and Processes link and search for queue. Mike From Mike.Hansen at atmel.com Wed Apr 23 15:54:11 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Wed, 23 Apr 2008 07:54:11 -0600 Subject: [Tutor] knowing when a list is updated by a thread In-Reply-To: <480F3DC5.2010704@gmail.com> References: <17d58cc40804222322i27d0b4cdn1379be903ef7c2d6@mail.gmail.com> <17d58cc40804222326o4db02141sde44028f956227c3@mail.gmail.com><480F2693.80109@tds.net> <480F3DC5.2010704@gmail.com> Message-ID: <7941B2693F32294AAF16C26B679A258D01F6F1F3@csomb01.corp.atmel.com> > Evey time someone recommends Queue I think "oh boy this will > really help > me". Then I go to the Library Reference, read the Queue docs > and think > "oh boy who can help me understand this". Even the sample code is > confusing. > > Is there some other documentation or example? > > > -- > Bob Gailer http://effbot.org/librarybook/queue.htm Here's a direct link to the queue module. Mike From kent37 at tds.net Wed Apr 23 17:02:33 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 23 Apr 2008 11:02:33 -0400 Subject: [Tutor] Using Queue Message-ID: <1c2a2c590804230802w3690ff97qb5ec5a5c4103025b@mail.gmail.com> On Wed, Apr 23, 2008 at 9:46 AM, bob gailer wrote: > Evey time someone recommends Queue I think "oh boy this will really help > me". Then I go to the Library Reference, read the Queue docs and think "oh > boy who can help me understand this". Even the sample code is confusing. Can you say what is confusing about it? Do you have a specific use in mind? Do you understand threading? Queue is used to facilitate communication between threads, so any Queue example includes multiple threads. In the simplest case, you have producer and consumer threads, and a single shared instance of Queue. Each producer thread adds items to the queue using Queue.put(). Consumer threads remove items with Queue.get(). The benefits: - get() and put() are thread safe - get() blocks if the queue is empty - no need for a polling loop - put() blocks if the queue is full Additionally if the consumers call Queue.task_done() for each consumed item, Queue.join() will block until all tasks are complete, then continue. Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Apr 23 19:17:58 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 23 Apr 2008 13:17:58 -0400 Subject: [Tutor] Using Queue In-Reply-To: <1c2a2c590804230802w3690ff97qb5ec5a5c4103025b@mail.gmail.com> References: <1c2a2c590804230802w3690ff97qb5ec5a5c4103025b@mail.gmail.com> Message-ID: <480F6F46.4000303@gmail.com> Kent Johnson wrote: > On Wed, Apr 23, 2008 at 9:46 AM, bob gailer > wrote: > > Evey time someone recommends Queue I think "oh boy this will > really help me". Then I go to the Library Reference, read the > Queue docs and think "oh boy who can help me understand this". > Even the sample code is confusing. > > > Can you say what is confusing about it? "The Queue module implements a multi-producer, multi-consumer FIFO queue. I understand producer, comsumer, FIFO. I don't understand multi- "It is especially useful in threads programming when information must be exchanged safely between multiple threads. " I understand threads. I've written some (to me fairly sophisticated) programs using Threading and conditions. I understand that threads might want to exchange information. I guess that queue supports the exchange by receiving and releasing items. Is that true? I don't know what "safely" means. "The Queue class in this module implements all the required locking semantics." I have no idea what that means nor does any of the ensuing documentation explain. > Do you have a specific use in mind? I have an application that uses Threading. It is not a producer, consumer application, just a bunch of threads that are started at the same time. And they do not communicate with each other, just with the main thread. But that seems to be true of Queue also. > Queue is used to facilitate communication between threads, so any > Queue example includes multiple threads. > > Regarding the sample code: I must add (by trial and error) at least these 3 lines to the main program: from threading import * from Queue import Queue num_worker_threads = 3 Then it bombs: File "J:\python\queue.py", line 17, in for item in source(): NameError: name 'source' is not defined No idea what source is supposed to be. A callable object? And where in this example are the producer threads? -- Bob Gailer 919-636-4239 Chapel Hill, NC From marc.tompkins at gmail.com Wed Apr 23 19:25:43 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 23 Apr 2008 10:25:43 -0700 Subject: [Tutor] Using Queue In-Reply-To: <480F6F46.4000303@gmail.com> References: <1c2a2c590804230802w3690ff97qb5ec5a5c4103025b@mail.gmail.com> <480F6F46.4000303@gmail.com> Message-ID: <40af687b0804231025u194675a4n74dd3a379fc0b417@mail.gmail.com> I for one would like to thank Bob for asking the question! So far I hadn't had the guts. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Wed Apr 23 19:36:44 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 23 Apr 2008 18:36:44 +0100 Subject: [Tutor] Using Queue In-Reply-To: <480F6F46.4000303@gmail.com> References: <1c2a2c590804230802w3690ff97qb5ec5a5c4103025b@mail.gmail.com> <480F6F46.4000303@gmail.com> Message-ID: <480F73AC.1090703@timgolden.me.uk> bob gailer wrote: > Kent Johnson wrote: >> On Wed, Apr 23, 2008 at 9:46 AM, bob gailer > > wrote: >> >> Evey time someone recommends Queue I think "oh boy this will >> really help me". Then I go to the Library Reference, read the >> Queue docs and think "oh boy who can help me understand this". >> Even the sample code is confusing. >> >> >> Can you say what is confusing about it? > > "The Queue module implements a multi-producer, multi-consumer FIFO queue. > > I understand producer, comsumer, FIFO. > > I don't understand multi- That means -- and this is perhaps Queue's raison d'etre -- that several threads can read from and write to it "simultaneously" (from their perspective) without having to worry about locks and the usual problems of a memory structure shared between threads. > "It is especially useful in threads programming when information must be > exchanged safely between multiple threads. " > > I understand threads. I've written some (to me fairly sophisticated) > programs using Threading and conditions. > > I understand that threads might want to exchange information. > > I guess that queue supports the exchange by receiving and releasing > items. Is that true? It supports it be letting, say, thread tA write to queue qA, which thread tB reads from. (Using put & get, optionally with timeouts). > I don't know what "safely" means. If you've done some thread programming, I assume you're familiar with the potential pitfalls, including race conditions, deadlocks and so on? "Safely" means "without your having to worry about those things". > "The Queue class in this module implements all the required locking > semantics." I have no idea what that means nor does any of the ensuing > documentation explain. Normally if you want to have a thread access some data which *might* be written to by another thread at, effectively, the same time, the normal thing is to have each thread lock the data: get hold of a flag which grants it exclusive access to the data until the lock is released. (This is sometimes called a critical section). Without that lock, it's possible for one thread to be half-way through its update when it is switched out and the other thread switched in. Now the data is in an intermediate state (which you don't want). >> Do you have a specific use in mind? > > I have an application that uses Threading. It is not a producer, > consumer application, just a bunch of threads that are started at the > same time. And they do not communicate with each other, just with the > main thread. But that seems to be true of Queue also. Yes, that's a typical setup for Queue: the main thread creates a Queue and passes it to each thread it creates. Say you had an example where you had a pool of worker threads, each one performing a calculation. A common approach is to have two Queues: request &# response. The code would look something like this (entirely untested): import threading import Queue class CalcThread (threading.Thread): def __init__ (self, requests, responses): threading.Thread.__init__ (self) self.setDaemon (True) self.requests = requests self.responses = responses def run (self): while True: a, b = self.requests.get () self.responses.put (a + b) if __name__ == '__main__': requests = Queue.Queue () responses = Queue.Queue () for i in range (5): CalcThread (requests, responses).start () requests.put ((1, 5)) requests.put ((2, 6)) print responses.get () print responses.get () As it stands this code is fairly stunted, but I'm trying to keep it simple enough to understand easily. TJG From bhawsar.vaibhav at gmail.com Wed Apr 23 19:21:51 2008 From: bhawsar.vaibhav at gmail.com (Vaibhav.bhawsar) Date: Wed, 23 Apr 2008 13:21:51 -0400 Subject: [Tutor] knowing when a list is updated by a thread In-Reply-To: <7941B2693F32294AAF16C26B679A258D01F6F1EE@csomb01.corp.atmel.com> References: <17d58cc40804222322i27d0b4cdn1379be903ef7c2d6@mail.gmail.com> <17d58cc40804222326o4db02141sde44028f956227c3@mail.gmail.com> <480F2693.80109@tds.net> <480F3DC5.2010704@gmail.com> <7941B2693F32294AAF16C26B679A258D01F6F1EE@csomb01.corp.atmel.com> Message-ID: <17d58cc40804231021q120bb10aj94695ee82a2682a7@mail.gmail.com> Some good ideas! Kent I looked at the queue module and that looks like something I would use. will post my results. Thanks On Wed, Apr 23, 2008 at 9:52 AM, Hansen, Mike wrote: > > > > Evey time someone recommends Queue I think "oh boy this will > > really help > > me". Then I go to the Library Reference, read the Queue docs > > and think > > "oh boy who can help me understand this". Even the sample code is > > confusing. > > > > Is there some other documentation or example? > > > > > > -- > > Bob Gailer > > http://effbot.org/zone/librarybook-index.htm > > That might help. It looks like it has some example code. Look at the > Threads and Processes link and search for queue. > > Mike > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Vaibhav Bhawsar -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Apr 23 19:59:51 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 23 Apr 2008 13:59:51 -0400 Subject: [Tutor] Using Queue In-Reply-To: <480F6F46.4000303@gmail.com> References: <1c2a2c590804230802w3690ff97qb5ec5a5c4103025b@mail.gmail.com> <480F6F46.4000303@gmail.com> Message-ID: <1c2a2c590804231059y1769d32ftaee0d588a6e7ba@mail.gmail.com> On Wed, Apr 23, 2008 at 1:17 PM, bob gailer wrote: > "The Queue module implements a multi-producer, multi-consumer FIFO queue. > > I understand producer, comsumer, FIFO. > > I don't understand multi- More than one producer and/or consumer > > > "It is especially useful in threads programming when information must be > exchanged safely between multiple threads. " > > I understand threads. I've written some (to me fairly sophisticated) > programs using Threading and conditions. > > I understand that threads might want to exchange information. > > I guess that queue supports the exchange by receiving and releasing items. > Is that true? Yes. Producers put things in the queue, consumers pull them out. Basically a FIFO where the two ends are used by different threads. > > I don't know what "safely" means. > > "The Queue class in this module implements all the required locking > semantics." I have no idea what that means nor does any of the ensuing > documentation explain. Ok, do you understand thread safety, or conversely, what kind of problems can happen when two threads share data without any kind of locking? For example, suppose you want a queue with a limited number of items allowed in it, and producers should block if the queue is full. You need an atomic "check for full and push" operation; otherwise you can have race conditions between two threads. If the queue has one empty slot, you have to protect against - thread A checks for queue full - not full - thread B checks for queue full - not full - thread A pushes - queue is now full - thread B pushes - overflow queue.Queue uses locks to prevent this and other problems. > Do you have a specific use in mind? > I have an application that uses Threading. It is not a producer, consumer > application, just a bunch of threads that are started at the same time. And > they do not communicate with each other, just with the main thread. But that > seems to be true of Queue also. Possibly you could use a Queue here. The main thread would be the only consumer; the rest of the threads would be producers. > > Queue is used to facilitate communication between threads, so any Queue > > example includes multiple threads. > > > > > > Regarding the sample code: > I must add (by trial and error) at least these 3 lines to the main > program: > > from threading import * > from Queue import Queue > num_worker_threads = 3 > > Then it bombs: > File "J:\python\queue.py", line 17, in > for item in source(): > NameError: name 'source' is not defined > > No idea what source is supposed to be. A callable object? And where in > this example are the producer threads? Yes, the example is really just a sketch. source is a callable object that returns an iterable object whose items represent some kind of unit of work. The threads created by calling Thread(target=worker) are the consumer threads. The main thread is the producer - it puts items into the queue in the for loop. Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Apr 23 20:04:38 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 23 Apr 2008 14:04:38 -0400 Subject: [Tutor] Using Queue In-Reply-To: <480F73AC.1090703@timgolden.me.uk> References: <1c2a2c590804230802w3690ff97qb5ec5a5c4103025b@mail.gmail.com> <480F6F46.4000303@gmail.com> <480F73AC.1090703@timgolden.me.uk> Message-ID: <1c2a2c590804231104v53259fcbxbe38544655ea400b@mail.gmail.com> On Wed, Apr 23, 2008 at 1:36 PM, Tim Golden wrote: > Yes, that's a typical setup for Queue: the main thread creates a > Queue and passes it to each thread it creates. Say you had an example > where you had a pool of worker threads, each one performing a > calculation. A common approach is to have two Queues: request &# > response. The code would look something like this (entirely untested): > There are many threadpool examples in the online Python cookbook, for example this one (picked mostly at random - see also links from there, the 'threading' topic of the cookbook, or search for 'pool'): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435883 Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From Steven.Cain at norfolk.gov Wed Apr 23 20:55:20 2008 From: Steven.Cain at norfolk.gov (Cain, Steven) Date: Wed, 23 Apr 2008 14:55:20 -0400 Subject: [Tutor] Needing help with variables In-Reply-To: References: Message-ID: I have the code below and I am in need of a little help with variables. What I am trying to do is substitute a variable where it says insert variable. I actually need to place 3 variables. 1 for date, 1 for time and 1 for a string of text. Any help would be greatly appreciated. Steve def BackwardsReader(file, BLKSIZE = 4096): #"""Read a file line by line, backwards""" buf = "" file.seek(-1,2) lastchar = file.read(1) trailing_newline = (lastchar == "\n") while 1: newline_pos = buf.rfind("\n") pos = file.tell() if newline_pos != -1: # Found a newline line = buf[newline_pos+1:] buf = buf[:newline_pos] if pos or newline_pos or trailing_newline: line += "\n" yield line elif pos: # Need to fill buffer toread = min(BLKSIZE, pos) file.seek(-toread, 1) buf = file.read(toread) + buf file.seek(-toread, 1) if pos == toread: buf = "\n" + buf else: # Start-of-file return for line in BackwardsReader(open('stopServer.log')): if line[0] == '[': print line[1:8],line[9:16],line[62:93] ( insert Variable ) break From kent37 at tds.net Wed Apr 23 22:06:42 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 23 Apr 2008 16:06:42 -0400 Subject: [Tutor] Needing help with variables In-Reply-To: References: Message-ID: <1c2a2c590804231306x19a35c0dk5e2795913efb82e6@mail.gmail.com> On Wed, Apr 23, 2008 at 2:55 PM, Cain, Steven wrote: > I have the code below and I am in need of a little help with variables. > What I am trying to do is substitute a variable where it says insert > variable. I actually need to place 3 variables. 1 for date, 1 for time > and 1 for a string of text. > > Any help would be greatly appreciated. > > Steve > > def BackwardsReader(file, BLKSIZE = 4096): Presumably the files you are trying to read are too large to fit in memory? Otherwise this could be implemented as return reversed(file) > for line in BackwardsReader(open('stopServer.log')): > if line[0] == '[': > print line[1:8],line[9:16],line[62:93] ( insert Variable ) I'm not too sure what you want to do here. Do you want to create three variables with the three substrings? That would be date, time, text = line[1:8],line[9:16],line[62:93] or of course you could use three separate assignments: date = line[1:8] time = lline[9:16] text = line[62:93] Kent From marc.tompkins at gmail.com Thu Apr 24 03:26:55 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 23 Apr 2008 18:26:55 -0700 Subject: [Tutor] Open Source Hero my @$$! Message-ID: <40af687b0804231826u748f179am9451e1d62a350dfe@mail.gmail.com> Just thought I'd share something I found quite humorous... a while back, I heard about Microsoft's "Open Source Hero" program, and being a curious type I signed up. Hey, I love me some Open Source, and I wanna be a hero, right? My Hero Pack arrived a few days ago. It contains: a 90-day trial of Visual Studio 2008 and a 120-day trial of Windows Server 2008. Now don't get me wrong - I'm not ungrateful; I fully intend to try out Windows Server so I can see what I'll be facing over the next few months. But Visual Studio? Open Source? Am I missing the joke here? Any other Heros here? Anybody else find this as funny as I did? -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From Mike.Hansen at atmel.com Thu Apr 24 16:10:27 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Thu, 24 Apr 2008 08:10:27 -0600 Subject: [Tutor] Open Source Hero my @$$! In-Reply-To: <40af687b0804231826u748f179am9451e1d62a350dfe@mail.gmail.com> References: <40af687b0804231826u748f179am9451e1d62a350dfe@mail.gmail.com> Message-ID: <7941B2693F32294AAF16C26B679A258D01FD4C8C@csomb01.corp.atmel.com> > -----Original Message----- > On > Behalf Of Marc Tompkins > Sent: Wednesday, April 23, 2008 7:27 PM > To: python tutor; wxpython-users at lists.wxwidgets.org > Subject: [Tutor] Open Source Hero my @$$! > > Just thought I'd share something I found quite humorous... a > while back, I heard about Microsoft's "Open Source Hero" > program, and being a curious type I signed up. Hey, I love > me some Open Source, and I wanna be a hero, right? > > My Hero Pack arrived a few days ago. It contains: > a 90-day trial of Visual Studio 2008 > and > a 120-day trial of Windows Server 2008. > > Now don't get me wrong - I'm not ungrateful; I fully intend > to try out Windows Server so I can see what I'll be facing > over the next few months. But Visual Studio? Open Source? > Am I missing the joke here? > > Any other Heros here? Anybody else find this as funny as I did? I guess you can write open source software for 90 days using Microsoft's proprietary VS 2008. At least you can then try out IronPython or Python for .NET. From muchanek at gmail.com Thu Apr 24 22:13:31 2008 From: muchanek at gmail.com (kinuthia muchane) Date: Thu, 24 Apr 2008 23:13:31 +0300 Subject: [Tutor] Project Euler Problem 6 Message-ID: <1209068011.6645.13.camel@www.kinuthia.com> Hi, I am trying to solve problem 6 on the Project Euler, but when I submit my answer, I am told that it is wrong. Here is the problem: The sum of the squares of the first ten natural numbers is, 1? + 2? + ... + 10? = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)? = 55? = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 ? 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. And here is my code: def aux(): return sum([k*k for k in range(1,111)])# sum of the squares of the first one hundred numbers def aux1(): inter = sum([k for k in range(1,111))# square of the sum of the first one hundred numbers return inter**2 def aux2(): return aux1() - aux()# the difference of the two sums print aux2() ...which gives a result of 36821290. It worked fine with the example they have given but not with the hundred one... What am I missing? Thanks! Kinuthia... From steve at alchemy.com Thu Apr 24 22:16:10 2008 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 24 Apr 2008 13:16:10 -0700 Subject: [Tutor] Project Euler Problem 6 In-Reply-To: <1209068011.6645.13.camel@www.kinuthia.com> References: <1209068011.6645.13.camel@www.kinuthia.com> Message-ID: <20080424201610.GA51151@dragon.alchemy.com> On Thu, Apr 24, 2008 at 11:13:31PM +0300, kinuthia muchane wrote: > return sum([k*k for k in range(1,111)])# sum of the squares of the > first one hundred numbers Wouldn't the first hundred numbers be range(1,101)? > def aux1(): > inter = sum([k for k in range(1,111))# square of the sum of the first why use the list comprehension here, instead of simply saying: return sum(range(1,101) ** 2 -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From gallo.j at gmail.com Thu Apr 24 22:22:45 2008 From: gallo.j at gmail.com (joe gallo) Date: Thu, 24 Apr 2008 13:22:45 -0700 Subject: [Tutor] Project Euler Problem 6 In-Reply-To: <1209068011.6645.13.camel@www.kinuthia.com> References: <1209068011.6645.13.camel@www.kinuthia.com> Message-ID: <4b6381420804241322p3d009132md760935d79f85910@mail.gmail.com> It says: Find the difference between the sum of the squares of the first * one hundred* natural numbers and the square of the sum. You did range(1,111). On Thu, Apr 24, 2008 at 1:13 PM, kinuthia muchane wrote: > Hi, > > I am trying to solve problem 6 on the Project Euler, but when I submit > my answer, I am told that it is wrong. Here is the problem: > > > The sum of the squares of the first ten natural numbers is, > > > 1? + 2? + ... + 10? = 385 > The square of the sum of the first ten natural numbers is, > > > (1 + 2 + ... + 10)? = 55? = 3025 > Hence the difference between the sum of the squares of the first ten > natural numbers and the square of the sum is 3025 ? 385 = 2640. > > Find the difference between the sum of the squares of the first one > hundred natural numbers and the square of the sum. > > And here is my code: > > def aux(): > return sum([k*k for k in range(1,111)])# sum of the squares of the > first one hundred numbers > > def aux1(): > inter = sum([k for k in range(1,111))# square of the sum of the > first > one hundred numbers > return inter**2 > > def aux2(): > return aux1() - aux()# the difference of the two sums > > print aux2() > > ...which gives a result of 36821290. > > It worked fine with the example they have given but not with the hundred > one... What am I missing? > > Thanks! > Kinuthia... > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From muchanek at gmail.com Thu Apr 24 22:32:52 2008 From: muchanek at gmail.com (kinuthia muchane) Date: Thu, 24 Apr 2008 23:32:52 +0300 Subject: [Tutor] Euler Problem 6 Message-ID: <1209069172.5847.7.camel@www.kinuthia.com> Hi, I think I need to be more careful in the future. This line return sum([k*k for k in range(1,111)]) should be: return sum([k*k for k in range(1,101)]). ... and this one sum([k for k in range(1,101)) also changes to: sum([k for k in range(1,101)) Kinuthia... From amonroe at columbus.rr.com Fri Apr 25 00:45:05 2008 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu, 24 Apr 2008 18:45:05 -0400 Subject: [Tutor] 6x6 word square solver too slow Message-ID: <13886216482.20080424184505@columbus.rr.com> Any bright ideas on how I can speed this up? It seems REALLY slow for as little as it does. I'm trying to generate word squares like this: P R E Y L A V A O V E R T E N D except 6x6 rather than 4x4. In particular, the profiler indicates that {method 'join' of 'str' objects} is eating an awful lot of time (odd...), but I'm having a brain cramp trying to think up a workaround or alternate approach. The required sixwords.txt file can be gotten here: http://home.columbus.rr.com/javajack/sixwords.zip (wasn't sure if people would complain about a 43K attachment or not) Alan -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: 4cyte011b.py URL: From alan.gauld at btinternet.com Fri Apr 25 01:22:20 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Apr 2008 00:22:20 +0100 Subject: [Tutor] 6x6 word square solver too slow References: <13886216482.20080424184505@columbus.rr.com> Message-ID: "R. Alan Monroe" wrote > Any bright ideas on how I can speed this up? > It seems REALLY slow for as little as it does. I'm not sure its doing so "little"! > In particular, the profiler indicates that {method 'join' of 'str' > objects} is eating an awful lot of time (odd...), Not odd, consider this snippet from solve() for letter in nextletterset: for maybefuture in worddict[letter]: futurezip = zip(*currentwords+[maybefuture]) futureprefixes = [''.join(z) for z in futurezip] validprefixes = [f in worddict for f in futureprefixes] if not False in validprefixes: solve( currentwords + [maybefuture], depth + 1 ) Here you call join() at the third level of nested for loops. And then you call solve recursively at that same level where join gets called inside 3 more levels of loop. That effectively means join is getting called at 6 levels of loop nesting for just one recursive call, but you could be doing more than that. In fact it would be an interesting exercise to add a counter just before the join call to see how many times it gets called altogether - I predict a very big number.... :-) However, as to fixing it thats another story. It may be possibler to reduce the need to cycle over everything each time by using a combination of pre-sorting the lists and using a clever regex to select a subset of entries to which the comparisons need be done. But I'm not sure how much that would help, if at all. However I suspect any attempt to improve performance here needs a new algorithm and probably a clever data structure to minimise brute force tests. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From amonroe at columbus.rr.com Fri Apr 25 03:22:33 2008 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu, 24 Apr 2008 21:22:33 -0400 Subject: [Tutor] 6x6 word square solver too slow In-Reply-To: References: <13886216482.20080424184505@columbus.rr.com> Message-ID: <17195663947.20080424212233@columbus.rr.com> > Here you call join() at the third level of nested for loops. > And then you call solve recursively at that same level > where join gets called inside 3 more levels of loop. > That effectively means join is getting called at 6 levels > of loop nesting for just one recursive call, but you could > be doing more than that. I'm doing zip and list comprehension just as often, and they don't make a blip in the profiler. Maybe that's a shortcoming of the profiler itself? > In fact it would be an interesting > exercise to add a counter just before the join call to see > how many times it gets called altogether - I predict a > very big number.... :-) A 2000-3000 per go round. > However I suspect any attempt to improve performance > here needs a new algorithm and probably a clever data > structure to minimise brute force tests. If I knew of one, I would have used it :) Alan From whatpot at gmail.com Fri Apr 25 05:17:15 2008 From: whatpot at gmail.com (Vaibhav.bhawsar) Date: Thu, 24 Apr 2008 23:17:15 -0400 Subject: [Tutor] howto mysqldb dictionary cursor Message-ID: <17d58cc40804242017r46e1a11o63e079b4a31fa3e0@mail.gmail.com> I have been trying to get the DictCursor working with mysqldb module but can't seem to. I have pasted the basic connection code and the traceback from pydev. The connection does open with the default cursor class. can't figure out how to use the dict cursor class instead of the default one. many thanks. import MySQLdb import sys # connect to the MySQL server try: conn = MySQLdb.connect(host="localhost ",read_default_file='~/.my.cnf',db='test',cursorclass=MySQLdb.cursors.DictCursor) cur = conn.cursor() print conn except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit (1) Traceback (most recent call last): File "/Users/.....src/db/test.py", line 7, in ? conn = MySQLdb.connect(host="localhost",read_default_file='~/.my.cnf',db='te st',cursorclass=MySQLdb.cursors.DictCursor) AttributeError: 'module' object has no attribute 'cursors' -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Apr 25 09:41:07 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Apr 2008 08:41:07 +0100 Subject: [Tutor] 6x6 word square solver too slow References: <13886216482.20080424184505@columbus.rr.com> <17195663947.20080424212233@columbus.rr.com> Message-ID: "R. Alan Monroe" wrote >> That effectively means join is getting called at 6 levels >> of loop nesting for just one recursive call, but you could >> be doing more than that. > > I'm doing zip and list comprehension just as often, and they don't > make a blip in the profiler. Maybe that's a shortcoming of the > profiler itself? I wouldn't expect the comprehension to be shown but zip is a fair point. I would have expected zip and join to be pretty close in resource usage. >> how many times it gets called altogether - I predict a >> very big number.... :-) > > A 2000-3000 per go round. That's not as big as I thought, presumably the dictionary isn't that big? >> However I suspect any attempt to improve performance >> here needs a new algorithm and probably a clever data >> structure to minimise brute force tests. > > If I knew of one, I would have used it :) Ever the problem :-) Alan G. From kent37 at tds.net Fri Apr 25 14:43:56 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 Apr 2008 08:43:56 -0400 Subject: [Tutor] howto mysqldb dictionary cursor In-Reply-To: <17d58cc40804242017r46e1a11o63e079b4a31fa3e0@mail.gmail.com> References: <17d58cc40804242017r46e1a11o63e079b4a31fa3e0@mail.gmail.com> Message-ID: <4811D20C.6060203@tds.net> Vaibhav.bhawsar wrote: > I have been trying to get the DictCursor working with mysqldb module but > can't seem to. I have pasted the basic connection code and the traceback > from pydev. The connection does open with the default cursor class. > can't figure out how to use the dict cursor class instead of the default > one. many thanks. > > > import MySQLdb Try adding import MySQLdb.cursors Kent From jeff at drinktomi.com Fri Apr 25 20:55:54 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Fri, 25 Apr 2008 11:55:54 -0700 Subject: [Tutor] 6x6 word square solver too slow In-Reply-To: <17195663947.20080424212233@columbus.rr.com> References: <13886216482.20080424184505@columbus.rr.com> <17195663947.20080424212233@columbus.rr.com> Message-ID: <3270C06B-754D-4FCE-A3AF-050EB735A767@drinktomi.com> > >> However I suspect any attempt to improve performance >> here needs a new algorithm and probably a clever data >> structure to minimise brute force tests. > > If I knew of one, I would have used it :) I'd suggest googling for 'trie'. Tries are method of indexing sets of strings by prefix. As I recall, English words are more similar at the front, so once you have an indexing scheme you'll probably to do even less work if you index and search from the back of the words towards the front. -jeff From sanhitam at yahoo.com Sat Apr 26 01:32:27 2008 From: sanhitam at yahoo.com (Sanhita Mallick) Date: Fri, 25 Apr 2008 16:32:27 -0700 (PDT) Subject: [Tutor] Help with Recurring Function Message-ID: <979115.60724.qm@web55603.mail.re4.yahoo.com> Hi. I am struggling with a simple recurring function, but can't understand why this is happening. Please help. Here is the script. T(i) are trees (as in graphs). The program operates great, until the step where norm_ted is calculated. Mysteriously norm_ted becomes 0, even though "mag" value is calculated correctly. Also, strangely, sum_norm_ted also becomes zero. What am I missing? Thanks. -Sanhita ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ T = [F1, F2, F3] k = len(T) mean_ted = {} for i in range(k): sum_norm_ted = 0.0 mag = 0.0 norm_ted = 0.0 for j in range(k): if (i != j): ted= alg.ted(T[i], T[j]) print 'TED ' + str(i) + str(j) + ' is ' + str(ted) mag = 2 * (T[i].n + T[j].n) - 1 print 'MAG ' + str(i) + str(j) + ' is ' + str (mag) + ' and ' + str ( 2 * ted ) norm_ted = (2 * ted) / mag print 'norm_ted ' + str(i) + str(j) + ' is ' + str (norm_ted) sum_norm_ted = sum_norm_ted + norm_ted print 'sum_norm_ted ' + str(i) + str(j) + ' is ' + str (sum_norm_ted) From bgailer at gmail.com Sat Apr 26 03:35:28 2008 From: bgailer at gmail.com (bob gailer) Date: Fri, 25 Apr 2008 21:35:28 -0400 Subject: [Tutor] Help with Recurring Function In-Reply-To: <979115.60724.qm@web55603.mail.re4.yahoo.com> References: <979115.60724.qm@web55603.mail.re4.yahoo.com> Message-ID: <481286E0.2070602@gmail.com> Sanhita Mallick wrote: > Hi. > > I am struggling with a simple recurring function, but > can't understand why this is happening. Please help. > > Here is the script. T(i) are trees (as in graphs). > The program operates great, until the step where > norm_ted is calculated. Mysteriously norm_ted becomes > 0, even though "mag" value is calculated correctly. > Also, strangely, sum_norm_ted also becomes zero. > > What am I missing? > Well for one thing, some code. What are F1, F2 and F3? What is alg? Also your code got mangled by something in the email process leaving a lot of folded lines. Your code would be a lot easier to red if you use % formatting (e.g.): print 'TED %s %s is %s' % str(i, j, ted) or just print 'TED', i, j, 'is', ted I took the liberty of applying this to your code and reducing the indent size in hopes of it coming across easier to read. Also note the the 3 statements following the for i loop do nothing useful, so I removed them.\ And what is the use of mean_ted? It is created but never referenced. > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > T = [F1, F2, F3] > k = len(T) > mean_ted = {} > for i in range(k): > for j in range(k): > if (i != j): > ted = alg.ted(T[i], T[j]) > print 'TED %s %s is %s' % (i, j, ted) > mag = 2 * (T[i].n + T[j].n) - 1 > print 'MAG %s %s is %s and %s' % (i, j, mag, 2 * ted) > norm_ted = (2 * ted) / mag > print 'norm_ted %s %s is %s and %s' % (i, j, norm_ted) > sum_norm_ted = sum_norm_ted + norm_ted > print 'sum_norm_ted %s %s is %s' % (i, j, sum_norm_ted) > > -- Bob Gailer 919-636-4239 Chapel Hill, NC From kent37 at tds.net Sat Apr 26 03:54:24 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 Apr 2008 21:54:24 -0400 Subject: [Tutor] Help with Recurring Function In-Reply-To: <979115.60724.qm@web55603.mail.re4.yahoo.com> References: <979115.60724.qm@web55603.mail.re4.yahoo.com> Message-ID: <48128B50.7040006@tds.net> Sanhita Mallick wrote: > I am struggling with a simple recurring function What is a recurring function? Do you mean looping? > > Here is the script. T(i) are trees (as in graphs). > The program operates great, until the step where > norm_ted is calculated. Mysteriously norm_ted becomes > 0, even though "mag" value is calculated correctly. > Also, strangely, sum_norm_ted also becomes zero. > > What am I missing? Do you mean for sum_norm_ted to be the sum over all i and j? If so, you should initialize it before the start of the outer loop. I don't know why you are getting 0 at the end of the loop. It is as if sum_norm_ted and norm_ted are initialized but the inner loop doesn't run. Is this the exact code that you have trouble with? Kent > > Thanks. > -Sanhita > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > T = [F1, F2, F3] > k = len(T) > mean_ted = {} > for i in range(k): > sum_norm_ted = 0.0 > mag = 0.0 > norm_ted = 0.0 > for j in range(k): > if (i != j): > ted= alg.ted(T[i], T[j]) > print 'TED ' + str(i) + str(j) + ' is ' + > str(ted) > mag = 2 * (T[i].n + T[j].n) - 1 > print 'MAG ' + str(i) + str(j) + ' is ' + > str (mag) + ' and ' + str ( 2 * ted ) > norm_ted = (2 * ted) / mag > print 'norm_ted ' + str(i) + str(j) + ' is > ' + str (norm_ted) > sum_norm_ted = sum_norm_ted + norm_ted > print 'sum_norm_ted ' + str(i) + str(j) + > ' is ' + str (sum_norm_ted) > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Sat Apr 26 05:10:13 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 25 Apr 2008 20:10:13 -0700 Subject: [Tutor] Best way to convert list of ints to a string? Message-ID: <20080426031034.C24C91E4009@bag.python.org> An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Apr 26 05:28:03 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 Apr 2008 23:28:03 -0400 Subject: [Tutor] Best way to convert list of ints to a string? In-Reply-To: <20080426031034.C24C91E4009@bag.python.org> References: <20080426031034.C24C91E4009@bag.python.org> Message-ID: <4812A143.7020600@tds.net> Dick Moores wrote: > I have the feeling that I've either forgotten (or never knew) some basic > Python built-in or something, but in case I haven't, what's the best way > to convert a list of integers to a string? I dunno about 'best', but here is one way to do it: ''.join(map(str, intList)) Perhaps faster using iterator.imap() instead of map(). Kent From rdm at rcblue.com Sat Apr 26 07:57:52 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 25 Apr 2008 22:57:52 -0700 Subject: [Tutor] Best way to convert list of ints to a string? In-Reply-To: <4812A143.7020600@tds.net> References: <20080426031034.C24C91E4009@bag.python.org> <4812A143.7020600@tds.net> Message-ID: <20080426055806.DE8D91E4009@bag.python.org> At 08:28 PM 4/25/2008, Kent Johnson wrote: >Dick Moores wrote: >>I have the feeling that I've either forgotten (or never knew) some >>basic Python built-in or something, but in case I haven't, what's >>the best way to convert a list of integers to a string? > >I dunno about 'best', but here is one way to do it: >''.join(map(str, intList)) > >Perhaps faster using iterator.imap() instead of map(). I suppose you meant ''.join(itertools.imap(str, intList)) And for intList = [0,1,2,3,4,5,6,7,8,9], this is 2X slower than ''.join(map(str, intList)) . But for intList = 1000*[0,1,2,3,4,5,6,7,8,9], ''.join(itertools.imap(str, intList)) has a very small edge. Thanks, Kent, both of those are in my "never knew" category. Dick ================================ UliPad <>: http://code.google.com/p/ulipad/ Version 3.9 was released April 25! From alan.gauld at btinternet.com Sat Apr 26 09:37:47 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Apr 2008 08:37:47 +0100 Subject: [Tutor] Best way to convert list of ints to a string? References: <20080426031034.C24C91E4009@bag.python.org><4812A143.7020600@tds.net> <20080426055806.DE8D91E4009@bag.python.org> Message-ID: "Dick Moores" wrote > And for intList = [0,1,2,3,4,5,6,7,8,9], this is 2X slower than > ''.join(map(str, intList)) . > But for intList = 1000*[0,1,2,3,4,5,6,7,8,9], > ''.join(itertools.imap(str, intList)) has a very small edge. > > Thanks, Kent, both of those are in my "never knew" category. You could have used the more familiar: ''.join(str(n) for n in intList) Whis is just map using a comprehension style... Alan g From sanhitam at yahoo.com Sat Apr 26 14:16:34 2008 From: sanhitam at yahoo.com (Sanhita Mallick) Date: Sat, 26 Apr 2008 05:16:34 -0700 (PDT) Subject: [Tutor] Help with Recurring Function In-Reply-To: <48128B50.7040006@tds.net> Message-ID: <864974.94035.qm@web55608.mail.re4.yahoo.com> Hi Kent. sum_norm_ted is sum over each i, and all j. That is why it is initialize to zero at the beginning of each i loop. The inner loop IS running - which I checked by all the print statements. The value of "ted" and "mag" ARE being calculated correctly as checked by the "print" statement. But when we do norm_ted = (2 * ted) / mag becomes zero, and subsequently sum_norm_ted becomes zero. --- Kent Johnson wrote: > Sanhita Mallick wrote: > > > I am struggling with a simple recurring function > > What is a recurring function? Do you mean looping? > > > > Here is the script. T(i) are trees (as in graphs). > > The program operates great, until the step where > > norm_ted is calculated. Mysteriously norm_ted > becomes > > 0, even though "mag" value is calculated > correctly. > > Also, strangely, sum_norm_ted also becomes zero. > > > > What am I missing? > > Do you mean for sum_norm_ted to be the sum over all > i and j? If so, you > should initialize it before the start of the outer > loop. > > I don't know why you are getting 0 at the end of the > loop. It is as if > sum_norm_ted and norm_ted are initialized but the > inner loop doesn't > run. Is this the exact code that you have trouble > with? > > Kent > > > > Thanks. > > -Sanhita > > > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > T = [F1, F2, F3] > > k = len(T) > > mean_ted = {} > > for i in range(k): > > sum_norm_ted = 0.0 > > mag = 0.0 > > norm_ted = 0.0 > > for j in range(k): > > if (i != j): > > ted= alg.ted(T[i], T[j]) > > print 'TED ' + str(i) + str(j) + ' is > ' + > > str(ted) > > mag = 2 * (T[i].n + T[j].n) - 1 > > print 'MAG ' + str(i) + str(j) + ' is > ' + > > str (mag) + ' and ' + str ( 2 * ted ) > > norm_ted = (2 * ted) / mag > > print 'norm_ted ' + str(i) + str(j) + > ' is > > ' + str (norm_ted) > > sum_norm_ted = sum_norm_ted + norm_ted > > print 'sum_norm_ted ' + str(i) + > str(j) + > > ' is ' + str (sum_norm_ted) > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > From alan.gauld at btinternet.com Sat Apr 26 14:46:39 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Apr 2008 13:46:39 +0100 Subject: [Tutor] Help with Recurring Function References: <48128B50.7040006@tds.net> <864974.94035.qm@web55608.mail.re4.yahoo.com> Message-ID: "Sanhita Mallick" wrote > being calculated correctly as checked by the "print" > statement. But when we do > > norm_ted = (2 * ted) / mag It might be an integer division issue. Try norm_ted = (2*ted) / float(mag) Just a thought... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From amonroe at columbus.rr.com Sat Apr 26 17:04:22 2008 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat, 26 Apr 2008 11:04:22 -0400 Subject: [Tutor] 6x6 word square solver too slow In-Reply-To: <3270C06B-754D-4FCE-A3AF-050EB735A767@drinktomi.com> References: <13886216482.20080424184505@columbus.rr.com> <17195663947.20080424212233@columbus.rr.com> <3270C06B-754D-4FCE-A3AF-050EB735A767@drinktomi.com> Message-ID: <112231373387.20080426110422@columbus.rr.com> > I'd suggest googling for 'trie'. Tries are method of > indexing sets of strings by prefix. Ah, will look it up. > As I recall, English words are more similar at the > front, so once you have an indexing scheme you'll > probably to do even less work if you index and search > from the back of the words towards the front. I'll have to consider that. In the meantime, my current version is much improved - it caches rejects, so that if one word starting with 'ab' fails, it doesn't bother testing any further words starting with 'ab'. Also I started using psyco on it. Alan -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: 4cyte013b.py URL: From devsfan1830 at gmail.com Sun Apr 27 02:56:31 2008 From: devsfan1830 at gmail.com (James Duffy) Date: Sat, 26 Apr 2008 20:56:31 -0400 Subject: [Tutor] seeking help to a problem w/ sockets Message-ID: <000001c8a801$89e132d0$9da39870$@com> I have a problem w/ a file transfer receiver. They way it works is it binds a port for incoming transfer , when the file transfer is complete. It closes the connection and the socket, then loops back and restarts the bind and listen. I have it set so that the socket is reuseable, which is why this works. However, if the program that is using this function is closed while listening, it appears that it does not "un-bind" because when the program is reopened and a listen attepted to start I get a "port already in use" error. Only a reboot fixes this issue. This code is imported into a main GUI script. We have it set to execute some cleanup functions on exit, I need a function that can dig down to the thread the listener is running in, stop the listen and close the connection and socket. I basically need to get to the close function and then stop the while loop. Thanks in advance for any help anyone can give. My code for the listener class follows: class Reciever ( Thread ): # the reciever class for the test tool, runs as a separate thread from the main program def __init__( this ): Thread.__init__( this ) def run(this): this.process() def bindsock( this ): # create a new socket, bid the socket to the port, listen until connection recieved this.Lport=listen this.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) this.sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) this.sock.bind(('',this.Lport)) this.sock.listen(1) print "Listening on port " +str(this.Lport) def acceptsock( this ): #when connection is incoming, accept the connection this.conn, this.addr = this.sock.accept() print 'Got connection from', this.addr def transfer( this ): #when connection is full established, begin data download global filenumber print 'Starting media transfer ' openfile="XMLrecieved"+str(filenumber)+".xml" f = open(openfile,"wb") #create and open a new file for writing incoming data to while 1: data = this.conn.recv(1024) #check for incoming data if not data: break #if not present, break the loop f.write(data) #if data is present, write it to file and loop back f.close() #when loop is broken, close the file print "Got XML file:" + openfile print 'Closing media transfer' filenumber = filenumber + 1 def close( this ): #close all connections and sockets this.conn.close() this.sock.close() def process( this ): #this is the loop of the thread, it listens, receives, closes then repeats until entire program is closed while 1: this.bindsock() this.acceptsock() this.transfer() this.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Apr 27 09:40:39 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 27 Apr 2008 08:40:39 +0100 Subject: [Tutor] seeking help to a problem w/ sockets References: <000001c8a801$89e132d0$9da39870$@com> Message-ID: "James Duffy" wrote > works. However, if the program that is using this function is closed > while > listening, it appears that it does not "un-bind" because when the > program is > reopened and a listen attepted to start I get a "port already in > use" error. > Only a reboot fixes this issue. You don;t say what OS you are using but I have had this problem on *nix boxes where the socket/port is represented by a file in /tmp and you need to go in and kill the file manually(or by a script of course) before you can reopen the socket. If its not *nix then you may have to look at a similar fix on your OS - maybe in the registry of Windows for example. > the listen and close the connection and socket. I basically need to > get to > the close function and then stop the while loop. Thanks in advance > for any > help anyone can give. My code for the listener class follows: I haven't read the code, sorry, but could you use a try/finally wrapper around your threads? Just a thought, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sanhitam at yahoo.com Sun Apr 27 11:54:10 2008 From: sanhitam at yahoo.com (Sanhita Mallick) Date: Sun, 27 Apr 2008 02:54:10 -0700 (PDT) Subject: [Tutor] Help with Recurring Function In-Reply-To: Message-ID: <653269.86413.qm@web55601.mail.re4.yahoo.com> Hi Alan. Thanks a lot. It worked !!!! > ------------------------------ > > Message: 2 > Date: Sat, 26 Apr 2008 13:46:39 +0100 > From: "Alan Gauld" > Subject: Re: [Tutor] Help with Recurring Function > To: tutor at python.org > Message-ID: > Content-Type: text/plain; format=flowed; > charset="iso-8859-1"; > reply-type=original > > > "Sanhita Mallick" wrote > > > > being calculated correctly as checked by the > "print" > > statement. But when we do > > > > norm_ted = (2 * ted) / mag > > It might be an integer division issue. > > Try > > norm_ted = (2*ted) / float(mag) > > Just a thought... > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > From kent37 at tds.net Sun Apr 27 13:18:01 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 27 Apr 2008 07:18:01 -0400 Subject: [Tutor] seeking help to a problem w/ sockets In-Reply-To: <000001c8a801$89e132d0$9da39870$@com> References: <000001c8a801$89e132d0$9da39870$@com> Message-ID: <481460E9.5050904@tds.net> James Duffy wrote: > I have a problem w/ a file transfer receiver. They way it works is it > binds a port for incoming transfer , when the file transfer is complete. > It closes the connection and the socket, then loops back and restarts > the bind and listen. I have it set so that the socket is reuseable, > which is why this works. However, if the program that is using this > function is closed while listening, it appears that it does not > ?un-bind? because when the program is reopened and a listen attepted to > start I get a ?port already in use? error. Only a reboot fixes this > issue. This code is imported into a main GUI script. We have it set to > execute some cleanup functions on exit, I need a function that can dig > down to the thread the listener is running in, stop the listen and close > the connection and socket. I basically need to get to the close function > and then stop the while loop. The usual way to terminate a thread from another thread is to set a flag that the running thread checks periodically. Here is an example: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448 This discussion may be helpful: http://groups.google.com/group/comp.lang.python/browse_thread/thread/7f116836f1fd2805/6adcc7e371238fdd?lnk=gst Kent From mwalsh at groktech.org Sun Apr 27 15:36:54 2008 From: mwalsh at groktech.org (Martin Walsh) Date: Sun, 27 Apr 2008 08:36:54 -0500 Subject: [Tutor] seeking help to a problem w/ sockets In-Reply-To: <000001c8a801$89e132d0$9da39870$@com> References: <000001c8a801$89e132d0$9da39870$@com> Message-ID: <48148176.4080305@groktech.org> James Duffy wrote: > I have a problem w/ a file transfer receiver. They way it works is it > binds a port for incoming transfer , when the file transfer is complete. > It closes the connection and the socket, then loops back and restarts > the bind and listen. I have it set so that the socket is reuseable, > which is why this works. However, if the program that is using this > function is closed while listening, it appears that it does not > ?un-bind? because when the program is reopened and a listen attepted to > start I get a ?port already in use? error. Only a reboot fixes this > issue. This code is imported into a main GUI script. We have it set to > execute some cleanup functions on exit, I need a function that can dig It should be noted that my socket, threading, and related gui skillz are lacking, so beware. IIUC, the usual cause for an 'address already in use' error is when the server closes it's end of the socket first, leaving it in a TIME_WAIT state. Presumably, this would be a feature of tcp, and the socket is released after some timeout period to be sure the client is no longer communicating. However setting the socket options as you have, with setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1), is the typically suggested workaround in this situation. Also, given that you need to reboot to clear the error, I suspect that your gui program isn't actually terminating -- but instead hanging on the Receiver thread, and thus holding on to the socket. You can, of course, confirm with netstat and/or by checking the process list. If you just want the thread to die when you close the gui app, then you could also try to setDaemon(True) on your Receiver class -- which should allow the program to exit, that is -- if there are no non-daemon threads remaining. HTH, Marty From dineshbvadhia at hotmail.com Sun Apr 27 15:57:46 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sun, 27 Apr 2008 06:57:46 -0700 Subject: [Tutor] Loading and using large sparse matrices under Windows Message-ID: Hi! Does anyone on this list have experience of using the Scipy Sparse matrix library for loading and using very large datasets (>20,000 rows x >1m columns of integers) under Windows? I'm using a recent Scipy svn that supports (sparse) integer matrices but it still causes the pythonw.exe program to abort for the larger datasets. I have ample RAM to create, load and use the matrices. I posted a note on the Scipy list but thought I'd try here too as you always get a response! Plus, I need a solution to the problem pdq. Thanks! Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From keridee at jayco.net Mon Apr 28 17:53:39 2008 From: keridee at jayco.net (tiger12506) Date: Mon, 28 Apr 2008 10:53:39 -0500 Subject: [Tutor] seeking help to a problem w/ sockets References: <000001c8a801$89e132d0$9da39870$@com> <48148176.4080305@groktech.org> Message-ID: <002001c8a948$074aef30$0702a8c0@home> How is the window being closed? By someone forcing it to close? Or terminating the process? If someone is just closing the window you can setup an atexit handler that will close the socket before it finishes. However, if the process is being terminated, then you will have to use one of the other options. If that's the only way you have to close the program then you will definitely need a flag of some sort. I've been known to play all sorts of tricks. Most nastiest of which includes creating a file in a particular directory that the program periodically polls. Don't do this. Use threads. Or a non-blocking keypress or something. From alan.gauld at btinternet.com Sun Apr 27 17:07:38 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 27 Apr 2008 16:07:38 +0100 Subject: [Tutor] Loading and using large sparse matrices under Windows References: Message-ID: "Dinesh B Vadhia" wrote > I'm using a recent Scipy svn that supports (sparse) integer matrices > but it still causes the pythonw.exe program to abort for the > larger datasets. I have ample RAM to create, load and use > the matrices. Can you narrow the problem down any further? Do you have access to a different OS - Linux or MacOS say? (Maybe you could try one of the LiveCD trial versions of Linux?) That would prove it to be a Windows build of SciPy issue. Or even a Cygwin build of Python/SciPy? > I posted a note on the Scipy list Probably your best bet. > but thought I'd try here too as you always get a response! Well you got a response, but I'm not sure if it helps any! :-) Good luck, Alan G From metolone+gmane at gmail.com Sun Apr 27 17:13:01 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sun, 27 Apr 2008 08:13:01 -0700 Subject: [Tutor] seeking help to a problem w/ sockets References: <000001c8a801$89e132d0$9da39870$@com> Message-ID: "James Duffy" wrote in message news:000001c8a801$89e132d0$9da39870$@com... [snip] > def close( this ): #close all connections and sockets > this.conn.close() > this.sock.close() > > def process( this ): #this is the loop of the thread, it listens, > receives, closes then repeats until entire program is closed > while 1: > this.bindsock() > this.acceptsock() > this.transfer() > this.close() There is no need to close the server socket after each connection. Try: def close( this ): #close all connections and sockets this.conn.close() def process( this ): this.bindsock() while 1: this.acceptsock() this.transfer() this.close() Also, take a look at the SocketServer libary. It handles multiple simultaneous connections and the details of setting up and tearing down connections: import threading import SocketServer class MyHandler(SocketServer.StreamRequestHandler): def handle(self): print 'Starting media transfer ' openfile="XMLrecieved"+str(self.server.filenumber)+".xml" f = open(openfile,"wb") while 1: data = self.request.recv(1024) if not data: break f.write(data) f.close() print "Got XML file:" + openfile print 'Closing media transfer' self.server.filenumber += 1 class MyServer(SocketServer.ThreadingTCPServer): filenumber = 1 class MyThread(threading.Thread): def run(self): listen=2222 server = MyServer(('',listen),MyHandler) server.serve_forever() t=MyThread() t.setDaemon(True) t.start() --Mark From jeff at drinktomi.com Mon Apr 28 00:47:42 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Sun, 27 Apr 2008 15:47:42 -0700 Subject: [Tutor] seeking help to a problem w/ sockets In-Reply-To: <000001c8a801$89e132d0$9da39870$@com> References: <000001c8a801$89e132d0$9da39870$@com> Message-ID: <55C3B9F0-66EF-49D2-B8AB-B2A2F7421AEB@drinktomi.com> It sounds like a process is still listening on the port. If you're on a Unix system then you can use lsof (aka list open files) to locate the process holding on the socket. Killing the process should free the socket. Also, you don't have to close the socket after every connection completes. Try looking at the SocketServer module. It takes care of a lot of the details for you. - Jeff Younker - jeff at drinktomi.com - On Apr 26, 2008, at 5:56 PM, James Duffy wrote: > I have a problem w/ a file transfer receiver. They way it works is > it binds a port for incoming transfer , when the file transfer is > complete. It closes the connection and the socket, then loops back > and restarts the bind and listen. I have it set so that the socket > is reuseable, which is why this works. However, if the program that > is using this function is closed while listening, it appears that it > does not ?un-bind? because when the program is reopened and a listen > attepted to start I get a ?port already in use? error. Only a reboot > fixes this issue. This code is imported into a main GUI script. We > have it set to execute some cleanup functions on exit, I need a > function that can dig down to the thread the listener is running in, > stop the listen and close the connection and socket. I basically > need to get to the close function and then stop the while loop. > Thanks in advance for any help anyone can give. My code for the > listener class follows: > > class Reciever ( Thread ): # the reciever class for the test tool, > runs as a separate thread from the main program > > def __init__( this ): > Thread.__init__( this ) > > def run(this): > this.process() > > def bindsock( this ): # create a new socket, bid the socket to > the port, listen until connection recieved > this.Lport=listen > this.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > this.sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) > this.sock.bind(('',this.Lport)) > this.sock.listen(1) > print "Listening on port " +str(this.Lport) > > def acceptsock( this ): #when connection is incoming, accept the > connection > this.conn, this.addr = this.sock.accept() > > print 'Got connection from', this.addr > > def transfer( this ): #when connection is full established, > begin data download > global filenumber > print 'Starting media transfer ' > > openfile="XMLrecieved"+str(filenumber)+".xml" > f = open(openfile,"wb") #create and open a new file for > writing incoming data to > while 1: > data = this.conn.recv(1024) #check for incoming data > if not data: break #if not present, break the loop > f.write(data) #if data is present, write it to > file and loop back > f.close() #when loop is broken, close the file > > print "Got XML file:" + openfile > print 'Closing media transfer' > filenumber = filenumber + 1 > > def close( this ): #close all connections and sockets > this.conn.close() > this.sock.close() > > def process( this ): #this is the loop of the thread, it > listens, receives, closes then repeats until entire program is closed > while 1: > this.bindsock() > this.acceptsock() > this.transfer() > this.close() > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From zchunbo at hotmail.com Mon Apr 28 07:04:28 2008 From: zchunbo at hotmail.com (Kimbol Zhang) Date: Mon, 28 Apr 2008 00:04:28 -0500 Subject: [Tutor] [tutor] how to call GSL function from python using ctype Message-ID: i'm trying to call the function from GSL by ctype , the interface. while it seems i need to install some package from GSL. ef=cdll.libgsl.gsl_sf_erf above line gives below error : ef=cdll.libgsl.gsl_sf_erf File "C:\Python25\lib\ctypes\__init__.py", line 423, in __getattr__ dll = self._dlltype(name) File "C:\Python25\lib\ctypes\__init__.py", line 348, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 126] The specified module could not be found do i need to install sth? i already installed GnuWin32 and gsl-1.8 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Apr 28 09:18:19 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Apr 2008 08:18:19 +0100 Subject: [Tutor] [tutor] how to call GSL function from python using ctype References: Message-ID: "Kimbol Zhang" wrote > i'm trying to call the function from GSL by ctype , Any reason why you aren't using PyGSL or PyMix? Is there something in GSL that they don't give you? Alan G From twomol at hotmail.com Mon Apr 28 09:03:16 2008 From: twomol at hotmail.com (tuyun) Date: Mon, 28 Apr 2008 07:03:16 +0000 Subject: [Tutor] Debug C library in python program Message-ID: Hi May be this is a basic question, but I havent find answer through google :( I'm not familiar with python. I wrote a C library, and some body used the library in his python program, and found a bug of my library, I want to figure out what's wrong in my library. So how can I make a breakpoint for a suspect function in my C library when he is "running in " a python program. Is there a debugger or what, which like gdb, I just need to issue:b xxxxxxxx? Thanks in advance for my "amateurish question" :( Thanks Twomol _________________________________________________________________ ???MSN??????????????????? http://mobile.msn.com.cn/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Mon Apr 28 17:09:45 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 28 Apr 2008 10:09:45 -0500 Subject: [Tutor] Debug C library in python program In-Reply-To: References: Message-ID: <200804281009.45684.cfuller084@thinkingplanet.net> I expect if you take that route, you would have to compile the Python interpreter with debugging enabled, and then run that with gdb. A better idea might be to recompile your library to produce debugging output at strategic locations, and then output it to the console or a socket to some logging program. Note that the C stdout/stderr usually doesn't correspond to the ones in Python's sys module. Cheers On Monday 28 April 2008 02:03, tuyun wrote: > Hi > May be this is a basic question, but I havent find answer through google :( > I'm not familiar with python. I wrote a C library, and some body used the > library in his python program, and found a bug of my library, I want to > figure out what's wrong in my library. So how can I make a breakpoint for a > suspect function in my C library when he is "running in " a python program. > Is there a debugger or what, which like gdb, I just need to issue:b > xxxxxxxx? Thanks in advance for my "amateurish question" :( > > Thanks > Twomol > _________________________________________________________________ > ???MSN??????????????????? > http://mobile.msn.com.cn/ From zebra05 at gmail.com Mon Apr 28 19:24:16 2008 From: zebra05 at gmail.com (OkaMthembo) Date: Mon, 28 Apr 2008 19:24:16 +0200 Subject: [Tutor] Stackless Python Message-ID: Hi guys, I was just wondering...doesanybody think Stackless Python would be ideal for writing web apps, ie better for large systems? And are there Python hosts that run Stackless? Regards, -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Apr 28 19:33:07 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Apr 2008 18:33:07 +0100 Subject: [Tutor] Debug C library in python program References: Message-ID: "tuyun" wrote > I'm not familiar with python. I wrote a C library, > and some body used the library in his python program, > and found a bug ... > So how can I make a breakpoint for a suspect > function in my C library when he is "running in " > a python program. Not cleanly. I think the easiest way is to write the simplest C driver program that you can that mimics what the Python code does. See if you can replicate the fault condition and debug it there. Othewise you could spend a lot of time and end up changing the runtime environment so much its no longer valid! Python works well with working C code but debugging C from inside Python is not so easy. You can test it (does it work or not) easily but you can't step into the C code from the Python debugger and the C debugger won't play easily with Python. HTH Alan G. From alan.gauld at btinternet.com Mon Apr 28 19:39:41 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 28 Apr 2008 17:39:41 +0000 (GMT) Subject: [Tutor] [tutor] how to call GSL function from python using ctype Message-ID: <248623.52731.qm@web86704.mail.ukl.yahoo.com> > it's just an exercise for using 3rd party software. > do you mean GSL is better than pygsl or pyMix? No, PyGSL is a Python interface to GSL so you don't need to use ctypes. PyMix is similar but offers more than just GSL. But if you actually want experience of ctypes then they aren't really relevant Alan G. kimbol ----- Original Message ----- From: "Alan Gauld" To: Sent: Monday, April 28, 2008 2:18 AM Subject: Re: [Tutor] [tutor] how to call GSL function from python using ctype > > "Kimbol Zhang" wrote >> i'm trying to call the function from GSL by ctype , > > Any reason why you aren't using PyGSL or PyMix? > > Is there something in GSL that they don't give you? > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Mon Apr 28 20:07:08 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Apr 2008 19:07:08 +0100 Subject: [Tutor] Stackless Python References: Message-ID: "OkaMthembo" wrote > I was just wondering...does anybody think Stackless > Python would be ideal for writing web apps, ie better > for large systems? "ideal" and "better" are two very different things. While stackless might have some advantages over normal Python for large scale web apps there are other languages/solutions that are better still, so neither is ideal. But either provides a more productive environment than the alternatives. There are no perfect solutions, only compromises. The role of the engineer is to select the solution with least compromise for the problem at hand. Alan G. From dkuhlman at rexx.com Mon Apr 28 20:34:31 2008 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Mon, 28 Apr 2008 11:34:31 -0700 Subject: [Tutor] Debug C library in python program In-Reply-To: References: Message-ID: <20080428183431.GA1016@cutter.rexx.com> On Mon, Apr 28, 2008 at 07:03:16AM +0000, tuyun wrote: > > Hi > May be this is a basic question, but I havent find answer through google :( > I'm not familiar with python. I wrote a C library, and some body used the library in his python program, and found a bug of my library, I want to figure out what's wrong in my library. > So how can I make a breakpoint for a suspect function in my C library when he is "running in " a python program. > Is there a debugger or what, which like gdb, I just need to issue:b xxxxxxxx? > Thanks in advance for my "amateurish question" :( > > Thanks > Twomol Yes, I have been able to debug into a Python extension module using gdb on Linux. Attached are several files that should help. Here is a bit of explanation about the attached files: - run_gdb starts the gdb debugger and: (1) specifies a directory containing source files (-d flag); (2) specifies a file containing gdb commands (the -x flag and for example test2.gdb); (3) passes in the the program name (python) and the PID of the python process (that's what the ps command in back-ticks does). - test1.gdb and test2.gdb -- Sample gdb command files which can be used by run_gdb. Of particular interest are the ability to set breakpoints and to specify arguments that would be passed in from the command line if you were not running with the debugger. test1.gdb gives examples of doing both of these. Needless to say, you will need to modify the attached files for your use. If I recall correctly, you could separately: (1) start up your python test (with something like raw_input() in your test to temporarily stop the test) and then (2) start up gdb and attach it to that running python process in two separate steps. The run_gdb sample script combines those two steps. For more information try: - "man gdb" - The gdb manual: * "Debugging with GDB" http://www.delorie.com/gnu/docs/gdb/gdb_toc.html * "20.3 Command files" http://www.delorie.com/gnu/docs/gdb/gdb_191.html Hope this helps. It has been quite a while since I've done this, but I remember that it worked pretty slick. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman -------------- next part -------------- #!/bin/sh -v gdb -d /path/to/your/source/code -x test2.gdb python `ps -C python -o pid=` -------------- next part -------------- # Set arguments that would be passed in from the command line. set args --param ital 'no' --param border 2 camping_par.xsl camping_list.xml #set args --param ital 'no' --param border 2 --output tmp1.html camping_par.xsl camping_list.xml # Set breakpoints. b main b xsltProcess -------------- next part -------------- b translate_to_file b translate_to_string From norman at khine.net Mon Apr 28 20:37:18 2008 From: norman at khine.net (Norman Khine) Date: Mon, 28 Apr 2008 20:37:18 +0200 Subject: [Tutor] Menus with dictionaries or lists? Message-ID: <4816195E.9040704@khine.net> Hello, I have a csv file as follows: "bi";"Burundi";"none";"none" "km";"Comoros";"none";"none" "dj";"Djibouti";"none";"none" "er";"Eritrea";"none";"none" "us";"United States of America";"Alabama";"Black Belt" "us";"United States of America";"Alabama";"Central Alabama" "us";"United States of America";"Alabama";"Greater Birmingham" "uk";"United Kingdom";"East Anglia";"Cambridgeshire" "uk";"United Kingdom";"East Anglia";"Norfolk" "uk";"United Kingdom";"East Anglia";"Suffolk" "fr";"France";"Alsace";"Bas-Rhin" "fr";"France";"Alsace";"Haut-Rhin" "fr";"France";"Aquitaine";"Dordogne" I am trying to figure out a script on the command line so that you get a navigation through which a user can drill down by: Country ->Region -->County I have some countries for which I don't have data for region or county and I would want to exclude this from the list and only include the country that has a county. What is the most effective way to do this. Thanks Norman From pylinuxian at gmail.com Mon Apr 28 21:45:19 2008 From: pylinuxian at gmail.com (Arthur) Date: Mon, 28 Apr 2008 19:45:19 +0000 Subject: [Tutor] Menus with dictionaries or lists? In-Reply-To: <4816195E.9040704@khine.net> References: <4816195E.9040704@khine.net> Message-ID: http://www.amk.ca/python/howto/curses/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Mon Apr 28 20:56:09 2008 From: norman at khine.net (Norman Khine) Date: Mon, 28 Apr 2008 20:56:09 +0200 Subject: [Tutor] Menus with dictionaries or lists? In-Reply-To: References: <4816195E.9040704@khine.net> Message-ID: <48161DC9.5060900@khine.net> thanks for the link, but i was more interested in understanding lists and dictionaries thus I wanted to be able to see this on the command line. Arthur wrote: > http://www.amk.ca/python/howto/curses/ From alan.gauld at btinternet.com Mon Apr 28 22:37:32 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Apr 2008 21:37:32 +0100 Subject: [Tutor] Menus with dictionaries or lists? References: <4816195E.9040704@khine.net> Message-ID: "Norman Khine" wrote > I have a csv file as follows: > > "er";"Eritrea";"none";"none" > "us";"United States of America";"Alabama";"Central Alabama" > "uk";"United Kingdom";"East Anglia";"Cambridgeshire" > "uk";"United Kingdom";"East Anglia";"Norfolk" > "fr";"France";"Aquitaine";"Dordogne" > > I am trying to figure out a script on the command line so that you > get a navigation through which a user can drill down by: > > Country > ->Region > -->County Welcome message... There are XXX records to choose from. Select a main criteria for filtering list: Country(C), Region(R), District(D)? Select a secondary criteria for filtering list: Region(R), District(D)? 20,say> Select a District for filtering list: or Display final list matching criteria. Provide option for going back a level at each prompt. > I have some countries for which I don't have data for region or > county and I would want to exclude this from the list and only > include the country that has a county. Not quite sure what you mean, but if you just don't want to display them thats fairly straightforward to do by testing each record before printing. > What is the most effective way to do this. For low data volumes what I've suggested abopve will work with an in-memory data store - list or dictionary. If volumes are bigger you may be better buuilding sa SqlLite database and building up a dynamic SQL query string. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From pylinuxian at gmail.com Mon Apr 28 22:43:59 2008 From: pylinuxian at gmail.com (Arthur) Date: Mon, 28 Apr 2008 20:43:59 +0000 Subject: [Tutor] Menus with dictionaries or lists? In-Reply-To: References: <4816195E.9040704@khine.net> Message-ID: #!/usr/bin/python # import csv file = csv.reader(open("file.txt", "r"),delimiter=';') for row in file: # now each row is a list #print row #print row[0] cntry=row[0] row[0]={} row[0]['country']=row[1] row[0]['county']=row[2] print 'for country',cntry, row[0] this is simple enough i guess, use your imagination to finish it up ... to take input from user at cli you will use : raw_input("Enter Country") -------------- next part -------------- An HTML attachment was scrubbed... URL: From twomol at hotmail.com Tue Apr 29 03:24:44 2008 From: twomol at hotmail.com (tuyun) Date: Tue, 29 Apr 2008 01:24:44 +0000 Subject: [Tutor] =?utf-8?q?Debug_C_library_in_python_program=E2=80=8F?= Message-ID: HiMay be this is a basic question, but I havent find answer through google :(I'm not familiar with python. I wrote a C library, and some body used the library in his python program, and found a bug of my library, I want to figure out what's wrong in my library.So how can I make a breakpoint for a suspect function in my C library when he is "running in " a python program.Is there a debugger or what, which like gdb, I just need to issue:b functionname?Thanks in advance for my "amateurish question" :( ThanksTwomol _________________________________________________________________ ???MSN??????????????????? http://mobile.msn.com.cn/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From twomol at hotmail.com Tue Apr 29 03:33:57 2008 From: twomol at hotmail.com (tuyun) Date: Tue, 29 Apr 2008 01:33:57 +0000 Subject: [Tutor] =?utf-8?q?_RE=3A_Debug_C_library_in_python_program?= =?utf-8?b?4oCPKGNhbmNlbGVkICk=?= Message-ID: Sorry for this duplicated post, it's my mistake, plz ignore it Sorry From: twomol at hotmail.comTo: tutor at python.orgSubject: Debug C library in python program?Date: Tue, 29 Apr 2008 01:24:44 +0000 HiMay be this is a basic question, but I havent find answer through google :(I'm not familiar with python. I wrote a C library, and some body used the library in his python program, and found a bug of my library, I want to figure out what's wrong in my library.So how can I make a breakpoint for a suspect function in my C library when he is "running in " a python program.Is there a debugger or what, which like gdb, I just need to issue:b functionname?Thanks in advance for my "amateurish question" :( ThanksTwomol Windows Live Writer????????????????????? ????? _________________________________________________________________ ?????????live mail???????? http://get.live.cn/product/mail.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim.peters at gmail.com Tue Apr 29 08:55:19 2008 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 29 Apr 2008 02:55:19 -0400 Subject: [Tutor] 6x6 word square solver too slow In-Reply-To: <112231373387.20080426110422@columbus.rr.com> References: <13886216482.20080424184505@columbus.rr.com> <17195663947.20080424212233@columbus.rr.com> <3270C06B-754D-4FCE-A3AF-050EB735A767@drinktomi.com> <112231373387.20080426110422@columbus.rr.com> Message-ID: <1f7befae0804282355k60049ca6m6acafe275adfe76@mail.gmail.com> [Jeff Younker] >> I'd suggest googling for 'trie'. Tries are method of >> indexing sets of strings by prefix. [R. Alan Monroe] > Ah, will look it up. Or you can puzzle it out from the attached program ;-) > ... > In the meantime, my current version is > much improved - it caches rejects, so that if one word starting with > 'ab' fails, it doesn't bother testing any further words starting with > 'ab'. Also I started using psyco on it. A better algorithm is what's really needed, and that often means simpler. The attached strives for the simplest possible code in the recursive workhorse function (`_extend()`), and that implies trying to place only one letter at a time, instead of trying to place an entire word in one gulp. You might think that has to be slower, but check it out: on my box this runs about 40 times faster than the program you attached (but not using psyco in either case: pscyo can't be used usefully with my program, because its solver is a generator function and psyco gives up when it sees a generator). For example, 11.8 seconds versus 552 given seed "enigma", 44 vs 1805 given seed "serene", and 0.66 versus 30 given seed "python". It's an interesting problem, and I'm curious to see whether someone has a faster approach than this. -------------- next part -------------- A non-text attachment was scrubbed... Name: wsquare.py Type: text/x-python Size: 3320 bytes Desc: not available URL: From mugunth at gmail.com Tue Apr 29 09:16:29 2008 From: mugunth at gmail.com (Muguntharaj Subramanian) Date: Tue, 29 Apr 2008 12:46:29 +0530 Subject: [Tutor] pyHook related doubt Message-ID: <8dd9fd0804290016p5a6c91ebx249eb05e87bdf451@mail.gmail.com> Hi All, I am trying to create a custom keyboard driver program(like http://www.tavultesoft.com/keyman/ ) for windows using python. If this python script is run in the background, what is typed should be converted into my native language. For example if I hit 'a' in the keyboard, the output of the keyboard should be a tamil unicode character(which will be pre-defined by user). For making such program, i tried exploring pyHook based on this tutorial. http://mindtrove.info/articles/monitoring-global-input-with-pyhook/ >From the tutorial, I have learned to capture the keys typed, but couldn't understand how to change the keys before they reach the windows applications. Attached is the sample code I used (In this code basically i am trying to change all the keys typed to 'b' in this code, but its not working ) Please guide me on how i can change the keys sent to the application using pyHook. Or is there any other library that I can make use of to create such application. Regards, Mugunth -- http://mugunth.blogspot.com http://thamizha.com http://tamilblogs.com -- http://webspace2host.com "Your friendly hosting provider" -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: pyhook-example.py Type: text/x-python Size: 1038 bytes Desc: not available URL: From cappy2112 at gmail.com Tue Apr 29 14:40:19 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Tue, 29 Apr 2008 05:40:19 -0700 Subject: [Tutor] Tutor Digest, Vol 50, Issue 84 In-Reply-To: References: Message-ID: <8249c4ac0804290540p22dac9adn36e2799d5a56659b@mail.gmail.com> I think you may have to send a message to the event look of you application manually, to let it know you have a key event for it. You may also need to temporarily enable/disbale the keydown event handler for pyHook, or else you wont be able to easily break out of that code (at least I couldn't) :-) You might want to post your message on the Python Win32 list. This issue is specific to Window event handling and there are a lot of people on that list who probably can help with this specific issue. Message: 7 Date: Tue, 29 Apr 2008 12:46:29 +0530 From: "Muguntharaj Subramanian" Subject: [Tutor] pyHook related doubt To: Tutor at python.org Message-ID: <8dd9fd0804290016p5a6c91ebx249eb05e87bdf451 at mail.gmail.com> Content-Type: text/plain; charset="utf-8" Hi All, I am trying to create a custom keyboard driver program(like http://www.tavultesoft.com/keyman/ ) for windows using python. If this python script is run in the background, what is typed should be converted into my native language. For example if I hit 'a' in the keyboard, the output of the keyboard should be a tamil unicode character(which will be pre-defined by user). For making such program, i tried exploring pyHook based on this tutorial. http://mindtrove.info/articles/monitoring-global-input-with-pyhook/ >From the tutorial, I have learned to capture the keys typed, but couldn't understand how to change the keys before they reach the windows applications. Attached is the sample code I used (In this code basically i am trying to change all the keys typed to 'b' in this code, but its not working ) Please guide me on how i can change the keys sent to the application using pyHook. Or is there any other library that I can make use of to create such application. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kriti_satija at yahoo.co.in Tue Apr 29 15:34:07 2008 From: kriti_satija at yahoo.co.in (Kriti Satija) Date: Tue, 29 Apr 2008 14:34:07 +0100 (BST) Subject: [Tutor] removing subscription Message-ID: <647488.59753.qm@web8505.mail.in.yahoo.com> Remove my mail id from that i have subsribed in Python Tutor List. Did you know? You can CHAT without downloading messenger. Go to http://in.messenger.yahoo.com/webmessengerpromo.php/ From timmichelsen at gmx-topmail.de Tue Apr 29 16:00:18 2008 From: timmichelsen at gmx-topmail.de (Timmie) Date: Tue, 29 Apr 2008 14:00:18 +0000 (UTC) Subject: [Tutor] removing subscription References: <647488.59753.qm@web8505.mail.in.yahoo.com> Message-ID: Kriti Satija yahoo.co.in> writes: > > Remove my mail id from that i have subsribed in > Python Tutor List. Please do this by yourself going at the site mentioned in the mail footer: > _______________________________________________ > Tutor maillist - Tutor python.org > http://mail.python.org/mailman/listinfo/tutor > > From pydev at rscorp.ab.ca Tue Apr 29 18:22:08 2008 From: pydev at rscorp.ab.ca (Scott SA) Date: Tue, 29 Apr 2008 10:22:08 -0600 Subject: [Tutor] Python Best Practice/Style Guide question Message-ID: Per the interesting read at Can anyone explain the rationale behind this: - More than one space around an assignment (or other) operator to align it with another. Yes: x = 1 y = 2 long_variable = 3 No: x = 1 y = 2 long_variable = 3 The example is rather simplistic and I find the latter form much easier to read when there is more than three or four assignments. Furthermore, I don't like the use of 'x' and 'y' style variables for anything but classical references and concise loops favoring 'chart_x' and 'chart_y' (I have a crappy memory, more descriptive names help me, and those reading my code, keep track of what I'm doing). I _do_ see that in this example, it could be hard to follow which value is assigned to its respective name, but considering this _slightly_ less simplistic (though flawed) example: string_item = some_method(with_argument) y = 2 long_variable = antoher_method(with, multiple, arguments) another_string_item = some_method(with, more, arguments) Is easier to read (for me) as follows: string_item = some_method(with_argument) y = 2 long_variable = antoher_method(with, multiple, arguments) another_assignment = some_method(with, more, arguments) _Yes_ the order can be changed, but there are reasons why it might be inapropriate to reorder i.e. dependencies. TIA, Scott PS. There is a good best-practice link here too: From marc.tompkins at gmail.com Tue Apr 29 19:19:48 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 29 Apr 2008 10:19:48 -0700 Subject: [Tutor] Python Best Practice/Style Guide question In-Reply-To: References: Message-ID: <40af687b0804291019udda41bex3008072e7e1cedf7@mail.gmail.com> On Tue, Apr 29, 2008 at 9:22 AM, Scott SA wrote: > - More than one space around an assignment (or other) operator to > align it with another. > When I first started in Python, I was lining up all of my variable assignments in blocks; I, too, find it more readable. But then I read Guido's notes on preferred Python style (no, I don't have a link offhand), in which he deprecates lining things up... and suddenly I felt ashamed and started removing my extra spaces. When the guy who invented the language tells me I'm doing it wrong, who am I to argue? And after a while, I started to internalize the rule, so now every time I see code that's lined up with extra spaces it bugs me. He doesn't really give a rationale, and I haven't seen one elsewhere. I think the real answer to your question is "Guido doesn't like it, that's why." Actually, looking at your original message, there's one very good rationale: in my email client, the text of your message is in a proportional font, so your assignments don't line up anyway. All those extra spaces, and it still just looks ragged. Padding only works in monospace - of course, we all use monospace fonts in our respective editors, but the rest of the world uses proportional. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From mlangford.cs03 at gtalumni.org Tue Apr 29 20:01:01 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Tue, 29 Apr 2008 14:01:01 -0400 Subject: [Tutor] Python Best Practice/Style Guide question In-Reply-To: References: Message-ID: <82b4f5810804291101r4facb37eob2ec5b013e219f13@mail.gmail.com> This, like many style guidelines, is not something that necessary has an irrefutable reason. Sort of like driving on the left or right side of the road, it is pretty much custom. You'll get use to coding like that after a short time if you start. If you don't, nothing bad will happen to you, just it will look strange to a large number of people. For instance, while if( 3 == a) is a much safer way to write a C if statement than if( a == 3 ), I still use the former because it is a lot easier on the brains of people I work with (but use lint to catch the infamous if( a=3 ) ). Steve McConnell's Code Complete has an excellent chapter on this and other "whitespace code art" that basically boils down to while it seems like it adds, it takes a lot of time to maintain, so you're probably not coming out ahead in the long run. --Michael On Tue, Apr 29, 2008 at 12:22 PM, Scott SA wrote: > Per the interesting read at > > Can anyone explain the rationale behind this: > > - More than one space around an assignment (or other) operator to > align it with another. > > Yes: > > x = 1 > y = 2 > long_variable = 3 > > No: > > x = 1 > y = 2 > long_variable = 3 > > The example is rather simplistic and I find the latter form much easier to > read when there is more than three or four assignments. Furthermore, I don't > like the use of 'x' and 'y' style variables for anything but classical > references and concise loops favoring 'chart_x' and 'chart_y' (I have a > crappy memory, more descriptive names help me, and those reading my code, > keep track of what I'm doing). > > I _do_ see that in this example, it could be hard to follow which value is > assigned to its respective name, but considering this _slightly_ less > simplistic (though flawed) example: > > string_item = some_method(with_argument) > y = 2 > long_variable = antoher_method(with, multiple, arguments) > another_string_item = some_method(with, more, arguments) > > Is easier to read (for me) as follows: > > string_item = some_method(with_argument) > y = 2 > long_variable = antoher_method(with, multiple, arguments) > another_assignment = some_method(with, more, arguments) > > _Yes_ the order can be changed, but there are reasons why it might be > inapropriate to reorder i.e. dependencies. > > TIA, > > Scott > > PS. There is a good best-practice link here too: > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Tue Apr 29 21:14:39 2008 From: srilyk at gmail.com (W W) Date: Tue, 29 Apr 2008 14:14:39 -0500 Subject: [Tutor] Python Best Practice/Style Guide question In-Reply-To: <82b4f5810804291101r4facb37eob2ec5b013e219f13@mail.gmail.com> References: <82b4f5810804291101r4facb37eob2ec5b013e219f13@mail.gmail.com> Message-ID: <333efb450804291214g1e60957bx5e73df15f800c169@mail.gmail.com> Even with monospace, I can't really see it being that helpful, after all, in: x = 3 y = 5 foobar_fun = 20 3 and 5 are in no way related, x and 3 are. However, sometimes I break them up into more beautiful chunks: x = 3 y = 5 foobar_fun = 20 sometimes it's more helpful that way. just my 2.5c -Wayne On Tue, Apr 29, 2008 at 1:01 PM, Michael Langford wrote: > This, like many style guidelines, is not something that necessary has an > irrefutable reason. Sort of like driving on the left or right side of the > road, it is pretty much custom. > > You'll get use to coding like that after a short time if you start. If you > don't, nothing bad will happen to you, just it will look strange to a large > number of people. For instance, while if( 3 == a) is a much safer way to > write a C if statement than if( a == 3 ), I still use the former because it > is a lot easier on the brains of people I work with (but use lint to catch > the infamous if( a=3 ) ). > > Steve McConnell's Code Complete has an excellent chapter on this and other > "whitespace code art" that basically boils down to while it seems like it > adds, it takes a lot of time to maintain, so you're probably not coming out > ahead in the long run. > > --Michael > > > > On Tue, Apr 29, 2008 at 12:22 PM, Scott SA wrote: > > Per the interesting read at > > > > Can anyone explain the rationale behind this: > > > > - More than one space around an assignment (or other) operator to > > align it with another. > > > > Yes: > > > > x = 1 > > y = 2 > > long_variable = 3 > > > > No: > > > > x = 1 > > y = 2 > > long_variable = 3 > > > > The example is rather simplistic and I find the latter form much easier to > read when there is more than three or four assignments. Furthermore, I don't > like the use of 'x' and 'y' style variables for anything but classical > references and concise loops favoring 'chart_x' and 'chart_y' (I have a > crappy memory, more descriptive names help me, and those reading my code, > keep track of what I'm doing). > > > > I _do_ see that in this example, it could be hard to follow which value is > assigned to its respective name, but considering this _slightly_ less > simplistic (though flawed) example: > > > > string_item = some_method(with_argument) > > y = 2 > > long_variable = antoher_method(with, multiple, arguments) > > another_string_item = some_method(with, more, arguments) > > > > Is easier to read (for me) as follows: > > > > string_item = some_method(with_argument) > > y = 2 > > long_variable = antoher_method(with, multiple, arguments) > > another_assignment = some_method(with, more, arguments) > > > > _Yes_ the order can be changed, but there are reasons why it might be > inapropriate to reorder i.e. dependencies. > > > > TIA, > > > > Scott > > > > PS. There is a good best-practice link here too: > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > Michael Langford > Phone: 404-386-0495 > Consulting: http://www.RowdyLabs.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi From alan.gauld at btinternet.com Tue Apr 29 23:02:50 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 29 Apr 2008 22:02:50 +0100 Subject: [Tutor] Python Best Practice/Style Guide question References: <82b4f5810804291101r4facb37eob2ec5b013e219f13@mail.gmail.com> <333efb450804291214g1e60957bx5e73df15f800c169@mail.gmail.com> Message-ID: "W W" wrote > Even with monospace, I can't really see it being that helpful, after > all, in: > > x = 3 > y = 5 > foobar_fun = 20 > > 3 and 5 are in no way related, x and 3 are. However, sometimes I > break > them up into more beautiful chunks: In Python it doesn't make much difference but in C and other similar languages it helps a lot to line up assignments as the OP did because you can scan a list ov variables and see which ones have not been initialised before use. And uninitialised variables are probably the biggest single cause of bugs in C programs so the experienced C maintainer will go straight to the variable lists before doing anything else with a file. And if they are neatly lined up a blank line stands out like a sore thumb. (In fact the act of lining them up will often prompt a lazy developer to initialise variables himself, just to tidy things up!) But in Python where variables are created by assignment the concept of an unitialised variable dioesn't make sense. And because Python has garbage collection unitialised/non-freed pointers don't cause problems either... :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From scott at rscorp.ab.ca Tue Apr 29 20:28:26 2008 From: scott at rscorp.ab.ca (Scott Sandeman-Allen) Date: Tue, 29 Apr 2008 12:28:26 -0600 Subject: [Tutor] Python Best Practice/Style Guide question In-Reply-To: <40af687b0804291019udda41bex3008072e7e1cedf7@mail.gmail.com> Message-ID: On 4/29/08, Marc Tompkins (marc.tompkins at gmail.com) wrote: >On Tue, Apr 29, 2008 at 9:22 AM, Scott SA wrote: > >> - More than one space around an assignment (or other) operator to >> align it with another. >> > When the guy who invented the language >tells me I'm doing it wrong, who am I to argue? > And after a while, I started to internalize the rule, so now every time I see > code that's lined up with extra spaces it bugs me. With the mantra of making things obvious and clear, this extra visual density is contrary. In >He doesn't really give a rationale, and I haven't seen one elsewhere. I >think the real answer to your question is "Guido doesn't like it, that's >why." I have tremendous respect for Guido and many others. However, Guido may not like Sushi or John Prine (folk musician). That's okay, I didn't like them at first either. >Actually, looking at your original message, there's one very good >rationale: in my email client, the text of your message is in a >proportional font, so your assignments don't line up anyway. All those >extra spaces, and it still just looks ragged. Padding only works in >monospace - of course, we all use monospace fonts in our respective editors, >but the rest of the world uses proportional. Agreed, but as you point out the working tools are monospaced. I have to say that I find no other point in the document previouslly linked that I (a literal gnat's turd in the python realm of influence) find difficult to accept. I guess I'll just have to discuss this with my pharmacist and see if I can find a something more appropriate. It's really the only solution to an inexplicable tradition: "I'll have some of what he/she's having". ;-) Thanks for the quick reply and personal insight. Scott From bryan.fodness at gmail.com Tue Apr 29 23:54:29 2008 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Tue, 29 Apr 2008 17:54:29 -0400 Subject: [Tutor] string from input file Message-ID: I am trying to get values from an input file, 0.192 Custom 15 IN but, when I check to see if they are equal it is not true. f = open(infile, 'r') s = f.readlines() f.close() Block = str(s[1]) Angle = float(s[2]) Position = str(s[3]) if Block == 'Custom': print 'equal' if I print Block+'Custom', I get, Custom Custom when I would have expected CustomCustom Can someone help me figure out if I am not reading the values in correctly, is there a control character at the end? The float value is ok. -- "The game of science can accurately be described as a never-ending insult to human intelligence." - Jo?o Magueijo -------------- next part -------------- An HTML attachment was scrubbed... URL: From Mike.Hansen at atmel.com Wed Apr 30 00:07:50 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Tue, 29 Apr 2008 16:07:50 -0600 Subject: [Tutor] string from input file In-Reply-To: References: Message-ID: <7941B2693F32294AAF16C26B679A258D020B95A8@csomb01.corp.atmel.com> > -----Original Message----- > On > Behalf Of Bryan Fodness > Sent: Tuesday, April 29, 2008 3:54 PM > To: tutorpythonmailinglist Python > Subject: [Tutor] string from input file > > I am trying to get values from an input file, > > 0.192 > Custom > 15 > IN > > but, when I check to see if they are equal it is not true. > > f = open(infile, 'r') > s = f.readlines() > f.close() > > Block = str(s[1]) > Angle = float(s[2]) > Position = str(s[3]) > > if Block == 'Custom': > print 'equal' > > if I print Block+'Custom', I get, > > Custom > Custom > > when I would have expected > > CustomCustom > > Can someone help me figure out if I am not reading the > values in correctly, is there a control character at the end? > The float value is ok. Your string has a line ending in it, so it doesn't match. It's essentially "Custom\n". Just use a slice to remove the line ending character(\n). Also, I don't think you need to convert s[1] to a string. I think it's already a string. Block = s[1][:-1] In [1]: x = "Custom\n" In [2]: y = x[:-1] In [3]: y Out[3]: 'Custom' Mike From alan.gauld at btinternet.com Wed Apr 30 00:28:58 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 29 Apr 2008 23:28:58 +0100 Subject: [Tutor] string from input file References: Message-ID: "Bryan Fodness" wrote > f = open(infile, 'r') > s = f.readlines() > f.close() This just reads the lines as text from the file. It includes any whitespace and linefeeds in the file. Block = str(s[1]) Since its text you don;t need the str() but you probably should use rstrip() to rem,ove any training whitespace or newlines. Block = s[1].rstrip() > Angle = float(s[2]) This should be OK > Position = str(s[3]) As per Block > if Block == 'Custom': > print 'equal' > > if I print Block+'Custom', I get, > > Custom > Custom Block obviously has a newline. Try >>> print repr(Block) to see the \n More info on this in my Handling Files topic ih my tutorial. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sander.sweers at gmail.com Wed Apr 30 00:29:32 2008 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 30 Apr 2008 00:29:32 +0200 Subject: [Tutor] string from input file In-Reply-To: References: Message-ID: On Tue, Apr 29, 2008 at 11:54 PM, Bryan Fodness wrote: > I am trying to get values from an input file, > > 0.192 > Custom > 15 > IN > > but, when I check to see if they are equal it is not true. > > f = open(infile, 'r') > s = f.readlines() > f.close() > > Block = str(s[1]) > Angle = float(s[2]) > Position = str(s[3]) > > if Block == 'Custom': > print 'equal' > > if I print Block+'Custom', I get, > > Custom > Custom > > when I would have expected > > CustomCustom > > Can someone help me figure out if I am not reading the values in correctly, > is there a control character at the end? The float value is ok. There is a newline character \n at the end of each value. Below is an explanation from an interactive python session. >>> x = 'Custom\n' >>> y = x.strip() >>> y 'Custom' >>> x 'Custom\n' >>> print x Custom >>> print y Custom >>> print x + 'Custom' Custom Custom >>> print y + 'Custom' CustomCustom >>> .strip() wil strip out these newline characters so to get what you want you should use: Block = str(s[1].strip()) Greets Sander From pylinuxian at gmail.com Wed Apr 30 02:10:49 2008 From: pylinuxian at gmail.com (Arthur) Date: Wed, 30 Apr 2008 00:10:49 +0000 Subject: [Tutor] Python Best Practice/Style Guide question In-Reply-To: References: <40af687b0804291019udda41bex3008072e7e1cedf7@mail.gmail.com> Message-ID: i like to write variable the kamelWay (i learned it from some javascript book some time ago) but i never use spaces even in between : variableName=variableValue. i guess i like compact code with fewer lines ... always thought shorter programs run faster... & it also makes you feel that your way it the shortest smartest and fastest way ... since nobody can make it happen with less code that yours ... ;) -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Apr 30 09:32:49 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 30 Apr 2008 08:32:49 +0100 Subject: [Tutor] Python Best Practice/Style Guide question References: <40af687b0804291019udda41bex3008072e7e1cedf7@mail.gmail.com> Message-ID: "Arthur" wrote >i like to write variable the kamelWay (i learned it from some >javascript > book some time ago) Camel case is fine. I thionk it actually originated in smalltalk 74 so its been around a long time. > but i never use spaces even in between : > variableName=variableValue. But that's plain hard to read! And in a long program liable to lead to errors and make debugging much harder. Especially if its not you doing the debugging! :-) > i guess i like compact code with fewer lines ... always thought > shorter > programs run faster... There is a grain of truth in that but not much. In particular the speed at which the parser parses your code into byte code before executing it will be virtually unaltered by putting spaces in. For faster programs its shorter byte code that counts not shorter source code. > shortest smartest and fastest way ... since nobody can > make it happen with less code that yours ... ;) Well... they could replace all variable/function names with single characters... But they can easily shorten the byte code by using smarter instructions and better algorithms. The length of the source code(*) really doesn't bear much relation to the speed of the code. If you weant to write fast code aim to lay it out so the structure is crystal clear, that way you will spot how to improve your algorithm much more easily and that will make your code fly. (*) It can make a small difference in JavaScript however, not because it executes faster but because it will download faster! And in very old line by line BASIC interpreters it made avery small difference because they didn't produce byte code per se but just executed each line in turn. Removing spaces is the coding equivalent to an Olympic swimmer shaving his head rather than wearing a rubber hat to cut down drag. The difference is minimal to non existent. Style is of course a personal choice, but if you ever intend to share your code or work on bigger projects it is something that needs careful thought. Aim for beautiful code before fast code. Fast is easier to build starting from beautiful foundations. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From Mike.Hansen at atmel.com Wed Apr 30 16:18:28 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Wed, 30 Apr 2008 08:18:28 -0600 Subject: [Tutor] Strip? Message-ID: <7941B2693F32294AAF16C26B679A258D020B987A@csomb01.corp.atmel.com> strip( s[, chars]) Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on. Changed in version 2.2.3: The chars parameter was added. The chars parameter cannot be passed in earlier 2.2 versions. What characters are included as whitespace characters? Spaces? Tabs? Newlines? For some reason, I was reading whitespace as just spaces. Mike From wolfram.kraus at fen-net.de Wed Apr 30 16:40:51 2008 From: wolfram.kraus at fen-net.de (Wolfram Kraus) Date: Wed, 30 Apr 2008 16:40:51 +0200 Subject: [Tutor] Strip? In-Reply-To: <7941B2693F32294AAF16C26B679A258D020B987A@csomb01.corp.atmel.com> References: <7941B2693F32294AAF16C26B679A258D020B987A@csomb01.corp.atmel.com> Message-ID: Am 30.04.2008 16:18, Hansen, Mike schrieb: > strip( s[, chars]) > Return a copy of the string with leading and trailing characters > removed. If chars is omitted or None, whitespace characters are removed. > If given and not None, chars must be a string; the characters in the > string will be stripped from the both ends of the string this method is > called on. Changed in version 2.2.3: The chars parameter was added. The > chars parameter cannot be passed in earlier 2.2 versions. > > What characters are included as whitespace characters? Spaces? Tabs? > Newlines? For some reason, I was reading whitespace as just spaces. > > Mike See http://docs.python.org/lib/node39.html "whitespace A string containing all characters that are considered whitespace. On most systems this includes the characters space, tab, linefeed, return, formfeed, and vertical tab. Do not change its definition -- the effect on the routines strip() and split() is undefined." HTH, Wolfram From alan.gauld at btinternet.com Wed Apr 30 19:29:52 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 30 Apr 2008 18:29:52 +0100 Subject: [Tutor] Strip? References: <7941B2693F32294AAF16C26B679A258D020B987A@csomb01.corp.atmel.com> Message-ID: "Hansen, Mike" wrote > What characters are included as whitespace characters? Spaces? Tabs? > Newlines? For some reason, I was reading whitespace as just spaces. See wikipedia for miore info but: "...C defines whitespace to be "... space, horizontal tab, new-line, vertical tab, and form-feed"." So I'd guess CPython uses the same definition. Alan G From alan.gauld at btinternet.com Wed Apr 30 19:32:02 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 30 Apr 2008 18:32:02 +0100 Subject: [Tutor] Strip? References: <7941B2693F32294AAF16C26B679A258D020B987A@csomb01.corp.atmel.com> Message-ID: "Wolfram Kraus" wrote >> What characters are included as whitespace characters? Spaces? >> Tabs? >> Newlines? For some reason, I was reading whitespace as just spaces. > "whitespace > A string containing all characters that are considered > whitespace. On most systems this includes the characters space, tab, > linefeed, return, formfeed, and vertical tab. Do not change its > definition -- the effect on the routines strip() and split() is > undefined." >>> import string >>> for c in string.whitespace: ... print repr(c) ... '\t' '\n' '\x0b' '\x0c' '\r' ' ' >>> HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From nephish at gmail.com Wed Apr 30 20:13:56 2008 From: nephish at gmail.com (shawn bright) Date: Wed, 30 Apr 2008 13:13:56 -0500 Subject: [Tutor] send and receive HTTP POST Message-ID: <384c93600804301113t2532b97epad03d9d3c1d69cb6@mail.gmail.com> Hey there all, I have been spending some time trying to get my head around how to send info by POST and read the result. These are examples of what i need to read and write . I think i can pull off the writing part, but how do i call it? POST /soap/SMS.asmx HTTP/1.1 Host: api.upsidewireless.com Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "http://upsidewireless.com/webservice/sms/Send_Plain" string string string string Seven or Eight or Sixteen HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: length boolean string string string boolean boolean boolean boolean boolean string Thanks for any tips -shawn From kent37 at tds.net Wed Apr 30 21:05:38 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 30 Apr 2008 15:05:38 -0400 Subject: [Tutor] send and receive HTTP POST In-Reply-To: <384c93600804301113t2532b97epad03d9d3c1d69cb6@mail.gmail.com> References: <384c93600804301113t2532b97epad03d9d3c1d69cb6@mail.gmail.com> Message-ID: <1c2a2c590804301205g6f37df39q6d9b925d8cdecc9d@mail.gmail.com> > POST /soap/SMS.asmx HTTP/1.1 > Host: api.upsidewireless.com > Content-Type: text/xml; charset=utf-8 > Content-Length: length > SOAPAction: "http://upsidewireless.com/webservice/sms/Send_Plain" It looks like you need SOAPpy: http://diveintopython.org/soap_web_services/ Kent