From hunter92383 at gmail.com Sun Jul 1 00:02:57 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 30 Jun 2007 15:02:57 -0700 Subject: [Tutor] Mouse clicking In-Reply-To: References: <674d5ce60706301444u55415cc9wa55a434b1e14bb26@mail.gmail.com> Message-ID: <674d5ce60706301502o1edc26erd89720a26205c9e9@mail.gmail.com> can you take a look of these? It's very cryptic to me and more or less is not explained in any python tutorials. http://search.msdn.microsoft.com/search/results.aspx?view=msdn&qu=mouse_event http://search.msdn.microsoft.com/search/results.aspx?view=msdn&qu=keybd_event http://search.msdn.microsoft.com/search/results.aspx?view=msdn&qu=GetFocus -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070630/3b91e1ad/attachment.htm From hunter92383 at gmail.com Sun Jul 1 00:17:28 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 30 Jun 2007 15:17:28 -0700 Subject: [Tutor] 200 dollar questions! In-Reply-To: References: <100452.41767.qm@web86103.mail.ird.yahoo.com> Message-ID: <674d5ce60706301517n154d6f52n77c99be0f6df9a5d@mail.gmail.com> http://search.msdn.microsoft.com/search/results.aspx?view=msdn&qu=mo use_event http://search.msdn.microsoft.com/search/results.aspx?view=msdn&qu=ke ybd_event http://search.msdn.microsoft.com/search/results.aspx?view=msdn&qu=Ge tFocus I am using pywin32, for python 2.5 on windows xp. What I want to do is these: handle = Gethandle ("window_name") "window_name" = "123.txt" with notepad, for example. it should return a list if there are more than one with the same name. and then GainFocus(handle) Keyboard_event ( "hello python!") Mouse_event (x,y, left, 2) the (x,y) = should be relative to the active window and independent of the window's position. 2 as in clicking twice. Last, maximize, minimize, resize, move, kill, above(handle) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070630/572d80c4/attachment.html From alan.gauld at btinternet.com Sun Jul 1 01:14:49 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 1 Jul 2007 00:14:49 +0100 Subject: [Tutor] 200 dollar questions! References: <100452.41767.qm@web86103.mail.ird.yahoo.com> <674d5ce60706301517n154d6f52n77c99be0f6df9a5d@mail.gmail.com> Message-ID: "elis aeris" wrote > I am using pywin32, for python 2.5 on windows xp. > What I want to do is these: > > handle = Gethandle ("window_name") Try FindWindow(), it returns a handle given a class/window title > "window_name" = "123.txt" with notepad, for example. That looks like the title to me... > it should return a list if there are more than one with the same > name. Nope, it only returns one, but enumWindows will give you a list (or more accurately will yield a list if called repeatedly) > GainFocus(handle) I think you need SetFocus() here > Keyboard_event ( "hello python!") > Mouse_event (x,y, left, 2) > the (x,y) = should be relative to the active window and independent > of the > window's position. 2 as in clicking twice. Googling on MSDN gave this pagfe which describes how it works. http://msdn2.microsoft.com/en-us/library/ms646260.aspx > Last, maximize, minimize, resize, move, kill, > > above(handle) These can be done using PostMessage (not sure whether you mean Last is a command or "lastly" you want to do these things) Read the documentation and try it out. See what happens, if you can't get it to work come back to us with specific questions and sample code, plus any error messages you might get. Alan G. From alan.gauld at btinternet.com Sun Jul 1 01:21:26 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 1 Jul 2007 00:21:26 +0100 Subject: [Tutor] Mouse clicking References: <674d5ce60706301444u55415cc9wa55a434b1e14bb26@mail.gmail.com> <674d5ce60706301502o1edc26erd89720a26205c9e9@mail.gmail.com> Message-ID: "elis aeris" wrote in > It's very cryptic to me and more or less is not explained in any > python > tutorials. > > http://search.msdn.microsoft.com/search/results.aspx?view=msdn&qu=mouse_event > http://search.msdn.microsoft.com/search/results.aspx?view=msdn&qu=keybd_event > http://search.msdn.microsoft.com/search/results.aspx?view=msdn&qu=GetFocus It wouldn't be in a Python tutorial because its all about the Windows API and few Python programmers get involved with Windowes at that level. It can be done using PyWin32 but that is just a wrapper around the Windows C functions. You need to understand how they work (And Microsoft documentation is notoriously poor) Personally I do most of my low level Windows work using Borlands Delphi or C++Builder and use a couple of books on those tools along with the MS Help files. But the Python wrapper should work just as well. But, normally, a python programmer will step back and try to write a program that does what is needed directly in Python using a high level module rather than calling OS API calls directly. (Thus is true in Unix as well as Windows) So rather than try to robotically control Notepad say, its easier to write a Python program to edit the text file directly. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld (Which sadly seems to be down at the moment!) From hunter92383 at gmail.com Sun Jul 1 01:35:27 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 30 Jun 2007 16:35:27 -0700 Subject: [Tutor] 200 dollar questions! In-Reply-To: References: <100452.41767.qm@web86103.mail.ird.yahoo.com> <674d5ce60706301517n154d6f52n77c99be0f6df9a5d@mail.gmail.com> Message-ID: <674d5ce60706301635x7f800f60rdc425b643711fe93@mail.gmail.com> import win32api import win32ui window = win32ui.FindWindow(None, "123.txt") yourwindow.ShowWindow() Traceback (most recent call last): File "C:/python codes/gain_focus.py", line 3, in window = win32ui.FindWindow(None, "123.txt") win32ui: No window can be found. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070630/95e678a9/attachment.html From adecchi at gmail.com Sun Jul 1 02:26:54 2007 From: adecchi at gmail.com (Alejandro Decchi) Date: Sat, 30 Jun 2007 21:26:54 -0300 Subject: [Tutor] Help search file Message-ID: Hello Python user. I am a newbie with python and i am interesting to do a web apliation to search file on the hard disk and give a link to download the file found. Someone can give a help ??? Thz Ale -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070630/7c0a7da6/attachment.htm From hunter92383 at gmail.com Sun Jul 1 04:26:50 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 30 Jun 2007 19:26:50 -0700 Subject: [Tutor] 200 dollar questions! In-Reply-To: <674d5ce60706301517n154d6f52n77c99be0f6df9a5d@mail.gmail.com> References: <100452.41767.qm@web86103.mail.ird.yahoo.com> <674d5ce60706301517n154d6f52n77c99be0f6df9a5d@mail.gmail.com> Message-ID: <674d5ce60706301926i4b9ee2b6t5b2b66b8c6d6447a@mail.gmail.com> I ran this: import time import ImageGrab # Part of PIL from ctypes import * # Load up the Win32 APIs we need to use. 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 # Sleep for 2 seconds - click the window you want to grab. #time.sleep(2) # 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)) # Save the screenshot as a BMP. #image.save("c:\ee\screenshot.bmp") # Get the pixel 10 pixels along the top of the foreground window - this # will be a piece of the window border. print time.time() x = 0 y = 0 while x < 400: while y < 20: rgb = image.getpixel((10, 0)) y = y + 1 y = 0 x = x + 1 print time.time() # PIL returns colours as RGB values packed into a triple: print "RGB(%d, %d, %d)" % (rgb[0], rgb[1], rgb[2]) # This prints RGB(0, 74, 216) on my XP machine What that does is to take a screen shot and then pixelgetcolor() over 8000 (x,y) points for me it clocked at 0.08 seconds and I am trying cut it down to maybe 0.04 any hints on performance increase? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070630/65c32cf5/attachment.html From rabidpoobear at gmail.com Sun Jul 1 05:10:38 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 30 Jun 2007 22:10:38 -0500 Subject: [Tutor] 200 dollar questions! In-Reply-To: <674d5ce60706301926i4b9ee2b6t5b2b66b8c6d6447a@mail.gmail.com> References: <100452.41767.qm@web86103.mail.ird.yahoo.com> <674d5ce60706301517n154d6f52n77c99be0f6df9a5d@mail.gmail.com> <674d5ce60706301926i4b9ee2b6t5b2b66b8c6d6447a@mail.gmail.com> Message-ID: <46871B2E.7050106@gmail.com> elis aeris wrote: > I ran this: > [snip a lot of code] In the future, please send big sections of code as attachments. It is better in the regard that formatting is preserved as well as us not having to scroll down past a bunch of code to see what the issue is. Often, with just the traceback and an explanation of what the code is supposed to do, we already have a general idea of what the problem is, and probably where it is as well, and we can locate and explain the problem quickly. If we have to look through all the code before we know what the issue is, chances are, you will have fewer people willing to respond. > > What that does is to take a screen shot and then pixelgetcolor() over > 8000 (x,y) points No it doesn't. It gets the same pixel 8000 times. What exactly are you trying to accomplish here? In addition, the PIL manual mentions specifically that the image.getpixel method is slow, and if you need to process portions of the image you should go about it in a different manner. > > for me it clocked at 0.08 seconds and I am trying cut it down to maybe > 0.04 For something that executes this fast, I would suggest using a more accurate method of timing it. For example, using the timeit module and getting an average of 1,000 iterations, or something of that nature. > > any hints on performance increase? It depends what you're trying to do. Give us more info and we can help. -Luke From hunter92383 at gmail.com Sun Jul 1 05:30:13 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 30 Jun 2007 20:30:13 -0700 Subject: [Tutor] 200 dollar questions! In-Reply-To: <46871B2E.7050106@gmail.com> References: <100452.41767.qm@web86103.mail.ird.yahoo.com> <674d5ce60706301517n154d6f52n77c99be0f6df9a5d@mail.gmail.com> <674d5ce60706301926i4b9ee2b6t5b2b66b8c6d6447a@mail.gmail.com> <46871B2E.7050106@gmail.com> Message-ID: <674d5ce60706302030s2ea0d46am61a300f94a27d18b@mail.gmail.com> Yes, I am trying to write a OCR algorithm with neural network, but the theories of NN is of little importance, what I am trying to get ready for the project is run speed. the problem comes in a number of ways: first, as you mentioned, image.getpixel is not very fast, according to PIL http://www.pythonware.com/products/pil/ so an alternative should be searched for, also, I loop (x,y) x = 0 -1023 y = 0- 768 through and currently i use this: x = 0 y = 0 for x in xrange(1, 1024, 1): for y in xrange(1, 768, 1): rgb = image.getpixel ((10, 12)) according to http://www.python.org/doc/essays/list2str.html a while loop is slow than for, and then map is faster. as for that this: image.getpixel ((10, 12)) currently i only use the shell window itself, so i can't really loop 1024*768, that's why it's only 10 12, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070630/d5b66649/attachment.htm From rabidpoobear at gmail.com Sun Jul 1 05:32:29 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 30 Jun 2007 22:32:29 -0500 Subject: [Tutor] 200 dollar questions! In-Reply-To: <674d5ce60706302020wf28b499kbe5fe8652a7f3939@mail.gmail.com> References: <100452.41767.qm@web86103.mail.ird.yahoo.com> <674d5ce60706301517n154d6f52n77c99be0f6df9a5d@mail.gmail.com> <674d5ce60706301926i4b9ee2b6t5b2b66b8c6d6447a@mail.gmail.com> <46871B2E.7050106@gmail.com> <674d5ce60706302020wf28b499kbe5fe8652a7f3939@mail.gmail.com> Message-ID: <4687204D.3070002@gmail.com> elis aeris wrote: > Yes, I am trying to write a OCR algorithm with neural network, but the > theories of NN is of little importance, what I am trying to get ready > for the project is run speed. Yes, but what you're trying to do _is_ important. Example code that just loops over a small part of an image doesn't give us indication of what you're trying to do. For example - consider your image is 1024x768 but you only want to process 100x100 block of it. Then a good solution might be to use the image.crop method to reduce the image to only the part you care about, and then doing a getdata() on it, versus doing getpixel for every pixel in the 100x100 area. > > > the problem comes in a number of ways: > > > first, as you mentioned, image.getpixel is not very fast, > according to PIL > http://www.pythonware.com/products/pil/ > > so an alternative should be searched for, > > > also, I loop (x,y) > > x = 0 -1023 > y = 0- 768 through > > and currently i use this: > > > > x = 0 > y = 0 > for x in xrange(1, 1024, 1): > for y in xrange(1, 768, 1): > rgb = image.getpixel ((10, 12)) These loops don't go 0-1023 and 0-768 they go 1-1023 and 1-767 There is a function called getdata() that you can use to get all of the pixel data of the image at once. -Luke From hunter92383 at gmail.com Sun Jul 1 05:36:14 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 30 Jun 2007 20:36:14 -0700 Subject: [Tutor] 200 dollar questions! In-Reply-To: <4687204D.3070002@gmail.com> References: <100452.41767.qm@web86103.mail.ird.yahoo.com> <674d5ce60706301517n154d6f52n77c99be0f6df9a5d@mail.gmail.com> <674d5ce60706301926i4b9ee2b6t5b2b66b8c6d6447a@mail.gmail.com> <46871B2E.7050106@gmail.com> <674d5ce60706302020wf28b499kbe5fe8652a7f3939@mail.gmail.com> <4687204D.3070002@gmail.com> Message-ID: <674d5ce60706302036x50564b1au10c50185d66269c3@mail.gmail.com> which modules and origin is this function? is it the fastest way to get it? I am told to optimize getpixel (x, y) alone, so that's the only thing i am trying, it's part of a project that will go live in september, so the prof we are under hasn't one anything but some introductory readings. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070630/de7f51b4/attachment.html From hunter92383 at gmail.com Sun Jul 1 05:46:23 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 30 Jun 2007 20:46:23 -0700 Subject: [Tutor] optimization: faster than for Message-ID: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> I found this on the net, and it's a different arrangement to using for the author claims it will result in faster performance, but i can't find documents on it, because I can't figure out which parts are parameters and which parts on special words, for python. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070630/69499d52/attachment.htm -------------- next part -------------- The operations with explicit loop counters have to be translated into Python byte code and must be interpreted. Implicit loop counter can be incremented by the core code (translated from C sources). Try this: import timeit sWhile = """\ x = 0 y = 0 number_scanned = 0 while x < 1024: while y < 768: y = y + 1 number_scanned = number_scanned + 1 y = 0 x = x + 1 """ t = timeit.Timer(stmt=sWhile) print "%.2f usec/pass" % (1000000 * t.timeit(number=10)/10) sFor = """\ number_scanned = 0 for x in xrange(1024): for y in xrange(768): number_scanned = number_scanned + 1 """ t = timeit.Timer(stmt=sFor) print "%.2f usec/pass" % (1000000 * t.timeit(number=10)/10) The sWhile and sFor are the multiline strings containing the equivalent code written using while and for loop respectively. From kent37 at tds.net Sun Jul 1 06:15:47 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 01 Jul 2007 00:15:47 -0400 Subject: [Tutor] optimization: faster than for In-Reply-To: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> Message-ID: <46872A73.5030600@tds.net> elis aeris wrote: > I found this on the net, and it's a different arrangement to using for > > the author claims it will result in faster performance, but i can't find > documents on it, because I can't figure out which parts are parameters > and which parts on special words, for python. Where did you get this? Which version is claimed to be faster? The code you attached runs directly, just paste it into the interpreter. On my computer the second version takes about half the time of the first. What is your question? Kent From hunter92383 at gmail.com Sun Jul 1 06:17:53 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 30 Jun 2007 21:17:53 -0700 Subject: [Tutor] optimization: faster than for In-Reply-To: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> Message-ID: <674d5ce60706302117j47cec367s467bdde68cd21168@mail.gmail.com> The for version, as claimed by http://www.python.org/doc/essays/list2str.html -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070630/5073b83a/attachment.html From hunter92383 at gmail.com Sun Jul 1 06:18:53 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 30 Jun 2007 21:18:53 -0700 Subject: [Tutor] optimization: faster than for In-Reply-To: <46872A73.5030600@tds.net> References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> <46872A73.5030600@tds.net> Message-ID: <674d5ce60706302118w129fd3d3gc97b612aef2f5107@mail.gmail.com> my question, is there any other way to make it run faster, as described in the webpage, it's possible to use map() but I don't know how to do it with this one, 2 dimensional arrays. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070630/5a21c041/attachment.htm From kent37 at tds.net Sun Jul 1 06:28:39 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 01 Jul 2007 00:28:39 -0400 Subject: [Tutor] optimization: faster than for In-Reply-To: <674d5ce60706302118w129fd3d3gc97b612aef2f5107@mail.gmail.com> References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> <46872A73.5030600@tds.net> <674d5ce60706302118w129fd3d3gc97b612aef2f5107@mail.gmail.com> Message-ID: <46872D77.4060204@tds.net> elis aeris wrote: > my question, is there any other way to make it run faster, > > as described in the webpage, it's possible to use map() but I don't > know how to do it with this one, 2 dimensional arrays. How about number_scanned = 1024 * 768 ? But seriously, the example you gave doesn't do any real work, it is just contrasting two methods of looping. If this is a continuation of the 200 dollar questions thread, Luke has given you some good ideas but you don't seem to like them. In both cases, you are asking for optimizations of artificial problems. There is no point in even asking that question. You have to optimize the code that actually solves the problem you care about. Kent From hunter92383 at gmail.com Sun Jul 1 06:31:04 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 30 Jun 2007 21:31:04 -0700 Subject: [Tutor] optimization: faster than for In-Reply-To: <46872D77.4060204@tds.net> References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> <46872A73.5030600@tds.net> <674d5ce60706302118w129fd3d3gc97b612aef2f5107@mail.gmail.com> <46872D77.4060204@tds.net> Message-ID: <674d5ce60706302131k55858706wa5c2562fe20958ca@mail.gmail.com> x = 0 y = 0 for x in xrange(1,1024,1): for y in xrange(1,768,1): rgb = image.getpixel((10, 12)) Luke said there is a faster way to do image.getpixel((10, 12)) so i am still waiting on that, the above has been improved many times and it's a lot faster than while, I am trying to find out if there are any more new ways. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070630/df1b8913/attachment-0001.html From hunter92383 at gmail.com Sun Jul 1 06:33:16 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 30 Jun 2007 21:33:16 -0700 Subject: [Tutor] optimization: faster than for In-Reply-To: <674d5ce60706302131k55858706wa5c2562fe20958ca@mail.gmail.com> References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> <46872A73.5030600@tds.net> <674d5ce60706302118w129fd3d3gc97b612aef2f5107@mail.gmail.com> <46872D77.4060204@tds.net> <674d5ce60706302131k55858706wa5c2562fe20958ca@mail.gmail.com> Message-ID: <674d5ce60706302133r3a05d123i3736dc6af99f455e@mail.gmail.com> oh yeah, he said getdata() but i don't know where it comes from and image.getpixel((10, 12)) is from http://www.pythonware.com/products/pil/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070630/b0d045a2/attachment.htm From rabidpoobear at gmail.com Sun Jul 1 07:35:28 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 01 Jul 2007 00:35:28 -0500 Subject: [Tutor] 200 dollar questions! In-Reply-To: <674d5ce60706302035y293fe5bbg58d8b5b1ce5cd649@mail.gmail.com> References: <100452.41767.qm@web86103.mail.ird.yahoo.com> <674d5ce60706301517n154d6f52n77c99be0f6df9a5d@mail.gmail.com> <674d5ce60706301926i4b9ee2b6t5b2b66b8c6d6447a@mail.gmail.com> <46871B2E.7050106@gmail.com> <674d5ce60706302020wf28b499kbe5fe8652a7f3939@mail.gmail.com> <4687204D.3070002@gmail.com> <674d5ce60706302035y293fe5bbg58d8b5b1ce5cd649@mail.gmail.com> Message-ID: <46873D20.1020704@gmail.com> elis aeris wrote: > which modules and origin is this function? You can infer from the fact that your image object already has the pixel data stored within it that the getdata would be a method of the object. In other words, just call image.getdata() and, if I recall correctly, when you asked where this function was, I mentioned that it had an entry in the PIL handbook right next to the getpixel() entry. Googling "PIL Handbook" yields this page http://www.pythonware.com/library/pil/handbook/image.htm and, as I said, """ getdata *im.getdata()* => sequence Returns the contents of an image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations, including iteration and basic sequence access. To convert it to an ordinary sequence (e.g. for printing), use *list(im.getdata())*. getextrema *im.getextrema()* => 2-tuple Returns a 2-tuple containing the minimum and maximum values of the image. In the current version of PIL, this is only applicable to single-band images. getpixel *im.getpixel(xy)* => value or tuple Returns the pixel at the given position. If the image is a multi-layer image, this method returns a tuple. Note that this method is rather slow; if you need to process larger parts of an image from Python, you can either use pixel access objects (see *load*), or the *getdata* method. """ > > is it the fastest way to get it? It depends how much of the pixel data you're using. If you're using the whole image, then yes, getdata is probably the fastest way. If you're using a portion, depending on the dimensions, it may be faster to getpixel or it may be faster to crop the image and getdata, there's no telling. You'd have to test. IF one way were faster for every case, there'd only be one way to do it. > > I am told to optimize getpixel (x, y) alone, so that's the only thing > i am trying, it's part of a project that will go live in september, so > the prof we are under hasn't one anything but some introductory readings. Then keep working with that. If you have a specific requirement, and they won't let you change it, then do what you can. -Luke From alan.gauld at btinternet.com Sun Jul 1 10:15:14 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 1 Jul 2007 09:15:14 +0100 Subject: [Tutor] 200 dollar questions! References: <100452.41767.qm@web86103.mail.ird.yahoo.com><674d5ce60706301517n154d6f52n77c99be0f6df9a5d@mail.gmail.com> <674d5ce60706301635x7f800f60rdc425b643711fe93@mail.gmail.com> Message-ID: "elis aeris" wrote > import win32ui > window = win32ui.FindWindow(None, "123.txt") > yourwindow.ShowWindow() The title is incorrect. A Notepad window has a title like: 123.txt - Notepad So thats what you need to search for. I told you Windoze APIs were flakey! :-) Alan G From alan.gauld at btinternet.com Sun Jul 1 10:17:24 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 1 Jul 2007 09:17:24 +0100 Subject: [Tutor] optimization: faster than for References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com><46872A73.5030600@tds.net><674d5ce60706302118w129fd3d3gc97b612aef2f5107@mail.gmail.com><46872D77.4060204@tds.net><674d5ce60706302131k55858706wa5c2562fe20958ca@mail.gmail.com> <674d5ce60706302133r3a05d123i3736dc6af99f455e@mail.gmail.com> Message-ID: "elis aeris" wrote ` > oh yeah, he said getdata() but i don't know where it comes from He told you it was a method of the image... Another version of what you are doing uses a list comprehension which might be slightly faster: pixels = [image.getpixel((x,y)) for x in range(1024) for y in range(768)] But your example didn't show you doing anything with the pixels you retrieve, so just putting them in a list might not help! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sun Jul 1 14:01:21 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 01 Jul 2007 08:01:21 -0400 Subject: [Tutor] optimization: faster than for In-Reply-To: <674d5ce60706302131k55858706wa5c2562fe20958ca@mail.gmail.com> References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> <46872A73.5030600@tds.net> <674d5ce60706302118w129fd3d3gc97b612aef2f5107@mail.gmail.com> <46872D77.4060204@tds.net> <674d5ce60706302131k55858706wa5c2562fe20958ca@mail.gmail.com> Message-ID: <46879791.3060109@tds.net> elis aeris wrote: > x = 0 > y = 0 > for x in xrange(1,1024,1): > for y in xrange(1,768,1): > rgb = image.getpixel((10, 12)) > > > > Luke said there is a faster way to do image.getpixel((10, 12)) > > so i am still waiting on that, > > the above has been improved many times and it's a lot faster than while, > I am trying to find out if there are any more new ways. The problem is, you are making a very fast loop to do nothing. Your real code will have to do something and it will have different bottlenecks and different opportunities for optimization than this loop. Really what you are doing now is finding the fastest way to write loop code. One think that will help though is to make all the variables used in the loop be local. Try this: x = 0 y = 0 xrange_ = xrange i_getpixel = image.getpixel for x in xrange_(1,1024,1): for y in xrange_(1,768,1): rgb = i_getpixel((10, 12)) Here is a recipe that will do this kind of optimizations automatically: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 You can also try optimizing your code with psyco, if you are running on an Intel box, or use pyrex or ShedSkin to compile part of your code to an extension module. Kent From hunter92383 at gmail.com Sun Jul 1 17:02:49 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 1 Jul 2007 08:02:49 -0700 Subject: [Tutor] im.getdata() Message-ID: <674d5ce60707010802n2096f87bte4170c3abeeca107@mail.gmail.com> Googling "PIL Handbook" yields this page http://www.pythonware.com/library/pil/handbook/image.htm and, as I said, """ getdata *im.getdata()* => sequence Returns the contents of an image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations, including iteration and basic sequence access. To convert it to an ordinary sequence (e.g. for printing), use *list(im.getdata())*. How do I find out how the list look like? Is it list[x][y] ? or rather, how did you find out how this internal data type look like? how do I access it ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070701/ff43495a/attachment.htm From alan.gauld at btinternet.com Sun Jul 1 19:15:23 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 1 Jul 2007 18:15:23 +0100 Subject: [Tutor] im.getdata() References: <674d5ce60707010802n2096f87bte4170c3abeeca107@mail.gmail.com> Message-ID: "elis aeris" wrote > *im.getdata()* => sequence > > Returns the contents of an image as a sequence object > ... > Note that the sequence object returned by this method is an internal > PIL > data type, which only supports certain sequence operations, > including > iteration and basic sequence access. > How do I find out how the list look like? > > Is it list[x][y] ? > or rather, how did you find out how this internal data type look > like? I'm not sure why you care what it looks like internally, you can use indexing to access the pixels and you can iterate over them. What more do you need? The indexing will be one dimensional since the help page told you that the data was flattened. Thus 123 456 789 becomes 123456789 But mostly you won't care because you can iterate over the list using a standard for loop. And as ever in Python the easiest way to find out how things work is just to try it in the interpreter. Use a small bitmap (16x16 say?) and load it into a PIL image, use getdata and see what it looks like when you index it, iterate over it and print it. Working with the interpreter can eliminate most uncertainties when working with Python. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From eike.welk at gmx.net Sun Jul 1 20:05:14 2007 From: eike.welk at gmx.net (Eike Welk) Date: Sun, 01 Jul 2007 20:05:14 +0200 Subject: [Tutor] 200 dollar questions! In-Reply-To: <674d5ce60706302030s2ea0d46am61a300f94a27d18b@mail.gmail.com> References: <100452.41767.qm@web86103.mail.ird.yahoo.com> <46871B2E.7050106@gmail.com> <674d5ce60706302030s2ea0d46am61a300f94a27d18b@mail.gmail.com> Message-ID: <200707012005.14739.eike.welk@gmx.net> On Sunday 01 July 2007 05:30, elis aeris wrote: > Yes, I am trying to write a OCR algorithm with neural network, but > the theories of NN is of little importance, what I am trying to get > ready for the project is run speed. If you do serious image analysis you should maybe switch to NumPy and SciPy. http://www.scipy.org/ SciPy contains basic image analysis functions. On the mailing lists there might be people who do image analysis too. Regards, Eike. From eike.welk at gmx.net Sun Jul 1 19:50:19 2007 From: eike.welk at gmx.net (Eike Welk) Date: Sun, 01 Jul 2007 19:50:19 +0200 Subject: [Tutor] optimization: faster than for In-Reply-To: <674d5ce60706302117j47cec367s467bdde68cd21168@mail.gmail.com> References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> <674d5ce60706302117j47cec367s467bdde68cd21168@mail.gmail.com> Message-ID: <200707011950.19733.eike.welk@gmx.net> On Sunday 01 July 2007 06:17, elis aeris wrote: > The for version, as claimed by > > http://www.python.org/doc/essays/list2str.html The fastest version of the algorithm is this one: In [4]:import array In [5]:def f7(list): .5.: return array.array('B', list).tostring() .5.: In [6]:f7([97, 98, 99]) Out[6]:'abc' The implicit loop is the "tostring" function. It is written in C and it happens to perform the desired algorithm. So there is nothing magical about "implicit loops". It just means: Find a library function that is written in C and that performs your task. For manipulating images it means: Find some operations in PIL that do what you want, and don't look at pixel values. Kind regards, Eike. From eric at ericwalstad.com Sun Jul 1 19:59:00 2007 From: eric at ericwalstad.com (Eric Walstad) Date: Sun, 01 Jul 2007 10:59:00 -0700 Subject: [Tutor] write a movie file thumbnail in Linux... Message-ID: <4687EB64.3090004@ericwalstad.com> Hi all, Nautilus does it when I browse to a directory that contains images and movie files created with my digital camera. I see thumbnails of the image (jpeg) and the movie (mov) files. I use python to process (rename, make reduced resolution copies (PIL)) of my image files. I'd like to also have my python script make those cool thumbnails of the movie files, too. Anybody have recommendations for how to do this with Python or other Linux command line tools? Thanks in advance, Eric. From rabidpoobear at gmail.com Sun Jul 1 20:29:35 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 01 Jul 2007 13:29:35 -0500 Subject: [Tutor] write a movie file thumbnail in Linux... In-Reply-To: <4687EB64.3090004@ericwalstad.com> References: <4687EB64.3090004@ericwalstad.com> Message-ID: <4687F28F.9080305@gmail.com> Eric Walstad wrote: > Hi all, > > Nautilus does it when I browse to a directory that contains images and > movie files created with my digital camera. I see thumbnails of the > image (jpeg) and the movie (mov) files. > > I use python to process (rename, make reduced resolution copies (PIL)) > of my image files. I'd like to also have my python script make those > cool thumbnails of the movie files, too. > > Anybody have recommendations for how to do this with Python or other > Linux command line tools? > pyMedia can be used to process various movie types. The documentation isn't the greatest (especially compared to most other Python libraries) but I'm pretty sure it will work for pulling out specific frames (or just the first, or whatever.) -Luke From rschroev_nospam_ml at fastmail.fm Sun Jul 1 21:02:10 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 01 Jul 2007 21:02:10 +0200 Subject: [Tutor] im.getdata() In-Reply-To: <674d5ce60707010802n2096f87bte4170c3abeeca107@mail.gmail.com> References: <674d5ce60707010802n2096f87bte4170c3abeeca107@mail.gmail.com> Message-ID: elis aeris schreef: > Googling "PIL Handbook" yields this page > http://www.pythonware.com/library/pil/handbook/image.htm > > and, as I said, > """ > > > getdata > > *im.getdata()* => sequence If you're using PIL >= 1.1.6, there's also a pixel access object you can use (the documentation is on that same page, in the 'load' section: "(New in 1.1.6) In 1.1.6 and later, load returns a pixel access object that can be used to read and modify pixels. The access object behaves like a 2-dimensional array, so you can do: pix = im.load() print pix[x, y] pix[x, y] = value Access via this object is a lot faster than getpixel and putpixel." Perhaps that's more useful to you? A lot depends on exactly what you want to do with the pixel values. I think you would do everyone (including yourself) a favor by just telling us what you're going to do with the pixel values. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From hunter92383 at gmail.com Sun Jul 1 21:26:15 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 1 Jul 2007 12:26:15 -0700 Subject: [Tutor] im.getdata() In-Reply-To: References: <674d5ce60707010802n2096f87bte4170c3abeeca107@mail.gmail.com> Message-ID: <674d5ce60707011226m57c063cq409dd98f65866a52@mail.gmail.com> I am capturing a screen shot, but then the image was already image, how do I .load it ? it's not image.load() import time import ImageGrab # Part of PIL from ctypes import * class RECT(Structure): _fields_ = [ ('left', c_ulong), ('top', c_ulong), ('right', c_ulong), ('bottom', c_ulong) ] GetForegroundWindow = windll.user32.GetForegroundWindow GetWindowRect = windll.user32.GetWindowRect rect = RECT() foreground_window = GetForegroundWindow() GetWindowRect(foreground_window, byref(rect)) image = ImageGrab.grab((rect.left, rect.top, rect.right, rect.bottom)) print time.time() pix = image.load() print pix[x, y] x = 0 y = 0 for x in xrange(1,1024,1): for y in xrange(1,768,1): print pix[10,10] -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070701/87bb1998/attachment.htm From rschroev_nospam_ml at fastmail.fm Sun Jul 1 21:42:32 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 01 Jul 2007 21:42:32 +0200 Subject: [Tutor] im.getdata() In-Reply-To: <674d5ce60707011226m57c063cq409dd98f65866a52@mail.gmail.com> References: <674d5ce60707010802n2096f87bte4170c3abeeca107@mail.gmail.com> <674d5ce60707011226m57c063cq409dd98f65866a52@mail.gmail.com> Message-ID: elis aeris schreef: > > > I am capturing a screen shot, but then the image was already > > > image, how do I .load it ? > > it's not image.load() I see. In that case, you can't use the method I described; that only works if you load the image from disk (as far as I know). I think you'd better use getdata() as Alan described. Something like this, if you need to access the pixels column-by-column (Is that really what you want? You still haven't told us): # ... image = ImageGrab.grab ((rect.left, rect.top, rect.right, rect.bottom)) pixels = image.getdata() for x in xrange(0, 1024): for y in xrange(0, 768): print pixels[x + y * 768] Note: pixel indices start from 0, not from 1. If you want to access them row-by-row (as is generally more often the case) and you don't have a special need to have the x and y available: image = ImageGrab.grab ((rect.left, rect.top, rect.right, rect.bottom)) for pixel in image.getdata(): print pixel Anyway, you're printing a lot of pixels (786432 actually)... is that really what you want? -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From hunter92383 at gmail.com Sun Jul 1 22:26:17 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 1 Jul 2007 13:26:17 -0700 Subject: [Tutor] optimization: faster than for In-Reply-To: <200707011950.19733.eike.welk@gmx.net> References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> <674d5ce60706302117j47cec367s467bdde68cd21168@mail.gmail.com> <200707011950.19733.eike.welk@gmx.net> Message-ID: <674d5ce60707011326l3a77bfe3h795cac78ec3ad222@mail.gmail.com> ugh, can someone who is online at this time give me some pointers on how to read this? i don't know how to look it up, in is listed, out is not, so i am not sure if this is python at all. On 7/1/07, Eike Welk wrote: > > On Sunday 01 July 2007 06:17, elis aeris wrote: > > The for version, as claimed by > > > > http://www.python.org/doc/essays/list2str.html > > The fastest version of the algorithm is this one: > > In [4]:import array > > In [5]:def f7(list): > .5.: return array.array('B', list).tostring() > .5.: > > In [6]:f7([97, 98, 99]) > Out[6]:'abc' > > > The implicit loop is the "tostring" function. It is written in C and > it happens to perform the desired algorithm. So there is nothing > magical about "implicit loops". It just means: Find a library > function that is written in C and that performs your task. > > For manipulating images it means: Find some operations in PIL that do > what you want, and don't look at pixel values. > > Kind regards, > Eike. > _______________________________________________ > 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/20070701/40212689/attachment.htm From sigzero at gmail.com Sun Jul 1 22:31:39 2007 From: sigzero at gmail.com (Robert Hicks) Date: Sun, 01 Jul 2007 16:31:39 -0400 Subject: [Tutor] Fastest way to iterate through a file In-Reply-To: References: <468050D5.3020403@tds.net> Message-ID: Alan Gauld wrote: > "Robert Hicks" wrote >> This is the loop code: >> >> for line in f2: >> for id in idList: >> if id in line: >> print "%s: %s" % (id, f2.next()) >> found = "%s: %s" % (id, f2.next()) >> f3.write(found) >> > > While I note that you got a solution using regex one general > point worth noting is that you should, in nested loop cases like > this, at least use break in the inner loop. > Do you mean after the write? That is a good suggestion and thanks for making it Mr. Gauld. Robert From hunter92383 at gmail.com Sun Jul 1 22:34:52 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 1 Jul 2007 13:34:52 -0700 Subject: [Tutor] Fastest way to iterate through a file In-Reply-To: References: <468050D5.3020403@tds.net> Message-ID: <674d5ce60707011334n68ae9565ka7525740108d6e17@mail.gmail.com> no, this one: In [4]:import array In [5]:def f7(list): .5.: return array.array('B', list).tostring() .5.: In [6]:f7([97, 98, 99]) Out[6]:'abc' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070701/a9b0a51d/attachment.html From hunter92383 at gmail.com Sun Jul 1 22:38:48 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 1 Jul 2007 13:38:48 -0700 Subject: [Tutor] Fastest way to iterate through a file In-Reply-To: <674d5ce60707011334n68ae9565ka7525740108d6e17@mail.gmail.com> References: <468050D5.3020403@tds.net> <674d5ce60707011334n68ae9565ka7525740108d6e17@mail.gmail.com> Message-ID: <674d5ce60707011338o75f9df25x4627285426737803@mail.gmail.com> > The for version, as claimed by > > http://www.python.org/doc/essays/list2str.html The fastest version of the algorithm is this one: > In [4]:import array > > In [5]:def f7(list): > .5.: return array.array('B', list).tostring() > .5.: > > In [6]:f7([97, 98, 99]) > Out[6]:'abc' > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070701/06cc9dc2/attachment.htm From hunter92383 at gmail.com Sun Jul 1 23:12:18 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 1 Jul 2007 14:12:18 -0700 Subject: [Tutor] Fastest way to iterate through a file In-Reply-To: <674d5ce60707011338o75f9df25x4627285426737803@mail.gmail.com> References: <468050D5.3020403@tds.net> <674d5ce60707011334n68ae9565ka7525740108d6e17@mail.gmail.com> <674d5ce60707011338o75f9df25x4627285426737803@mail.gmail.com> Message-ID: <674d5ce60707011412g73dd32d3t2f2b505c1ceabf2b@mail.gmail.com> I found out that by making a copy of it, it can be load() ed ! it runs 3 times faster now import time import ImageGrab from ctypes import * class RECT(Structure): _fields_ = [ ('left', c_ulong), ('top', c_ulong), ('right', c_ulong), ('bottom', c_ulong) ] GetForegroundWindow = windll.user32.GetForegroundWindow GetWindowRect = windll.user32.GetWindowRect rect = RECT() foreground_window = GetForegroundWindow() GetWindowRect(foreground_window, byref(rect)) image = ImageGrab.grab((rect.left, rect.top, rect.right, rect.bottom)) start_time = time.time() num_pixels = 0 num_black = 0 pix = image.copy().load() print time.time() for x in xrange(200): for y in xrange(200): num_pixels += 1 if pix[x, y] == (0, 0, 0): num_black += 1 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070701/4d1e738d/attachment.html From rabidpoobear at gmail.com Sun Jul 1 23:18:33 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 01 Jul 2007 16:18:33 -0500 Subject: [Tutor] optimization: faster than for In-Reply-To: <674d5ce60707011326l3a77bfe3h795cac78ec3ad222@mail.gmail.com> References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> <674d5ce60706302117j47cec367s467bdde68cd21168@mail.gmail.com> <200707011950.19733.eike.welk@gmx.net> <674d5ce60707011326l3a77bfe3h795cac78ec3ad222@mail.gmail.com> Message-ID: <46881A29.7010809@gmail.com> elis aeris wrote: > ugh, can someone who is online at this time give me some pointers on > how to read this? > > i don't know how to look it up, > > in is listed, > out is not, so i am not sure if this is python at all. IN is what you INput into the python interpeter. OUT is what the interpreter OUTPUTS. it's a convention people use in order that they don't have to use the >>> (3 greater-than signs) to indicate an interpreter input, because the greater-than sign is also used by e-mail clients to indicate the level of quoting in a reply, so >>> will often end up as 3 vertical bars in e-mail clients. HTH, -Luke From hunter92383 at gmail.com Sun Jul 1 23:24:32 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 1 Jul 2007 14:24:32 -0700 Subject: [Tutor] optimization: faster than for In-Reply-To: <46881A29.7010809@gmail.com> References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> <674d5ce60706302117j47cec367s467bdde68cd21168@mail.gmail.com> <200707011950.19733.eike.welk@gmx.net> <674d5ce60707011326l3a77bfe3h795cac78ec3ad222@mail.gmail.com> <46881A29.7010809@gmail.com> Message-ID: <674d5ce60707011424w69792039ofd194c98bbd70142@mail.gmail.com> so this is the actual code? [4]:import array [5]:def f7(list): .5.: return array.array('B', list).tostring() .5.: [6]:f7([97, 98, 99]) Output on the screen: [6]:'abc'- Hide quoted text - -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070701/fdfd22a0/attachment.htm From hunter92383 at gmail.com Sun Jul 1 23:31:05 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 1 Jul 2007 14:31:05 -0700 Subject: [Tutor] optimization: faster than for In-Reply-To: <674d5ce60707011424w69792039ofd194c98bbd70142@mail.gmail.com> References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> <674d5ce60706302117j47cec367s467bdde68cd21168@mail.gmail.com> <200707011950.19733.eike.welk@gmx.net> <674d5ce60707011326l3a77bfe3h795cac78ec3ad222@mail.gmail.com> <46881A29.7010809@gmail.com> <674d5ce60707011424w69792039ofd194c98bbd70142@mail.gmail.com> Message-ID: <674d5ce60707011431y4f1ef56at14c035210912d97a@mail.gmail.com> oh i get it, it's line number. ######################## import array def f7(list): return array.array('B', list).tostring() f7([97, 98, 99]) ###################### NOW, this looks python ! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070701/49fc0b71/attachment.html From alan.gauld at btinternet.com Sun Jul 1 23:53:46 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 1 Jul 2007 22:53:46 +0100 Subject: [Tutor] optimization: faster than for References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com><674d5ce60706302117j47cec367s467bdde68cd21168@mail.gmail.com><200707011950.19733.eike.welk@gmx.net> <674d5ce60707011326l3a77bfe3h795cac78ec3ad222@mail.gmail.com> Message-ID: "elis aeris" wrote >> In [4]:import array >> In [5]:def f7(list): >> .5.: return array.array('B', list).tostring() >> .5.: >> >> In [6]:f7([97, 98, 99]) >> Out[6]:'abc' I can't remember which tool does this - IronPython maybe? but the Ins are Inputs, the numbers arethe current command (hence the continuation lines all have 5) and the OUT is the output. Alan G From hunter92383 at gmail.com Mon Jul 2 00:02:47 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 1 Jul 2007 15:02:47 -0700 Subject: [Tutor] optimization: faster than for In-Reply-To: References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> <674d5ce60706302117j47cec367s467bdde68cd21168@mail.gmail.com> <200707011950.19733.eike.welk@gmx.net> <674d5ce60707011326l3a77bfe3h795cac78ec3ad222@mail.gmail.com> Message-ID: <674d5ce60707011502h3d68ac4dn8f9eb751d414200b@mail.gmail.com> oh crancky! C# ! i better try to find the best way to do it with the official python genre before venturing into that world of pain without PIL ! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070701/dcdb20e4/attachment.htm From rabidpoobear at gmail.com Mon Jul 2 00:04:27 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 01 Jul 2007 17:04:27 -0500 Subject: [Tutor] optimization: faster than for In-Reply-To: <674d5ce60707011502h3d68ac4dn8f9eb751d414200b@mail.gmail.com> References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> <674d5ce60706302117j47cec367s467bdde68cd21168@mail.gmail.com> <200707011950.19733.eike.welk@gmx.net> <674d5ce60707011326l3a77bfe3h795cac78ec3ad222@mail.gmail.com> <674d5ce60707011502h3d68ac4dn8f9eb751d414200b@mail.gmail.com> Message-ID: <468824EB.8060502@gmail.com> elis aeris wrote: > oh crancky! C# ! > > > i better try to find the best way to do it with the official python > genre before venturing into that world of pain without PIL ! What are you talking about. From rabidpoobear at gmail.com Mon Jul 2 00:05:45 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 01 Jul 2007 17:05:45 -0500 Subject: [Tutor] Fastest way to iterate through a file In-Reply-To: <674d5ce60707011412g73dd32d3t2f2b505c1ceabf2b@mail.gmail.com> References: <468050D5.3020403@tds.net> <674d5ce60707011334n68ae9565ka7525740108d6e17@mail.gmail.com> <674d5ce60707011338o75f9df25x4627285426737803@mail.gmail.com> <674d5ce60707011412g73dd32d3t2f2b505c1ceabf2b@mail.gmail.com> Message-ID: <46882539.3030103@gmail.com> elis aeris wrote: > I found out that by making a copy of it, it can be load() ed ! ImageGrab returns an image instance. You can get the pixel data directly using getdata(). There's no reason to do what you're doing. -Luke From hunter92383 at gmail.com Mon Jul 2 00:06:38 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 1 Jul 2007 15:06:38 -0700 Subject: [Tutor] optimization: faster than for In-Reply-To: <468824EB.8060502@gmail.com> References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> <674d5ce60706302117j47cec367s467bdde68cd21168@mail.gmail.com> <200707011950.19733.eike.welk@gmx.net> <674d5ce60707011326l3a77bfe3h795cac78ec3ad222@mail.gmail.com> <674d5ce60707011502h3d68ac4dn8f9eb751d414200b@mail.gmail.com> <468824EB.8060502@gmail.com> Message-ID: <674d5ce60707011506s41398d49x8d27faaf5ce6083a@mail.gmail.com> my reply oh crancky! C# ! http://en.wikipedia.org/wiki/Iron_Python i better try to find the best way to do it with the official python genre before venturing into that world of pain without PIL ! Quote:- Hide quoted text - >> In [4]:import array >> In [5]:def f7(list): >> .5.: return array.array('B', list).tostring() >> .5.: >> >> In [6]:f7([97, 98, 99]) >> Out[6]:'abc' I can't remember which tool does this - IronPython maybe? but the Ins are Inputs, the numbers arethe current command (hence the continuation lines all have 5) and the OUT is the output. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070701/bad3c84d/attachment.html From rabidpoobear at gmail.com Mon Jul 2 00:08:59 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 01 Jul 2007 17:08:59 -0500 Subject: [Tutor] optimization: faster than for In-Reply-To: <674d5ce60707011506v50171d4ete72c82d91e77a278@mail.gmail.com> References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> <674d5ce60706302117j47cec367s467bdde68cd21168@mail.gmail.com> <200707011950.19733.eike.welk@gmx.net> <674d5ce60707011326l3a77bfe3h795cac78ec3ad222@mail.gmail.com> <674d5ce60707011502h3d68ac4dn8f9eb751d414200b@mail.gmail.com> <468824EB.8060502@gmail.com> <674d5ce60707011506v50171d4ete72c82d91e77a278@mail.gmail.com> Message-ID: <468825FB.1030305@gmail.com> elis aeris wrote: > my reply > oh crancky! C# ! > > http://en.wikipedia.org/wiki/Iron_Python > > i better try to find the best way to do it with the official python > genre before venturing into that world of pain without PIL ! Please don't reply directly to me. Iron Python is an implementation of Python in .NET similarly Jython is an implementation of Python in Java. This doesn't have anythign to do with their libraries. The example code > >> In [4]:import array > >> In [5]:def f7(list): > >> .5.: return array.array('B', list).tostring() > >> .5.: > >> > >> In [6]:f7([97, 98, 99]) > >> Out[6]:'abc' Would run in IronPython, Jython or cPython. The way that the code is marked up (adding In or >>> before each line) is a feature of the IDE that one uses. Did you even try the code? -Luke From john at fouhy.net Mon Jul 2 00:12:12 2007 From: john at fouhy.net (John Fouhy) Date: Mon, 2 Jul 2007 10:12:12 +1200 Subject: [Tutor] optimization: faster than for In-Reply-To: References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> <674d5ce60706302117j47cec367s467bdde68cd21168@mail.gmail.com> <200707011950.19733.eike.welk@gmx.net> <674d5ce60707011326l3a77bfe3h795cac78ec3ad222@mail.gmail.com> Message-ID: <5e58f2e40707011512o2212e8b6ra78b4469e95ebed5@mail.gmail.com> On 02/07/07, Alan Gauld wrote: > > "elis aeris" wrote > > >> In [4]:import array > >> In [5]:def f7(list): > >> .5.: return array.array('B', list).tostring() > >> .5.: > >> > >> In [6]:f7([97, 98, 99]) > >> Out[6]:'abc' > I can't remember which tool does this - IronPython maybe? It's IPython -- http://ipython.scipy.org/moin/ -- John. From hunter92383 at gmail.com Mon Jul 2 00:17:14 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 1 Jul 2007 15:17:14 -0700 Subject: [Tutor] optimization: faster than for In-Reply-To: <468825FB.1030305@gmail.com> References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> <674d5ce60706302117j47cec367s467bdde68cd21168@mail.gmail.com> <200707011950.19733.eike.welk@gmx.net> <674d5ce60707011326l3a77bfe3h795cac78ec3ad222@mail.gmail.com> <674d5ce60707011502h3d68ac4dn8f9eb751d414200b@mail.gmail.com> <468824EB.8060502@gmail.com> <674d5ce60707011506v50171d4ete72c82d91e77a278@mail.gmail.com> <468825FB.1030305@gmail.com> Message-ID: <674d5ce60707011517o6e411750qd345c89112b7d2ec@mail.gmail.com> of course. but i tried only the code, not rewriting the pixelget part into that, because I have to understand it first. so, i should look into ipython's doc for this code? ok, import array def f7(list): return array.array('B', list).tostring() f7([97, 98, 99]) Out[6]:'abc' searching with ipython search engine returns returns "parrel computing" ack, so i call the array.array function, and tostring() function, I have no idea how to read that. @_@ what a great one liner! On 7/1/07, Luke Paireepinart wrote: > > elis aeris wrote: > > my reply > > oh crancky! C# ! > > > > http://en.wikipedia.org/wiki/Iron_Python > > > > i better try to find the best way to do it with the official python > > genre before venturing into that world of pain without PIL ! > Please don't reply directly to me. > > Iron Python is an implementation of Python in .NET > similarly Jython is an implementation of Python in Java. > This doesn't have anythign to do with their libraries. > The example code > > >> In [4]:import array > > >> In [5]:def f7(list): > > >> .5.: return array.array('B', list).tostring() > > >> .5.: > > >> > > >> In [6]:f7([97, 98, 99]) > > >> Out[6]:'abc' > Would run in IronPython, Jython or cPython. > The way that the code is marked up (adding In or >>> before each line) > is a feature of the IDE that one uses. > Did you even try the code? > -Luke > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070701/771dadac/attachment.htm From alan.gauld at btinternet.com Mon Jul 2 00:38:08 2007 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 1 Jul 2007 22:38:08 +0000 (GMT) Subject: [Tutor] Power Shells [WAS:] optimization: faster than for Message-ID: <929536.53263.qm@web86101.mail.ird.yahoo.com> > > >> In [6]:f7([97, 98, 99]) > > >> Out[6]:'abc' > > I can't remember which tool does this - IronPython maybe? > > It's IPython -- http://ipython.scipy.org/moin/ Now for some reason I assumed IPython was the IDE for IronPython. Having checked out the web link its obviously completely unrelated! PyCrust, IPython, SPE, Eclipse/PyDev Suddenly it seems like I have an embarassment of advanced shells to choose from. At risk of starting a religious war, who favours which and why? Alan G. (Currently using PyCrust and playing with SPE) From hunter92383 at gmail.com Mon Jul 2 00:42:27 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 1 Jul 2007 15:42:27 -0700 Subject: [Tutor] Power Shells [WAS:] optimization: faster than for In-Reply-To: <929536.53263.qm@web86101.mail.ird.yahoo.com> References: <929536.53263.qm@web86101.mail.ird.yahoo.com> Message-ID: <674d5ce60707011542h350674a5hcc5589c0bee9f7a6@mail.gmail.com> Oie, as if the battle for the best text editor is not enough ... Well, can you run a test for me? Use the best for-equivalent and run the code below, instead of 1024*768, scale to 800*600 , just so the window you are screen shotting from is small enough. import time import ImageGrab # Part of PIL from ctypes import * # Load up the Win32 APIs we need to use. 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 # Sleep for 2 seconds - click the window you want to grab. #time.sleep(2) # 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)) # Save the screenshot as a BMP. #image.save("c:\ee\screenshot.bmp") # Get the pixel 10 pixels along the top of the foreground window - this # will be a piece of the window border. print time.time() pix = image.load() print pix[x, y] x = 0 y = 0 for x in xrange(1,1024,1): for y in xrange(1,768,1): rgb = pix[x,y] print time.time() # PIL returns colours as RGB values packed into a triple: #print "RGB(%d, %d, %d)" % (rgb[0], rgb[1], rgb[2]) # This prints RGB(0, 74, 216) on my XP machine -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070701/d0f43666/attachment.htm From kent37 at tds.net Mon Jul 2 01:01:54 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 01 Jul 2007 19:01:54 -0400 Subject: [Tutor] Power Shells [WAS:] optimization: faster than for In-Reply-To: <929536.53263.qm@web86101.mail.ird.yahoo.com> References: <929536.53263.qm@web86101.mail.ird.yahoo.com> Message-ID: <46883262.7070404@tds.net> ALAN GAULD wrote: >>>>> In [6]:f7([97, 98, 99]) >>>>> Out[6]:'abc' >>> I can't remember which tool does this - IronPython maybe? >> It's IPython -- http://ipython.scipy.org/moin/ > > Now for some reason I assumed IPython was the IDE for IronPython. > Having checked out the web link its obviously completely unrelated! > > PyCrust, IPython, SPE, Eclipse/PyDev > > Suddenly it seems like I have an embarassment of advanced > shells to choose from. At risk of starting a religious war, who > favours which and why? I like IPython. I only use a fraction of its features. Some that I like are - persistent and smart command history, so for example when I start the shell, type 'fr' and up-arrow, it will show me the last 'from xx import yy' I typed. I'm using Django a lot and frequently import the same model classes so this is very handy. - remembers the results of each line, for example _10 is the result of line 10. - automatic pretty-printing, for example lists will have newlines inserted between items as needed - smart tab completion - smart paste - you can edit a multi-line command in a separate editor - verbose stack traces - usually I turn this off but it can be handy - colorized stack traces and integrated help Kent From kent37 at tds.net Mon Jul 2 01:03:04 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 01 Jul 2007 19:03:04 -0400 Subject: [Tutor] Fastest way to iterate through a file In-Reply-To: <674d5ce60707011334n68ae9565ka7525740108d6e17@mail.gmail.com> References: <468050D5.3020403@tds.net> <674d5ce60707011334n68ae9565ka7525740108d6e17@mail.gmail.com> Message-ID: <468832A8.7000500@tds.net> elis aeris wrote: > no, this one: > > > > In [4]:import array > > In [5]:def f7(list): > .5.: return array.array('B', list).tostring() > .5.: > > In [6]:f7([97, 98, 99]) > Out[6]:'abc' That has nothing at all to do with reading lines of a file. It is the fastest way to solve one particular problem, not every loop. Kent From alan.gauld at btinternet.com Mon Jul 2 01:08:11 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 2 Jul 2007 00:08:11 +0100 Subject: [Tutor] optimization: faster than for References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com><674d5ce60706302117j47cec367s467bdde68cd21168@mail.gmail.com><200707011950.19733.eike.welk@gmx.net><674d5ce60707011326l3a77bfe3h795cac78ec3ad222@mail.gmail.com><674d5ce60707011502h3d68ac4dn8f9eb751d414200b@mail.gmail.com><468824EB.8060502@gmail.com><674d5ce60707011506v50171d4ete72c82d91e77a278@mail.gmail.com><468825FB.1030305@gmail.com> <674d5ce60707011517o6e411750qd345c89112b7d2ec@mail.gmail.com> Message-ID: "elis aeris" wrote > so, i should look into ipython's doc for this code? No, Ipython is just another shell, like IDLE. Its not a different version of python, it just displays its prompts differently is all. Alan G. From hunter92383 at gmail.com Mon Jul 2 01:13:38 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 1 Jul 2007 16:13:38 -0700 Subject: [Tutor] Fastest way to iterate through a file In-Reply-To: <468832A8.7000500@tds.net> References: <468050D5.3020403@tds.net> <674d5ce60707011334n68ae9565ka7525740108d6e17@mail.gmail.com> <468832A8.7000500@tds.net> Message-ID: <674d5ce60707011613r237f5f71q72e3b3a5c325d5f7@mail.gmail.com> in that case, can we talk about what this is? import array def f7(list): return array.array('B', list).tostring() f7([97, 98, 99]) Out[6]:'abc' It's only one line, and it's faster than for(), getting through this one might just end my quest for optimized python source code. (then i ll begin the hacking on the psycho and things ...) so, array is a module, and then from that, a function called array is called, and then tostring, ugh, what does it mean ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070701/c8e84452/attachment.html From alan.gauld at btinternet.com Mon Jul 2 01:13:10 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 2 Jul 2007 00:13:10 +0100 Subject: [Tutor] Power Shells [WAS:] optimization: faster than for References: <929536.53263.qm@web86101.mail.ird.yahoo.com> <674d5ce60707011542h350674a5hcc5589c0bee9f7a6@mail.gmail.com> Message-ID: "elis aeris" wrote > Use the best for-equivalent and run the code below, Elis, Can you tell us what exactly you are trying to do? I'm not sure whether its just running tests on loop contructs or trying to get a list of pixels from an image (and if so to do what with them?) Until we know what your underlying project is trying to achieve its impossible to give sensible help in making things run faster. As Kent mentioned the things you do with the pixels are likely to make as much difference to total performance as the loops you use. Python is not C and the fastest solution in one scenario might not be fastest in another. It's better to get the best solution that works then tune it for speed where its actually necessary. What performance do you actually need? What is too slow at the moment? Are you in danger of succumbing to the danger of premature optimisation? It looks a lot like it from your posts. Alan G. From hunter92383 at gmail.com Mon Jul 2 01:21:36 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 1 Jul 2007 16:21:36 -0700 Subject: [Tutor] Fastest way to iterate through a file In-Reply-To: <46882539.3030103@gmail.com> References: <468050D5.3020403@tds.net> <674d5ce60707011334n68ae9565ka7525740108d6e17@mail.gmail.com> <674d5ce60707011338o75f9df25x4627285426737803@mail.gmail.com> <674d5ce60707011412g73dd32d3t2f2b505c1ceabf2b@mail.gmail.com> <46882539.3030103@gmail.com> Message-ID: <674d5ce60707011621y3650f2e3k96d7e4028b67bd09@mail.gmail.com> oh i want to bring something up, there is this one line which i think is suggesting that there is a way to use this object that the document says it's a lot faster than getdata and getpixel. *im.load()* Allocates storage for the image and loads it from the file (or from the source, for lazy operations). In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. (New in 1.1.6) In 1.1.6 and later, *load* returns a pixel access object that can be used to read and modify pixels. The access object behaves like a 2-dimensional array, so you can do: pix = im.load() print pix[x, y] pix[x, y] = value Access via this object is a lot faster than *getpixel* and *putpixel*. according to it, this load function is a new addition to 1.1.6, and this object is different from the rest. On 7/1/07, Luke Paireepinart wrote: > > elis aeris wrote: > > I found out that by making a copy of it, it can be load() ed ! > ImageGrab returns an image instance. > You can get the pixel data directly using getdata(). > There's no reason to do what you're doing. > -Luke > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070701/08c93c49/attachment.html From hunter92383 at gmail.com Mon Jul 2 02:16:41 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 1 Jul 2007 17:16:41 -0700 Subject: [Tutor] Power Shells [WAS:] optimization: faster than for In-Reply-To: References: <929536.53263.qm@web86101.mail.ird.yahoo.com> <674d5ce60707011542h350674a5hcc5589c0bee9f7a6@mail.gmail.com> Message-ID: <674d5ce60707011716r49b9f64fu1a94900cffb20b86@mail.gmail.com> http://memoryhacking.com/forums/viewtopic.php?p=1195#1195 On 7/1/07, Alan Gauld wrote: > > > "elis aeris" wrote > > > Use the best for-equivalent and run the code below, > > Elis, > > Can you tell us what exactly you are trying to do? > > I'm not sure whether its just running tests on loop contructs > or trying to get a list of pixels from an image (and if so to do > what with them?) > > Until we know what your underlying project is trying to achieve > its impossible to give sensible help in making things run faster. > As Kent mentioned the things you do with the pixels are likely > to make as much difference to total performance as the loops > you use. Python is not C and the fastest solution in one scenario > might not be fastest in another. It's better to get the best solution > that works then tune it for speed where its actually necessary. > > What performance do you actually need? > What is too slow at the moment? > > Are you in danger of succumbing to the danger of premature > optimisation? It looks a lot like it from your posts. > > 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/20070701/58c1d76f/attachment.htm From mhoy4 at cox.net Mon Jul 2 03:09:00 2007 From: mhoy4 at cox.net (Mike Hoy) Date: Sun, 01 Jul 2007 18:09:00 -0700 Subject: [Tutor] put data from text file into list Message-ID: <4688502C.6070102@cox.net> is it possible to take information contained inside a text file and put it into a list? My text file contains info derived from a list so it looks like this: ['foo','bar']. From reed at reedobrien.com Mon Jul 2 06:58:13 2007 From: reed at reedobrien.com (Reed O'Brien) Date: Mon, 2 Jul 2007 00:58:13 -0400 Subject: [Tutor] Fastest way to iterate through a file In-Reply-To: <674d5ce60707011613r237f5f71q72e3b3a5c325d5f7@mail.gmail.com> References: <468050D5.3020403@tds.net> <674d5ce60707011334n68ae9565ka7525740108d6e17@mail.gmail.com> <468832A8.7000500@tds.net> <674d5ce60707011613r237f5f71q72e3b3a5c325d5f7@mail.gmail.com> Message-ID: On Jul 1, 2007, at 7:13 PM, elis aeris wrote: > > might just end my quest for > optimized python source code. > ugh, > > what does it mean ? elias, We have two MAJOR rules regarding optimization. These rules really go beyond python, but this is a good place to learn them. The two rules of optimization: The first is: 1) DON'T DO IT! The second is only for advanced programmers. 2) Don't do it, yet! Until you have working code, there is nothing to optimize. You can spend months optimizing and refactoring a for loop only to find out that you are hung up on a network operation. Write the program first. Then see if it needs tweaking. other wise you are simply rewriting this: for None in None: pass ~ro -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070702/1bf6cc47/attachment.html From reed at reedobrien.com Mon Jul 2 07:06:49 2007 From: reed at reedobrien.com (Reed O'Brien) Date: Mon, 2 Jul 2007 01:06:49 -0400 Subject: [Tutor] Power Shells [WAS:] optimization: faster than for In-Reply-To: <929536.53263.qm@web86101.mail.ird.yahoo.com> References: <929536.53263.qm@web86101.mail.ird.yahoo.com> Message-ID: On Jul 1, 2007, at 6:38 PM, ALAN GAULD wrote: > Suddenly it seems like I have an embarassment of advanced > shells to choose from. At risk of starting a religious war, who > favours which and why? > > Alan, I have been using ipython for the last few months. I am barely touching teh surface of what it is capable of. there are of course silly shortcuts like so: In [16]: def foo(x): print x ....: ....: In [18]: def bar(x, y, z): print x, y, z ....: ....: In [20]: ;foo 1 2 3 -------> foo("1 2 3") 1 2 3 In [21]: ,bar 1 2 3 -------> bar("1", "2", "3") 1 2 3 note the ; and , that auto quote for you. The main reason I like it is that is leaves me real shell access and auto complete for filepaths and such. I use it with the zope debugger, too. ~ro From hunter92383 at gmail.com Mon Jul 2 07:27:11 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 1 Jul 2007 22:27:11 -0700 Subject: [Tutor] Power Shells [WAS:] optimization: faster than for In-Reply-To: References: <929536.53263.qm@web86101.mail.ird.yahoo.com> Message-ID: <674d5ce60707012227i269b7e84n101cb20ee355f17b@mail.gmail.com> uh, can i ask about something very quickly? how do i write a function to do a pop up window with designated window name, type (ok, cancel, those) and message? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070701/9503bfb6/attachment.html From eike.welk at gmx.net Mon Jul 2 08:41:51 2007 From: eike.welk at gmx.net (Eike Welk) Date: Mon, 02 Jul 2007 08:41:51 +0200 Subject: [Tutor] optimization: faster than for In-Reply-To: References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> <674d5ce60707011326l3a77bfe3h795cac78ec3ad222@mail.gmail.com> Message-ID: <200707020841.52730.eike.welk@gmx.net> On Sunday 01 July 2007 23:53, Alan Gauld wrote: > "elis aeris" wrote > > >> In [4]:import array > >> In [5]:def f7(list): > >> .5.: return array.array('B', list).tostring() > >> .5.: > >> > >> In [6]:f7([97, 98, 99]) > >> Out[6]:'abc' > > I can't remember which tool does this - IronPython maybe? It is IPython. I like it because it has better help, syntax coloring and it plays well with Matplotlib. Regards, Eike. From hunter92383 at gmail.com Mon Jul 2 08:47:02 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 1 Jul 2007 23:47:02 -0700 Subject: [Tutor] optimization: faster than for In-Reply-To: <200707020841.52730.eike.welk@gmx.net> References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com> <674d5ce60707011326l3a77bfe3h795cac78ec3ad222@mail.gmail.com> <200707020841.52730.eike.welk@gmx.net> Message-ID: <674d5ce60707012347x5d41c6aei450fca4fa0b6a8da@mail.gmail.com> > >> In [4]:import array > >> In [5]:def f7(list): > >> .5.: return array.array('B', list).tostring() > >> .5.: > >> > >> In [6]:f7([97, 98, 99]) > >> Out[6]:'abc' ugh the code it self is not generic python, that was an example of how to do this my project is OCR http://www.eternite.co.uk/gundam_clips/ocr.PNG The letter I equals to "282" because it has 2 points on the y axis of the first point, and 8 points on the y axis on the second, and then 2 on the last one. So the string would be translated into: 28201722030033330000004222400722240172206 and so on. ##################### so what I am going to have is a string like above and what I 'll have is a list of tuples, for instance [a, 222] , [b,333] and so forth how do I write the fastest code to do this optimization is immediately needed because the job is done as soon this translation is complete. so two bottle neck image.getdata() is a good solution, i haven't found a better one, and the other bottle neck is this translation process. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070701/7dd60a8f/attachment.htm From thorsten at thorstenkampe.de Mon Jul 2 11:28:48 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 2 Jul 2007 10:28:48 +0100 Subject: [Tutor] Power Shells [WAS:] optimization: faster than for References: <929536.53263.qm@web86101.mail.ird.yahoo.com> <674d5ce60707012227i269b7e84n101cb20ee355f17b@mail.gmail.com> Message-ID: * elis aeris (Sun, 1 Jul 2007 22:27:11 -0700) > uh, can i ask about something very quickly? Don't hijack a completely unreleated thread. > how do i write a function to do > > a pop up window with designated window name, type (ok, cancel, those) and > message? Okay, a very quick answer: EasyGUI From hunter92383 at gmail.com Mon Jul 2 11:32:07 2007 From: hunter92383 at gmail.com (elis aeris) Date: Mon, 2 Jul 2007 02:32:07 -0700 Subject: [Tutor] pop up window Message-ID: <674d5ce60707020232r576089bcl2dd2e45be6979c4@mail.gmail.com> i won't do that again, i am a 2 day newbie (hello) uh, how about a less quick one that's built-in in python ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070702/f3843951/attachment.html From thorsten at thorstenkampe.de Mon Jul 2 11:42:56 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 2 Jul 2007 10:42:56 +0100 Subject: [Tutor] pop up window References: <674d5ce60707020232r576089bcl2dd2e45be6979c4@mail.gmail.com> Message-ID: * elis aeris (Mon, 2 Jul 2007 02:32:07 -0700) > i won't do that again, i am a 2 day newbie (hello) > > uh, > > how about a less quick one that's built-in in python ? Are you replying to me? Please quote the parts you are referring to. Anyway, Python does not come with "built-in pop-up support". From kent37 at tds.net Mon Jul 2 13:57:39 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 02 Jul 2007 07:57:39 -0400 Subject: [Tutor] put data from text file into list In-Reply-To: <4688502C.6070102@cox.net> References: <4688502C.6070102@cox.net> Message-ID: <4688E833.4020207@tds.net> Mike Hoy wrote: > is it possible to take information contained inside a text file and put > it into a list? My text file contains info derived from a list so it > looks like this: ['foo','bar']. If the file is Python syntax (including an assignment) you can import it directly. Or try one of these recipes: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/281056 Kent From bhaaluu at gmail.com Mon Jul 2 14:18:29 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 2 Jul 2007 08:18:29 -0400 Subject: [Tutor] Power Shells [WAS:] optimization: faster than for In-Reply-To: <929536.53263.qm@web86101.mail.ird.yahoo.com> References: <929536.53263.qm@web86101.mail.ird.yahoo.com> Message-ID: Greetings, I am new, and have been lurking and reading Python tutorials in the background, while reading the posts from this list. Since I have looked at so many things, I'm not sure where I found this, but it works great (I'm running a version of Debian GNU/Linux). I use the vim text editor, and this is a .vimrc file that makes vim work just like an IDE: ---------------------8<-----cut here------->8------------- " .vimrc " " Created by Jeff Elkner 23 January 2006 " Last modified 2 February 2006 " " Turn on syntax highlighting and autoindenting syntax enable filetype indent on " set autoindent width to 4 spaces (see " http://www.vim.org/tips/tip.php?tip_id=83) set nu set et set sw=4 set smarttab " Bind key to running the python interpreter on the currently active " file. (curtesy of Steve Howell from email dated 1 Feb 2006). map :w\|!python % ---------------------8<-----cut here------->8------------- Otherwise, I just use the vanilla Python interactive interpreter. I have tried IDLE, but didn't care for it. This is a great computer programming list. Many thanks to everyone who contributes. -- bhaaluu at gmail dot com On 7/1/07, ALAN GAULD wrote: > > It's IPython -- http://ipython.scipy.org/moin/ > > Now for some reason I assumed IPython was the IDE for IronPython. > Having checked out the web link its obviously completely unrelated! > > PyCrust, IPython, SPE, Eclipse/PyDev > > Suddenly it seems like I have an embarassment of advanced > shells to choose from. At risk of starting a religious war, who > favours which and why? > > Alan G. > (Currently using PyCrust and playing with SPE) From eike.welk at gmx.net Mon Jul 2 15:42:05 2007 From: eike.welk at gmx.net (Eike Welk) Date: Mon, 02 Jul 2007 15:42:05 +0200 Subject: [Tutor] Power Shells [WAS:] optimization: faster than for In-Reply-To: <929536.53263.qm@web86101.mail.ird.yahoo.com> References: <929536.53263.qm@web86101.mail.ird.yahoo.com> Message-ID: <200707021542.05886.eike.welk@gmx.net> On Monday 02 July 2007 00:38, ALAN GAULD wrote: > > > >> In [6]:f7([97, 98, 99]) > > > >> Out[6]:'abc' > > > > > > I can't remember which tool does this - IronPython maybe? > > > > It's IPython -- http://ipython.scipy.org/moin/ > > Now for some reason I assumed IPython was the IDE for IronPython. > Having checked out the web link its obviously completely unrelated! > > PyCrust, IPython, SPE, Eclipse/PyDev > > Suddenly it seems like I have an embarassment of advanced > shells to choose from. At risk of starting a religious war, who > favours which and why? I like IPython for interactive sessions, because of the better help facilities and because it has special support for Matplotlib. (It keeps the display thread running.) I used IPython in the example because I thought that it would clarify the point. (Especially the "In [6]", "Out[6]:" prompts.) But the opposite was true: It created additional confusion. I use IPython however not very often. I use PyDev for programming and it has no usable support for an interactive shell. Instead I write small test programs and look at them in the debugger. PyDev's debugger frontend is quite good. > > Alan G. > (Currently using PyCrust and playing with SPE) > > Regards, Eike. From rondosxx at yahoo.com Mon Jul 2 15:47:25 2007 From: rondosxx at yahoo.com (ron) Date: Mon, 2 Jul 2007 06:47:25 -0700 (PDT) Subject: [Tutor] Tutor Digest, Vol 41, Issue 7 In-Reply-To: Message-ID: <907981.18855.qm@web52508.mail.re2.yahoo.com> hi steve, I have summer class for next three monday and wednesday evenings. we'll catch up someday. sorry, ron ____________________________________________________________________________________ Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz From hunter92383 at gmail.com Mon Jul 2 15:57:18 2007 From: hunter92383 at gmail.com (elis aeris) Date: Mon, 2 Jul 2007 06:57:18 -0700 Subject: [Tutor] Tutor Digest, Vol 41, Issue 7 In-Reply-To: <907981.18855.qm@web52508.mail.re2.yahoo.com> References: <907981.18855.qm@web52508.mail.re2.yahoo.com> Message-ID: <674d5ce60707020657k724b76dcj9de02b9e5d487ceb@mail.gmail.com> they cancelled this class http://reg.cstudies.ubc.ca/course_info.cfm?courseid=IP468 due to low enrollment. I'd love to be in a class. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070702/a47e1816/attachment.html From simplebob at gmail.com Mon Jul 2 18:46:02 2007 From: simplebob at gmail.com (Daniel McQuay) Date: Mon, 2 Jul 2007 12:46:02 -0400 Subject: [Tutor] Automating Windows (Maintenance) Message-ID: <6d87ecf40707020946q5e13febfiddd4c42125e22ac1@mail.gmail.com> Hey guys, I wondering if any one uses Python to do such things as defragment, clean up temp files, check for hard drive errors, check for unusual processes running, and so on. I am in charge of maintaining a lot of Windows PC's and it would make life so much easier if i could automate some of these tasks. I am pretty new to Python but I seem to understand it a little better than VB Script. I have been Googling Windows Automation and getting some pretty good links but most if not all are done using batch scripts and VB Script. I have a batch script that cleans up temp files and defragments the hard drive but I would like to know if Python is a good candidate for this or should I just stick to what is built into Windows. Thank in advance, -- Daniel McQuay HDR Time Traveler www.pittbullsecure.com www.Jaluno.com H: 814.341.9013 M: 814.421.3863 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070702/c4b6fa97/attachment.htm From mail at timgolden.me.uk Mon Jul 2 20:45:14 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 02 Jul 2007 19:45:14 +0100 Subject: [Tutor] Automating Windows (Maintenance) In-Reply-To: <6d87ecf40707020946q5e13febfiddd4c42125e22ac1@mail.gmail.com> References: <6d87ecf40707020946q5e13febfiddd4c42125e22ac1@mail.gmail.com> Message-ID: <468947BA.6010401@timgolden.me.uk> Daniel McQuay wrote: > I wondering if any one uses Python to do such things as defragment, > clean up temp files, check for hard drive errors, check for unusual > processes running, and so on. I am in charge of maintaining a lot of > Windows PC's and it would make life so much easier if i could automate > some of these tasks. I am pretty new to Python but I seem to understand > it a little better than VB Script. I have been Googling Windows > Automation and getting some pretty good links but most if not all are > done using batch scripts and VB Script. I have a batch script that > cleans up temp files and defragments the hard drive but I would like to > know if Python is a good candidate for this or should I just stick to > what is built into Windows. WMI is probably the answer to a lot of those kind of things. In general, if you have a sys-adminy task to do under Windows, put "WMI " into your favourite search engine and see what comes out.[0] Then get the Python WMI module [1] and convert the example from VBS to Python. And Bob's your uncle. [2] TJG [0] eg, http://msdn2.microsoft.com/EN-US/library/aa394592.aspx [1] http://timgolden.me.uk/python/wmi.html [2] Well *my* uncle, at least: I do actually have an uncle called Bob. From mail at timgolden.me.uk Mon Jul 2 20:45:14 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 02 Jul 2007 19:45:14 +0100 Subject: [Tutor] Automating Windows (Maintenance) In-Reply-To: <6d87ecf40707020946q5e13febfiddd4c42125e22ac1@mail.gmail.com> References: <6d87ecf40707020946q5e13febfiddd4c42125e22ac1@mail.gmail.com> Message-ID: <468947BA.6010401@timgolden.me.uk> Daniel McQuay wrote: > I wondering if any one uses Python to do such things as defragment, > clean up temp files, check for hard drive errors, check for unusual > processes running, and so on. I am in charge of maintaining a lot of > Windows PC's and it would make life so much easier if i could automate > some of these tasks. I am pretty new to Python but I seem to understand > it a little better than VB Script. I have been Googling Windows > Automation and getting some pretty good links but most if not all are > done using batch scripts and VB Script. I have a batch script that > cleans up temp files and defragments the hard drive but I would like to > know if Python is a good candidate for this or should I just stick to > what is built into Windows. WMI is probably the answer to a lot of those kind of things. In general, if you have a sys-adminy task to do under Windows, put "WMI " into your favourite search engine and see what comes out.[0] Then get the Python WMI module [1] and convert the example from VBS to Python. And Bob's your uncle. [2] TJG [0] eg, http://msdn2.microsoft.com/EN-US/library/aa394592.aspx [1] http://timgolden.me.uk/python/wmi.html [2] Well *my* uncle, at least: I do actually have an uncle called Bob. From mail at timgolden.me.uk Mon Jul 2 20:45:59 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 02 Jul 2007 19:45:59 +0100 Subject: [Tutor] Automating Windows (Maintenance) In-Reply-To: <6d87ecf40707020946q5e13febfiddd4c42125e22ac1@mail.gmail.com> References: <6d87ecf40707020946q5e13febfiddd4c42125e22ac1@mail.gmail.com> Message-ID: <468947E7.20007@timgolden.me.uk> Daniel McQuay wrote: > I wondering if any one uses Python to do such things as defragment, > clean up temp files, check for hard drive errors, check for unusual > processes running, and so on. I am in charge of maintaining a lot of > Windows PC's and it would make life so much easier if i could automate > some of these tasks. I am pretty new to Python but I seem to understand > it a little better than VB Script. I have been Googling Windows > Automation and getting some pretty good links but most if not all are > done using batch scripts and VB Script. I have a batch script that > cleans up temp files and defragments the hard drive but I would like to > know if Python is a good candidate for this or should I just stick to > what is built into Windows. WMI is probably the answer to a lot of those kind of things. In general, if you have a sys-adminy task to do under Windows, put "WMI " into your favourite search engine and see what comes out.[0] Then get the Python WMI module [1] and convert the example from VBS to Python. And Bob's your uncle. [2] TJG [0] eg, http://msdn2.microsoft.com/EN-US/library/aa394592.aspx [1] http://timgolden.me.uk/python/wmi.html [2] Well *my* uncle, at least: I do actually have an uncle called Bob. From alan.gauld at btinternet.com Mon Jul 2 22:50:41 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 2 Jul 2007 21:50:41 +0100 Subject: [Tutor] optimization: faster than for References: <674d5ce60706302046h629a1c9dsb2fce097265dfb65@mail.gmail.com><674d5ce60707011326l3a77bfe3h795cac78ec3ad222@mail.gmail.com> <200707020841.52730.eike.welk@gmx.net> <674d5ce60707012347x5d41c6aei450fca4fa0b6a8da@mail.gmail.com> Message-ID: "elis aeris" wrote > The letter I equals to "282" because it has 2 points on the y axis > of the > first point, and 8 points on the y axis on the second, and then 2 on > the > last one. > > So the string would be translated into: > > 28201722030033330000004222400722240172206 and so on. > > ##################### > so what I am going to have is a string like above and what I 'll > have is > > a list of tuples, for instance [a, 222] , [b,333] and so forth Better to use a dictionary keyed by m=number, I think: letters = { 222: 'a', 333: 'b',....} Then access it with letters[num] Now all you have to do is extract groups of 3 digits from the string which can be done using slicing and indexing: for index in range(0,len(codeString),3): num = int(codeString[index:index+3]) myString.append(letters[num]) Which will result in myString containing all the letter equivalents. > how do I write the fastest code to do this Once you get it working you can profile the code to find out how to make it faster, but until you get it working its pointless to worry about making it faster. Making broken code faster just results in faster bugs. > optimization is immediately needed because the job is done as soon > this > translation is complete. Optimization is only needed if the simple solution is too slow. How you define "too slow" is not clear to us at this point. And optimisation stops when the code is no longer "too slow" > image.getdata() is a good solution, i haven't found a better one, OK, Go with getdata for now. The next trick is to create your lists of numbers which involves summing the columns of pixels. > and the other bottle neck is this translation process. Try the (untested) solution offered above and see how well the total solution works. Then we can decide how much speed up it needs - if any. And we can start to work out the most beneficial place to do that speedup. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From vladoportos at vladoportos.sk Mon Jul 2 23:48:38 2007 From: vladoportos at vladoportos.sk (Vladimir Strycek) Date: Mon, 02 Jul 2007 23:48:38 +0200 Subject: [Tutor] Searching for word in text file Message-ID: <468972B6.1000001@vladoportos.sk> Hi all, i need script which open two text files and take first word from the first file, runn throught first fords of second file and give me result if its there or not... what i have so far is: import re, string # Nacitanie suborov na porovnanie subor1 = open("snow.txt", "r") subor2 = open("anakin.txt", "r") def prehladaj(najdi): for riadok1 in subor2.readlines(): z = riadok1.rsplit(" ") if najdi in z[2]: return z[3] def porovnaj(): for riadok in subor1.readlines(): x = riadok.rsplit(" ") #rozdelime do array dany riadok kde v 2 bude nazov a verzia v 3 print x[2] + " " + x[3] print prehladaj(x[2]) #vytvorenie tabulky print " Server: snow Server: anakin" print "--------------------------------------------------------------------" print " Name Version Version" porovnaj() subor1.close() subor2.close() the snow.txt looks like: B3693AA C.03.86.00 HP GlancePlus/UX for s800 11i B3901BA B.11.11.14 HP C/ANSI C Developer's Bundle for HP-UX (S800) B3913DB C.03.65 HP aC++ Compiler (S800) B4967AA C.03.86.00 HP MeasureWare Server Agent for s800 11i B5458DA C.01.18.04 HP-UX Runtime Environment for Java* B5725AA B.3.5.89 HP-UX Installation Utilities (Ignite-UX) etc... anakint.txt is the same but different versions of programs.... im not sure why tmi script dont work ( only for first one ) What i basicaly need is to look up if version of programs match on bouth text files diff in linux wont work for it cause there are not the same programs on the same lines... Any idea why mi script is not working or any suggestion for different aproach ? Best regards Vladimir From alan.gauld at btinternet.com Mon Jul 2 23:56:21 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 2 Jul 2007 22:56:21 +0100 Subject: [Tutor] pop up window References: <674d5ce60707020232r576089bcl2dd2e45be6979c4@mail.gmail.com> Message-ID: "Thorsten Kampe" wrote in message news:f6ahb5$drg$1 at sea.gmane.org... >* elis aeris (Mon, 2 Jul 2007 02:32:07 -0700) >> i won't do that again, i am a 2 day newbie (hello) >> >> uh, >> >> how about a less quick one that's built-in in python ? > > Are you replying to me? Please quote the parts you are referring to. > Anyway, Python does not come with "built-in pop-up support". Depends what you mean by 'built-in'. The tkinter package includes the common dialogs which do most of what EasyGUI does(but not all) But for simple message boxes its OK. Check my GUI topic in my tutorial (which is now back online again) for simple examples. Here is one: import tkMessageBox tkMessageBox.showinfo("Window Text", "A short message") -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Jul 3 01:00:29 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 3 Jul 2007 00:00:29 +0100 Subject: [Tutor] Automating Windows (Maintenance) References: <6d87ecf40707020946q5e13febfiddd4c42125e22ac1@mail.gmail.com> Message-ID: "Daniel McQuay" wrote > I wondering if any one uses Python to do such things as defragment, > clean up > temp files, check for hard drive errors, check for unusual processes > running, and so on. Mostly I rely on Windows schedulling to do those things because the tools exist I just use them. But the last is something that could be done in Python, either using windows services or even the os module. And of course you can execute Windows rograms from Python using os.system or the new subprocess module > am pretty new to Python but I seem to understand it a little better > than VB > Script. Anything you can do in VBScript you can do in Python, especially using WSH which makes a lot of these kinds of tasks easier. > a batch script that cleans up temp files and defragments the hard > drive but > I would like to know if Python is a good candidate for this or > should I > just stick to what is built into Windows. I tend to use the OS for OS tasks wherever possible. Defragging for example is a simple enough thing to set up using Windows scheduller But where I have to program then I use the tool that feels right for the job, which for me could be any of Python, Delphi, DOS or VBScript., -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From keridee at jayco.net Tue Jul 3 00:04:18 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 2 Jul 2007 22:04:18 -0000 Subject: [Tutor] Here's what you need Message-ID: <05ec01c7bcf4$f3badba0$43fce004@JSLAPTOP> Dear elis: I just read the large volume of messages that you have sent causing mild confusion and misunderstanding relating to your OCR project. You have expressed wishes to learn python quickly, and to take a class. Therefore, I suggest you look here - any of these are more than enough of a 'class'. http://www.freenetpages.co.uk/hp/alan.gauld/ http://www.diveintopython.org/ http://www.byteofpython.info/ http://www.python.org/doc/current/tut/tut.html If you feel that these 'beginner' tutorials are beneath you, consider that after you read these tutorials and ask questions about the material they present on this list, you would have a good feeling for what is "built-in" to python, and which constructs present the best speed, and would have received as much learning from them as from any class you take. Now as for PIL, I do not have much experience. Even so, a short 20 second trip to google gave me this, which gives all of the advice about getdata, getpixel, load, etc. that this list has provided so far, and everything else that you need. http://www.pythonware.com/library/pil/handbook/index.htm Reading the forum link that you posted in one of your messages, I was shocked that you would find OCR easier than reading the RAM where the game messages are stored. I am pulling my hair out at the fact that you don't have the programming background to cower at using OCR for this type of project. If you are curious, (I would very much so recommend this), visit some C/C++ tutorials and learn a little about what compiled languages are. You will learn all about pointers, the stack, function calls, etc. You will thank yourself someday. (Sorry if this is too diminuitive - I'm shaking from the arggghhh!!! feeling) Okay, now that i've had that little rant, do this: Write a script that does what you want, the OCR, the converting to text, etc., without caring how long it takes to run. No one can fix code that you haven't written. Just try as hard as you can. Here are guidlines to how you should approach this if you don't know how. Step 1) Save a picture of the screen to a bmp file. (Print screen button, then paste into MSPaint) 2) Use PIL to load the image in. 3) Use getpixel or getdata - It doesn't matter at this stage! Just get code that *runs* 4) Loop through the pixels building either a dictionary or a nested list like in your post 5) Create an origin (darn what's the word???) a template, a beginning, a reference (ahh that's good) a reference list, one that you can compare the dict or list in #4 against to get characters. 6) Use the compare in #5 to build a string of characters that you print out (using print) If you have any troubles with these steps towards writing a working script, then write to this list, being sure to explain how you thought what you wrote would work, how it doesn't fit the result you want to acheive, the complete code (since you seem to cause confusion with fragments of code) as an attachment(!) ( Don't worry it won't be *that* long), any error messages you get, which step you are on (by description, not number, thank you), and a complete overview of what you are trying to acheive (That would be - "Write a Optical Character Recognition script that reads the screen of a game and converts it into the equivalent text") HTH you and the other members of the list, Jacob S. P.S. Google is your friend, my friend From keridee at jayco.net Tue Jul 3 00:36:47 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 2 Jul 2007 22:36:47 -0000 Subject: [Tutor] Automating Windows (Maintenance) References: <6d87ecf40707020946q5e13febfiddd4c42125e22ac1@mail.gmail.com> Message-ID: <06ce01c7bcf9$7d3f2f80$43fce004@JSLAPTOP> > "Daniel McQuay" wrote > >> I wondering if any one uses Python to do such things as defragment, >> clean up >> temp files, check for hard drive errors, check for unusual processes >> running, and so on. Watch and be amazed... #################### import os os.system('defrag.exe c:') os.system('pause') # waits for keypress, delete if you don't want it os.system('chkdsk.exe c:') #################### For more control over defrag and chkdsk, open a command prompt and type in program name followed by a space and then /? ex. defrag.exe /? The cleanup temp files is more difficult. It depends on how much you want to do. Usually it is sufficient to delete the contents of the windows/temp folder. This will delete cookies, temporary files, internet temp files that are commonly cleaned up by sys admin. So you can add os.system('del /s /f /s /q C:\windows\temp\*') Again, the meaning of the command switches can be found by typing in prompt 'del /?' (without quotes) That takes care of most of your problems, no? There are more things that you wish to automate, I'm sure. Easiest is to search for the command line equivalents of all your normal tasks. For checking processes, you can search for a tool on the internet that lists currently running processes. Here's an example. http://technet2.microsoft.com/windowsserver/en/library/d41f22ce-93c8-4884-90db-f4b8e8fdc3ec1033.mspx?mfr=true You would have to read those from a file, though. Not a problem with python, right? If you are really interested in a program that does this, I could be encouraged to write one for you (in C) - Although, it would most certainly be better to find api s that allow you to do this in python. Google. HTH, Jacob S. From alan.gauld at btinternet.com Tue Jul 3 09:01:13 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 3 Jul 2007 08:01:13 +0100 Subject: [Tutor] Automating Windows (Maintenance) References: <6d87ecf40707020946q5e13febfiddd4c42125e22ac1@mail.gmail.com> <06ce01c7bcf9$7d3f2f80$43fce004@JSLAPTOP> Message-ID: "Tiger12506" wrote > The cleanup temp files is more difficult. It depends on how much you > want to > do. Usually it is sufficient to delete the contents of the > windows/temp > folder. This will delete cookies, temporary files, internet temp > files that > are commonly cleaned up by sys admin. So you can add os.system('del > /s /f > /s /q C:\windows\temp\*') For deleting files you get more control doing it from within Python. os.remove() will delete files. > For checking processes, you can search for a tool on the internet > that lists > currently running processes. Again this kind of thing can be done with the _winreg module for reading the registry. (or using WSH) > If you are really interested in a program that does this, I could be > encouraged to write one for you (in C) - Although, it would most > certainly > be better to find api s that allow you to do this in python. Google. All the windows APIs are available to Python, no C required. See the recent threads on mouse events for more on that topic. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From atomiclemon at hotmail.com Tue Jul 3 09:46:42 2007 From: atomiclemon at hotmail.com (Ben Waldin) Date: Tue, 3 Jul 2007 19:46:42 +1200 Subject: [Tutor] how long? Message-ID: How long will it take until I successfully create my own working program that is useful? I have crated the address book ones in the tutors and just want to know how long it takes before I start to create my own thought up programs that will be useful. Thanks Ben _________________________________________________________________ Discover the new Windows Vista http://search.msn.com/results.aspx?q=windows+vista&mkt=en-US&form=QBRE -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070703/aafababb/attachment.html From terry.kemmerer at gmail.com Tue Jul 3 09:51:31 2007 From: terry.kemmerer at gmail.com (Terry) Date: Tue, 03 Jul 2007 00:51:31 -0700 Subject: [Tutor] n.isalnum() is failing Message-ID: <1183449091.12516.64.camel@localhost.localdomain> Hi! I am running Python 2.5, and I have an IF statement in the below program that does not seem to be doing it's job. The program simply acquires a range of years from the user and prints out all the leap years between the two dates. I am having trouble in trapping for possible user errors. I am using x.isalnum() to check that I have a number for each year entered, and it doesn't look to me like it is functioning properly. When I purposely enter bad data, such as 'aaaa' for one of the a year entries, the IF statement: if start.isalnum() == 1 and end.isalnum() == 1: -Fails to detect that 'aaaa' is not a number and lets the program then die tragically a horrible sudden awkward death on the very next line: start = int(start); end = int(end) Traceback (most recent call last): File "/home/lucky/Documents/Python_Programs/leap_years.py", line 119, in start = int(start); end = int(end) ValueError: invalid literal for int() with base 10: 'aaaa' If I say on the commandline: >>> n = 'aaaa' >>> n.isalnum() True <------------It seems to me it should be saying False!!! >>> My program starts here: def leap(yyyy): answer = 0 t1 = yyyy / 4 if t1 == int(t1): t2 = yyyy / 100 t3 = yyyy / 400 if t2 <> int(t2) or t3 == int(t3): answer = "-- leap year!" return answer print "This program finds all leap years between two dates.";print;print start = raw_input("Enter yyyy for beginning year : ") end = raw_input("Enter yyyy for ending year : ") if len(start) == 4 and len(end) == 4: if start.isalnum() == 1 and end.isalnum() == 1: #<----------fails to detect 'aaaa' as not a number start = int(start); end = int(end) #<----------commits suicide here if start > 0 and end > start: print; print for i in range(start, end + 1): answer = leap(i) if answer != 0: print i, answer print "Done!" -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070703/fa81e8f8/attachment.htm From wolfram.kraus at fen-net.de Tue Jul 3 10:38:32 2007 From: wolfram.kraus at fen-net.de (Wolfram Kraus) Date: Tue, 03 Jul 2007 10:38:32 +0200 Subject: [Tutor] n.isalnum() is failing In-Reply-To: <1183449091.12516.64.camel@localhost.localdomain> References: <1183449091.12516.64.camel@localhost.localdomain> Message-ID: Use isdigit instead of isalnum. HTH, Wolfram On 03.07.2007 09:51, Terry wrote: > Hi! > > I am running Python 2.5, and I have an IF statement in the below program > that does not seem > to be doing it's job. The program simply acquires a range of years from > the user and prints out > all the leap years between the two dates. I am having trouble in > trapping for possible user > errors. I am using x.isalnum() to check that I have a number for each > year entered, and it > doesn't look to me like it is functioning properly. > > When I purposely enter bad data, such as 'aaaa' for one of the a year > entries, the IF statement: > > if start.isalnum() == 1 and end.isalnum() == 1: > > -Fails to detect that 'aaaa' is not a number and lets the program then > die tragically a horrible > sudden awkward death on the very next line: > > start = int(start); end = int(end) > > Traceback (most recent call last): > File "/home/lucky/Documents/Python_Programs/leap_years.py", line 119, > in > start = int(start); end = int(end) > ValueError: invalid literal for int() with base 10: 'aaaa' > > If I say on the commandline: > >>>> n = 'aaaa' >>>> n.isalnum() > True <------------It seems to me it should be saying > False!!! >>>> > > > My program starts here: > > def leap(yyyy): > answer = 0 > t1 = yyyy / 4 > if t1 == int(t1): > t2 = yyyy / 100 > t3 = yyyy / 400 > if t2 <> int(t2) or t3 == int(t3): > answer = "-- leap year!" > return answer > > print "This program finds all leap years between two dates.";print;print > > start = raw_input("Enter yyyy for beginning year : ") > end = raw_input("Enter yyyy for ending year : ") > > if len(start) == 4 and len(end) == 4: > if start.isalnum() == 1 and end.isalnum() == 1: > #<----------fails to detect 'aaaa' as not a number > start = int(start); end = > int(end) #<----------commits > suicide here > if start > 0 and end > start: > print; print > for i in range(start, end + 1): > answer = leap(i) > if answer != 0: > print i, answer > print "Done!" > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From bhaaluu at gmail.com Tue Jul 3 11:06:20 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 3 Jul 2007 05:06:20 -0400 Subject: [Tutor] n.isalnum() is failing In-Reply-To: <1183449091.12516.64.camel@localhost.localdomain> References: <1183449091.12516.64.camel@localhost.localdomain> Message-ID: Greetings, Perhaps the first thing you should do, before checking whether the user entered 'aaaa' instead of '2000' is to get the leap year function working properly. Definition: Leap years occur according to the following formula: a leap year is divisible by four, but not by one hundred, unless it is divisible by four hundred. I find that definition to be a wee bit misleading. This might help: A leap year is divisible by four, with a REMAINDER of zero. The remainder of a division is found in python with the "%" operator. So you might want to check and see IF the remainders are zero or one, TRUE or FALSE. When I run your program, entering two four-digit years, this is the output: This program finds all leap years between two dates. Enter yyyy for beginning year : 1995 Enter yyyy for ending year : 2000 1995 -- leap year! 1996 -- leap year! 1997 -- leap year! 1998 -- leap year! 1999 -- leap year! 2000 -- leap year! Done! Since we know that ALL of those years can't be leap years, it means that your leap() function isn't doing something right? I suggest that you get leap() working properly first, then tackle the other problem. Cheers! -- bhaaluu at gmail dot com On 7/3/07, Terry wrote: > > Hi! > > I am running Python 2.5, and I have an IF statement in the below program > that does not seem > to be doing it's job. The program simply acquires a range of years from the > user and prints out > all the leap years between the two dates. I am having trouble in trapping > for possible user > errors. I am using x.isalnum() to check that I have a number for each year > entered, and it > doesn't look to me like it is functioning properly. > > When I purposely enter bad data, such as 'aaaa' for one of the a year > entries, the IF statement: > > if start.isalnum() == 1 and end.isalnum() == 1: > > -Fails to detect that 'aaaa' is not a number and lets the program then die > tragically a horrible > sudden awkward death on the very next line: > > start = int(start); end = int(end) > > Traceback (most recent call last): > File > "/home/lucky/Documents/Python_Programs/leap_years.py", line > 119, in > start = int(start); end = int(end) > ValueError: invalid literal for int() with base 10: 'aaaa' > > If I say on the commandline: > > >>> n = 'aaaa' > >>> n.isalnum() > True <------------It seems to me it should be saying > False!!! > >>> > > > My program starts here: > > def leap(yyyy): > answer = 0 > t1 = yyyy / 4 > if t1 == int(t1): > t2 = yyyy / 100 > t3 = yyyy / 400 > if t2 <> int(t2) or t3 == int(t3): > answer = "-- leap year!" > return answer > > print "This program finds all leap years between two dates.";print;print > > start = raw_input("Enter yyyy for beginning year : ") > end = raw_input("Enter yyyy for ending year : ") > > if len(start) == 4 and len(end) == 4: > if start.isalnum() == 1 and end.isalnum() == 1: > #<----------fails to detect 'aaaa' as not a number > start = int(start); end = int(end) > #<----------commits suicide here > if start > 0 and end > start: > print; print > for i in range(start, end + 1): > answer = leap(i) > if answer != 0: > print i, answer > print "Done!" > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From =?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2KfYqg==?= Tue Jul 3 10:51:50 2007 From: =?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2KfYqg==?= (=?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2KfYqg==?=) Date: Tue, 03 Jul 2007 11:51:50 +0300 Subject: [Tutor] n.isalnum() is failing In-Reply-To: <1183449091.12516.64.camel@localhost.localdomain> References: <1183449091.12516.64.camel@localhost.localdomain> Message-ID: <468A0E26.1060504@saudi.net.sa> Terry wrote: > Hi! > Hi... > I am using x.isalnum() to check that I have a number for each year > entered, and it doesn't look to me like it is functioning properly. That's because "x.isalnum()" will return True if "x" is not empty and it's content are *either* an Alpha or a Number (which is not what you want)! You need to use "x.isdigit()" for your need. Typing "help(str)" inside the Python shell will read: | isalnum(...) | S.isalnum() -> bool | | Return True if all characters in S are alphanumeric | and there is at least one character in S, False otherwise. | | isalpha(...) | S.isalpha() -> bool | | Return True if all characters in S are alphabetic | and there is at least one character in S, False otherwise. | | isdigit(...) | S.isdigit() -> bool | | Return True if all characters in S are digits | and there is at least one character in S, False otherwise. Ziyad. From thorsten at thorstenkampe.de Tue Jul 3 12:29:59 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 3 Jul 2007 11:29:59 +0100 Subject: [Tutor] how long? References: Message-ID: * Ben Waldin (Tue, 3 Jul 2007 19:46:42 +1200) > How long will it take until I successfully create my own working program that is useful? I have crated the address book ones in the tutors and just want to know how long it takes before I start to create my own thought up programs that will be useful. Thanks Ben Approximately ten days, four hours and six minutes From andreas at kostyrka.org Tue Jul 3 14:16:35 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 03 Jul 2007 14:16:35 +0200 Subject: [Tutor] n.isalnum() is failing In-Reply-To: <1183449091.12516.64.camel@localhost.localdomain> References: <1183449091.12516.64.camel@localhost.localdomain> Message-ID: <468A3E23.7030104@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Consider using something like: try: start, end = int(start), int(end) except ValueError: print "oops it was not a number." Andreas Terry wrote: > Hi! > > I am running Python 2.5, and I have an IF statement in the below program > that does not seem > to be doing it's job. The program simply acquires a range of years from > the user and prints out > all the leap years between the two dates. I am having trouble in > trapping for possible user > errors. I am using x.isalnum() to check that I have a number for each > year entered, and it > doesn't look to me like it is functioning properly. > > When I purposely enter bad data, such as 'aaaa' for one of the a year > entries, the IF statement: > > if start.isalnum() == 1 and end.isalnum() == 1: > > -Fails to detect that 'aaaa' is not a number and lets the program then > die tragically a horrible > sudden awkward death on the very next line: > > start = int(start); end = int(end) > > Traceback (most recent call last): > File "/home/lucky/Documents/Python_Programs/leap_years.py", line 119, > in > start = int(start); end = int(end) > ValueError: invalid literal for int() with base 10: 'aaaa' > > If I say on the commandline: > >>>> n = 'aaaa' >>>> n.isalnum() > True <------------It seems to me it should be saying > False!!! > > > My program starts here: > > def leap(yyyy): > answer = 0 > t1 = yyyy / 4 > if t1 == int(t1): > t2 = yyyy / 100 > t3 = yyyy / 400 > if t2 <> int(t2) or t3 == int(t3): > answer = "-- leap year!" > return answer > > print "This program finds all leap years between two dates.";print;print > > start = raw_input("Enter yyyy for beginning year : ") > end = raw_input("Enter yyyy for ending year : ") > > if len(start) == 4 and len(end) == 4: > if start.isalnum() == 1 and end.isalnum() == 1: > #<----------fails to detect 'aaaa' as not a number > start = int(start); end = int(end) > #<----------commits suicide here > if start > 0 and end > start: > print; print > for i in range(start, end + 1): > answer = leap(i) > if answer != 0: > print i, answer > print "Done!" > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGij4jHJdudm4KnO0RAnKcAJ4lQWC3g0RklnwDwbpldapIeGFxDwCg2ayR Mr6uMnoXINQHF3QTLO6Rl34= =0kzm -----END PGP SIGNATURE----- From picioslug at gmail.com Tue Jul 3 16:07:53 2007 From: picioslug at gmail.com (Picio) Date: Tue, 3 Jul 2007 16:07:53 +0200 Subject: [Tutor] MySQL -->Python-->XML for JSviz Message-ID: <825bef0c0707030707w10660dc4h1d1ea58ed2bb40d3@mail.gmail.com> Hello all, I need some advice to choose an xml generator for jsviz a tool in javascript to create some wonderful graphs (SnowFlake or Force directed). Starting from a SQL table (mysql) I need to create a XML file with a structure like this: Where nodes attributes are the MySQL table fields (the PK will be the attribute). I know there are a lot of good tools to do this in pyhton (some maybe is already shipped with pyton itself), but since I need a lot of flexibility for the future I'd like to use an Object relational mapper like SQLAlchemy or SQLObject todo the job. When I say flexibility, I have in mind a solution to have multiple formats coming outside of the ORM: json, csv, plain text etc... Am I wrong? Can someone advice something? -- http://picio.gotdns.com ...Il mio blog su NSLU2 From Mike.Hansen at atmel.com Tue Jul 3 17:42:22 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Tue, 3 Jul 2007 09:42:22 -0600 Subject: [Tutor] how long? In-Reply-To: References: Message-ID: <57B026980605A64F9B23484C5659E32E8F4ECB@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Ben Waldin > Sent: Tuesday, July 03, 2007 1:47 AM > To: tutor at python.org > Subject: [Tutor] how long? > > How long will it take until I successfully create my own > working program that is useful? I have crated the address > book ones in the tutors and just want to know how long it > takes before I start to create my own thought up programs > that will be useful. Thanks Ben > What kind of programs do you have in mind? Maybe you can break down a program you want into pieces and work on a piece of it. Maybe you want some sort of GUI program. Well, first you can create a command line version on it. Then later you can make it a GUI program. The tutor list can help when you have questions. Mike From ravennso at gmail.com Tue Jul 3 18:00:31 2007 From: ravennso at gmail.com (Jessica Griffin) Date: Tue, 3 Jul 2007 09:00:31 -0700 Subject: [Tutor] how long? In-Reply-To: References: Message-ID: On 7/3/07, Ben Waldin wrote: > > How long will it take until I successfully create my own working program > that is useful? I have crated the address book ones in the tutors and just > want to know how long it takes before I start to create my own thought up > programs that will be useful. Thanks Ben > > > -- This depends entirely on the following things: 1) How motivated are you? 2) How much time are you willing to put in? 3) What do you call "useful"? There is no set "time frame" you can count on. No matter what some books/teachers may tell you, you *cannot* "Learn how to (do whatever) in X number of hours"---that's an unreasonable standard to hold yourself to. But the more motivated you are to learn, the more you *will* learn. And the more time you put in, the "faster" you will acquire that knowledge. For more on this idea, read Peter Norvig's excellent essay "Teach Yourself Programming in Ten Years" at That pretty much answers 1 and 2, but to answer 3, you have to think about what you mean by a "useful" program. That is entirely subjective, and I think you're backing yourself into a bad corner by thinking of a *program* as useful/nonuseful. The beauty of a language like Python is that it is easy to build different "modules," if you will, that you can use over and over again in new and creative ways. So perhaps instead of thinking in terms of "how useful is this *program*" you should be thinking "how useful is this *skill*." The answer, for each skill you learn, will be different, but if you think of it that way, you'll be a lot more satisfied with your daily progress. For example: If you are learning how to print text to the screen, such as the basic "Hello World" that almost everyone learns first, that *is* useful, because *without* that, you can't really do anything else. See what I'm getting at here? Once you build a basic toolbox of skills, then you can begin to look for challenges that need to be solved. And in order to do that, you are only limited by the skills you have, and by your own imagination. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070703/a858a3b4/attachment.htm From hmm at woolgathering.cx Tue Jul 3 17:57:03 2007 From: hmm at woolgathering.cx (William O'Higgins Witteman) Date: Tue, 3 Jul 2007 11:57:03 -0400 Subject: [Tutor] UTF-8 filenames encountered in os.walk Message-ID: <20070703155703.GA3682@sillyrabbi.dyndns.org> I have several programs which traverse a Windows filesystem with French characters in the filenames. I have having trouble dealing with these filenames when outputting these paths to an XML file - I get UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 ... etc. That happens when I try to convert to UTF-8. I know what os will give me UFT-8 if I give it UTF-8, and I am trying to do that, but somewhere down the line it seems like it reverts to ASCII, and then I get these errors. Has anyone found a silver bullet for ensuring that all the filenames encountered by os.walk are treated as UTF-8? Thanks. -- yours, William From cloudneozero at gmail.com Tue Jul 3 18:50:26 2007 From: cloudneozero at gmail.com (Ark) Date: Tue, 3 Jul 2007 11:50:26 -0500 Subject: [Tutor] Help with plugins Message-ID: <9dd22c9c0707030950g4a6ce2e1gaec51d4d1f9d7d63@mail.gmail.com> Hi! First, my english may be bad, so I apoligize. This is the first time i mail the list and it's about something i've been investigating, but i haven't found enough information. I want to learn how to do extensible aplications using plugins. I've found some how tos an tutorials, but they're not deep enough for my needs, and i need your help with documentation about the topic, or with everything you consider helpful. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070703/0f02eb92/attachment.htm From Barry.Carroll at datalogic.com Tue Jul 3 19:01:32 2007 From: Barry.Carroll at datalogic.com (Carroll, Barry) Date: Tue, 3 Jul 2007 10:01:32 -0700 Subject: [Tutor] how long? In-Reply-To: Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595BD8@eugsrv400.psc.pscnet.com> > -----Original Message----- > Message: 7 > Date: Tue, 3 Jul 2007 19:46:42 +1200 > From: Ben Walden > Subject: [Tutor] how long? > To: > Message-ID: > Content-Type: text/plain; charset="iso-8859-1" > > How long will it take until I successfully create my own working program > that is useful? I have crated the address book ones in the tutors and just > want to know how long it takes before I start to create my own thought up > programs that will be useful. Thanks Ben > _________________________________________________________________ Hi, Ben. The quick answer to your question is another question: what do you want to do? If you have done the tutorial examples successfully, you probably have the basics of Python down well enough to begin a project of your own right now. So, pick an idea that interests you or a function that you need and start in! When you run into trouble ask for help here. Plenty of people are happy to help out. If you have trouble coming up with an idea for a project, check python.org for existing projects in need of help (anybody know the exact URL?). There are lots of ongoing projects looking for programmers to assist, with tasks ranging from novice to guru skill levels. You should be able to find something that will challenge you without overwhelming you. Good luck! Regards, Barry barry.carroll at datalogic.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From david at graniteweb.com Tue Jul 3 19:45:19 2007 From: david at graniteweb.com (David Rock) Date: Tue, 3 Jul 2007 12:45:19 -0500 Subject: [Tutor] Help with plugins In-Reply-To: <9dd22c9c0707030950g4a6ce2e1gaec51d4d1f9d7d63@mail.gmail.com> References: <9dd22c9c0707030950g4a6ce2e1gaec51d4d1f9d7d63@mail.gmail.com> Message-ID: <20070703174519.GA6871@wdfs.graniteweb.com> * Ark [2007-07-03 11:50]: > Hi! > First, my english may be bad, so I apoligize. > This is the first time i mail the list and it's about something i've been > investigating, but i haven't found enough information. > I want to learn how to do extensible aplications using plugins. I've found > some how tos an tutorials, but they're not deep enough for my needs, and i > need your help with documentation about the topic, or with everything you > consider helpful. I think we need some more information explaining what you are trying to accomplish. Can you supply an example of an "extensible application" and also a longer description of what you mean when you say "plugin." Perhaps some links to what you have looked at so far would also help to clarify? -- David Rock david at graniteweb.com From kent37 at tds.net Tue Jul 3 20:01:30 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 03 Jul 2007 14:01:30 -0400 Subject: [Tutor] Help with plugins In-Reply-To: <9dd22c9c0707030950g4a6ce2e1gaec51d4d1f9d7d63@mail.gmail.com> References: <9dd22c9c0707030950g4a6ce2e1gaec51d4d1f9d7d63@mail.gmail.com> Message-ID: <468A8EFA.6060907@tds.net> Ark wrote: > Hi! > First, my english may be bad, so I apoligize. > This is the first time i mail the list and it's about something i've > been investigating, but i haven't found enough information. > I want to learn how to do extensible aplications using plugins. I've > found some how tos an tutorials, but they're not deep enough for my > needs, and i need your help with documentation about the topic, or with > everything you consider helpful. Googling 'python plugin' finds quite a few examples including this one which is very simple: http://pytute.blogspot.com/2007/04/python-plugin-system.html and this which seems pretty detailed: http://lucumr.pocoo.org/blogarchive/python-plugin-system and this: http://peak.telecommunity.com/DevCenter/setuptools#dynamic-discovery-of-services-and-plugins Kent From wildcard2007 at comcast.net Tue Jul 3 21:19:58 2007 From: wildcard2007 at comcast.net (Terry) Date: Tue, 03 Jul 2007 12:19:58 -0700 Subject: [Tutor] n.isalnum() is failing Message-ID: <1183490398.21577.18.camel@localhost.localdomain> Ha Ha Ha It appears I was having a very blond day. For some reason, I was mentally verbalizing to myself, each time I looked at x.isalnum(), "X IS-ALL-NUMBERS", instead of "X IS-Alpha-Numeric". I remember thinking......if one can call it that....., "I wonder why x.isdigit() is singular for only one digit????.......why couldn't they have made it plural and singular? (It might help to realize the example I was looking at for x.digit() showed it only operating on one digit. But then, one must remember that blond is sometimes really blond.....once it starts. And you are sooo right, I need to fix the leap() portion of the program. Thanks! It will be nice to get back to the program without stubbornly trying to coerce or trick poor isalnum() into doing what it can't do. Terry -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070703/514c3f61/attachment.html From terry.kemmerer at gmail.com Tue Jul 3 22:10:57 2007 From: terry.kemmerer at gmail.com (Terry) Date: Tue, 03 Jul 2007 13:10:57 -0700 Subject: [Tutor] [Fwd: [Fwd: Re: n.isalnum() is failing]] Message-ID: <1183493457.21577.44.camel@localhost.localdomain> Hi Bhaaluu, I have misled you. I am working on a section ABOVE the program I showed, that I am thinking to have my most used elements in, left in a state of being # remarks. In other words, I am thinking of creating a set of most used CONVENTIONS and leave them as a blank file. Thus, when I need to write a new program, I just grab the blank CONVENTIONS, and rename it to my newest program name. I have no idea if this is a good idea or not, it is just how I used to start a program in BASIC 25 years ago.....or so. What you didn't see, was the following line which I had enable in the Conventions area and neglected to conscientiously reveal: from __future__ import division With that line enabled, my divisions are floating point, rather than integer, and using the same years you did, my program yields the following results: >>> This program finds all leap years between two dates. Enter yyyy for beginning year : 1995 Enter yyyy for ending year : 2000 1996 -- leap year! 2000 -- leap year! Done! >>> I admit, I have never seen the "%" operator before. I should probably learn to use it.....but I had felt this overpowering need wash over me to get it done and see it happen without spending more time researching. It was one of those primal things where you have this need to do more than you can. So, instead, I was using the "t1 == int(t1)" type compare, that I learned in BASIC about 25 years ago, to discover a remainder or no. My blond brain is currently thinking that works....but the day is young. And maybe "%" is faster? Have a great day! -------- Forwarded Message -------- From: bhaaluu To: Terry , Tutor at python.org Subject: Re: [Tutor] n.isalnum() is failing Date: Tue, 3 Jul 2007 05:06:20 -0400 Greetings, Perhaps the first thing you should do, before checking whether the user entered 'aaaa' instead of '2000' is to get the leap year function working properly. Definition: Leap years occur according to the following formula: a leap year is divisible by four, but not by one hundred, unless it is divisible by four hundred. I find that definition to be a wee bit misleading. This might help: A leap year is divisible by four, with a REMAINDER of zero. The remainder of a division is found in python with the "%" operator. So you might want to check and see IF the remainders are zero or one, TRUE or FALSE. When I run your program, entering two four-digit years, this is the output: This program finds all leap years between two dates. Enter yyyy for beginning year : 1995 Enter yyyy for ending year : 2000 1995 -- leap year! 1996 -- leap year! 1997 -- leap year! 1998 -- leap year! 1999 -- leap year! 2000 -- leap year! Done! Since we know that ALL of those years can't be leap years, it means that your leap() function isn't doing something right? I suggest that you get leap() working properly first, then tackle the other problem. Cheers! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070703/3a07bbcb/attachment.html From alan.gauld at btinternet.com Tue Jul 3 22:21:49 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 3 Jul 2007 21:21:49 +0100 Subject: [Tutor] how long? References: <2BBAEE949D384D40A2B851287ADB6A4304595BD8@eugsrv400.psc.pscnet.com> Message-ID: "Carroll, Barry" wrote > If you have trouble coming up with an idea for a project, check > python.org for existing projects in need of help Or even try sourceforge.net. You can search for OpenSource projects that need help and filter by language. Or try UselessPython for a list of programming challenges - some of which have not been done yet. Or try taking the Python Challenge adventure game - each step involves solving a problem in Python and the answer gives you the url for the next challenge. But best of all is simply to find a task you do often and automate it using Python. Maybe its working out tax returns or expenses or planning an itinery or a shopping list. Or maybe you fancy creating a game? Or what about synchronising your web site with your PC? Lots of things, just use your imagination and remember that if you can do it manually then Python can probably go at least part way to automate it.... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Jul 3 22:42:33 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 3 Jul 2007 21:42:33 +0100 Subject: [Tutor] n.isalnum() is failing References: <1183449091.12516.64.camel@localhost.localdomain> Message-ID: "Terry" wrote > trapping for possible user errors. > I am using x.isalnum() to check that I have a number First, alnum() checks for alpha-numeric characters so will allow both alphabetic characters and numerics. BUT in python its better to ask forgiveness that permission so don't bother doing the check but catch the errors when they occur: try: start = int(start); end = int(end) except: ValueError: start = None # or whatever you prefer > def leap(yyyy): > answer = 0 > t1 = yyyy / 4 > if t1 == int(t1): For integer division this will always be true. > t2 = yyyy / 100 > t3 = yyyy / 400 > if t2 <> int(t2) or t3 == int(t3): and similarly the second test will always be true. > answer = "-- leap year!" thus this will always be true. > start = raw_input("Enter yyyy for beginning year : ") > end = raw_input("Enter yyyy for ending year : ") The easiest way to solve your conversion problems is to do it at source so wrap raw_input in a call to int() and wrap both prompts in a try/except as shown above. try: start = int(raw_input....) end = int(raw_input....) except ValueError: pass # do something with error > if len(start) == 4 and len(end) == 4: that way you don't need these lines but can instead test if the numeric value is greater than some lower limit > if start.isalnum() == 1 and end.isalnum() == 1: > #<----------fails to detect 'aaaa' as not a number > start = int(start); end = int(end) > #<----------commits suicide here > if start > 0 and end > start: As you are doing it start can never be less than 1000 (unless the user enters 0001 I suppose...) Also in Python you can use the neater style of if 0 < start < end: to test whether start lies between 0 and end. > for i in range(start, end + 1): > answer = leap(i) > if answer != 0: Its best not to mix return types in a function. If it is a leap year you return a string. If it's not, you return a number - 0. It would probably be better for the function to return a boolean: True if it is a leap year and False if not. That style of function is often called a predicate and is usually named with an 'is' in front so it would become isLeapYear() Then this test becomes the more readable for y in range(start, end+1): # use y for year instead of meaningless i if isLeapYear(y): print i, 'is a leap year' 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 Tue Jul 3 23:31:02 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 3 Jul 2007 22:31:02 +0100 Subject: [Tutor] MySQL -->Python-->XML for JSviz References: <825bef0c0707030707w10660dc4h1d1ea58ed2bb40d3@mail.gmail.com> Message-ID: "Picio" wrote > I know there are a lot of good tools to do this in pyhton Yep, you could use minidom and I think ElementTree can write XML as well as read it. > flexibility for the future I'd like to use an Object relational > mapper > like SQLAlchemy or SQLObject todo the job. ORMs are good at translkating between objects in memory and SQL they are not generally good at XML. You will probably be better combining an ORM with a templating system like Kid or Cheetah. They are designed to generate XML and fill in the blanks with data. > have in mind a solution to have multiple formats coming outside of > the > ORM: json, csv, plain text etc... Kid can definitely do XML, JSON. The ORM and plain Python is probably best for plain text and similarly the csv module will handle that format. HTH Alan G. From alan.gauld at btinternet.com Tue Jul 3 23:32:43 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 3 Jul 2007 22:32:43 +0100 Subject: [Tutor] UTF-8 filenames encountered in os.walk References: <20070703155703.GA3682@sillyrabbi.dyndns.org> Message-ID: "William O'Higgins Witteman" wrote >I have several programs which traverse a Windows filesystem with >French > characters in the filenames. I suspect you need to set the Locale at the top of your file. Do a search for locale in this lists archive where we had a thread on this a few months ago. HTH, Alan G From alan.gauld at btinternet.com Tue Jul 3 23:41:27 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 3 Jul 2007 22:41:27 +0100 Subject: [Tutor] [Fwd: Re: n.isalnum() is failing]] References: <1183493457.21577.44.camel@localhost.localdomain> Message-ID: "Terry" wrote > I was using the "t1 == int(t1)" type compare, that I > learned in BASIC about 25 years ago, to discover > a remainder or no. What a pity. Even the most elementary BASIC has always had the MOD operator for finding remainders. and a \ operator for integer division. Thus in GW BASIC (from around 1981) PRINT 10\3 -> 3 PRINT 10 MOD 3 -> 1 > that works....but the day is young. And maybe "%" is faster? Probably, but not by enough that you'll notice unless you are testing a few centuries worth of dates! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Jul 3 23:50:31 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 03 Jul 2007 17:50:31 -0400 Subject: [Tutor] MySQL -->Python-->XML for JSviz In-Reply-To: <825bef0c0707030707w10660dc4h1d1ea58ed2bb40d3@mail.gmail.com> References: <825bef0c0707030707w10660dc4h1d1ea58ed2bb40d3@mail.gmail.com> Message-ID: <468AC4A7.5080608@tds.net> Picio wrote: > Hello all, I need some advice to choose an xml generator for jsviz a > tool in javascript to create some wonderful graphs (SnowFlake or Force > directed). > > Starting from a SQL table (mysql) I need to create a XML file with a > structure like this: > > > > > > > > > > Where nodes attributes are the MySQL table fields (the PK will be the > attribute). > I know there are a lot of good tools to do this in pyhton (some maybe > is already shipped with pyton itself), but since I need a lot of > flexibility for the future I'd like to use an Object relational mapper > like SQLAlchemy or SQLObject todo the job. When I say flexibility, I > have in mind a solution to have multiple formats coming outside of the > ORM: > json, csv, plain text etc... I'm not sure why you need an ORM here. ISTM you just need a database connection, the name of a table containing the data and a list of the fields you want to pull out of it. Then a simple SELECT gets you the data in a list of lists; pass the same list of field names and the list of data to whatever output formatter you want. I think the whole program would only be 20-30 lines of code. ElementTree is a good XML package, it is part of Python 2.5 and available as an add-on for older Python versions. Kent From kent37 at tds.net Tue Jul 3 23:52:14 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 03 Jul 2007 17:52:14 -0400 Subject: [Tutor] UTF-8 filenames encountered in os.walk In-Reply-To: References: <20070703155703.GA3682@sillyrabbi.dyndns.org> Message-ID: <468AC50E.1060607@tds.net> Alan Gauld wrote: > "William O'Higgins Witteman" wrote > >> I have several programs which traverse a Windows filesystem with >> French >> characters in the filenames. > > I suspect you need to set the Locale at the top of your file. Do you mean the # -*- coding: -*- comment? That only affects the encoding of the source file itself. Kent From kent37 at tds.net Tue Jul 3 23:56:49 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 03 Jul 2007 17:56:49 -0400 Subject: [Tutor] UTF-8 filenames encountered in os.walk In-Reply-To: <20070703155703.GA3682@sillyrabbi.dyndns.org> References: <20070703155703.GA3682@sillyrabbi.dyndns.org> Message-ID: <468AC621.3040900@tds.net> William O'Higgins Witteman wrote: > I have several programs which traverse a Windows filesystem with French > characters in the filenames. > > I have having trouble dealing with these filenames when outputting these > paths to an XML file - I get UnicodeDecodeError: 'ascii' codec can't > decode byte 0xe9 ... etc. That happens when I try to convert to UTF-8. > > I know what os will give me UFT-8 if I give it UTF-8, and I am trying to > do that, but somewhere down the line it seems like it reverts to ASCII, > and then I get these errors. > > Has anyone found a silver bullet for ensuring that all the filenames > encountered by os.walk are treated as UTF-8? Thanks. Some code would help here, there are so many ways people get confused by UTF-8 and stumble over the subtleties of Python's use of Unicode. Particularly the code that gives you the error. The error you quote is a decode error, whereas converting to UTF-8 is encoding. Also it would be helpful to figure out for sure what you are getting from os.walk() - is it UTF-8 or Unicode? The best way to find out is to print repr(filename) and see what you get on output. Kent From terry.kemmerer at gmail.com Wed Jul 4 01:37:47 2007 From: terry.kemmerer at gmail.com (Terry) Date: Tue, 03 Jul 2007 16:37:47 -0700 Subject: [Tutor] n.isalnum() is failing In-Reply-To: References: <1183449091.12516.64.camel@localhost.localdomain> Message-ID: <1183505867.3391.13.camel@localhost.localdomain> Alan, Wow! Those changes radically change the program! Is there a way to get the try-exception to cause the end user questions to be repeated until acceptable answers are given? Like a kind of "return" or "repeat" command that could be added to the except side of things? try: start = int(raw_input("Enter yyyy for beginning year : ")) end = int(raw_input("Enter yyyy for ending year : ")) except ValueError: print "Must be a integer number as YEAR." I also noticed that I had to make the statement "start = end = 0" prior to the 'try'. To my eye, it looks to me that 'start' and 'end' are being declared inside the try-exception, but evidently python does not agree. Thanks, Terry On Tue, 2007-07-03 at 21:42 +0100, Alan Gauld wrote: > "Terry" wrote > > > trapping for possible user errors. > > I am using x.isalnum() to check that I have a number > > First, alnum() checks for alpha-numeric characters so > will allow both alphabetic characters and numerics. > > BUT in python its better to ask forgiveness that permission > so don't bother doing the check but catch the errors when > they occur: > > try: start = int(start); end = int(end) > except: ValueError: start = None # or whatever you prefer > > > def leap(yyyy): > > answer = 0 > > t1 = yyyy / 4 > > if t1 == int(t1): > > For integer division this will always be true. > > > t2 = yyyy / 100 > > t3 = yyyy / 400 > > if t2 <> int(t2) or t3 == int(t3): > > and similarly the second test will always be true. > > > answer = "-- leap year!" > > thus this will always be true. > > > start = raw_input("Enter yyyy for beginning year : ") > > end = raw_input("Enter yyyy for ending year : ") > > The easiest way to solve your conversion problems > is to do it at source so wrap raw_input in a call to int() > and wrap both prompts in a try/except as shown above. > > try: > start = int(raw_input....) > end = int(raw_input....) > except ValueError: pass # do something with error > > > if len(start) == 4 and len(end) == 4: > > that way you don't need these lines but can instead > test if the numeric value is greater than some lower > limit > > > if start.isalnum() == 1 and end.isalnum() == 1: > > #<----------fails to detect 'aaaa' as not a number > > start = int(start); end = int(end) > > #<----------commits suicide here > > if start > 0 and end > start: > > As you are doing it start can never be less than 1000 > (unless the user enters 0001 I suppose...) > > Also in Python you can use the neater style of > > if 0 < start < end: > > to test whether start lies between 0 and end. > > > for i in range(start, end + 1): > > answer = leap(i) > > if answer != 0: > > Its best not to mix return types in a function. If it is a > leap year you return a string. If it's not, you return a > number - 0. It would probably be better for the function > to return a boolean: True if it is a leap year and False > if not. That style of function is often called a predicate > and is usually named with an 'is' in front so it would > become isLeapYear() Then this test becomes the more > readable > > for y in range(start, end+1): # use y for year instead of meaningless > i > if isLeapYear(y): > print i, 'is a leap year' > > HTH, > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070703/8b17ea2c/attachment.html From alan.gauld at btinternet.com Wed Jul 4 02:07:25 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Jul 2007 01:07:25 +0100 Subject: [Tutor] n.isalnum() is failing References: <1183449091.12516.64.camel@localhost.localdomain> <1183505867.3391.13.camel@localhost.localdomain> Message-ID: "Terry" wrote > Wow! Those changes radically change the program! > > Is there a way to get the try-exception to cause the > end user questions to be repeated until acceptable > answers are given? Put the whole blocxk inside a while loop: start = end = None while start == None: try: start = int(raw_input("Enter yyyy for beginning year : ")) end = int(raw_input("Enter yyyy for ending year : ")) except ValueError: print "Must be a integer number as YEAR." start = end = None > I also noticed that I had to make the statement "start = end = 0" You shouldn't need to but its better to do so. For one thing if you don't (before we introduce the loop which needs start to be there) and the error occurs then start and end won't exist HTH, Alan G. From alan.gauld at btinternet.com Wed Jul 4 02:09:15 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Jul 2007 01:09:15 +0100 Subject: [Tutor] UTF-8 filenames encountered in os.walk References: <20070703155703.GA3682@sillyrabbi.dyndns.org> <468AC50E.1060607@tds.net> Message-ID: "Kent Johnson" wrote >> I suspect you need to set the Locale at the top of your file. > > Do you mean the > # -*- coding: -*- > comment? That only affects the encoding of the source file itself. No, I meant the Locale but I got it mixed up with the encoding in how it is set. Oops! Alan G. From jjcrump at myuw.net Wed Jul 4 02:03:25 2007 From: jjcrump at myuw.net (Jon Crump) Date: Tue, 3 Jul 2007 17:03:25 -0700 (PDT) Subject: [Tutor] UTF-8 title() string method In-Reply-To: <1183505867.3391.13.camel@localhost.localdomain> References: <1183449091.12516.64.camel@localhost.localdomain> <1183505867.3391.13.camel@localhost.localdomain> Message-ID: Dear All, I have some utf-8 unicode text with lines like this: ANVERS-LE-HOMONT, Maine. ANGOUL?ME, Angoumois. ANDELY (le Petit), Normandie. which I'm using as-is in this line of code: place.append(line.strip()) What I would prefer would be something like this: place.append(line.title().strip()) which works for most lines, giving me, for example: Anvers-Le-Homont, Maine. and Andely (Le Petit), Normandie. but where there are diacritics involved, title() gives me: Angoul?Me, Angoumois. Can anyone give the clueless a clue on how to manage such unicode strings more effectively? Many thanks, Jon From carroll at tjc.com Wed Jul 4 03:04:16 2007 From: carroll at tjc.com (Terry Carroll) Date: Tue, 3 Jul 2007 18:04:16 -0700 (PDT) Subject: [Tutor] UTF-8 filenames encountered in os.walk In-Reply-To: <20070703155703.GA3682@sillyrabbi.dyndns.org> Message-ID: On Tue, 3 Jul 2007, William O'Higgins Witteman wrote: > Has anyone found a silver bullet for ensuring that all the filenames > encountered by os.walk are treated as UTF-8? Thanks. What happens if you specify the starting directory as a Unicode string, rather than an ascii string, e.g., if you're walking the current directory: for thing in os.walk(u'.'): instead of: for thing in os.walk('.'): From carroll at tjc.com Wed Jul 4 03:30:13 2007 From: carroll at tjc.com (Terry Carroll) Date: Tue, 3 Jul 2007 18:30:13 -0700 (PDT) Subject: [Tutor] UTF-8 title() string method In-Reply-To: Message-ID: On Tue, 3 Jul 2007, Jon Crump wrote: > but where there are diacritics involved, title() gives me: > > AngoulMe, Angoumois. > > Can anyone give the clueless a clue on how to manage such unicode strings > more effectively? I think setting the locale is the trick: >>> s1 = open("text.txt").readline() >>> print s1 ANGOUL.ME, Angoumois. >>> print s1.title() Angoul.Me, Angoumois. >>> import locale >>> locale.setlocale(locale.LC_ALL,('french')) 'French_France.1252' >>> print s1.title() Angoul.me, Angoumois. (sorry about the '.' for the characters that my term program won't accept) You might have to hunt around and experiment for the right locale that will work in all your cases. From terry.kemmerer at gmail.com Wed Jul 4 08:34:28 2007 From: terry.kemmerer at gmail.com (Terry) Date: Tue, 03 Jul 2007 23:34:28 -0700 Subject: [Tutor] n.isalnum() is failing Message-ID: <1183530868.3391.96.camel@localhost.localdomain> For anyone who was following this, here is the finished, non floating point, program, after all the kind advice received has been incorporated into it (hopefully I have the leap year logic right...): # *** (7) MAIN BODY -- The Buck Starts Here! *************** def isLeapYear(y): if y % 4 == 0: if y % 100 == 0 and y % 400 == 1: answer = False return answer answer = True return answer answer = False return answer print "This program finds all leap years between any two dates.";print;print start = end = None while start == None: try: start = int(raw_input("Enter yyyy for beginning year : ")) end = int(raw_input("Enter yyyy for ending year : ")) except ValueError: print;print "YEAR must be a integer number -- TRY AGAIN!" start = end = None if 1 <= start < end: print; print for y in range(start, end + 1): answer = isLeapYear(y) if answer == True: print y, "--leap year!" print "Done!" *** EXECUTION *** >>> This program finds all leap years between any two dates. Enter yyyy for beginning year : 1900 Enter yyyy for ending year : 2000 1900 --leap year! 1904 --leap year! 1908 --leap year! 1912 --leap year! 1916 --leap year! 1920 --leap year! 1924 --leap year! 1928 --leap year! 1932 --leap year! 1936 --leap year! 1940 --leap year! 1944 --leap year! 1948 --leap year! 1952 --leap year! 1956 --leap year! 1960 --leap year! 1964 --leap year! 1968 --leap year! 1972 --leap year! 1976 --leap year! 1980 --leap year! 1984 --leap year! 1988 --leap year! 1992 --leap year! 1996 --leap year! 2000 --leap year! Done! >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070703/3f4c864f/attachment.html From alan.gauld at btinternet.com Wed Jul 4 10:24:14 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Jul 2007 09:24:14 +0100 Subject: [Tutor] n.isalnum() is failing References: <1183530868.3391.96.camel@localhost.localdomain> Message-ID: "Terry" wrote > def isLeapYear(y): > if y % 4 == 0: > if y % 100 == 0 and y % 400 == 1: > answer = False > return answer > answer = True > return answer > answer = False > return answer Not quite. y%400 == 1 will only be true for years like 2001, 1601 etc! You need to invert the test so y % 400 != 0. (or use not) But there is a more direct way: Lets recap: 1) A year that is divisible by 4 is a leap year. (Y % 4) == 0 2) but: a year that is divisible by 100 is not a leap year. (Y % 100) != 0 3) 3) however a year that is divisible by 400 is a leap year. (Y % 400) == 0 So a year that is divisible by 400 is *always* a leap year: if y % 400 == 0: return True Now we need a combined test for the other 2 cases. If its divisible by 4 and not by 100 its a leap year: if (y % 4 == 0) and not (y %100 == 0): return True So we can combine the definitions to give: def isLeapYear(y): if y % 400 == 0: return True if (y % 4 == 0) and not (y %100 == 0): return True else: return False Which is shorter and clearer IMHO. (You could combine it into one line but I personally think that would make the rules less clear.) This is one of the cases where using multiple returns makes the code clearer in my view. > print "This program finds all leap years between any two > dates.";print;print > > start = end = None > while start == None: > try: > start = int(raw_input("Enter yyyy for beginning year : ")) > end = int(raw_input("Enter yyyy for ending year : ")) > > except ValueError: > print;print "YEAR must be a integer number -- TRY AGAIN!" > start = end = None > > if 1 <= start < end: > print; print > for y in range(start, end + 1): > answer = isLeapYear(y) > if answer == True: > print y, "--leap year!" Also the point of a predicate function is that it returns a boolean value so you don;t need any intermediate variables. You can just use it in the condition, like if isLeapYear(y): print y, '--leap year' By using a predicate style name (isXXXXX) the code becomes clearer than when you introduce an intermediate variable where the reader then has to backtrack to see what the test value is based on. > 1900 --leap year! This is wrong, 1900 is divisible by 100 but not by 400... > 1904 --leap year! > 1908 --leap year! > ... > 2000 --leap year! Whereas 2000 is correct because it is divisible by 400. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From nitinchandra1 at gmail.com Wed Jul 4 11:09:33 2007 From: nitinchandra1 at gmail.com (nitin chandra) Date: Wed, 4 Jul 2007 14:39:33 +0530 Subject: [Tutor] Calculating Deflection angles Message-ID: <965122bf0707040209i18964b1csfbb9815a7510f2b8@mail.gmail.com> Hello Every One, I create a list of coordinates of 2 lines. X11,Y11 & X12,Y12 as starting and ending of one line. X21,Y21 & X22, Y22 as starting and ending of the 2nd line. Now is there any way to calculate the deflection angle between the two lines? Will any modules be required other than Python 2.3 (on Linux)? and How will it be done? TIA, Nitin From alan.gauld at btinternet.com Wed Jul 4 11:22:23 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Jul 2007 10:22:23 +0100 Subject: [Tutor] Calculating Deflection angles References: <965122bf0707040209i18964b1csfbb9815a7510f2b8@mail.gmail.com> Message-ID: "nitin chandra" wrote > I create a list of coordinates of 2 lines. > X11,Y11 & X12,Y12 as starting and ending of one line. > X21,Y21 & X22, Y22 as starting and ending of the 2nd line. > > Now is there any way to calculate the deflection angle between the > two > lines? Will any modules be required other than Python 2.3 (on > Linux)? This is a standard math problem to which you can apply the standard math techniques. You can use the trigonometry functions found in the math module. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From mi1492 at cox.net Wed Jul 4 15:46:36 2007 From: mi1492 at cox.net (Lucio Arteaga) Date: Wed, 4 Jul 2007 08:46:36 -0500 Subject: [Tutor] Basic english Message-ID: <001001c7be41$bdc87090$6400a8c0@bilbilis> I just finish to right a script to teach ESL. I will be using as vocabulary Basic English . This was created in 1930 an consist of only 800 words . This script is very small just two kb. plus the Basic vocabulary. Is anyone there to help me to compile this file into win32 so could be used in PC without having to install python in each PC using it. This will be possible, i.e to install Python in the PC used by Helping Hands, a church group that is going to sponsor the ESL classess. Thank you Lucio -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070704/673dca50/attachment.html From alan.gauld at btinternet.com Wed Jul 4 16:14:49 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Jul 2007 15:14:49 +0100 Subject: [Tutor] Basic english References: <001001c7be41$bdc87090$6400a8c0@bilbilis> Message-ID: "Lucio Arteaga" wrote > Is anyone there to help me to compile this file into win32 > so could be used in PC without having to install python > in each PC using it. Python is an interpreted language so you always need to install an interpreter, the only question is whether you do this explicitly, once only, or whether you hide the interpreter inside a pseudo exe file and thus install a version of Python for every program. If you feel you must do the latter then look at py2exe which will create the necesary bundle for you. If you just want to install Python alongside your program almost any windows installer can do that for you. Alan G From hmm at woolgathering.cx Wed Jul 4 16:51:11 2007 From: hmm at woolgathering.cx (William O'Higgins Witteman) Date: Wed, 4 Jul 2007 10:51:11 -0400 Subject: [Tutor] UTF-8 filenames encountered in os.walk In-Reply-To: References: <20070703155703.GA3682@sillyrabbi.dyndns.org> Message-ID: <20070704145111.GA8569@sillyrabbi.dyndns.org> On Tue, Jul 03, 2007 at 06:04:16PM -0700, Terry Carroll wrote: > >> Has anyone found a silver bullet for ensuring that all the filenames >> encountered by os.walk are treated as UTF-8? Thanks. > >What happens if you specify the starting directory as a Unicode string, >rather than an ascii string, e.g., if you're walking the current >directory: > > for thing in os.walk(u'.'): > >instead of: > > for thing in os.walk('.'): This is a good thought, and the crux of the problem. I pull the starting directories from an XML file which is UTF-8, but by the time it hits my program, because there are no extended characters in the starting path, os.walk assumes ascii. So, I recast the string as UTF-8, and I get UTF-8 output. The problem happens further down the line. I get a list of paths from the results of os.walk, all in UTF-8, but not identified as such. If I just pass my list to other parts of the program it seems to assume either ascii or UTF-8, based on the individual list elements. If I try to cast the whole list as UTF-8, I get an exception because it is assuming ascii and receiving UTF-8 for some list elements. I suspect that my program will have to make sure to recast all equivalent-to-ascii strings as UTF-8 while leaving the ones that are already extended alone. -- yours, William From kent37 at tds.net Wed Jul 4 17:28:53 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 04 Jul 2007 11:28:53 -0400 Subject: [Tutor] UTF-8 filenames encountered in os.walk In-Reply-To: <20070704145111.GA8569@sillyrabbi.dyndns.org> References: <20070703155703.GA3682@sillyrabbi.dyndns.org> <20070704145111.GA8569@sillyrabbi.dyndns.org> Message-ID: <468BBCB5.7040300@tds.net> William O'Higgins Witteman wrote: >> for thing in os.walk(u'.'): >> >> instead of: >> >> for thing in os.walk('.'): > > This is a good thought, and the crux of the problem. I pull the > starting directories from an XML file which is UTF-8, but by the time it > hits my program, because there are no extended characters in the > starting path, os.walk assumes ascii. So, I recast the string as UTF-8, > and I get UTF-8 output. The problem happens further down the line. > > I get a list of paths from the results of os.walk, all in UTF-8, but not > identified as such. If I just pass my list to other parts of the > program it seems to assume either ascii or UTF-8, based on the > individual list elements. If I try to cast the whole list as UTF-8, I > get an exception because it is assuming ascii and receiving UTF-8 for > some list elements. FWIW, I'm pretty sure you are confusing Unicode strings and UTF-8 strings, they are not the same thing. A Unicode string uses 16 bits to represent each character. It is a distinct data type from a 'regular' string. Regular Python strings are byte strings with an implicit encoding. One possible encoding is UTF-8 which uses one or more bytes to represent each character. Some good reading on Unicode and utf-8: http://www.joelonsoftware.com/articles/Unicode.html http://effbot.org/zone/unicode-objects.htm If you pass a unicode string (not utf-8) to os.walk(), the resulting lists will also be unicode. Again, it would be helpful to see the code that is getting the error. > I suspect that my program will have to make sure to recast all > equivalent-to-ascii strings as UTF-8 while leaving the ones that are > already extended alone. It is nonsense to talk about 'recasting' an ascii string as UTF-8; an ascii string is *already* UTF-8 because the representation of the characters is identical. OTOH it makes sense to talk about converting an ascii string to a unicode string. Kent From carroll at tjc.com Wed Jul 4 17:40:08 2007 From: carroll at tjc.com (Terry Carroll) Date: Wed, 4 Jul 2007 08:40:08 -0700 (PDT) Subject: [Tutor] Calculating Deflection angles In-Reply-To: <965122bf0707040209i18964b1csfbb9815a7510f2b8@mail.gmail.com> Message-ID: On Wed, 4 Jul 2007, nitin chandra wrote: > Hello Every One, > > I create a list of coordinates of 2 lines. > X11,Y11 & X12,Y12 as starting and ending of one line. > X21,Y21 & X22, Y22 as starting and ending of the 2nd line. > > Now is there any way to calculate the deflection angle between the two > lines? Will any modules be required other than Python 2.3 (on Linux)? I'm looking at my old book "A Programmer's Geometry" now. If you first put the equations for each line in the AX+BY+C=0 form, i.e., Line 1: A1*X + B1*Y + C1 = 0 Line 2: A2*X + B2*Y + C2 = 0 Then the angle between them is found by: theta = acos( (A1*A2 + B1*B2) / sqrt((A1**2+B1**2)*(A2**2+B2**2)) ) From hmm at woolgathering.cx Wed Jul 4 18:00:08 2007 From: hmm at woolgathering.cx (William O'Higgins Witteman) Date: Wed, 4 Jul 2007 12:00:08 -0400 Subject: [Tutor] UTF-8 filenames encountered in os.walk In-Reply-To: <468BBCB5.7040300@tds.net> References: <20070703155703.GA3682@sillyrabbi.dyndns.org> <20070704145111.GA8569@sillyrabbi.dyndns.org> <468BBCB5.7040300@tds.net> Message-ID: <20070704160008.GC8569@sillyrabbi.dyndns.org> On Wed, Jul 04, 2007 at 11:28:53AM -0400, Kent Johnson wrote: >FWIW, I'm pretty sure you are confusing Unicode strings and UTF-8 >strings, they are not the same thing. A Unicode string uses 16 bits to >represent each character. It is a distinct data type from a 'regular' >string. Regular Python strings are byte strings with an implicit >encoding. One possible encoding is UTF-8 which uses one or more bytes to >represent each character. > >Some good reading on Unicode and utf-8: >http://www.joelonsoftware.com/articles/Unicode.html >http://effbot.org/zone/unicode-objects.htm The problem is that the Windows filesystem uses UTF-8 as the encoding for filenames, but os doesn't seem to have a UTF-8 mode, just an ascii mode and a Unicode mode. >If you pass a unicode string (not utf-8) to os.walk(), the resulting >lists will also be unicode. > >Again, it would be helpful to see the code that is getting the error. The code is quite complex for not-relevant-to-this-problem reasons. The gist is that I walk the FS, get filenames, some of which get written to an XML file. If I leave the output alone I get errors on reading the XML file. If I try to change the output so that it is all Unicode, I get errors because my UTF-8 data sometimes looks like ascii, and I don't see a UTF-8-to-Unicode converter in the docs. >>I suspect that my program will have to make sure to recast all >>equivalent-to-ascii strings as UTF-8 while leaving the ones that are >>already extended alone. > >It is nonsense to talk about 'recasting' an ascii string as UTF-8; an >ascii string is *already* UTF-8 because the representation of the >characters is identical. OTOH it makes sense to talk about converting an >ascii string to a unicode string. Then what does mystring.encode("UTF-8") do? -- yours, William From Andy.cheesman at bristol.ac.uk Wed Jul 4 18:07:40 2007 From: Andy.cheesman at bristol.ac.uk (Andy Cheesman) Date: Wed, 04 Jul 2007 17:07:40 +0100 Subject: [Tutor] rotation within arrays Message-ID: <468BC5CC.6060200@bristol.ac.uk> Dear People, I wondering if any of you lovely people can make a suggestion on a problem which I have with a n dimensional array. For example, I've a 3x3 array and I have been mapping an element from 1D to the one directly above it. 3->12 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 The problem which I have is that I now need to rotated alternative layer of the arrays but I still need to have the original mapping i.e 3 -> 12. 0 1 2 3 4 5 6 7 8 11 14 17 10 13 16 9 12 15 Does anyone have any suggestions for how to do this? Thanks Andy From adecchi at gmail.com Wed Jul 4 18:09:06 2007 From: adecchi at gmail.com (Alejandro Decchi) Date: Wed, 4 Jul 2007 13:09:06 -0300 Subject: [Tutor] Help search files Message-ID: Hello Someone can help me how to search file in a directory. I need to do a form where the user write the word to search and if the file was found the user must could download the file making click in the link Sorry my english thz Alex -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070704/c4c5c774/attachment.html From python at venix.com Wed Jul 4 18:48:40 2007 From: python at venix.com (Lloyd Kvam) Date: Wed, 04 Jul 2007 12:48:40 -0400 Subject: [Tutor] UTF-8 filenames encountered in os.walk In-Reply-To: <20070704160008.GC8569@sillyrabbi.dyndns.org> References: <20070703155703.GA3682@sillyrabbi.dyndns.org> <20070704145111.GA8569@sillyrabbi.dyndns.org> <468BBCB5.7040300@tds.net> <20070704160008.GC8569@sillyrabbi.dyndns.org> Message-ID: <1183567720.3912.301.camel@localhost.localdomain> On Wed, 2007-07-04 at 12:00 -0400, William O'Higgins Witteman wrote: > On Wed, Jul 04, 2007 at 11:28:53AM -0400, Kent Johnson wrote: > > >FWIW, I'm pretty sure you are confusing Unicode strings and UTF-8 > >strings, they are not the same thing. A Unicode string uses 16 bits to > >represent each character. It is a distinct data type from a 'regular' > >string. Regular Python strings are byte strings with an implicit > >encoding. One possible encoding is UTF-8 which uses one or more bytes to > >represent each character. > > > >Some good reading on Unicode and utf-8: > >http://www.joelonsoftware.com/articles/Unicode.html > >http://effbot.org/zone/unicode-objects.htm > > The problem is that the Windows filesystem uses UTF-8 as the encoding > for filenames, but os doesn't seem to have a UTF-8 mode, just an ascii > mode and a Unicode mode. Are you converting your utf-8 strings to unicode? unicode_file_name = utf8_file_name.decode('UTF-8') > >If you pass a unicode string (not utf-8) to os.walk(), the resulting > >lists will also be unicode. > > > >Again, it would be helpful to see the code that is getting the error. > > The code is quite complex for not-relevant-to-this-problem reasons. The > gist is that I walk the FS, get filenames, some of which get written to > an XML file. If I leave the output alone I get errors on reading the > XML file. If I try to change the output so that it is all Unicode, I > get errors because my UTF-8 data sometimes looks like ascii, and I don't > see a UTF-8-to-Unicode converter in the docs. > It is probably worth the effort to put together a simpler piece of code that can illustrate the problem. > >>I suspect that my program will have to make sure to recast all > >>equivalent-to-ascii strings as UTF-8 while leaving the ones that are > >>already extended alone. > > > >It is nonsense to talk about 'recasting' an ascii string as UTF-8; an > >ascii string is *already* UTF-8 because the representation of the > >characters is identical. OTOH it makes sense to talk about converting an > >ascii string to a unicode string. > > Then what does mystring.encode("UTF-8") do? It uses utf8 encoding rules to convert mystring FROM unicode to a string. If mystring is *NOT* unicode but simply a string, it appears to do a round trip decode and encode of the string. This allows you to find encoding errors, but if there are no errors the result is the same as what you started with. The data in a file (streams of bytes) are encoded to represent unicode characters. The stream must be decoded to recover the underlying unicode. The unicode must be encoded when written to files. utf-8 is just one of many possible encoding schemes. -- Lloyd Kvam Venix Corp From alan.gauld at btinternet.com Wed Jul 4 19:00:13 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Jul 2007 18:00:13 +0100 Subject: [Tutor] Help search files References: Message-ID: "Alejandro Decchi" wrote > form where the user write the word to search > and if the file was found Do you mean the word is the filename (use glob module) or the word is inside the file (use os.walk)? Amnd do you need an exact match or a wild card search. The latter will use either glob or regular expressions(re module) > user must could download the file making click in the link You can use the ftlib module for that. HTH, Alan G From alan.gauld at btinternet.com Wed Jul 4 19:01:56 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Jul 2007 18:01:56 +0100 Subject: [Tutor] rotation within arrays References: <468BC5CC.6060200@bristol.ac.uk> Message-ID: "Andy Cheesman" > The problem which I have is that I now need to rotated alternative > layer > of the arrays but I still need to have the original mapping i.e 3 -> > 12. Is your problem how to rotate the array? Or how to preserve the mapping? or both? I don't know offhand how to do either but I'm not sure which I should be thinking about first! Alan G From adecchi at gmail.com Wed Jul 4 19:20:29 2007 From: adecchi at gmail.com (Alejandro Decchi) Date: Wed, 4 Jul 2007 14:20:29 -0300 Subject: [Tutor] Help search files In-Reply-To: References: Message-ID: The user put the word or the regular expresion in a textbox i need to do when ther user press the buttom submit call the file for example search.py . I need to do this search.py file to find the file looking for ther user. If the file or files are found i want to the user can download the files found making click in the link listed in ther form On 7/4/07, Alan Gauld wrote: > > > "Alejandro Decchi" wrote > > > form where the user write the word to search > > and if the file was found > > Do you mean the word is the filename (use glob module) > or the word is inside the file (use os.walk)? > > Amnd do you need an exact match or a wild card search. > The latter will use either glob or regular expressions(re module) > > > user must could download the file making click in the link > > You can use the ftlib module for that. > > HTH, > > 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/20070704/5ca1c023/attachment.htm From alan.gauld at btinternet.com Wed Jul 4 19:27:06 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Jul 2007 18:27:06 +0100 Subject: [Tutor] Help search files References: Message-ID: "Alejandro Decchi" wrote > The user put the word or the regular expresion in a textbox i need > to do > when ther user press the buttom submit call the file for example > search.py . > I need to do this search.py file to find the file looking for ther > user. Is the word the user enters the name of the file to be found? Or is it a word that we must search for inside the files? Alan G From adecchi at gmail.com Wed Jul 4 19:38:23 2007 From: adecchi at gmail.com (Alejandro Decchi) Date: Wed, 4 Jul 2007 14:38:23 -0300 Subject: [Tutor] Help search files In-Reply-To: References: Message-ID: Is the word or part of the word that the user enters in the texbox .And this word is the name of the file to be found On 7/4/07, Alan Gauld wrote: > > > "Alejandro Decchi" wrote > > > The user put the word or the regular expresion in a textbox i need > > to do > > when ther user press the buttom submit call the file for example > > search.py . > > I need to do this search.py file to find the file looking for ther > > user. > > Is the word the user enters the name of the file to be found? > Or is it a word that we must search for inside the files? > > > 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/20070704/28c9c261/attachment.html From carroll at tjc.com Wed Jul 4 19:44:44 2007 From: carroll at tjc.com (Terry Carroll) Date: Wed, 4 Jul 2007 10:44:44 -0700 (PDT) Subject: [Tutor] UTF-8 filenames encountered in os.walk In-Reply-To: <20070704160008.GC8569@sillyrabbi.dyndns.org> Message-ID: On Wed, 4 Jul 2007, William O'Higgins Witteman wrote: > >It is nonsense to talk about 'recasting' an ascii string as UTF-8; an > >ascii string is *already* UTF-8 because the representation of the > >characters is identical. OTOH it makes sense to talk about converting an > >ascii string to a unicode string. > > Then what does mystring.encode("UTF-8") do? I'm pretty iffy on this stuff myself, but as I see it, you basically have three kinds of things here. First, an ascii string: s = 'abc' In hex, this is 616263; 61 for 'a'; 62 for 'b', 63 for 'c'. Second, a unicode string: u = u'abc' I can't say what this is "in hex" because that's not meaningful. A Unicode character is a code point, which can be represented in a variety of ways, depending on the encoding used. So, moving on.... Finally, you can have a sequence of bytes, which are stored in a string as a buffer, that shows the particular encoding of a particular string: e8 = s.encode("UTF-8") e16 = s.encode("UTF-16") Now, e8 and e16 are each strings (of bytes), the content of which tells you how the string of characters that was encoded is represented in that particular encoding. In hex, these look like this. e8: 616263 (61 for 'a'; 62 for 'b', 63 for 'c') e16: FFFE6100 62006300 (FFEE for the BOM, 6100 for 'a', 6200 for 'b', 6300 for 'c') Now, superficially, s and e8 are equal, because for plain old ascii characters (which is all I've used in this example), UTF-8 is equivalent to ascii. And they compare the same: >>> s == e8 True But that's not true of the UTF-16: >>> s == e16 False >>> e8 == e16 False So (and I'm open to correction on this), I think of the encode() method as returning a string of bytes that represents the particular encoding of a string value -- and it can't be used as the string value itself. But you can get that string value back (assuming all the characters map to ascii): >>> s8 = e8.decode("UTF-8") >>> s16 = e16.decode("UTF-16") >>> s == s8 == s16 True From alan.gauld at btinternet.com Wed Jul 4 19:55:51 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Jul 2007 18:55:51 +0100 Subject: [Tutor] Help search files References: Message-ID: "Alejandro Decchi" wrote > Is the word or part of the word that the user enters in the texbox . > And this word is the name of the file to be found Ok, In that case use the glob function in the glob module. It returns a list of all files that match a pattern: >>> import glob >>> files = glob.glob("*.txt") >>> print files For more powerful searches you can use os.walk() See the OS topic in my tutorial for more examples of using glob and os.walk HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Wed Jul 4 20:26:42 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 04 Jul 2007 14:26:42 -0400 Subject: [Tutor] UTF-8 filenames encountered in os.walk In-Reply-To: <20070704160008.GC8569@sillyrabbi.dyndns.org> References: <20070703155703.GA3682@sillyrabbi.dyndns.org> <20070704145111.GA8569@sillyrabbi.dyndns.org> <468BBCB5.7040300@tds.net> <20070704160008.GC8569@sillyrabbi.dyndns.org> Message-ID: <468BE662.8070706@tds.net> William O'Higgins Witteman wrote: > The problem is that the Windows filesystem uses UTF-8 as the encoding > for filenames, That's not what I get. For example, I made a file called "T?st.txt" and looked at what os.listdir() gives me. (os.listdir() is what os.walk() uses to get the file and directory names.) If I pass a byte string as the directory name, I get byte strings back, not in utf-8, but apparently in cp1252 (or latin-1, but this is Windows so it's probably cp1252): >>> os.listdir('C:\Documents and Settings') ['Administrator', 'All Users', 'Default User', 'LocalService', 'NetworkService', 'T\xe9st.txt'] Note the \xe9 which is the cp1252 representation of ?. If I give the directory as a unicode string, the results are all unicode strings as well: >>> os.listdir(u'C:\Documents and Settings') [u'Administrator', u'All Users', u'Default User', u'LocalService', u'NetworkService', u'T\xe9st.txt'] In neither case does it give me utf-8. > but os doesn't seem to have a UTF-8 mode, just an ascii > mode and a Unicode mode. It has a unicode string mode and a byte string mode. > The code is quite complex for not-relevant-to-this-problem reasons. The > gist is that I walk the FS, get filenames, some of which get written to > an XML file. If I leave the output alone I get errors on reading the > XML file. What kind of errors? Be specific! Show the code that generates the error. I'll hazard a guess that you are writing the cp1252 characters to the XML file but not specifying the charset of the file, or specifying it as utf-8, and the reader croaks on the cp1252. > If I try to change the output so that it is all Unicode, I > get errors because my UTF-8 data sometimes looks like ascii, How do you change the output? What do you mean, the utf-8 data looks like ascii? Ascii data *is* utf-8, they should look the same. > I don't > see a UTF-8-to-Unicode converter in the docs. If s is a byte string containing utf-8, then s.decode('utf-8') is the equivalent unicode string. >>> I suspect that my program will have to make sure to recast all >>> equivalent-to-ascii strings as UTF-8 while leaving the ones that are >>> already extended alone. >> It is nonsense to talk about 'recasting' an ascii string as UTF-8; an >> ascii string is *already* UTF-8 because the representation of the >> characters is identical. OTOH it makes sense to talk about converting an >> ascii string to a unicode string. > > Then what does mystring.encode("UTF-8") do? It depends on what mystring is. If it is a unicode string, it converts it to a plain (byte) string containing the utf-8 representation of mystring. For example, In [8]: s=u'\xe9' # Note the leading "u" - this is a unicode string In [9]: s.encode('utf-8') Out[9]: '\xc3\xa9' If mystring is a string, it is converted to a unicode string using the default encoding (ascii unless you have changed it), then that string is converted to utf-8. This can work out two ways: - if mystring originally contained only ascii characters, the result is identical to the original: In [1]: s='abc' In [2]: s.encode('utf-8') Out[2]: 'abc' In [4]: s.encode('utf-8') == s Out[4]: True - if mystring contains non-ascii characters, then the implicit *decode* using the ascii codec will fail with an exception: In [5]: s = '\303\251' In [6]: s.encode('utf-8') ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in : 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128) Note this is exactly the same error you would get if you explicitly tried to convert to unicode using the ascii codec, because that is what is happening under the hood: In [11]: s.decode('ascii') ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in : 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128) Again, it would really help if you would - show some code - show some data - learn more about unicode, utf-8, character encodings and python strings. Kent From adecchi at gmail.com Wed Jul 4 20:27:52 2007 From: adecchi at gmail.com (Alejandro Decchi) Date: Wed, 4 Jul 2007 15:27:52 -0300 Subject: [Tutor] Help search files In-Reply-To: References: Message-ID: perfect but can you give me a link to find a file in a directory.Because i do not the function to search files in some directory. Can you give an example : On 7/4/07, Alan Gauld wrote: > > > "Alejandro Decchi" wrote > > > Is the word or part of the word that the user enters in the texbox . > > And this word is the name of the file to be found > > Ok, In that case use the glob function in the glob module. > It returns a list of all files that match a pattern: > > >>> import glob > >>> files = glob.glob("*.txt") > >>> print files > > For more powerful searches you can use os.walk() > > See the OS topic in my tutorial for more examples of > using glob and os.walk > > 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/20070704/ec52e6fd/attachment.htm From andreas at kostyrka.org Wed Jul 4 20:35:37 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 04 Jul 2007 20:35:37 +0200 Subject: [Tutor] Calculating Deflection angles In-Reply-To: <965122bf0707040209i18964b1csfbb9815a7510f2b8@mail.gmail.com> References: <965122bf0707040209i18964b1csfbb9815a7510f2b8@mail.gmail.com> Message-ID: <468BE879.9090404@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Well, first that sounds somehow like a homework assignment, so only some hints: a) work out the underlying math. Consider all special edge cases. b) I'm not completely sure what you need, but a feeling in the stomach tells me that you might need the atan function, it's provided in Python in the math module. Andreas nitin chandra wrote: > Hello Every One, > > I create a list of coordinates of 2 lines. > X11,Y11 & X12,Y12 as starting and ending of one line. > X21,Y21 & X22, Y22 as starting and ending of the 2nd line. > > Now is there any way to calculate the deflection angle between the two > lines? Will any modules be required other than Python 2.3 (on Linux)? > > and > > How will it be done? > > TIA, > > Nitin > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGi+h4HJdudm4KnO0RAgaTAKDV9dRcoFRuFpU0l0uNRrVmmUGZvACgm2B8 ute28hDtZfeMQGg+0QoF7Mo= =kBWC -----END PGP SIGNATURE----- From alan.gauld at btinternet.com Wed Jul 4 20:35:44 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Jul 2007 19:35:44 +0100 Subject: [Tutor] Help search files References: Message-ID: Just set the current directory to the one you want to search using os.chdir(myPath) or pass a full path to glob: glob.glob("/some/path/to/search/*.txt") HTH, Alan G. "Alejandro Decchi" wrote in message news:a1885f340707041127j39756c40j256762f6c1350812 at mail.gmail.com... > perfect but can you give me a link to find a file in a > directory.Because i > do not the function to search files in some directory. Can you give > an > example : > > On 7/4/07, Alan Gauld wrote: >> >> >> "Alejandro Decchi" wrote >> >> > Is the word or part of the word that the user enters in the >> > texbox . >> > And this word is the name of the file to be found >> >> Ok, In that case use the glob function in the glob module. >> It returns a list of all files that match a pattern: >> >> >>> import glob >> >>> files = glob.glob("*.txt") >> >>> print files >> >> For more powerful searches you can use os.walk() >> >> See the OS topic in my tutorial for more examples of >> using glob and os.walk >> >> 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 >> > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From andreas at kostyrka.org Wed Jul 4 20:39:24 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 04 Jul 2007 20:39:24 +0200 Subject: [Tutor] how long? In-Reply-To: References: Message-ID: <468BE95C.8070401@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 You forgot the uncertainty of 1000% :) Actually, Python is relativly easy to learn, but I've known people that were trained by the Arbeitsamt (government employment office), which never, even after months could predict the output of programs like: for x in xrange(3): for y in xrange(3): print x, y, x * y Guess one needs a certain level of abstract thinking to be a programmer ;) Andreas Thorsten Kampe wrote: > * Ben Waldin (Tue, 3 Jul 2007 19:46:42 +1200) >> How long will it take until I successfully create my own working program that is useful? I have crated the address book ones in the tutors and just want to know how long it takes before I start to create my own thought up programs that will be useful. Thanks Ben > > Approximately ten days, four hours and six minutes > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGi+lcHJdudm4KnO0RAhiHAKCgEGezriWG5kigHBut8FnuEB9F7QCdE+X/ 0AEw/jigdaEtbXNYVSMH7OI= =UBkm -----END PGP SIGNATURE----- From bgailer at alum.rpi.edu Wed Jul 4 20:40:14 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 04 Jul 2007 11:40:14 -0700 Subject: [Tutor] rotation within arrays In-Reply-To: <468BC5CC.6060200@bristol.ac.uk> References: <468BC5CC.6060200@bristol.ac.uk> Message-ID: <468BE98E.7070704@alum.rpi.edu> Andy Cheesman wrote: > Dear People, > > I wondering if any of you lovely people can make a suggestion on a > problem which I have with a n dimensional array. > For example, I've a 3x3 array What mechanism (module?) are you using to store the array? Or are you asking us for a recommendation? > and I have been mapping an element from 1D > to the one directly above it. 3->12 > > 0 1 2 > 3 4 5 > 6 7 8 > > 9 10 11 > 12 13 14 > 15 16 17 > > The problem which I have is that I now need to rotated alternative layer > of the arrays arrays? I only see the 2nd as "rotated". And do you mean "transpose"? That is what the result looks like. What prevents you from keeping the original for the mapping and also having a transposed copy? > but I still need to have the original mapping i.e 3 -> 12. > > 0 1 2 > 3 4 5 > 6 7 8 > > 11 14 17 > 10 13 16 > 9 12 15 > The mapping can be defined in another array (I'm using origin 1 indexing here): 1,1 1,2 1,3 2,1 2,2 2,3 3,1 3,2 3,3 Then you'd transpose that when you transpose the other array. -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From kent37 at tds.net Wed Jul 4 20:47:45 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 04 Jul 2007 14:47:45 -0400 Subject: [Tutor] UTF-8 filenames encountered in os.walk In-Reply-To: References: Message-ID: <468BEB51.90806@tds.net> Terry Carroll wrote: > I'm pretty iffy on this stuff myself, but as I see it, you basically have > three kinds of things here. > > First, an ascii string: > > s = 'abc' > > In hex, this is 616263; 61 for 'a'; 62 for 'b', 63 for 'c'. > > Second, a unicode string: > > u = u'abc' > > I can't say what this is "in hex" because that's not meaningful. A > Unicode character is a code point, which can be represented in a variety > of ways, depending on the encoding used. So, moving on.... > > Finally, you can have a sequence of bytes, which are stored in a string as > a buffer, that shows the particular encoding of a particular string: > > e8 = s.encode("UTF-8") > e16 = s.encode("UTF-16") > > Now, e8 and e16 are each strings (of bytes), the content of which tells > you how the string of characters that was encoded is represented in that > particular encoding. I would say that there are two kinds of strings, byte strings and unicode strings. Byte strings have an implicit encoding. If the contents of the byte string are all ascii characters, you can generally get away with ignoring that they are in an encoding, because most of the common 8-bit character encodings include plain ascii as a subset (all the latin-x encodings, all the Windows cp12xx encodings, and utf-8 all have ascii as a subset), so an ascii string can be interpreted as any of those encodings without error. As soon as you get away from ascii, you have to be aware of the encoding of the string. encode() really wants a unicode string not a byte string. If you call encode() on a byte string, the string is first converted to unicode using the default encoding (usually ascii), then converted with the given encoding. > > In hex, these look like this. > > e8: 616263 (61 for 'a'; 62 for 'b', 63 for 'c') > e16: FFFE6100 62006300 > (FFEE for the BOM, 6100 for 'a', 6200 for 'b', 6300 for 'c') > > Now, superficially, s and e8 are equal, because for plain old ascii > characters (which is all I've used in this example), UTF-8 is equivalent > to ascii. And they compare the same: > >>>> s == e8 > True They are equal in every sense, I don't know why you consider this superficial. And if your original string was not ascii the encode() would fail with a UnicodeDecodeError. > > But that's not true of the UTF-16: > >>>> s == e16 > False >>>> e8 == e16 > False > > So (and I'm open to correction on this), I think of the encode() method as > returning a string of bytes that represents the particular encoding of a > string value -- and it can't be used as the string value itself. The idea that there is somehow some kind of string value that doesn't have an encoding will bring you a world of hurt as soon as you venture out of the realm of pure ascii. Every string is a particular encoding of character values. It's not any different from "the string value itself". > > But you can get that string value back (assuming all the characters map > to ascii): > >>>> s8 = e8.decode("UTF-8") >>>> s16 = e16.decode("UTF-16") >>>> s == s8 == s16 > True You can get back to the ascii-encoded representation of the string. Though here you are hiding something - s8 and s16 are unicode strings while s is a byte string. In [13]: s = 'abc' In [14]: e8 = s.encode("UTF-8") In [15]: e16 = s.encode("UTF-16") In [16]: s8 = e8.decode("UTF-8") In [17]: s16 = e16.decode("UTF-16") In [18]: s8 Out[18]: u'abc' In [19]: s16 Out[19]: u'abc' In [20]: s Out[20]: 'abc' In [21]: type(s8) == type(s) Out[21]: False The way I think of it is, unicode is the "pure" representation of the string. (This is nonsense, I know, but I find it a convenient mnemonic.) encode() converts from the "pure" representation to an encoded representation. The encoding can be ascii, latin-1, utf-8... decode() converts from the coded representation back to the "pure" one. Kent From hmm at woolgathering.cx Wed Jul 4 21:07:40 2007 From: hmm at woolgathering.cx (William O'Higgins Witteman) Date: Wed, 4 Jul 2007 15:07:40 -0400 Subject: [Tutor] UTF-8 filenames encountered in os.walk In-Reply-To: <468BEB51.90806@tds.net> References: <468BEB51.90806@tds.net> Message-ID: <20070704190740.GD8569@sillyrabbi.dyndns.org> On Wed, Jul 04, 2007 at 02:47:45PM -0400, Kent Johnson wrote: >encode() really wants a unicode string not a byte string. If you call >encode() on a byte string, the string is first converted to unicode >using the default encoding (usually ascii), then converted with the >given encoding. Aha! That helps. Something else that helps is that my Python code is generating output that is received by several other tools. Interesting facts: Not all .NET XML parsers (nor IE6) accept valid UTF-8 XML. I am indeed seeing filenames in cp1252, even though the Microsoft docs say that filenames are in UTF-8. Filenames in Arabic are in UTF-8. What I have to do is to check the encoding of the filename as received by os.walk (and thus os.listdir) and convert them to Unicode, continue to process them, and then encode them as UTF-8 for output to XML. In trying to work around bad 3rd party tools and inconsistent data I introduced errors in my Python code. The problem was in treating all filenames the same way, when they were not being created the same way by the filesystem. Thanks for all the help and suggestions. -- yours, William From adecchi at gmail.com Wed Jul 4 21:14:04 2007 From: adecchi at gmail.com (Alejandro Decchi) Date: Wed, 4 Jul 2007 16:14:04 -0300 Subject: [Tutor] Help search files In-Reply-To: References: Message-ID: Ok but i have this form: Documento sin título

 

 

And i do not how to find the file looking for the user and list the file to can download it.Can you give me an example ???? Sorry to be a newbie !!! On 7/4/07, Alan Gauld wrote: > > Just set the current directory to the one you want to search using > > os.chdir(myPath) > > or pass a full path to glob: > > glob.glob("/some/path/to/search/*.txt") > > HTH, > > Alan G. > > "Alejandro Decchi" wrote in message > news:a1885f340707041127j39756c40j256762f6c1350812 at mail.gmail.com... > > perfect but can you give me a link to find a file in a > > directory.Because i > > do not the function to search files in some directory. Can you give > > an > > example : > > > > On 7/4/07, Alan Gauld wrote: > >> > >> > >> "Alejandro Decchi" wrote > >> > >> > Is the word or part of the word that the user enters in the > >> > texbox . > >> > And this word is the name of the file to be found > >> > >> Ok, In that case use the glob function in the glob module. > >> It returns a list of all files that match a pattern: > >> > >> >>> import glob > >> >>> files = glob.glob("*.txt") > >> >>> print files > >> > >> For more powerful searches you can use os.walk() > >> > >> See the OS topic in my tutorial for more examples of > >> using glob and os.walk > >> > >> 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 > >> > > > > > > -------------------------------------------------------------------------------- > > > > _______________________________________________ > > 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/20070704/31cffb76/attachment.html From terry.kemmerer at gmail.com Wed Jul 4 21:17:32 2007 From: terry.kemmerer at gmail.com (Terry) Date: Wed, 04 Jul 2007 12:17:32 -0700 Subject: [Tutor] [Fwd: Re: n.isalnum() is failing] Message-ID: <1183576653.1097.20.camel@localhost.localdomain> Thanks Alan, I managed to get totally confused by the different definitions of calculating a leap year. The book (Core Python) described the exercise thus: "Modulus. Determine whether a given year is a leap year, using the following formula: a leap year is one that is divisible by four, but not by one hundred, unless it is also divisible by four hundred." That sounded to me like: y % 4 ==0 and (y % 100==1 or y % 400==0) Then, after reading it ten more time I became uncertain and decided to find another definition and compare them. I found U.S. Naval Observatory: "According to the Gregorian calendar, which is the civil calendar in use today, years evenly divisible by 4 are leap years, with the exception of centurial years that are not evenly divisible by 400." Comparing the two, confused me a bit more, and I ended up ignoring the first definition, saying to myself, all 4th years are leap years, unless they are y % 100 ==0 AND y % 400==1. That sounded clearer....but, evidently, not correct. Ha Ha Ha I liked the way you directly formed it. It was more like my old IF-THEN statements.....to the point and we're out of here. def isLeapYear(y): if y % 4 == 0: return True if (y % 4 == 0) and not (y %100 == 0): return True else: return False I am checking out your python tutor web site at http://www.freenetpages.co.uk It looks like it surpasses by far other's I have checked out. Great job! Thanks for the correction and the methodology! Terry > def isLeapYear(y): > if y % 4 == 0: > if y % 100 == 0 and y % 400 == 1: > answer = False > return answer > answer = True > return answer > answer = False > return answer Not quite. y%400 == 1 will only be true for years like 2001, 1601 etc! You need to invert the test so y % 400 != 0. (or use not) But there is a more direct way: Lets recap: 1) A year that is divisible by 4 is a leap year. (Y % 4) == 0 2) but: a year that is divisible by 100 is not a leap year. (Y % 100) != 0 3) 3) however a year that is divisible by 400 is a leap year. (Y % 400) == 0 So a year that is divisible by 400 is *always* a leap year: if y % 400 == 0: return True Now we need a combined test for the other 2 cases. If its divisible by 4 and not by 100 its a leap year: if (y % 4 == 0) and not (y %100 == 0): return True So we can combine the definitions to give: def isLeapYear(y): if y % 400 == 0: return True if (y % 4 == 0) and not (y %100 == 0): return True else: return False Which is shorter and clearer IMHO. (You could combine it into one line but I personally think that would make the rules less clear.) This is one of the cases where using multiple returns makes the code clearer in my view. > print "This program finds all leap years between any two > dates.";print;print > > start = end = None > while start == None: > try: > start = int(raw_input("Enter yyyy for beginning year : ")) > end = int(raw_input("Enter yyyy for ending year : ")) > > except ValueError: > print;print "YEAR must be a integer number -- TRY AGAIN!" > start = end = None > > if 1 <= start < end: > print; print > for y in range(start, end + 1): > answer = isLeapYear(y) > if answer == True: > print y, "--leap year!" Also the point of a predicate function is that it returns a boolean value so you don;t need any intermediate variables. You can just use it in the condition, like if isLeapYear(y): print y, '--leap year' By using a predicate style name (isXXXXX) the code becomes clearer than when you introduce an intermediate variable where the reader then has to backtrack to see what the test value is based on. > 1900 --leap year! This is wrong, 1900 is divisible by 100 but not by 400... > 1904 --leap year! > 1908 --leap year! > ... > 2000 --leap year! Whereas 2000 is correct because it is divisible by 400. HTH, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070704/fdd911fb/attachment.html From jjcrump at myuw.net Wed Jul 4 22:17:09 2007 From: jjcrump at myuw.net (Jon Crump) Date: Wed, 4 Jul 2007 13:17:09 -0700 (PDT) Subject: [Tutor] UTF-8 title() string method In-Reply-To: References: Message-ID: Terry, thanks. Sadly, I'm still missing something. I've tried all the aliases in locale.py, most return locale.Error: unsupported locale setting one that doesn't is: >>> locale.setlocale(locale.LC_ALL, ('fr_fr')) 'fr_fr' but if I set it thus it returns: Angoul??Me, Angoumois. I'm running python 2.5 on a Mac iBook G4 osX 10.4.10, and this encoding stuff is terra incognita for me On Tue, 3 Jul 2007, Terry Carroll wrote: > I think setting the locale is the trick: > >>>> s1 = open("text.txt").readline() >>>> print s1 > ANGOUL.ME, Angoumois. >>>> print s1.title() > Angoul.Me, Angoumois. >>>> import locale >>>> locale.setlocale(locale.LC_ALL,('french')) > 'French_France.1252' >>>> print s1.title() > Angoul.me, Angoumois. > You might have to hunt around and experiment for the right locale that > will work in all your cases. From kent37 at tds.net Wed Jul 4 22:25:33 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 04 Jul 2007 16:25:33 -0400 Subject: [Tutor] UTF-8 filenames encountered in os.walk In-Reply-To: <20070704190740.GD8569@sillyrabbi.dyndns.org> References: <468BEB51.90806@tds.net> <20070704190740.GD8569@sillyrabbi.dyndns.org> Message-ID: <468C023D.7040405@tds.net> William O'Higgins Witteman wrote: > On Wed, Jul 04, 2007 at 02:47:45PM -0400, Kent Johnson wrote: > >> encode() really wants a unicode string not a byte string. If you call >> encode() on a byte string, the string is first converted to unicode >> using the default encoding (usually ascii), then converted with the >> given encoding. > > Aha! That helps. Something else that helps is that my Python code is > generating output that is received by several other tools. Interesting > facts: > > Not all .NET XML parsers (nor IE6) accept valid UTF-8 XML. Yikes! Are you sure it isn't a problem with your XML? > I am indeed seeing filenames in cp1252, even though the Microsoft docs > say that filenames are in UTF-8. > > Filenames in Arabic are in UTF-8. Not on my computer (Win XP) in os.listdir(). With filenames of T?st.txt and ?.txt (that's \u0642, an Arabic character), os.listdir() gives me >>> os.listdir('.') ['Administrator', 'All Users', 'Default User', 'LocalService', 'NetworkService', 'T\xe9st.txt', '?.txt'] >>> os.listdir(u'.') [u'Administrator', u'All Users', u'Default User', u'LocalService', u'NetworkService', u'T\xe9st.txt', u'\u0642.txt'] So with a byte string directory it fails, with a unicode directory it gives unicode, not utf-8. > What I have to do is to check the encoding of the filename as received > by os.walk (and thus os.listdir) and convert them to Unicode, continue > to process them, and then encode them as UTF-8 for output to XML. How do you do that? AFAIK there is no completely reliable way to determine the encoding of a byte string by looking at it; the most common approach is to try to find one that successfully decodes the string; more sophisticated variations look at the distribution of character codes. Anyway if you use the Unicode file names you shouldn't have to worry about this. Kent From kent37 at tds.net Wed Jul 4 22:33:11 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 04 Jul 2007 16:33:11 -0400 Subject: [Tutor] UTF-8 title() string method In-Reply-To: References: <1183449091.12516.64.camel@localhost.localdomain> <1183505867.3391.13.camel@localhost.localdomain> Message-ID: <468C0407.1080406@tds.net> Jon Crump wrote: > Dear All, > > I have some utf-8 unicode text with lines like this: > > ANVERS-LE-HOMONT, Maine. > ANGOUL?ME, Angoumois. > ANDELY (le Petit), Normandie. > > which I'm using as-is in this line of code: > > place.append(line.strip()) > > What I would prefer would be something like this: > > place.append(line.title().strip()) > > which works for most lines, giving me, for example: > > Anvers-Le-Homont, Maine. > and > Andely (Le Petit), Normandie. > > but where there are diacritics involved, title() gives me: > > Angoul?Me, Angoumois. > > Can anyone give the clueless a clue on how to manage such unicode > strings more effectively? First, don't confuse unicode and utf-8. Second, convert the string to unicode and then title-case it, then convert back to utf-8 if you need to: In [3]: s='ANGOUL\303\212ME, Angoumois' In [5]: s Out[5]: 'ANGOUL\xc3\x8aME, Angoumois' In [4]: s.title() Out[4]: 'Angoul\xc3\x8aMe, Angoumois' In [10]: print s.title() Angoul?Me, Angoumois In [6]: u=s.decode('utf-8') In [7]: u.title() Out[7]: u'Angoul\xeame, Angoumois' In [8]: print u.title() ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in : 'ascii' codec can't encode character u'\xea' in position 6: ordinal not in range(128) Oops, print is trying to convert to a byte string with the default encoding, have to give it some help... In [9]: print u.title().encode('utf-8') Angoul?me, Angoumois Kent From kent37 at tds.net Wed Jul 4 22:33:55 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 04 Jul 2007 16:33:55 -0400 Subject: [Tutor] UTF-8 title() string method In-Reply-To: References: Message-ID: <468C0433.3060704@tds.net> Terry Carroll wrote: > I think setting the locale is the trick: > >>>> s1 = open("text.txt").readline() >>>> print s1 > ANGOUL.ME, Angoumois. >>>> print s1.title() > Angoul.Me, Angoumois. >>>> import locale >>>> locale.setlocale(locale.LC_ALL,('french')) > 'French_France.1252' >>>> print s1.title() > Angoul.me, Angoumois. I think your file is cp1252 not utf-8 as the OP specified... Ken From samrobertsmith at gmail.com Thu Jul 5 00:06:14 2007 From: samrobertsmith at gmail.com (linda.s) Date: Wed, 4 Jul 2007 15:06:14 -0700 Subject: [Tutor] hash Message-ID: <1d987df30707041506j6809cafgf534186b59cf258e@mail.gmail.com> what is the use of def __hash__(self)? I can not understand the document. any example? thanks, Linda From nephish at gmail.com Thu Jul 5 00:21:21 2007 From: nephish at gmail.com (shawn bright) Date: Wed, 4 Jul 2007 17:21:21 -0500 Subject: [Tutor] cyclical redundancy check Message-ID: <384c93600707041521h6436141cg1441031595f5a3e7@mail.gmail.com> Hello there all, Does anyone know where i can find a function that does an 8 bit Cyclical Redundancy Check. I need it to verify data, and i need to be able to create one given an 12 byte message. Does anyone know much about doing this in python ? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070704/9cb752cf/attachment.html From nephish at gmail.com Thu Jul 5 00:23:27 2007 From: nephish at gmail.com (shawn bright) Date: Wed, 4 Jul 2007 17:23:27 -0500 Subject: [Tutor] cyclical redundancy check In-Reply-To: <384c93600707041521h6436141cg1441031595f5a3e7@mail.gmail.com> References: <384c93600707041521h6436141cg1441031595f5a3e7@mail.gmail.com> Message-ID: <384c93600707041523w7e86e56bj352dcccd210ebee0@mail.gmail.com> wait, sorry, thats 16 bits total, a low byte and a high byte. If that makes more sense thanks On 7/4/07, shawn bright wrote: > > Hello there all, > > Does anyone know where i can find a function that does an 8 bit Cyclical > Redundancy Check. > I need it to verify data, and i need to be able to create one given an 12 > byte message. Does anyone know much about doing this in python ? > > thanks > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070704/740626c7/attachment.htm From andreas at kostyrka.org Thu Jul 5 00:26:16 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 05 Jul 2007 00:26:16 +0200 Subject: [Tutor] hash In-Reply-To: <1d987df30707041506j6809cafgf534186b59cf258e@mail.gmail.com> References: <1d987df30707041506j6809cafgf534186b59cf258e@mail.gmail.com> Message-ID: <468C1E88.4020102@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Simple, defining __hash__ on a class allows you to supply a hash value for instances of your class. andreas at andi-lap:~> cat /tmp/hash.py class X: def __hash__(self): print "HASH CALLED" return 123 print hash(X()) andreas at andi-lap:~> python /tmp/hash.py HASH CALLED 123 Andreas linda.s wrote: > what is the use of def __hash__(self)? > I can not understand the document. > any example? thanks, > Linda > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGjB6IHJdudm4KnO0RAskJAKC4WZHo1Kv6MrHOzSWULOgMa+pDsgCgznRy Thwd2n1BgWjW8OEDUIILHXY= =y2W0 -----END PGP SIGNATURE----- From alan.gauld at btinternet.com Thu Jul 5 01:38:39 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Jul 2007 00:38:39 +0100 Subject: [Tutor] Help search files References: Message-ID: "Alejandro Decchi" wrote > Ok but i have this form: > >
action="/cgi-bin/search.py"> OK, You didn't make it clear that you meant a CGI program, I was assuming you meant a GUI program. That adds a whole heap of extra complexity. A lot depends on what web mechanism/framework you are using. If we assume the standard cgi module then you need to get the submited data out of the request with the field_storage dictionary. Then you need to call your search function and finally format the results as HTML. Either offer to downoad a particular file and have a second request start the download or just send the file back, but that could be an unexpected result. I'd offer the file as a link and let the user click on it to fetch it from the server. But web programming is a whole different ball game. You should look up some simple examples first. Alan G. From carroll at tjc.com Thu Jul 5 01:43:51 2007 From: carroll at tjc.com (Terry Carroll) Date: Wed, 4 Jul 2007 16:43:51 -0700 (PDT) Subject: [Tutor] UTF-8 filenames encountered in os.walk In-Reply-To: <468BEB51.90806@tds.net> Message-ID: On Wed, 4 Jul 2007, Kent Johnson wrote: > Terry Carroll wrote: > > Now, superficially, s and e8 are equal, because for plain old ascii > > characters (which is all I've used in this example), UTF-8 is equivalent > > to ascii. And they compare the same: > > > >>>> s == e8 > > True > > They are equal in every sense, I don't know why you consider this > superficial. And if your original string was not ascii the encode() > would fail with a UnicodeDecodeError. Superficial in the sense that I was using only characters in the ascii character set, so that the same byte encoding in UTF-8. so: >>> 'abc'.decode("UTF-8") u'abc' works But UTF-8 can hold other characters, too; for example >>> '\xe4\xba\xba'.decode("UTF-8") u'\u4eba' (Chinese character for "person") I'm just saying that UTF-8 encodes ascii characters to themselves; but UTF-8 is not the same as ascii. I think we're ultimately saying the same thing; to merge both our ways of putting it, I think, is that ascii will map to UTF-8 identically; but UTF-8 may map back or it will raise UnicodeDecodeError. I just didn't want to leave the impression "Yeah, UTF-8 & ascii, they're the same thing." From kent37 at tds.net Thu Jul 5 03:05:43 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 04 Jul 2007 21:05:43 -0400 Subject: [Tutor] UTF-8 filenames encountered in os.walk In-Reply-To: References: Message-ID: <468C43E7.6010602@tds.net> Terry Carroll wrote: > I'm just saying that UTF-8 encodes ascii characters to themselves; but > UTF-8 is not the same as ascii. > > I think we're ultimately saying the same thing; to merge both our ways of > putting it, I think, is that ascii will map to UTF-8 identically; but > UTF-8 may map back or it will raise UnicodeDecodeError. > > I just didn't want to leave the impression "Yeah, UTF-8 & ascii, they're > the same thing." I hope neither of us gave that impression! I think you are right, we just have different ways of thinking about it. Any ascii string is also a valid utf-8 string (and latin-1, and many other encodings), but the opposite is not true. Kent From adecchi at gmail.com Thu Jul 5 04:33:36 2007 From: adecchi at gmail.com (Alejandro Decchi) Date: Wed, 4 Jul 2007 23:33:36 -0300 Subject: [Tutor] Help search files In-Reply-To: References: Message-ID: Yes I have a debian server runing apache. Can you give me a link ? Because i do not how to make the search and list the files found to download On 7/4/07, Alan Gauld wrote: > > "Alejandro Decchi" wrote > > > Ok but i have this form: > > > > > action="/cgi-bin/search.py"> > > OK, You didn't make it clear that you meant a CGI program, > I was assuming you meant a GUI program. That adds a whole > heap of extra complexity. A lot depends on what web > mechanism/framework you are using. If we assume the > standard cgi module then you need to get the submited > data out of the request with the field_storage dictionary. > Then you need to call your search function and finally > format the results as HTML. Either offer to downoad a > particular file and have a second request start the download > or just send the file back, but that could be an unexpected result. > I'd offer the file as a link and let the user click on it to fetch it > from the server. > > But web programming is a whole different ball game. > You should look up some simple examples first. > > 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/20070704/ae1c5078/attachment.htm From sarliz73 at yahoo.com Thu Jul 5 06:45:53 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Wed, 4 Jul 2007 21:45:53 -0700 (PDT) Subject: [Tutor] Help! Pickle file Message-ID: <387295.10574.qm@web35101.mail.mud.yahoo.com> This may sound silly, but when writing a program where there is a pickle file, how does that get included into the entire program? For instance; to create a new pickle file.. ******************************************** #!/usr/bin/python # Filename: pickling.py import cPickle as p #import pickle as p (snipped from python.org) ******************************************** Does this fall anywhere in the program in particular? I'm REALLY unfamiliar with this and I'm using Python for Dummies and Python.org. Thanks! SJ --------------------------------- Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070704/92fd16a6/attachment.htm From john at fouhy.net Thu Jul 5 06:57:41 2007 From: john at fouhy.net (John Fouhy) Date: Thu, 5 Jul 2007 16:57:41 +1200 Subject: [Tutor] Help! Pickle file In-Reply-To: <387295.10574.qm@web35101.mail.mud.yahoo.com> References: <387295.10574.qm@web35101.mail.mud.yahoo.com> Message-ID: <5e58f2e40707042157n5bd3c035rfcc96d6aa1e30d1d@mail.gmail.com> On 05/07/07, Sara Johnson wrote: > This may sound silly, but when writing a program where there is a pickle > file, how does that get included into the entire program? For instance; Hi Sara, You create pickles with pickle.dump and you read them with pickle.load. For example: ####### create.py ####### import pickle data = ['one', 'two', 'three'] outfile = open('data.pickle', 'wb') pickle.dump(data, outfile) outfile.close() ################# ######## load.py ######## import pickle infile = open('data.pickle') data = pickle.load(infile) print data ################# If you run the first script, it will create a pickle of the list ['one', 'two', 'three']. You'll be able to see the file in the directory where you ran the script; you can even look at it if you like. The second script will read the pickle and reconstruct the list. Hope this helps! -- John. From janos.juhasz at VELUX.com Thu Jul 5 07:30:35 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Thu, 5 Jul 2007 07:30:35 +0200 Subject: [Tutor] n.isalnum() is failing In-Reply-To: Message-ID: Hi Terry > "According to the Gregorian calendar, which is the civil calendar in use > today, years evenly divisible by 4 are leap years, with the exception of > centurial years that are not evenly divisible by 400." > def isLeapYear(y): > if y % 4 == 0: return True As it always return True, if y%4 == 0, there is problem with the exceptions > if (y % 4 == 0) and not (y %100 == 0): return True > else: return False I feel that, the cleanest way to translate the definition into Boolean logic is to do it backward instead of thinking on the exceptions. def leap_year(year): if year%400 == 0: return True # We said these years are always leap year if year%100 == 0: return False # the exception handled already if year%4 == 0: return True # no problem with the exceptions return False # this it the default ps hungarians name format: family name, christian name hungarian date format: year/month/day Your logic is backward, and mine is the forward, isn't it? ;) Janos -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070705/3e33dd34/attachment.html From alan.gauld at btinternet.com Thu Jul 5 11:17:16 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Jul 2007 10:17:16 +0100 Subject: [Tutor] n.isalnum() is failing References: Message-ID: "J?nos Juh?sz" wrote >> def isLeapYear(y): >> if y % 4 == 0: return True > As it always return True, if y%4 == 0, there is problem with the > exceptions My original function had %400 not %4 so it worked. >> if (y % 4 == 0) and not (y %100 == 0): return True >> else: return False > > > I feel that, the cleanest way to translate the definition into > Boolean > logic is to do it backward instead of thinking on the exceptions. > > def leap_year(year): > if year%400 == 0: return True # these are always leap year > if year%100 == 0: return False # the exception handled already > if year%4 == 0: return True # no problem with the exceptions > return False # this it the default But I rather like this one since the combined and/not expression is less clear and more prone to confusion.. And in fact it can be simplified even further: def isLeapYear(y): if y % 400: return True if y % 100: return False return y % 4 == 0 > hungarians name format: family name, christian name > hungarian date format: year/month/day > Your logic is backward, and mine is the forward, isn't it? ;) :-) Alan G. From alan.gauld at btinternet.com Thu Jul 5 11:27:41 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Jul 2007 10:27:41 +0100 Subject: [Tutor] Help search files References: Message-ID: "Alejandro Decchi" wrote > Yes I have a debian server runing apache. Can you give me a link? I could give you lots of links but which is most useful will depend on your level of knowledge. I get the impression that you are not experienced in Web development and so may not even understand concepts like CGI? If so the best place to start is by searching for a Web tutorial on how to write CGI applications. There are many of these and probably one in your native language, read that first. Then look at the CGI tutorial onthe Python web site: http://wiki.python.org/moin/CgiScripts as well as the documentation on the cgi module: http://docs.python.org/lib/module-cgi.html > do not how to make the search and list the files found to download The list of files is just plain HTML. Here is some very primitive code: print "
    " for name in ['foo.txt','bar.txt', 'baz.txt']: print "
  • %s
  • " % name print "
" In your case you need to surround the name with an anchor link too. None of this is Python specific it is just basic web programming in HTML. HTH, Alan G. > > On 7/4/07, Alan Gauld wrote: >> >> "Alejandro Decchi" wrote >> >> > Ok but i have this form: >> > >> > > > action="/cgi-bin/search.py"> >> >> OK, You didn't make it clear that you meant a CGI program, >> I was assuming you meant a GUI program. That adds a whole >> heap of extra complexity. A lot depends on what web >> mechanism/framework you are using. If we assume the >> standard cgi module then you need to get the submited >> data out of the request with the field_storage dictionary. >> Then you need to call your search function and finally >> format the results as HTML. Either offer to downoad a >> particular file and have a second request start the download >> or just send the file back, but that could be an unexpected result. >> I'd offer the file as a link and let the user click on it to fetch >> it >> from the server. >> >> But web programming is a whole different ball game. >> You should look up some simple examples first. >> >> Alan G. >> >> >> _______________________________________________ >> 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 > From alan.gauld at btinternet.com Thu Jul 5 11:34:34 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Jul 2007 10:34:34 +0100 Subject: [Tutor] hash References: <1d987df30707041506j6809cafgf534186b59cf258e@mail.gmail.com> Message-ID: "linda.s" wrote > what is the use of def __hash__(self)? > I can not understand the document. > any example? First, do you understand what a hash is? Do you want an example of writing a hash - see Andreas reply. Or do you want to know when/how to use a hash? As Andreas said the __hash__ method makes an object hashable in the same way that the other __xxx__ methods modify the standard operations/behaviours of the object. Wikipedia has a good page on hash functions: http://en.wikipedia.org/wiki/Hash_%28computer_science%29 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 Thu Jul 5 11:43:49 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Jul 2007 10:43:49 +0100 Subject: [Tutor] Help! Pickle file References: <387295.10574.qm@web35101.mail.mud.yahoo.com> Message-ID: "Sara Johnson" wrote > This may sound silly, but when writing a program where > there is a pickle file, how does that get included into the > entire program? For instance; > > to create a new pickle file.. > ******************************************** > #!/usr/bin/python > # Filename: pickling.py > > import cPickle as p > Does this fall anywhere in the program in particular? This simply imports the pickle module like any other. As such its conventional to place the imports at the top of the source file. However that doesn't do any pickling or unpickling it just makes the name pickle accessible to your program. > I'm REALLY unfamiliar with this and I'm using Python > for Dummies and Python.org. Recall that the idea behind pickle is to make your data persistent between program runs (or even during long runs in case the program crashes). So you pickle the data when you finish processing it and want to preserve it safely on the disk for future use. You unpickle it again when you need to use it or at the start of your program. Typically the high level structure of your code might be: import pickle if pickle file exists: data = pickle.load(pickle_file) # process data here pickle.dump(data) sys.exit() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dhruva_lives at yahoo.com Thu Jul 5 11:47:56 2007 From: dhruva_lives at yahoo.com (Dhruva Kulkarni) Date: Thu, 5 Jul 2007 02:47:56 -0700 (PDT) Subject: [Tutor] From C to Python Message-ID: <891158.17770.qm@web32802.mail.mud.yahoo.com> Hi, I am a C guy wanting to switch to Python for some application-type-tasks that might be done in Python much quicker and sooner and smaller than in C...I have fiddled around with Python and looked through the tutorial, but i'm a bit lost when there are no pointers ( pun intended! ). I could not find any material on 'what-happens-when' type questions, e.g.( how functions are implemented --> stack-frame struct , parameter passing by value / reference ? ), and the whole 'identity vs equality' thing, plus the dynamic-typing-of-objects... So i can see that Python programers must be thinking in a very un-'byte'-ly way, so do I need to unlearn the C way of wandering in 'byteland' ? And where can i find the ten commandments for Pythonland>? Thanks! dhruva. --------------------------------- It's here! Your new message! Get new email alerts with the free Yahoo! Toolbar. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070705/fdd9da44/attachment.html From alun.griffiths at dsl.pipex.com Thu Jul 5 08:30:27 2007 From: alun.griffiths at dsl.pipex.com (Alun Griffiths) Date: Thu, 05 Jul 2007 07:30:27 +0100 Subject: [Tutor] (no subject) Message-ID: <6.1.2.0.2.20070705071108.04489890@pop.dsl.pipex.com> Hi I am trying to build a simple model of a gas field. At the moment I have these objects: GasWell represents the behaviour of a gas well GasFluid represents the thermodynamic behaviour of the gas GasField represents the field itself The GasField object defines properties such as pressure and volume. The fluid within it is represented by the GasFluid object which also defines the properties of the fluid flowing through GasWell objects associated with a particular GasField. GasWell can be moved from one GasField object to another, so take the appropriate fluid behaviour from the GasFluid associated with the GasField to which it belongs. At the moment, the GasField definition looks something like this Class GasField(Object): def __init__(name, pres, vol, fluid, wells): self.name=name self.pres=pres self.vol=vol self.fluid=fluid # GasFluid object self.wells=wells # List of GasWell objects No problems with creating the WELL list since I just append a bunch of GasWell objects to a new list. The problem I have is how a particular GasWell knows which field it belongs to. The only way I can think of so far involves some form of cross referencing where we define the GasField with an empty WELL list, define the GasWells by setting the field it belongs to explicitly then updating the WELL list "externally". For example wells = [] stuff = GasFluid( params ) field = GasField("My field", p, V, stuff, wells) well1 = GasWell(params, field) well2 = GasWell(params, field) well3 = GasWell(params, field) wells.append(well1) wells.append(well2) wells.append(well2) new_field.wells = wells This cross-referencing of GasField and GasWells doesn't seem right to me - if we move a well from one field to another we have to update the GasWell object and the GasField.wells list. Is there a more pythonic (or more sensible) way of doing this? Thanks in advance Alun Griffiths From kent37 at tds.net Thu Jul 5 14:07:24 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 05 Jul 2007 08:07:24 -0400 Subject: [Tutor] From C to Python In-Reply-To: <891158.17770.qm@web32802.mail.mud.yahoo.com> References: <891158.17770.qm@web32802.mail.mud.yahoo.com> Message-ID: <468CDEFC.3060200@tds.net> Dhruva Kulkarni wrote: > Hi, > I am a C guy wanting to switch to Python for some > application-type-tasks that might be done in Python much quicker and > sooner and smaller than in C...I have fiddled around with Python and > looked through the tutorial, but i'm a bit lost when there are no > pointers ( pun intended! ). I could not find any material on > 'what-happens-when' type questions, e.g.( how functions are implemented > --> stack-frame struct , parameter passing by value / reference ? ), > and the whole 'identity vs equality' thing, plus the > dynamic-typing-of-objects... > So i can see that Python programers must be thinking in a very > un-'byte'-ly way, so do I need to unlearn the C way of wandering in > 'byteland' ? And where can i find the ten commandments for Pythonland>? Yes, you need to leave your C ways behind. Don't worry, you'll like it here :-) The biggest shift is in the way you think about variables. In C, a variable is a container for a value. In Python, a variable is a name for a value; a reference. In C terms, think of it as a pointer to a value. This might help, especially the introduction :-) http://effbot.org/zone/python-objects.htm There is a lot of dispute over what to call the semantics of argument passing (pass by value? pass by reference?), but the concept is pretty simple. Function arguments are references that are bound to names in the local scope of the function. The reference is passed by value. One name for this is "call by object reference". In C terms, if you think of variables as pointers to values, and argument passing as copying the pointer, you will get the idea. BTW the semantics of assignment and those of argument passing are identical - they both bind a name to a value in the local scope. One consequence of this is that aliasing happens all the time. If two names are bound to the same mutable object, any changes to the object are visible through either name: In [11]: a=[1, 2, 3] In [12]: b=a In [13]: a.append(4) In [14]: a Out[14]: [1, 2, 3, 4] In [15]: b Out[15]: [1, 2, 3, 4] You really don't have to worry about stack frames and how functions are implemented (they are objects too), at least not initially, just let Python take care of it for you. I wouldn't worry about identity vs equality, either; usually you are interested in equality. I don't know about ten commandments, but you can see the Zen of Python by typing 'import this' at the Python interpreter prompt. Kent From adecchi at gmail.com Thu Jul 5 14:11:21 2007 From: adecchi at gmail.com (Alejandro Decchi) Date: Thu, 5 Jul 2007 09:11:21 -0300 Subject: [Tutor] Help search files In-Reply-To: References: Message-ID: Yes i am a newbie in web design but i understand the concept of CGI. My problem is that I do not know how to do a search based in binary files.Forexample a user conect to my webpage and dicide to search windows.iso he write in the textbox and put submit and must appear the result to download the link. Thz On 7/5/07, Alan Gauld wrote: > > "Alejandro Decchi" wrote > > > Yes I have a debian server runing apache. Can you give me a link? > > I could give you lots of links but which is most useful will depend > on your level of knowledge. I get the impression that you are not > experienced in Web development and so may not even understand > concepts like CGI? If so the best place to start is by searching for > a Web tutorial on how to write CGI applications. There are many > of these and probably one in your native language, read that first. > > Then look at the CGI tutorial onthe Python web site: > > http://wiki.python.org/moin/CgiScripts > > as well as the documentation on the cgi module: > > http://docs.python.org/lib/module-cgi.html > > > do not how to make the search and list the files found to download > > The list of files is just plain HTML. Here is some very > primitive code: > > print "
    " > for name in ['foo.txt','bar.txt', 'baz.txt']: > print "
  • %s
  • " % name > print "
" > > In your case you need to surround the name with an anchor link too. > None of this is Python specific it is just basic web programming in > HTML. > > HTH, > > Alan G. > > > > > On 7/4/07, Alan Gauld wrote: > >> > >> "Alejandro Decchi" wrote > >> > >> > Ok but i have this form: > >> > > >> > >> > action="/cgi-bin/search.py"> > >> > >> OK, You didn't make it clear that you meant a CGI program, > >> I was assuming you meant a GUI program. That adds a whole > >> heap of extra complexity. A lot depends on what web > >> mechanism/framework you are using. If we assume the > >> standard cgi module then you need to get the submited > >> data out of the request with the field_storage dictionary. > >> Then you need to call your search function and finally > >> format the results as HTML. Either offer to downoad a > >> particular file and have a second request start the download > >> or just send the file back, but that could be an unexpected result. > >> I'd offer the file as a link and let the user click on it to fetch > >> it > >> from the server. > >> > >> But web programming is a whole different ball game. > >> You should look up some simple examples first. > >> > >> Alan G. > >> > >> > >> _______________________________________________ > >> 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 > > > > > _______________________________________________ > 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/20070705/bc0b2054/attachment.htm From kent37 at tds.net Thu Jul 5 14:17:15 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 05 Jul 2007 08:17:15 -0400 Subject: [Tutor] (no subject) In-Reply-To: <6.1.2.0.2.20070705071108.04489890@pop.dsl.pipex.com> References: <6.1.2.0.2.20070705071108.04489890@pop.dsl.pipex.com> Message-ID: <468CE14B.1020302@tds.net> Alun Griffiths wrote: > Hi > > I am trying to build a simple model of a gas field. At the moment I have > these objects: > GasWell represents the behaviour of a gas well > GasFluid represents the thermodynamic behaviour of the gas > GasField represents the field itself > > The GasField object defines properties such as pressure and volume. The > fluid within it is represented by the GasFluid object which also defines > the properties of the fluid flowing through GasWell objects associated with > a particular GasField. GasWell can be moved from one GasField object to > another, so take the appropriate fluid behaviour from the GasFluid > associated with the GasField to which it belongs. > > At the moment, the GasField definition looks something like this > > Class GasField(Object): > def __init__(name, pres, vol, fluid, wells): > self.name=name > self.pres=pres > self.vol=vol > self.fluid=fluid # GasFluid object > self.wells=wells # List of GasWell objects > > No problems with creating the WELL list since I just append a bunch of > GasWell objects to a new list. > > The problem I have is how a particular GasWell knows which field it belongs > to. The only way I can think of so far involves some form of cross > referencing where we define the GasField with an empty WELL list, define > the GasWells by setting the field it belongs to explicitly then updating > the WELL list "externally". For example > > wells = [] > stuff = GasFluid( params ) > field = GasField("My field", p, V, stuff, wells) > well1 = GasWell(params, field) > well2 = GasWell(params, field) > well3 = GasWell(params, field) > > wells.append(well1) > wells.append(well2) > wells.append(well2) > new_field.wells = wells > > This cross-referencing of GasField and GasWells doesn't seem right to me - > if we move a well from one field to another we have to update the GasWell > object and the GasField.wells list. Is there a more pythonic (or more > sensible) way of doing this? If the well needs to know what field it is in then you are stuck with some cross-referencing. The way to keep your sanity is to make a method of GasField or GasWell that changes both, then use that method instead of direct assignment. For example, class GasField(object): def add_well(self, well): self.wells.append(well) well.field = self or, either by itself of together with the above, class GasWell(object): def add_to_field(self, field): field.add_well(self) self.field = field # don't need this if using the above add_well() You could make GasWell.field a property so it is automatically added to field.wells when you assign it. Kent From andreas at kostyrka.org Thu Jul 5 14:35:18 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 05 Jul 2007 14:35:18 +0200 Subject: [Tutor] From C to Python In-Reply-To: <891158.17770.qm@web32802.mail.mud.yahoo.com> References: <891158.17770.qm@web32802.mail.mud.yahoo.com> Message-ID: <468CE586.6050303@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Well, philosophically every object "name" is a pointer to a PyObject on C level. The only difference is, that you cannot do anything but assign these pointers (no pointer arithmetic) and memory is managed automatically. If you want to know what happens for real, you can start on the Python/C API documentation. Not the typical way to approach to learning Python, but it would certainly give you an idea what happens on the C level. And yes, you have to unlearn the C way, and it's not a bad thing. C makes you think about everything yourself. Python manages many things for you. Basically you need to move your thinking from how the CPU will achieve the goal to describing what should be done, with way less consideration for the CPU. Actually, trying to do "byte level" programming in Python will produce slow programs :) Andreas Dhruva Kulkarni wrote: > Hi, > I am a C guy wanting to switch to Python for some application-type-tasks that might be done in Python much quicker and sooner and smaller than in C...I have fiddled around with Python and looked through the tutorial, but i'm a bit lost when there are no pointers ( pun intended! ). I could not find any material on 'what-happens-when' type questions, e.g.( how functions are implemented --> stack-frame struct , parameter passing by value / reference ? ), and the whole 'identity vs equality' thing, plus the dynamic-typing-of-objects... > So i can see that Python programers must be thinking in a very un-'byte'-ly way, so do I need to unlearn the C way of wandering in 'byteland' ? And where can i find the ten commandments for Pythonland>? Thanks! > dhruva. > > > --------------------------------- > It's here! Your new message! > Get new email alerts with the free Yahoo! Toolbar. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGjOWGHJdudm4KnO0RAougAJ4qmJoBAWqBWU6nHzQX7r2T07uGBgCfYmlB XiCwHHMEuUBtsNk65CYNIl4= =04UF -----END PGP SIGNATURE----- From dhruva_lives at yahoo.com Thu Jul 5 15:24:52 2007 From: dhruva_lives at yahoo.com (Dhruva Kulkarni) Date: Thu, 5 Jul 2007 06:24:52 -0700 (PDT) Subject: [Tutor] Fwd: Re: From C to Python Message-ID: <38812.23437.qm@web32801.mail.mud.yahoo.com> Dhruva Kulkarni wrote: Date: Thu, 5 Jul 2007 06:12:13 -0700 (PDT) From: Dhruva Kulkarni Subject: Re: [Tutor] From C to Python To: Kent Johnson Thanks for the link, i was afraid it might be something like that :-) Ok, i get the idea about the referencing, but i got some (;-)) doubts : 1.if I want to duplicate some 'mutable object' , then just assignment wont work, so i'm sure there must be some way of explicitly telling the interp to duplicate ( or do i have create another list and then copy and... ) also, as an afterthought, can i also do some operator-overloading ? 2.The scoping rules in C go from innermost to outermost, does this also happen in Python? Also, i couldn't find the keywords for data encapsulation ( private protected in c++ ).. 3. I guess this list will never end, so if you could just point me to some sort of reference guide to Python.... From what Py scripts i've seen , i guess Python is capable of doing tasks easily, as compared to C, at the expense of hiding some lower details from the programmer. Very cool for applications. But, ( talking at a *very* high level), supposing i have to build an application that has to do some concurrent tasks ( each task is a diff process/thread ), and some sort of IPC is necessary(signals etc) , and also performance profiling of each thread is necessary ( for balancing sub-system bandwidths etc ), then is Python the way to go for this too? I had originally intended to use Python just for some cosmetic UI applets that look and feel nice and are a pain to code in C/c++, and do the *real* thing in C/C++, but i would like to know if Python can be used here as well...( I read some *scary* comments about the multi-threading module of Python and the Global Interpreter Lock... ) Thnks for your time, dhruva Kent Johnson wrote: Dhruva Kulkarni wrote: > Hi, > I am a C guy wanting to switch to Python for some > application-type-tasks that might be done in Python much quicker and > sooner and smaller than in C...I have fiddled around with Python and > looked through the tutorial, but i'm a bit lost when there are no > pointers ( pun intended! ). I could not find any material on > 'what-happens-when' type questions, e.g.( how functions are implemented > --> stack-frame struct , parameter passing by value / reference ? ), > and the whole 'identity vs equality' thing, plus the > dynamic-typing-of-objects... > So i can see that Python programers must be thinking in a very > un-'byte'-ly way, so do I need to unlearn the C way of wandering in > 'byteland' ? And where can i find the ten commandments for Pythonland>? Yes, you need to leave your C ways behind. Don't worry, you'll like it here :-) The biggest shift is in the way you think about variables. In C, a variable is a container for a value. In Python, a variable is a name for a value; a reference. In C terms, think of it as a pointer to a value. This might help, especially the introduction :-) http://effbot.org/zone/python-objects.htm There is a lot of dispute over what to call the semantics of argument passing (pass by value? pass by reference?), but the concept is pretty simple. Function arguments are references that are bound to names in the local scope of the function. The reference is passed by value. One name for this is "call by object reference". In C terms, if you think of variables as pointers to values, and argument passing as copying the pointer, you will get the idea. BTW the semantics of assignment and those of argument passing are identical - they both bind a name to a value in the local scope. One consequence of this is that aliasing happens all the time. If two names are bound to the same mutable object, any changes to the object are visible through either name: In [11]: a=[1, 2, 3] In [12]: b=a In [13]: a.append(4) In [14]: a Out[14]: [1, 2, 3, 4] In [15]: b Out[15]: [1, 2, 3, 4] You really don't have to worry about stack frames and how functions are implemented (they are objects too), at least not initially, just let Python take care of it for you. I wouldn't worry about identity vs equality, either; usually you are interested in equality. I don't know about ten commandments, but you can see the Zen of Python by typing 'import this' at the Python interpreter prompt. Kent --------------------------------- Don't get soaked. Take a quick peak at the forecast with theYahoo! Search weather shortcut. --------------------------------- Get your own web address. Have a HUGE year through Yahoo! Small Business. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070705/9cc6bce4/attachment.htm From alan.gauld at btinternet.com Thu Jul 5 16:41:42 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Jul 2007 15:41:42 +0100 Subject: [Tutor] Help search files References: Message-ID: "Alejandro Decchi" wrote > Yes i am a newbie in web design but i understand the concept of CGI. OK, I'll ignore that aspect for now. > My problem is that I do not know how to do a search based in binary > files.For example a user conect to my webpage and dicide to search > windows.iso he write in the textbox and put submit and must appear > the > result to download the link. You said that you were searching the file name not the content so it makes no difference if the file is text or binary. Use glob.glob to get a list of files matching a pattern. Or, use os.listdir to get all files and then manually compare each filename to your input pattern. Here is a very simple example using glob ################# import glob pattern = raw_input("What file name? ") for filename in glob.glob(pattern): print filename, "matches", pattern ################## Now, what still puzzles you? -- 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 Jul 5 17:08:45 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Jul 2007 16:08:45 +0100 Subject: [Tutor] From C to Python References: <38812.23437.qm@web32801.mail.mud.yahoo.com> Message-ID: "Dhruva Kulkarni" wrote > Ok, i get the idea about the referencing, but i got some (;-)) > doubts : Many C/C++ programs find the transition a bit scary at first because they are giving up control of the low level details. But the truth is that in higher level languages like Python (and Lisp and smalltalk etc) you just don't need that level of control. You are not hand carving the thing from a solid tree trunk, you are assembling prefabricated items from the building yard. > 1.if I want to duplicate some 'mutable object' , then > just assignment wont work, so i'm sure there must > be some way of explicitly telling the interp to duplicate Yes, you can use the copy methods/modules. For simple sequence types you can use slicing: a = [1,2,3] b = a # a refernce to the same list c = a[:] # a copy of the list > ( or do i have create another list and then copy No, take a copy using the slice. > can i also do some operator-overloading ? Yes, you can define the operator methods (__add__, __mul__ etc) for any class you define. > 2.The scoping rules in C go from innermost to outermost, > does this also happen in Python? Sort of, but they are different and you should read up on the namespaces and scoping rules in the docs. > Also, i couldn't find the keywords for data encapsulation > ( private protected in c++ ).. A foolish overhyped concept thats rarely used in Python or indeed most dynamically typed OO languages) :-) Actually you can pull a few tricks that partially hide data but in practice most Python classes use the approach that we are all consenting adults and should use the methods as intended and not mess with data directly wherever possible. (A naming convention of a leading underscore is often used to suggest that the data should not be accessed directly) More seriously, much of the data protection used in C++ is due to the contraints of using a static, strictly typed data model. Once you get used to doing OOP using dynamic typing the need for that level of control becomes much lower. Again its the C/C++ culture of absolute control of the data showing through. Thats only really needed when you have to worry about byte alignment and register usage etc etc. > 3. I guess this list will never end, so if you could just > point me to some sort of reference guide to Python.... The language reference and other documentation is pretty good. > But, ( talking at a *very* high level), supposing i have to > build an application that has to do some concurrent tasks > ( each task is a diff process/thread ), and some sort of IPC > is necessary(signals etc) , Multi threading and IPC are easily achieved using pipes, sockets, XML/RPC and SOAP. There are also CORBA compliant ORBs and other middleware exotica available > performance profiling of each thread is necessary I haven't tried profiling threads, but it may be possible. I'm not sure how refined the profiling module is for threading. > use Python just for some cosmetic UI applets that look > and feel nice and are a pain to code in C/c++, and do > the *real* thing in C/C++, The beauty of python is you can quickly prototype the whole thing in Python then bit by bt replace the functions with C/C++/Java whatever. The surprising thing is how little of it you need to replace in most cases! But the old adage of get it working before optimising it works here too. > ( I read some *scary* comments about the multi-threading > module of Python and the Global Interpreter Lock... ) I don't know of any foolproof threading scvheme, but python works if you follow the rules. If you start trying to do "clever" things outside those boundaries then scary things can start to happen. But you rarely need to do that if you let the language do the work and trust it to get it right. 99% of the time it does! And for the fancy stuff some C and a SWIG wrapper can soon make it available in python... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From wcyeee at gmail.com Thu Jul 5 17:23:04 2007 From: wcyeee at gmail.com (wc yeee) Date: Thu, 5 Jul 2007 11:23:04 -0400 Subject: [Tutor] lambda: print('x') raises SyntaxError? Message-ID: Hi. Is there a reason the code below raises a syntax error? It's probably something silly on my part, but I can't figure it out: >>> b = lambda: print('bar') File "", line 1 b = lambda: print('bar') ^ SyntaxError: invalid syntax This code seems to work fine, so I don't know why the "print" statement in the above code is wrong. >>> print('bar') bar This works fine too: >>> import sys >>> a = lambda: sys.stdout.write('foo\n') >>> a() foo What am I missing? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070705/06e84473/attachment.htm From kent37 at tds.net Thu Jul 5 17:33:04 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 05 Jul 2007 11:33:04 -0400 Subject: [Tutor] From C to Python In-Reply-To: References: <38812.23437.qm@web32801.mail.mud.yahoo.com> Message-ID: <468D0F30.4000403@tds.net> Alan Gauld wrote: > "Dhruva Kulkarni" wrote >> Also, i couldn't find the keywords for data encapsulation >> ( private protected in c++ ).. > > More seriously, much of the data protection used in C++ is > due to the contraints of using a static, strictly typed data model. > Once you get used to doing OOP using dynamic typing the > need for that level of control becomes much lower. Again its > the C/C++ culture of absolute control of the data showing through. > Thats only really needed when you have to worry about byte > alignment and register usage etc etc. Reminiscing...when I first learned Java I was doing a lot of C++ coding. For a while I missed the expressiveness of C++, where you can say *exactly* what you mean, for example in the use of const. After a while I realized that all that expressiveness didn't really buy me much safety or functionality, and that I was better off without it because it is just less to think about. Switching from Java to Python I had to give up on static typing and realize that again, it is a lot of conceptual and (finger) typing overhead that doesn't really buy that much in safety or functionality. Python skips all the bondage-and-discipline and goes straight to working code ;-) Now I look at Java and cringe and can't imaging writing C++...the biggest risk of learning Python is that you won't want to use any other language again :-) Kent From kent37 at tds.net Thu Jul 5 17:34:59 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 05 Jul 2007 11:34:59 -0400 Subject: [Tutor] lambda: print('x') raises SyntaxError? In-Reply-To: References: Message-ID: <468D0FA3.1090902@tds.net> wc yeee wrote: > Hi. Is there a reason the code below raises a syntax error? It's > probably something silly on my part, but I can't figure it out: > > > >>> b = lambda: print('bar') > File "", line 1 > b = lambda: print('bar') > ^ > SyntaxError: invalid syntax The body of a lambda has to be an expression, not a statement. print is a statement. > > > This code seems to work fine, so I don't know why the "print" statement > in the above code is wrong. Don't know how it can work fine if it won't compile; what's your secret? ;-) > This works fine too: > > >>> import sys > >>> a = lambda: sys.stdout.write('foo\n') > >>> a() > foo Right, that is an expression and it is the workaround for your original problem. Kent From tnoyeaux at msn.com Thu Jul 5 18:33:13 2007 From: tnoyeaux at msn.com (Tony Noyeaux) Date: Thu, 5 Jul 2007 12:33:13 -0400 Subject: [Tutor] Guidance on a Begginer Project. Message-ID: Taking on a pet project to teach myself some things and hone some amateur skills.Wondering if you could help point me in the right direction and assist me with some technical points as i get stuck.I have a basic idea of how i would do this,... but i'm not sure whether it is the best way. So ... hence my guidance seeking.Stage 1 will be a small prototype program,... once i can get it all workin in small form, i will then expand it greatly to an end state that i'm looking for.Once the program executes. The user will be asked to choose between 3 things.. listed as option ABC or 123. Once they choose,... a random code, ... will give them a result based on their choice. Then they will be given 3 more choices. Random code again.Just 2 questions asked overall... ending with a summary based on what happened based on their responces.eg.1st Phase choose A, B or CIf you choose A,... random result of DEF can happenIf you choose B,... random result of GHI can happenIf you choose C,... random result of JKL can happen2nd Phase You are given another choice based on the random result above.Person chose C, their random result was LFrom L, they are given 3 things to choose from.If they choose A... random result of MNO can happenIf they choose B... random result of PQR can happenIf they choose C... random result of STU can happen... summary given...You choose to do 'x'.... as a result the first random result,.. this led you into situation b.. and you chose 'y'... as a result ... this is what happened.So there will be alot of stored data as potential outcomes stored.From choice 1,... 9 possible outcomes.After Choice 2... could see upto 81 different outcomes 9x9So over all there would be 90 total outcomes listed in a table. To be randomly drawn form...., ... How would you begin coding this..., let me know the best way for me to nut this out. I hope it will teach me alot as a i go.Once i have this small prototype built.. i plan to expand it.Project 2 i want to have 'weighted randoms' if possible.. making some out comes more likely then others. Having more choses, more phases.Any assistence would be greatly appreciated.Tony Noyeaux _________________________________________________________________ Missed the show?? Watch videos of the Live Earth Concert on MSN. http://liveearth.msn.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070705/40ae5a04/attachment.html From wescpy at gmail.com Thu Jul 5 18:36:27 2007 From: wescpy at gmail.com (wesley chun) Date: Thu, 5 Jul 2007 09:36:27 -0700 Subject: [Tutor] lambda: print('x') raises SyntaxError? In-Reply-To: <468D0FA3.1090902@tds.net> References: <468D0FA3.1090902@tds.net> Message-ID: <78b3a9580707050936k50729574j98c1b65f035029b1@mail.gmail.com> On 7/5/07, Kent Johnson wrote: > wc yeee wrote: > > Hi. Is there a reason the code below raises a syntax error? It's > > probably something silly on my part, but I can't figure it out: > > > > > > >>> b = lambda: print('bar') > > File "", line 1 > > b = lambda: print('bar') > > ^ > > SyntaxError: invalid syntax > > The body of a lambda has to be an expression, not a statement. print is > a statement. > > > > > This works fine too: > > > > >>> import sys > > >>> a = lambda: sys.stdout.write('foo\n') > > >>> a() > > foo > > Right, that is an expression and it is the workaround for your original > problem. one thing to keep in mind when thinking, "is this an expression or a statement?" is that the former will always evaluate to some sort of Python object (numerical calculation, function return value [your case above], some string you've built, etc.) whereas the latter will not have any kind of intrisic value (print, while, if, class, def... none of these have a "value"). on a partially-related note, print will be changing to a function in the next generation of Python... see PEP 3105: http://www.python.org/dev/peps/pep-3105/ for a list of some of the other changes coming down the line: http://www.python.org/dev/peps/pep-3100/ cheers, -- 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 nephish at gmail.com Thu Jul 5 18:40:16 2007 From: nephish at gmail.com (shawn bright) Date: Thu, 5 Jul 2007 11:40:16 -0500 Subject: [Tutor] help with translating a c function to a python function Message-ID: <384c93600707050940i75d2bd72kd66bbe0356c010b7@mail.gmail.com> hello all, i have a c function from some modbus documentation that i need to translate into python. it looks like this: unsigned short CRC16(puchMsg, usDataLen) unsigned char *puchMsg ; unsigned short usDataLen ; { unsigned char uchCRCHi = 0xFF ; unsigned char uchCRCLo = 0xFF ; unsigned uIndex ; while (usDataLen??) { uIndex = uchCRCHi ^ *puchMsgg++ ; uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ; uchCRCLo = auchCRCLo[uIndex] ; } return (uchCRCHi << 8 | uchCRCLo) ; } some of it i can make out, but i can't seem to figgure out this part ' auchCRCHi[uIndex}; it looks like a typo, because there is a closing } that does not match the opening [. anyway, if someone could kinda give me a push, it would help me out a lot. thanks From alan.gauld at btinternet.com Thu Jul 5 19:22:28 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Jul 2007 18:22:28 +0100 Subject: [Tutor] Guidance on a Begginer Project. References: Message-ID: "Tony Noyeaux" wrote > ...could see upto 81 different outcomes 9x9So over all there would > be 90 total outcomes listed in a table. I'd probably go for a set of nested dictionaries (or maybe just lists) and data drive the code. Thus the code becomes fairly trivial and the complexity lies in the data, which is easily extended. If you go down that rtoute think about the structure both in data terms but also how you will layout the code in your file. choices = { 1 : { A : { X: 'Some Outcome', Y : 'Some other' } B : { P: 'Another', Q: 'More' } } 2 : { C: ...etc... } Now the first choice (c1) is one of choices.keys() The second choice (c2) is one of choices[c1].keys() and the outcome is one of choices[c1][c2].keys() You may need to tweak that but hopefully it gives some kind of idea. Let the data structure guide the code for problems of this type. HTH, Alan G. From nephish at gmail.com Thu Jul 5 19:29:31 2007 From: nephish at gmail.com (shawn bright) Date: Thu, 5 Jul 2007 12:29:31 -0500 Subject: [Tutor] help with translating a c function to a python function In-Reply-To: <384c93600707050940i75d2bd72kd66bbe0356c010b7@mail.gmail.com> References: <384c93600707050940i75d2bd72kd66bbe0356c010b7@mail.gmail.com> Message-ID: <384c93600707051029i6b6c5dd1lf5e5f20431b2fc77@mail.gmail.com> oh, here is what i have so far, but is not giving me the right values def crc16(data): crc_hi = 0xff crc_lo = 0xff for x in data: crc_index = crc_hi ^ x crc_hi = crc_lo ^ (crc_hi | crc_index) crc_lo = crc_lo | crc_index return (crc_hi << 8 | crc_lo) whaddya think? On 7/5/07, shawn bright wrote: > hello all, > > i have a c function from some modbus documentation that i need to > translate into python. > > it looks like this: > > > unsigned short CRC16(puchMsg, usDataLen) > unsigned char *puchMsg ; > unsigned short usDataLen ; > { > unsigned char uchCRCHi = 0xFF ; > unsigned char uchCRCLo = 0xFF ; > unsigned uIndex ; > while (usDataLen??) > { > uIndex = uchCRCHi ^ *puchMsgg++ ; > uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ; > uchCRCLo = auchCRCLo[uIndex] ; > } > return (uchCRCHi << 8 | uchCRCLo) ; > } > > some of it i can make out, but i can't seem to figgure out > this part ' auchCRCHi[uIndex}; > it looks like a typo, because there is a closing } that does not match > the opening [. > > anyway, if someone could kinda give me a push, it would help me out a lot. > thanks > From alan.gauld at btinternet.com Thu Jul 5 19:29:11 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Jul 2007 18:29:11 +0100 Subject: [Tutor] help with translating a c function to a python function References: <384c93600707050940i75d2bd72kd66bbe0356c010b7@mail.gmail.com> Message-ID: "shawn bright" wrote while (usDataLen??) { uIndex = uchCRCHi ^ *puchMsgg++ ; uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ; uchCRCLo = auchCRCLo[uIndex] ; } return (uchCRCHi << 8 | uchCRCLo) ; } > this part ' auchCRCHi[uIndex}; > it looks like a typo, because there is a closing } that does not > match > the opening [. Its probably a typo but there is one (pretty remote, and horrible) possible way for it to be valid which is if uIndex is a macro that expands to complete the square bracket expression and introduce an expression which needs a brace to finish it. But thats just perverse, so I think its a mistake! (Especially since I just noticed uIndex is used elsewhere without any closing brace) Alan G. From jjcrump at myuw.net Thu Jul 5 19:29:54 2007 From: jjcrump at myuw.net (Jon Crump) Date: Thu, 5 Jul 2007 10:29:54 -0700 (PDT) Subject: [Tutor] UTF-8 title() string method In-Reply-To: <468C0407.1080406@tds.net> References: <1183449091.12516.64.camel@localhost.localdomain> <1183505867.3391.13.camel@localhost.localdomain> <468C0407.1080406@tds.net> Message-ID: On Wed, 4 Jul 2007, Kent Johnson wrote: > First, don't confuse unicode and utf-8. Too late ;-) already pitifully confused. > Second, convert the string to unicode and then title-case it, then convert > back to utf-8 if you need to: I'm having trouble figuring out where, in the context of my code, to effect these translations. In parsing the text file, I depend on matching a re: if re.match(r'[A-Z]{2,}', line) to identify and process the place name data. If I translate the line to unicode, the re fails. The whole program isn't very long, so at the risk of embarrassing myself, I'm including the whole ugly, kludgy thing below. I hope I'm not hereby violating any conventions of the list. Kent will recognize the ranges() function (which works a treat, by the way, and was very instructive, thanks). In addition to the title case problem, if anyone has pointers on how to make this look a little less like a Frankenstein's monster (all improbably bolted together), such tutelage would be gratefully recieved. The end product is intended to be a simple xml file and, apart from the title case problem it works well enough. A sample of the text file input is included at the bottom. #!/usr/bin/python import re input = open('sample.txt', 'r') text = input.readlines() months = {'January':1, 'February':2, 'March':3, 'April':4, 'May':5, 'June':6, 'July':7, 'August':8, 'September':9, 'October':10, 'November':11, 'December':12} def ranges(data): i = iter(data) first = last = i.next() try: while True: next = i.next() if next > last+1: yield (first, last) first = last = next else: last = next except StopIteration: yield (first, last) def parse_month_string(monthstring, year, title): res=[] monthstring_regex = re.compile('^(\w+)\s+(\d.*)\.$') monthstring_elements = monthstring_regex.match(monthstring) month = monthstring_elements.group(1) days = ranges([int(x) for x in re.split(',', monthstring_elements.group(2))]) for start, end in days: if start == end: res.append('' % (year, months[month], start, title.strip())) else: res.append('' % (year, months[month], start, year, months[month], end, title.strip())) return res def parse_year_string(yearstring, title): res=[] yearstring_regex = re.compile('(\d\d\d\d)\.\s+(\w+)\s+(\d.*)\.$') yearstring_elements = yearstring_regex.match(yearstring) year = yearstring_elements.group(1) month = yearstring_elements.group(2) days = ranges([int(x) for x in re.split(',', yearstring_elements.group(3))]) for start, end in days: if start == end: res.append('' % (year, months[month], start, title.strip())) else: res.append('' % (year, months[month], start, year, months[month], end, title.strip())) return res def places(data): place=[data[0]] for line in data: if re.match(r'[A-Z]{2,}', line): if place: yield place place = [] place.append(line.strip()) elif re.match(r'(\d\d\d\d)\.\s+(\w+)\s+(\d.*)\.$', line): yearstring_regex = re.compile('(\d\d\d\d)\.\s+(\w+)\s+(\d.*)\.$') yearstring_elements = yearstring_regex.match(line) year = yearstring_elements.group(1) title = place[0] place.append(parse_year_string(line, title)) elif re.match(r'^(\w+)\s+(\d.*)\.$', line): place.append(parse_month_string(line, year, title)) yield place for x in places(text): for y in x[1:]: for z in y: print z ############# here begins sample of the text file input: ABERGAVENNY, Monmouthshire. 1211. March 12. ALEN?ON, Normandie. 1199. November 3. 1200. September 6, 7. 1201. July 18. 1202. February 20, 21. August 8, 9, 10, 12. September 29. 1202. October 3, 29. December 7. 1203. January 15, 16, 17, 18, 19, 25. August 11, 12, 13, 14, 15. ALLERTON, Yorkshire. 1201. February 28. 1212. June 29. September 1, 2, 6. 1213. February 6, 7. September 16. 1216. January 6. ANDELY (le Petit), Normandie. 1199. August 18, 19, 28, 29, 30, 31. September 1. October 21, 26, 27. 1200. January 11. May 11, 12, 17. May 18, 19, 20, 21, 22, 23, 24, 25, 26. 1201. June 9, 10, 11, 25, 26, 27. October 23, 24, 25, 26, 28. December 15. 1202. March 27, 28, 29. April 4, 22, 23, 24, 25, 26, 28. ANGERS, Anjou. 1200. June 18, 19, 20, 21. 1202. September 4, 15. 1206. September, 8, 9, 10, 11, 12, 13, 20, 21. 1214. June 17, 18. ANGOUL?ME, Angoumois. 1200. August 26. 1202. February 4, 5. 1214. March 13, 14, 15. April 5, 6. July 28, 29, 30. August 17, 18. ANVERS-LE-HOMONT, Maine. 1199. September 18. From nephish at gmail.com Thu Jul 5 19:52:22 2007 From: nephish at gmail.com (shawn bright) Date: Thu, 5 Jul 2007 12:52:22 -0500 Subject: [Tutor] help with translating a c function to a python function In-Reply-To: References: <384c93600707050940i75d2bd72kd66bbe0356c010b7@mail.gmail.com> Message-ID: <384c93600707051052h2264dcc2kf6ef02299c485c31@mail.gmail.com> Thanks Alan, so do you think my translation is close? i do not know a lick of c. Nope, not one line. thanks shawn On 7/5/07, Alan Gauld wrote: > > "shawn bright" wrote > while (usDataLen??) > { > uIndex = uchCRCHi ^ *puchMsgg++ ; > uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ; > uchCRCLo = auchCRCLo[uIndex] ; > } > return (uchCRCHi << 8 | uchCRCLo) ; > } > > > this part ' auchCRCHi[uIndex}; > > it looks like a typo, because there is a closing } that does not > > match > > the opening [. > > Its probably a typo but there is one (pretty remote, and horrible) > possible way for it to be valid which is if uIndex is a macro that > expands to complete the square bracket expression and introduce > an expression which needs a brace to finish it. But thats > just perverse, so I think its a mistake! (Especially since I just > noticed uIndex is used elsewhere without any closing brace) > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Thu Jul 5 19:52:54 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 05 Jul 2007 13:52:54 -0400 Subject: [Tutor] UTF-8 title() string method In-Reply-To: References: <1183449091.12516.64.camel@localhost.localdomain> <1183505867.3391.13.camel@localhost.localdomain> <468C0407.1080406@tds.net> Message-ID: <468D2FF6.8030607@tds.net> Jon Crump wrote: > On Wed, 4 Jul 2007, Kent Johnson wrote: >> First, don't confuse unicode and utf-8. > > Too late ;-) already pitifully confused. This is a good place to start correcting that: http://www.joelonsoftware.com/articles/Unicode.html >> Second, convert the string to unicode and then title-case it, then >> convert back to utf-8 if you need to: > > I'm having trouble figuring out where, in the context of my code, to > effect these translations. if s is your utf-8 string, instead of s.title(), use s.decode('utf-8').title().encode('utf-8') > In parsing the text file, I depend on > matching a re: > > if re.match(r'[A-Z]{2,}', line) > > to identify and process the place name data. If I translate the line to > unicode, the re fails. I don't know why that is, re works with unicode strings: In [1]: import re In [2]: re.match(r'[A-Z]{2,}', 'ABC') Out[2]: <_sre.SRE_Match object at 0x12078e0> In [3]: re.match(r'[A-Z]{2,}', u'ABC') Out[3]: <_sre.SRE_Match object at 0x11c1f00> Kent From jjcrump at myuw.net Thu Jul 5 20:26:31 2007 From: jjcrump at myuw.net (Jon Crump) Date: Thu, 5 Jul 2007 11:26:31 -0700 (PDT) Subject: [Tutor] UTF-8 title() string method In-Reply-To: <468D2FF6.8030607@tds.net> References: <1183449091.12516.64.camel@localhost.localdomain> <1183505867.3391.13.camel@localhost.localdomain> <468C0407.1080406@tds.net> <468D2FF6.8030607@tds.net> Message-ID: On Thu, 5 Jul 2007, Kent Johnson wrote: >> First, don't confuse unicode and utf-8. > > Too late ;-) already pitifully confused. > This is a good place to start correcting that: > http://www.joelonsoftware.com/articles/Unicode.html Thanks for this, it's just what I needed! > if s is your utf-8 string, instead of s.title(), use > s.decode('utf-8').title().encode('utf-8') Eureka! I was trying to make the round-trip _way_ too complicated. >> to identify and process the place name data. If I translate the line to >> unicode, the re fails. > > I don't know why that is, re works with unicode strings: > In [1]: import re > In [2]: re.match(r'[A-Z]{2,}', 'ABC') > Out[2]: <_sre.SRE_Match object at 0x12078e0> > In [3]: re.match(r'[A-Z]{2,}', u'ABC') > Out[3]: <_sre.SRE_Match object at 0x11c1f00> Of course. I was misinterpreting why things were failing. It wasn't the regex, it was the decode() encode() round-trip. (a powerful argument for getting familiar with try/except error handling!) Again, many thanks for the education! Jon From alan.gauld at btinternet.com Thu Jul 5 23:22:03 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Jul 2007 22:22:03 +0100 Subject: [Tutor] help with translating a c function to a python function References: <384c93600707050940i75d2bd72kd66bbe0356c010b7@mail.gmail.com> <384c93600707051029i6b6c5dd1lf5e5f20431b2fc77@mail.gmail.com> Message-ID: "shawn bright" wrote > oh, here is what i have so far, but is not giving me the right > values > > def crc16(data): > crc_hi = 0xff > crc_lo = 0xff > for x in data: > crc_index = crc_hi ^ x So far so good.. > crc_hi = crc_lo ^ (crc_hi | crc_index) But the C code here is: > uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ; > crc_lo = crc_lo | crc_index now I assume the a in front indicates an array - which since its not defined locally must be global somewhere. And they are indexing it So your code should be something like: crc_hi = crc_lo ^ CRC_hiList[crc_index] > uchCRCLo = auchCRCLo[uIndex] ; and crc_lo = CRC_loList[crc_index] return (crc_hi << 8 | crc_lo) > whaddya think? I think I'm guessing quite a lot and that your C function is not truly standalone. :-) But I think the corrupt operations are indexes into an array. But where the array is defined is anyones guess. And in C a pointer can also be an array so auchCRCHi could be defined as SOMETYPE *auchCRCHi or SOMETYPE auchCRCHi[n] HTH, Alan G. On 7/5/07, shawn bright wrote: > hello all, > > i have a c function from some modbus documentation that i need to > translate into python. > > it looks like this: > > > unsigned short CRC16(puchMsg, usDataLen) > unsigned char *puchMsg ; > unsigned short usDataLen ; > { > unsigned char uchCRCHi = 0xFF ; > unsigned char uchCRCLo = 0xFF ; > unsigned uIndex ; > while (usDataLen??) > { > uIndex = uchCRCHi ^ *puchMsgg++ ; > uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ; > uchCRCLo = auchCRCLo[uIndex] ; > } > return (uchCRCHi << 8 | uchCRCLo) ; > } > > some of it i can make out, but i can't seem to figgure out > this part ' auchCRCHi[uIndex}; > it looks like a typo, because there is a closing } that does not > match > the opening [. > > anyway, if someone could kinda give me a push, it would help me out > a lot. > thanks > _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From hunter92383 at gmail.com Thu Jul 5 23:30:58 2007 From: hunter92383 at gmail.com (elis aeris) Date: Thu, 5 Jul 2007 14:30:58 -0700 Subject: [Tutor] Fastest way to iterate through a file In-Reply-To: <674d5ce60707011334n68ae9565ka7525740108d6e17@mail.gmail.com> References: <468050D5.3020403@tds.net> <674d5ce60707011334n68ae9565ka7525740108d6e17@mail.gmail.com> Message-ID: <674d5ce60707051430u127ef70dp606fda6d5dae1440@mail.gmail.com> I need some of a something to be imported into python these are the functions I need, anyway know anything that might do any of the following? Eg: suppose the class' name is autowindow: autowindow.gainfocus(handle) put the window of that handle into focus. import autowindow autowindow.imagechecksum() autowindow.imagechecksum("c:\image\image.bmp") autowindow.areachecksum() sum = autowindow.areachecksum(x1,y1,x2,y2) absolute screen coordinate autowindow.getmousepos() pos = autowindow.getmousepos() pos = {x, y} autowindow.restart() reboot computer autowindow.shutdown() shutdown computer autowindow.winexist() true/false = autowindow.winexist() handle or window name. (no class wanted!) autowindow.listwindows() autowindow.listwindows("window name") returns a list of handles if multiple window of the same name. autowindow.GainFocus() autowindow.GainFocus() window name or handle autowindow.KeyboardEvent(text) autowindow.KeyboardEvent("Python rocks!", keyholddelay ) keyholddelay = miliseconds. autowindow.mouseclick(button, clicks) autowindow.MouseEvent(x, y, button, clicks) autowindow.mousemove() autowindow.mousemove(x,y, speed) autowindow.winMove(x, y) autowindow.winResize(x, y) autowindow.winMinimize() autowindow.winMaximize() autowindow.winClose() they all take handle autowindow.listwindows() autowindow.listwindows("window name") returns a list of handles if multiple autowindow.hotkey() autowindow.hotkey(keyboard key, function) keyboard key = any key on keyboard function = function to start auntwindow.run ( /source/exe.exe, "image.bmp" ) autowindow.msgbox("window name", "window message", box_number ) box_number = 1, 2, 3 OK = 1 OK + Cancel = 2 Yes + No = 3 return = autowindow.msgbox("window name", "window message", box_number ) return ok = 1 cancel = 2 yes = 3 no = 4 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070705/71c5d41a/attachment.htm From picioslug at gmail.com Fri Jul 6 00:57:50 2007 From: picioslug at gmail.com (Picio) Date: Fri, 6 Jul 2007 00:57:50 +0200 Subject: [Tutor] python and javascript Message-ID: <825bef0c0707051557uc811a3eifdbb1c237d35d75@mail.gmail.com> Hello, I'd like to have some advice about a good mailing list about javascript. I'm asking here because I'd like to have both python and javascript people on the same mailing list. My idea is that some of you participates also in other mailing lists and maybe some of those are about javascript: knowledge mix !?!?! I know It's a strange question, please don't become mad at me. I'm currentlu involved in a project where I will use javascript and python and I don't know any mailing list about the former... Thanks a lot. Daniele -- http://picio.gotdns.com/wordpress/ ...my blog on NSLU2 From alan.gauld at btinternet.com Fri Jul 6 01:03:46 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 6 Jul 2007 00:03:46 +0100 Subject: [Tutor] Fastest way to iterate through a file References: <468050D5.3020403@tds.net> <674d5ce60707011334n68ae9565ka7525740108d6e17@mail.gmail.com> <674d5ce60707051430u127ef70dp606fda6d5dae1440@mail.gmail.com> Message-ID: "elis aeris" >I need some of a something to be imported into python Maybe. > these are the functions I need, anyway know anything that might do > any of > the following? Assuming you are still talking about Windows XP... > suppose the class' name is autowindow: What kind of class? No such class exists so are you proposing to create it? Is it based on a Windows object? Remember python is a programming language not a GUI toolkit. If you want to do things to a GUI you need a toolkit. It might be linked to the native Win32 API through winall or ctypes or it might be a cross platform toolkit like Tkinter or wxPython, but its not part of Python. > autowindow.gainfocus(handle) > put the window of that handle into focus. The Win32 SetFocus function does that. > import autowindow > autowindow.imagechecksum() > autowindow.imagechecksum("c:\image\image.bmp") > autowindow.areachecksum() > > sum = autowindow.areachecksum(x1,y1,x2,y2) absolute screen > coordinate Its unlikely any GUI toolkit will do that, it sounds more like a job for a graphics toolkit like PIL. > autowindow.getmousepos() Mouse events carry the x/y coordinates. Just trap any mouse move and it will tell you where it is. > autowindow.restart() > autowindow.shutdown() This is hardware dependant, some computers won;t allow it. But on Windows you can try using the API as described on this page (which I found with a simple google search on Win32 restart shutdown) http://blogs.msdn.com/brad_mccabe/archive/2005/03/02/383542.aspx > autowindow.winexist() > true/false = autowindow.winexist() > handle or window name. (no class wanted!) FindWindow will effectively do this. > autowindow.listwindows() EnumWindows does this for you We discussed both of these recently. > autowindow.GainFocus() You already asked for this. > autowindow.KeyboardEvent(text) Yep, all toolkits allow you to trap a keyboard event. Most distinguish between key down and key up as well as the generic keypress. Or if you want to simulate a keyboard event you can use PostMessage. Again we discussed this recently. > autowindow.KeyboardEvent("Python rocks!", keyholddelay ) > keyholddelay = miliseconds. No idea what this is supposed to be/do. > autowindow.mouseclick(button, clicks) > autowindow.MouseEvent(x, y, button, clicks) > autowindow.mousemove() > autowindow.mousemove(x,y, speed) > autowindow.winMove(x, y) > autowindow.winResize(x, y) > autowindow.winMinimize() > autowindow.winMaximize() > autowindow.winClose() These are all standard event types. > they all take handle And if you want to simulate them use PostMessage > autowindow.listwindows() > autowindow.listwindows("window name") > returns a list of handles if multiple You are repeating yourself again. > autowindow.hotkey() > autowindow.hotkey(keyboard key, function) > keyboard key = any key on keyboard > function = function to start Not sure, there may be a Windows function for this but I haven't seen it... > auntwindow.run ( /source/exe.exe, "image.bmp" ) Try ExecFile or WinExec > autowindow.msgbox("window name", "window message", box_number ) Standard windows MsgBox function Have you actually tried looking for these on MSDN for yourself. They are standard windows functions. They are mapped into Python by the toolkirs but the basic functions are pure windows and documented in MSDN. Recall I recommended reading the web page on how to ask smart questions? One of the key points is not to ask the same questions multiple times of the same audience - and especially not in the same message! Also provide some context abvout why you need the information. What you are trying to achieve etc. Othewise you will get the same level of vagueness back that you provide. -- 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 Jul 6 01:32:58 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 6 Jul 2007 00:32:58 +0100 Subject: [Tutor] python and javascript References: <825bef0c0707051557uc811a3eifdbb1c237d35d75@mail.gmail.com> Message-ID: "Picio" wrote > I know It's a strange question, please don't become mad at me. I'm > currentlu involved in a project where I will use javascript and > python Not so strange. JavaScript is the undoubted king of browser side scripting, Python doesn't really play in that arena at all. Most web apps will need at least some JavaScript on the client side, even if the main app is in Python. Indeed the TurboGears web framework includes mochikit which is designed to make JavaScript easier for Python programmers by adding python like features to JavaScript. However any help I've needed for my very basic JavaScript code has been obtained fom the main JavaScript newsgroup: comp.lang.javascript HTH, Alan G From rabidpoobear at gmail.com Fri Jul 6 04:04:17 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 05 Jul 2007 21:04:17 -0500 Subject: [Tutor] (no subject) In-Reply-To: <6.1.2.0.2.20070705071108.04489890@pop.dsl.pipex.com> References: <6.1.2.0.2.20070705071108.04489890@pop.dsl.pipex.com> Message-ID: <468DA321.9040305@gmail.com> [snip e-mail] > > Thanks in advance > > Alun Griffiths > > Alun - Please use a relevant subject line next time you start a thread - all these (no subject) e-mails wreak havoc on those of us who have our e-mail clients set up to display e-mails as threads, rather than just sorted by date. Whenever a message with this subject is sent to the list, it revives a thread I've had since 2006, which is, as you could probably imagine, a few hundred entries long, and I have to scroll through to find your e-mail. Additionally, it is more likely that you will get help if people can tell just from the subject line what your general problem is. -Luke From rfquerin at gmail.com Fri Jul 6 06:40:56 2007 From: rfquerin at gmail.com (Richard Querin) Date: Fri, 6 Jul 2007 00:40:56 -0400 Subject: [Tutor] How can I escape a pound symbol in my script? Message-ID: <7d81675b0707052140s1aeb8850yee1c4a5002bc31c1@mail.gmail.com> Hi, I'm writing a very simple python script which writes out some predefined text to a file (which will later become part of an html file). I need to write out a pound sign '#' to the file and I can't figure out how to escape it. I've tried '\#' and '\u0023', but neither works. How can I do it? Thanks. RQ From rikard.bosnjakovic at gmail.com Fri Jul 6 06:50:32 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Fri, 6 Jul 2007 06:50:32 +0200 Subject: [Tutor] How can I escape a pound symbol in my script? In-Reply-To: <7d81675b0707052140s1aeb8850yee1c4a5002bc31c1@mail.gmail.com> References: <7d81675b0707052140s1aeb8850yee1c4a5002bc31c1@mail.gmail.com> Message-ID: On 7/6/07, Richard Querin wrote: > I'm writing a very simple python script which writes out some > predefined text to a file (which will later become part of an html > file). I need to write out a pound sign '#' to the file and I can't > figure out how to escape it. I've tried '\#' and '\u0023', but neither > works. How can I do it? Works fine here: $ python -c 'open("foo","w").write("?")' $ cat foo ? Try to include parts of your code that's not working to this list for us to see, there might be some other errors in it. -- - Rikard - http://bos.hack.org/cv/ From john at fouhy.net Fri Jul 6 06:53:41 2007 From: john at fouhy.net (John Fouhy) Date: Fri, 6 Jul 2007 16:53:41 +1200 Subject: [Tutor] How can I escape a pound symbol in my script? In-Reply-To: <7d81675b0707052140s1aeb8850yee1c4a5002bc31c1@mail.gmail.com> References: <7d81675b0707052140s1aeb8850yee1c4a5002bc31c1@mail.gmail.com> Message-ID: <5e58f2e40707052153x62edf5f2ia4e5fb8fbfdd7a80@mail.gmail.com> On 06/07/07, Richard Querin wrote: > I'm writing a very simple python script which writes out some > predefined text to a file (which will later become part of an html > file). I need to write out a pound sign '#' to the file and I can't > figure out how to escape it. I've tried '\#' and '\u0023', but neither > works. How can I do it? Why do you need to? # doesn't mean anything special inside a quoted string. >>> s = "# foo" >>> print s # foo From rfquerin at gmail.com Fri Jul 6 06:59:25 2007 From: rfquerin at gmail.com (Richard Querin) Date: Fri, 6 Jul 2007 00:59:25 -0400 Subject: [Tutor] How can I escape a pound symbol in my script? In-Reply-To: <5e58f2e40707052153x62edf5f2ia4e5fb8fbfdd7a80@mail.gmail.com> References: <7d81675b0707052140s1aeb8850yee1c4a5002bc31c1@mail.gmail.com> <5e58f2e40707052153x62edf5f2ia4e5fb8fbfdd7a80@mail.gmail.com> Message-ID: <7d81675b0707052159u3890adb1p57c5fc797e3e941a@mail.gmail.com> Thanks for the quick responses guys... I was fooled by Vim and my own inexperience. I had forgotten to escape a preceding quote and the pound symbol was generating a python comment which showed up in syntax highlighting... Grrr. Problem fixed now. [walking away embarrassed...] ;) From rabidpoobear at gmail.com Fri Jul 6 07:15:00 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 06 Jul 2007 00:15:00 -0500 Subject: [Tutor] How can I escape a pound symbol in my script? In-Reply-To: References: <7d81675b0707052140s1aeb8850yee1c4a5002bc31c1@mail.gmail.com> Message-ID: <468DCFD4.4050501@gmail.com> Rikard Bosnjakovic wrote: > On 7/6/07, Richard Querin wrote: > > >> I'm writing a very simple python script which writes out some >> predefined text to a file (which will later become part of an html >> file). I need to write out a pound sign '#' to the file and I can't >> figure out how to escape it. I've tried '\#' and '\u0023', but neither >> works. How can I do it? >> > > Works fine here: > > $ python -c 'open("foo","w").write("?")' > $ cat foo > ? > I thought this was very amusing. If it wasn't meant as a joke, sorry. I laughed. > Try to include parts of your code that's not working to this list for > us to see, there might be some other errors in it. > I second this. Including code in your post is paramount. Also, I like to use the word paramount. -Luke From alan.gauld at btinternet.com Fri Jul 6 10:07:24 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 6 Jul 2007 09:07:24 +0100 Subject: [Tutor] How can I escape a pound symbol in my script? References: <7d81675b0707052140s1aeb8850yee1c4a5002bc31c1@mail.gmail.com> Message-ID: Moving somewhat off topic... > > file). I need to write out a pound sign '#' to the file > Works fine here: > $ python -c 'open("foo","w").write("?")' I always find it amusing when Americans refer to the hash or square symbol (#) as a pound sign (?). This is of course an historical feature of old keyboards when, to get a hash symbol (#), you had to type a pound sign(?), ie shift 3. In the UK the pound sign (? - shift 3) was actually used as a pound sign for currency so their hash is located at the extreme left of the middle row (and in various other places on some keyboards!) I wonder how many other countries refer to the hash symbol as a pound sign? Alan G. From kent37 at tds.net Fri Jul 6 12:48:34 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 06 Jul 2007 06:48:34 -0400 Subject: [Tutor] How can I escape a pound symbol in my script? In-Reply-To: References: <7d81675b0707052140s1aeb8850yee1c4a5002bc31c1@mail.gmail.com> Message-ID: <468E1E02.4040101@tds.net> Alan Gauld wrote: > Moving somewhat off topic... > >>> file). I need to write out a pound sign '#' to the file >> Works fine here: >> $ python -c 'open("foo","w").write("?")' > > I always find it amusing when Americans refer to the > hash or square symbol (#) as a pound sign (?). This > is of course an historical feature of old keyboards > when, to get a hash symbol (#), you had to type a > pound sign(?), ie shift 3. That is a very interesting explanation but I prefer this one: http://en.wikipedia.org/wiki/Number_sign#Naming_convention_within_the_USA # is an abbreviation for 'pound' the weight, not 'pound' the unit of currency. Of course the correct name for this symbol is 'octothorpe' :-) http://en.wiktionary.org/wiki/Octothorpe Kent From alan.gauld at btinternet.com Fri Jul 6 13:55:07 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 6 Jul 2007 12:55:07 +0100 Subject: [Tutor] How can I escape a pound symbol in my script? References: <7d81675b0707052140s1aeb8850yee1c4a5002bc31c1@mail.gmail.com> <468E1E02.4040101@tds.net> Message-ID: "Kent Johnson" wrote > > is of course an historical feature of old keyboards > > when, to get a hash symbol (#), you had to type a > > pound sign(?), ie shift 3. > > That is a very interesting explanation but I prefer this one: > http://en.wikipedia.org/wiki/Number_sign#Naming_convention_within_the_USA > > # is an abbreviation for 'pound' the weight, not 'pound' the unit > of currency. Interesting indeed. I got my explanation in high school around 1972. It went like this.... The pound and the dollar were the main currencies in use when Remington introduced the QWERTY keyboard on their early typewriters. The pound sign was Shift-3 and the dollar shift-4. When the US introduced the # symbol (in the early 1920's?) to keyboards they used the pound sign position (because the pound had decreased in usage by then) and the symbol was called the pound sign because that was what was traditionally on the key used. The symbol is called hash is the UK because its derived from the more term cross-hatch, where the symbol is like the cross hatching used for shading when sketching, which in turn is often called hatching. And that was part of our Modern History class and was examinable! :-) An alternative explanation for hash that I've seen is that it relates to cooking where a hash is a meal composed of ingredients cut into cubes and the symbol is remminiscent of the cut lines made when cubing (or hashing) the meat etc. > Of course the correct name for this symbol is 'octothorpe' :-) > http://en.wiktionary.org/wiki/Octothorpe That I would query, the article says the Bell labs folks claim to have coined the term in 1964 but the symbol has been in use for at least a hundred years. Although whether it had an official name up till then I don't know... In fact the name most likely I'd have thought would be "sharp" as in music notation, which is where, I think, it originated. And this is really off-topic now! :-) Alan G. From connorsml at gmail.com Fri Jul 6 14:02:50 2007 From: connorsml at gmail.com (Michael Connors) Date: Fri, 6 Jul 2007 13:02:50 +0100 Subject: [Tutor] How can I escape a pound symbol in my script? In-Reply-To: References: <7d81675b0707052140s1aeb8850yee1c4a5002bc31c1@mail.gmail.com> <468E1E02.4040101@tds.net> Message-ID: "And this is really off-topic now! :-)" Really interesting though, hopefully it will come up in a pub quiz. On 06/07/07, Alan Gauld wrote: > > "Kent Johnson" wrote > > > > is of course an historical feature of old keyboards > > > when, to get a hash symbol (#), you had to type a > > > pound sign(?), ie shift 3. > > > > That is a very interesting explanation but I prefer this one: > > > http://en.wikipedia.org/wiki/Number_sign#Naming_convention_within_the_USA > > > > # is an abbreviation for 'pound' the weight, not 'pound' the unit > > of currency. > > Interesting indeed. I got my explanation in high school around 1972. > It went like this.... > The pound and the dollar were the main currencies in use when > Remington > introduced the QWERTY keyboard on their early typewriters. The pound > sign > was Shift-3 and the dollar shift-4. When the US introduced the # > symbol > (in the early 1920's?) to keyboards they used the pound sign position > (because the pound had decreased in usage by then) and the symbol > was called the pound sign because that was what was traditionally on > the key used. > > The symbol is called hash is the UK because its derived from > the more term cross-hatch, where the symbol is like the cross > hatching used for shading when sketching, which in turn is often > called hatching. > > And that was part of our Modern History class and was examinable! :-) > > An alternative explanation for hash that I've seen is that it relates > to cooking where a hash is a meal composed of ingredients cut > into cubes and the symbol is remminiscent of the cut lines made > when cubing (or hashing) the meat etc. > > > Of course the correct name for this symbol is 'octothorpe' :-) > > http://en.wiktionary.org/wiki/Octothorpe > > That I would query, the article says the Bell labs folks claim to have > coined > the term in 1964 but the symbol has been in use for at least a hundred > years. Although whether it had an official name up till then I don't > know... In fact the name most likely I'd have thought would be "sharp" > as in music notation, which is where, I think, it originated. > > And this is really off-topic now! :-) > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070706/7d5e71af/attachment.htm From rondosxx at yahoo.com Fri Jul 6 14:41:44 2007 From: rondosxx at yahoo.com (ron) Date: Fri, 6 Jul 2007 05:41:44 -0700 (PDT) Subject: [Tutor] How can I escape a pound symbol in my script? Message-ID: <231662.89425.qm@web52504.mail.re2.yahoo.com> in the US, # is a symbol for weight, not currency. How do you write out, with a quick symbol, "I'm going to buy 3# of potatoes? Of course now you're metric, but did you also use 'pounds' for weight before that? ____________________________________________________________________________________Ready for the edge of your seat? Check out tonight's top picks on Yahoo! TV. http://tv.yahoo.com/ From mail at timgolden.me.uk Fri Jul 6 14:45:02 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 06 Jul 2007 13:45:02 +0100 Subject: [Tutor] How can I escape a pound symbol in my script? In-Reply-To: <231662.89425.qm@web52504.mail.re2.yahoo.com> References: <231662.89425.qm@web52504.mail.re2.yahoo.com> Message-ID: <468E394E.1070606@timgolden.me.uk> ron wrote: > in the US, # is a symbol for weight, not currency. I didn't know that; I assumed it was only used for ordinal numbering (as in Item #3). # How do you write out, with a quick symbol, "I'm going to > buy 3# of potatoes? Assuming that "you" is us Brits, then: 3lb (that's lowercase-l, lowercase-b in case it doesn't show up easily in your font). TJG From nephish at gmail.com Fri Jul 6 18:38:02 2007 From: nephish at gmail.com (shawn bright) Date: Fri, 6 Jul 2007 11:38:02 -0500 Subject: [Tutor] back on bytes Message-ID: <384c93600707060938p59692d3dr735b41091cf477a5@mail.gmail.com> hello all, i have a number 12480 i have a low byte of 192 and a high byte of 176 so i can do this IDLE 1.2.1 ==== No Subprocess ==== >>> (176 & 127) * 256 + 192 12480 but if i start with the 12480, how do i get the two bytes (lo and hi) that make it up? i kinda know what i am doing here, but keep getting tripped up thanks shawn From malaclypse2 at gmail.com Fri Jul 6 19:48:08 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 6 Jul 2007 13:48:08 -0400 Subject: [Tutor] back on bytes In-Reply-To: <384c93600707060938p59692d3dr735b41091cf477a5@mail.gmail.com> References: <384c93600707060938p59692d3dr735b41091cf477a5@mail.gmail.com> Message-ID: <16651e80707061048t5f392d06x47a8a5441d305dc1@mail.gmail.com> On 7/6/07, shawn bright wrote: > i have a number 12480 > i have a low byte of 192 and a high byte of 176 Maybe I'm being dense, but that doesn't make any sense at all to me. The high byte of 12480 is 48, and the low byte is 192, isn't it? Because (48 * 256) + 192 = 12480? In your formula ( (176 & 127) * 256 + 192 ) you're only using 7 bits of your high byte. Why are you masking off that last bit? And if you mask it off, how do you expect to recover it going the other direction? I suppose for this particular example, the following would work, but it doesn't seem like what you really are after: >>> n = 12480 >>> low_byte = n & 0xFF >>> low_byte 192 >>> hi_byte = n >> 8 >>> hi_byte 48 # Add the extra bit back in that was masked off >>> hi_byte = hi_byte+128 >>> hi_byte 176 >>> -- Jerry From wcyeee at gmail.com Fri Jul 6 20:39:31 2007 From: wcyeee at gmail.com (wcyee) Date: Fri, 6 Jul 2007 14:39:31 -0400 Subject: [Tutor] lambda: print('x') raises SyntaxError? In-Reply-To: <78b3a9580707050936k50729574j98c1b65f035029b1@mail.gmail.com> References: <468D0FA3.1090902@tds.net> <78b3a9580707050936k50729574j98c1b65f035029b1@mail.gmail.com> Message-ID: Ahh. It seems so obvious now. :) Thanks, Wesley & Kent! On 7/5/07, wesley chun wrote: > > On 7/5/07, Kent Johnson wrote: > > wc yeee wrote: > > > Hi. Is there a reason the code below raises a syntax error? It's > > > probably something silly on my part, but I can't figure it out: > > > > > > > > > >>> b = lambda: print('bar') > > > File "", line 1 > > > b = lambda: print('bar') > > > ^ > > > SyntaxError: invalid syntax > > > > The body of a lambda has to be an expression, not a statement. print is > > a statement. > > > > > > > > This works fine too: > > > > > > >>> import sys > > > >>> a = lambda: sys.stdout.write('foo\n') > > > >>> a() > > > foo > > > > Right, that is an expression and it is the workaround for your original > > problem. > > > one thing to keep in mind when thinking, "is this an expression or a > statement?" is that the former will always evaluate to some sort of > Python object (numerical calculation, function return value [your case > above], some string you've built, etc.) whereas the latter will not > have any kind of intrisic value (print, while, if, class, def... none > of these have a "value"). > > on a partially-related note, print will be changing to a function in > the next generation of Python... see PEP 3105: > > http://www.python.org/dev/peps/pep-3105/ > > for a list of some of the other changes coming down the line: > http://www.python.org/dev/peps/pep-3100/ > > cheers, > -- 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 > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070706/17ec101e/attachment.html From terry.kemmerer at gmail.com Sat Jul 7 00:49:39 2007 From: terry.kemmerer at gmail.com (Terry) Date: Fri, 06 Jul 2007 15:49:39 -0700 Subject: [Tutor] n.isalnum() is failing In-Reply-To: References: Message-ID: <1183762179.10615.61.camel@localhost.localdomain> Hi Janos, Quote: Your logic is backward, and mine is the forward, isn't it? ;) The Story of My Life! --Terry On Thu, 2007-07-05 at 07:30 +0200, J?nos Juh?sz wrote: > > Hi Terry > > > "According to the Gregorian calendar, which is the civil calendar in > use > > today, years evenly divisible by 4 are leap years, with the > exception of > > centurial years that are not evenly divisible by 400." > > > def isLeapYear(y): > > if y % 4 == 0: return True > As it always return True, if y%4 == 0, there is problem with the > exceptions > > if (y % 4 == 0) and not (y %100 == 0): return True > > else: return False > > > I feel that, the cleanest way to translate the definition into Boolean > logic > is to do it backward instead of thinking on the exceptions. > > def leap_year(year): > if year%400 == 0: return True # We said these years are always > leap year > if year%100 == 0: return False # the exception handled already > if year%4 == 0: return True # no problem with the exceptions > return False # this it the default > > > ps > hungarians name format: family name, christian name > hungarian date format: year/month/day > Your logic is backward, and mine is the forward, isn't it? ;) > > > Janos > > _______________________________________________ > 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/20070706/b5eac1a2/attachment.html From terry.kemmerer at gmail.com Sat Jul 7 00:50:52 2007 From: terry.kemmerer at gmail.com (Terry) Date: Fri, 06 Jul 2007 15:50:52 -0700 Subject: [Tutor] [Fwd: [Fwd: Re: n.isalnum() is failing]] Message-ID: <1183762252.10615.63.camel@localhost.localdomain> Hi Alan, Yes! That is succinct and sweet! I think I like that one the best of all! Terry -------- Forwarded Message -------- From: Alan Gauld To: tutor at python.org Subject: Re: [Tutor] n.isalnum() is failing Date: Thu, 5 Jul 2007 10:17:16 +0100 "J?nos Juh?sz" wrote >> def isLeapYear(y): >> if y % 4 == 0: return True > As it always return True, if y%4 == 0, there is problem with the > exceptions My original function had %400 not %4 so it worked. >> if (y % 4 == 0) and not (y %100 == 0): return True >> else: return False > > > I feel that, the cleanest way to translate the definition into > Boolean > logic is to do it backward instead of thinking on the exceptions. > > def leap_year(year): > if year%400 == 0: return True # these are always leap year > if year%100 == 0: return False # the exception handled already > if year%4 == 0: return True # no problem with the exceptions > return False # this it the default But I rather like this one since the combined and/not expression is less clear and more prone to confusion.. And in fact it can be simplified even further: def isLeapYear(y): if y % 400: return True if y % 100: return False return y % 4 == 0 > hungarians name format: family name, christian name > hungarian date format: year/month/day > Your logic is backward, and mine is the forward, isn't it? ;) :-) 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/20070706/41b6bdad/attachment.htm From carroll at tjc.com Sat Jul 7 09:37:59 2007 From: carroll at tjc.com (Terry Carroll) Date: Sat, 7 Jul 2007 00:37:59 -0700 (PDT) Subject: [Tutor] back on bytes In-Reply-To: <16651e80707061048t5f392d06x47a8a5441d305dc1@mail.gmail.com> Message-ID: On Fri, 6 Jul 2007, Jerry Hill wrote: > In your formula ( (176 & 127) * 256 + 192 ) you're only using 7 bits > of your high byte. Why are you masking off that last bit? I know in MP3 files, some of the ID3 lengths are coded this way, i.e. as a four-byte field, each byte of which has the high-order bit set to zero, and the other seven bits significant, for a total of a 28-bit integer. For example, 0x00000101 would equal 129 (not 257, as one would expect). Scrounging through some old code, I used to use this to pull out the length: def ID3TagLength(s): """ Given a 4-byte string s, decode as ID3 tag length """ return (ord(s[0]) * 0x200000 + ord(s[1]) * 0x4000 + ord(s[2]) * 0x80 + ord(s[3]) ) From alan.gauld at btinternet.com Sat Jul 7 10:07:53 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 7 Jul 2007 09:07:53 +0100 Subject: [Tutor] back on bytes References: <16651e80707061048t5f392d06x47a8a5441d305dc1@mail.gmail.com> Message-ID: "Terry Carroll" wrote >> In your formula ( (176 & 127) * 256 + 192 ) you're only using 7 >> bits >> of your high byte. Why are you masking off that last bit? > .... > Scrounging through some old code, I used to use this to pull out the > length: > > def ID3TagLength(s): > """ > Given a 4-byte string s, decode as ID3 tag length > """ > return (ord(s[0]) * 0x200000 + > ord(s[1]) * 0x4000 + > ord(s[2]) * 0x80 + > ord(s[3]) ) I'm intrigued as to why people are using weird combinations of math to manipulate bitstrings given that Python has a full set of bitwise operators. Surely it is easier and more obvious to simply shift the bits right or left using >> and << and use bitwise and/or operations than do all this multiplication and addition malarky. (Its also a lot faster!) If you are going to operate at the bit level why not use the bit level operations? Curious. Alan G. From kent37 at tds.net Sat Jul 7 13:51:27 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 07 Jul 2007 07:51:27 -0400 Subject: [Tutor] back on bytes In-Reply-To: References: <16651e80707061048t5f392d06x47a8a5441d305dc1@mail.gmail.com> Message-ID: <468F7E3F.5010800@tds.net> Alan Gauld wrote: > Surely it is easier and more obvious > to simply shift the bits right or left using >> and << and use > bitwise and/or operations than do all this multiplication and > addition malarky. (Its also a lot faster!) Are you sure about that? With Python 2.5 on a MacBook Pro it seems to be *slightly* faster: src $ python -m timeit "5 << 21; 10 << 21; 50 << 21; 247 << 21" 10000000 loops, best of 3: 0.0917 usec per loop src $ python -m timeit "5 * 0x200000; 10 * 0x200000; 50 * 0x200000; 247 * 0x200000" 10000000 loops, best of 3: 0.0924 usec per loop .0917/.0924 = 0.99242424242424254 src $ python -m timeit -s "nums=range(256); mults=range(1, 22)" "for i in nums:" " for m in mults:" " i< <468F7E3F.5010800@tds.net> Message-ID: "Kent Johnson" wrote >> to simply shift the bits right or left using >> and << and use >> bitwise and/or operations than do all this multiplication and >> addition malarky. (Its also a lot faster!) > > Are you sure about that? With Python 2.5 on a MacBook Pro it seems > to > be *slightly* faster: > > src $ python -m timeit "5 << 21; 10 << 21; 50 << 21; 247 << 21" > 10000000 loops, best of 3: 0.0917 usec per loop > > src $ python -m timeit "5 * 0x200000; 10 * 0x200000; 50 * 0x200000; > 247 > * 0x200000" > 10000000 loops, best of 3: 0.0924 usec per loop OK, I really should learn not to make assumptions about how Python works speed wise, its usually too clever for me. In past lives I've found multiplication/addition to be a factor of 2 or 3 times slower than shifting/ORing. I still think it's faster to write since if you just want to shift 7 places right you don't have to think "what's 2 ** 7?" and then multiply by that value. And ORing things together with a bitwise OR is usually just a single operation whereas adding them together is usually many clock cycles. But, lo and behold, when I try timing that in Python addition looks to be about 10% faster than bitwise OR which is astonishing! Alan Gauld at xp ~ $ python -m timeit "128 | 7" 10000000 loops, best of 3: 0.146 usec per loop Alan Gauld at xp ~ $ python -m timeit "128 + 7" 10000000 loops, best of 3: 0.115 usec per loop I guess this relates to our discussion about moving from C to Python, its best not to think too much about the low level workings, just write the clearest code and trust Python to do the right thing! But in this case I still think the bitwise operations are more obviously related to the task than using arithmetic operations. Alan G. From nephish at gmail.com Sat Jul 7 14:16:52 2007 From: nephish at gmail.com (shawn bright) Date: Sat, 7 Jul 2007 07:16:52 -0500 Subject: [Tutor] back on bytes In-Reply-To: <468F7E3F.5010800@tds.net> References: <16651e80707061048t5f392d06x47a8a5441d305dc1@mail.gmail.com> <468F7E3F.5010800@tds.net> Message-ID: <384c93600707070516m7ef059fp922e0f2d183983f@mail.gmail.com> Well, I contacted the programmer of these controls and the reason they mask the MSB on these reports is to designate what type of sensor it is. If the MSB is set, the sensor is one type, if not, another. So, knowing that i could put these together ok. To me, the speed is of no consequence like it would be if i were processing files, these sensors report anywhere from 6 to 12 bytes total, and we get them at the rate of about 20 / minute. Having said all that, I want to express thanks to this list, especially you guys, Kent and Alan, not just for the help here the past week, but also what i have been able to dig out of my gmail archives from help you gave me on similar issues months ago. I appreciate it a lot. shawn On 7/7/07, Kent Johnson wrote: > Alan Gauld wrote: > > Surely it is easier and more obvious > > to simply shift the bits right or left using >> and << and use > > bitwise and/or operations than do all this multiplication and > > addition malarky. (Its also a lot faster!) > > Are you sure about that? With Python 2.5 on a MacBook Pro it seems to > be *slightly* faster: > > src $ python -m timeit "5 << 21; 10 << 21; 50 << 21; 247 << 21" > 10000000 loops, best of 3: 0.0917 usec per loop > > src $ python -m timeit "5 * 0x200000; 10 * 0x200000; 50 * 0x200000; 247 > * 0x200000" > 10000000 loops, best of 3: 0.0924 usec per loop > > .0917/.0924 = 0.99242424242424254 > > src $ python -m timeit -s "nums=range(256); mults=range(1, 22)" "for i > in nums:" " for m in mults:" " i< 1000 loops, best of 3: 564 usec per loop > > src $ python -m timeit -s "nums=range(256); mults=[1< range(1, 22)]" "for i in nums:" " for m in mults:" " i*m" > 1000 loops, best of 3: 579 usec per loop > > src $ python -m timeit -s "nums=range(256); mults=[1< range(1, 22)]" "for i in nums:" " for m in mults:" " pass" > 10000 loops, best of 3: 195 usec per loop > > If the last timing is a reasonable estimate of the loop overhead in the > previous two, then roughly the speed difference is 579-195=384 vs > 564-195=369 and shifting is 369/384.=0.9609375 the speed of multiplication. > > My guess is the integer multiply in my computer recognizes this simple > case and optimizes it to a shift. > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From cubexican at gmail.com Sat Jul 7 20:22:06 2007 From: cubexican at gmail.com (Keith) Date: Sat, 7 Jul 2007 13:22:06 -0500 Subject: [Tutor] Parsing webserver log files Message-ID: I'm very new to python (about a couple days now) and as part of my internship, my supervisor wanted me to learn python and write something that will parse webserver logs files and give a list of IPs and the requested URL. Seeing as this needs to be a reflection of my own work I want to write all of the program but I needed some direction. I've been moving up step by step, first using regular expressions to find IP addresses and URLs within a line of a log file and list them. Now I'm at a point where I'll need to differentiate between lines of the log file and generate a long list of IP and corresponding URL. Like I said, I'm using regular expressions to distinguish IPs and URLs within a line and (from the way my supervisor is pointing me) I'll need to utilize the built in functions file() and readlines() along with the regular expressions to be able to write the final program. Basically, I'm looking for some direction on how to write the program I've been instructed to write utilizing regular expressions and by opening the file within python using open() or file(). I don't have any programming experience and the webserver log files are from an Apache HTTP server and are therefore in that format. Thanks From alan.gauld at btinternet.com Sat Jul 7 21:12:10 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 7 Jul 2007 20:12:10 +0100 Subject: [Tutor] Parsing webserver log files References: Message-ID: "Keith" wrote > I've been moving up step by step, first using regular expressions > to > find IP addresses and URLs within a line of a log file and list > them. It sounds like you are on the right lines. > Now I'm at a point where I'll need to differentiate between lines of > the log file and generate a long list of IP and corresponding URL. If you put your code for processing a single line into a function then you can just iterate over the log file using a for loop. Use your function to extract the IP and URL and then write those to a report or just append to a list. > I'll need to utilize the built in functions file() and readlines() You may not need readlines because files are now iterable so you can just do: for line in file('logfile.log'): processLine(line) > and by opening the file within python using open() or file(). I > don't > have any programming experience and the webserver log files are from > an Apache HTTP server and are therefore in that format. You are heading the right way. Use functions to package up buits of discrete functionality and write a high level program using those functions. HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sarliz73 at yahoo.com Sun Jul 8 07:34:33 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Sat, 7 Jul 2007 22:34:33 -0700 (PDT) Subject: [Tutor] Key Error Message-ID: <473211.6523.qm@web35108.mail.mud.yahoo.com> Sorry, this is probably too general a question, but I can't find any specific information on it. What exactly is a "key error" and how do I clear it? I entered something like this: abcd=h[key]['ABCD'] and when I run it I'm getting KeyError: 'ABCD' What does this mean? Thanks! --------------------------------- Shape Yahoo! in your own image. Join our Network Research Panel today! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070707/dffb26b2/attachment.htm From broek at cc.umanitoba.ca Sun Jul 8 08:21:25 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sun, 08 Jul 2007 02:21:25 -0400 Subject: [Tutor] Key Error In-Reply-To: <473211.6523.qm@web35108.mail.mud.yahoo.com> References: <473211.6523.qm@web35108.mail.mud.yahoo.com> Message-ID: <46908265.7030205@cc.umanitoba.ca> Sara Johnson said unto the world upon 07/08/2007 01:34 AM: > Sorry, this is probably too general a question, but I can't find > any specific information on it. What exactly is a "key error" and > how do I clear it? > > I entered something like this: > > abcd=h[key]['ABCD'] > > and when I run it I'm getting > > KeyError: 'ABCD' > > What does this mean? > > Thanks! > Hi Sara, It means you've tried to access a data structure (most likely a dictionary) with a key that does not exist in that structure. Witness >>> my_dict={42:"Six times seven", 1: "The loneliest number"} >>> my_dict[42] 'Six times seven' >>> my_dict['42'] Traceback (most recent call last): File "", line 1, in KeyError: '42' >>> my_dict[17] Traceback (most recent call last): File "", line 1, in KeyError: 17 >>> It isn't a question of `clearing' it, but of tracking down the wrong assumption behind your code. It may be that you thought you were using a key you'd added before and were wrong (my_dict['42'] as opposed to my_dict[42] shows a common source of that). But, from your > abcd=h[key]['ABCD'] I'm guessing that you've got the key-access syntax a bit wrong. Did you mean abcd = h['ABCD'] instead? HTH, Brian vdB From sarliz73 at yahoo.com Sun Jul 8 18:10:32 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Sun, 8 Jul 2007 09:10:32 -0700 (PDT) Subject: [Tutor] Key Error In-Reply-To: Message-ID: <362062.566.qm@web35103.mail.mud.yahoo.com> Probably best if I skip the example and show what code I do have: ~~~~~~~~~~~ for key in h.keys(): wssd=h[key]['WSSD'] wspd=h[key]['WSPD'] wmax=h[key]['WMAX'] newi=h[key]['NEWI'] if wssd<-989. or wspd<-989. or wmax<-989.: break if wspd==0.: break ~~~~~~~~~~~~~~~~~ Where the "newi" = "abcd" that I showed before. I have no where else in my code anything pertaining to these 4 keys. The first 3 were there, and produce no errors. I am making adjustments to an existing script. I only have C programming knowledge so my thought was that it "newi" was just a variable that needed to be assigned. You'll notice the parameters below (i.e., if wssd < -989 ) but there is obviously nothing for "newi" at the moment. The program's only error at the moment seems to be this line: newi=h[key]['NEWI'] But as you can see, the other items are set up the same way. Thanks bundles!!! Sara Message: 7 Date: Sun, 08 Jul 2007 02:21:25 -0400 From: Brian van den Broek Subject: Re: [Tutor] Key Error To: sarliz73 at gmail.com Cc: tutor at python.org Message-ID: <46908265.7030205 at cc.umanitoba.ca> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Sara Johnson said unto the world upon 07/08/2007 01:34 AM: > Sorry, this is probably too general a question, but I can't find > any specific information on it. What exactly is a "key error" and > how do I clear it? > > I entered something like this: > > abcd=h[key]['ABCD'] > > and when I run it I'm getting > > KeyError: 'ABCD' > > What does this mean? > > Thanks! > Hi Sara, It means you've tried to access a data structure (most likely a dictionary) with a key that does not exist in that structure. Witness >>> my_dict={42:"Six times seven", 1: "The loneliest number"} >>> my_dict[42] 'Six times seven' >>> my_dict['42'] Traceback (most recent call last): File "", line 1, in KeyError: '42' >>> my_dict[17] Traceback (most recent call last): File "", line 1, in KeyError: 17 >>> It isn't a question of `clearing' it, but of tracking down the wrong assumption behind your code. It may be that you thought you were using a key you'd added before and were wrong (my_dict['42'] as opposed to my_dict[42] shows a common source of that). But, from your > abcd=h[key]['ABCD'] I'm guessing that you've got the key-access syntax a bit wrong. Did you mean abcd = h['ABCD'] instead? HTH, Brian vdB --------------------------------- Don't get soaked. Take a quick peak at the forecast with theYahoo! Search weather shortcut. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070708/5ecf5259/attachment.html From hunter92383 at gmail.com Sun Jul 8 18:21:38 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 8 Jul 2007 09:21:38 -0700 Subject: [Tutor] object names Message-ID: <674d5ce60707080921k35129e17v84b36fde75e30529@mail.gmail.com> I need to create object with numbers, for instance, i need to create 5 object of names like these object_1 object_2 and so on, how do I write a script that would do it when I specify that I need # number of it? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070708/8cd5bcc6/attachment.htm From hunter92383 at gmail.com Sun Jul 8 18:22:24 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 8 Jul 2007 09:22:24 -0700 Subject: [Tutor] object names In-Reply-To: <674d5ce60707080921k35129e17v84b36fde75e30529@mail.gmail.com> References: <674d5ce60707080921k35129e17v84b36fde75e30529@mail.gmail.com> Message-ID: <674d5ce60707080922pd5d6a9fif7c7be0070d3c9dc@mail.gmail.com> or it's not an object but common variables. var_1 var_2 and so on -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070708/f989cd27/attachment.html From bgailer at alum.rpi.edu Sun Jul 8 18:33:55 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 08 Jul 2007 09:33:55 -0700 Subject: [Tutor] Key Error In-Reply-To: <362062.566.qm@web35103.mail.mud.yahoo.com> References: <362062.566.qm@web35103.mail.mud.yahoo.com> Message-ID: <469111F3.90308@alum.rpi.edu> Sara Johnson wrote: > > Probably best if I skip the example and show what code I do have: > ~~~~~~~~~~~ > for key in h.keys(): > wssd=h[key]['WSSD'] > wspd=h[key]['WSPD'] > wmax=h[key]['WMAX'] > newi=h[key]['NEWI'] > if wssd<-989. or wspd<-989. or wmax<-989.: break > if wspd==0.: break > ~~~~~~~~~~~~~~~~~ > Where the "newi" = "abcd" that I showed before. I have no where else > in my code anything pertaining to these 4 keys. The first 3 were > there, and produce no errors. I am making adjustments to an existing > script. I only have C programming knowledge so my thought was that it > "newi" was just a variable that needed to be assigned. You'll notice > the parameters below (i.e., if wssd < -989 ) but there is obviously > nothing for "newi" at the moment. The program's only error at the > moment seems to be this line: > > newi=h[key]['NEWI'] > But as you can see, the other items are set up the same way. Most likely h is a dictionary, and the values are also dictionaries. At least one of the value dictionaries has no key "NEWI". To see what h is, put: print h before the for statement. You should see something like: {'somekey': {'WSSD': 3, 'WSPD': 4, 'WMAX': 5, 'NEWI': 6}, 'anotherkey': ...} Python uses braces with key : value pairs to represent a dictionary. If that does not help you, post the result (or attach if it is really long). Then we need to find how h itself was created. Any clues about that? -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From alan.gauld at btinternet.com Sun Jul 8 18:45:40 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 8 Jul 2007 17:45:40 +0100 Subject: [Tutor] Key Error References: <362062.566.qm@web35103.mail.mud.yahoo.com> Message-ID: "Sara Johnson" wrote > Probably best if I skip the example and show what code I do have: > ~~~~~~~~~~~ > for key in h.keys(): > wssd=h[key]['WSSD'] > wspd=h[key]['WSPD'] > wmax=h[key]['WMAX'] > newi=h[key]['NEWI'] > if wssd<-989. or wspd<-989. or wmax<-989.: break > if wspd==0.: break > ~~~~~~~~~~~~~~~~~ > Where the "newi" = "abcd" that I showed before. OK, Then that is telling us that h is a dictionary containing further dictionaries inside. The error tells us that at least one of the dictionaries does not have a key 'NEWI' If this code is supposed to be production strength it is not of good quality. It should either be defending these dictionary accesses with a try/except block or it should be using the get() method of the dictionary to force a default value. (The tests at the end are poorly written too. If one of my team produced code like this I'd be having strong words with them!) Which is the best solution will depend on the situation... > I have no where else in my code anything pertaining to > these 4 keys. Might I suggest grep? :-) > The first 3 were there, and produce no errors. I am making > adjustments to an existing script. I only have C programming > knowledge I hope you have at least basic Python too? Otherwise even reading the code will be difficult. While Python is easy to read thats a strictly relative measure! > so my thought was that it "newi" was just a variable that > needed to be assigned. newi is indeed a "just a variable" that is being assigned a value, but the value does not exist. This is a data error, your problems lie in the initialisation of the dictionaries coupled to the vulnerability of the code to this kind of error. > You'll notice the parameters below (i.e., if wssd < -989 ) but > there is obviously nothing for "newi" at the moment. Indeed, but there may be further on. Its certainly not involved in any of these tests. > The program's only error at the moment seems to be this line: > > newi=h[key]['NEWI'] The program has several errors IMHO but the one that is causing the interpreter to complain is due to non existent data. You need to find why that data is missing. Or, you could find a valid default value and assign that, either through a try/except block or by uysing a get() instead of key access. -- 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 Jul 8 18:53:48 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 8 Jul 2007 17:53:48 +0100 Subject: [Tutor] object names References: <674d5ce60707080921k35129e17v84b36fde75e30529@mail.gmail.com> Message-ID: "elis aeris" wrote > for instance, i need to create 5 object of names like these > > object_1 > object_2 > and so on, It's very unlikely that you need to do this. The usual solution in cases like this is to store the objects in a collection object, either a list or a dictionary. You can then access them by index or name. For example: # create some objects with a list objects = [] for n in range(5): objects.append(n) # now fetch number 3 print objects[3] # fetch them all in turn for object in objects: print object # repeat above with a dictionary d = {} for n in range(5): name = 'object_' + str(n) d[name] = n # fetch object_3 print d['object_3'] # fetch all for object in d.keys() print d[object] If that solution won't work for you for some reason tell us why and we can provide ways to do what you need. But using a collection will work for the vast majority of cases. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dos.fool at gmail.com Sun Jul 8 18:54:51 2007 From: dos.fool at gmail.com (max .) Date: Sun, 8 Jul 2007 10:54:51 -0600 Subject: [Tutor] backslashes Message-ID: <857e4c3d0707080954i46bf31e5r9135e18bcbcbb74f@mail.gmail.com> hello i am writing a simple password tester that uses a word list and am running into some problems when i read the words from a text file they are written to the screen with a backslash at the end and i cant seem to find a way to get rid of them here is the script: __name__="dictionary password tester" __author__="max baseman (dos.fool at gmail.com)" __version__="0.1" __discription__="tests a password against a dictonary" ############################################################# print print password=raw_input("password >") passlist=open("/Users/max/passlist.rtf","r") # passlist is just a list of 50,000 words guesses=0 for line in passlist: line=line.replace('\ ','') #heres what i was trying now guesses=guesses+1 line=line.lower() print line if line==password: print print print"you password was",line,"and it took",guesses,"guesses" break p.s i am about to look up how to type to python and not show the text for the password bit but if anyone knows please explain any help would be great thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070708/3bb219a0/attachment.htm From bgailer at alum.rpi.edu Sun Jul 8 19:20:35 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 08 Jul 2007 10:20:35 -0700 Subject: [Tutor] Key Error In-Reply-To: <91c4f0860707081011g48bff9c7gaceb1d55752fd570@mail.gmail.com> References: <362062.566.qm@web35103.mail.mud.yahoo.com> <469111F3.90308@alum.rpi.edu> <91c4f0860707081011g48bff9c7gaceb1d55752fd570@mail.gmail.com> Message-ID: <46911CE3.4090107@alum.rpi.edu> Sara Johnson wrote: > Okay, it is VERY long! So long in fact that I can't get to the top of > it to copy from where it begins. Basically it's a series of codes > like 'WSSD' followed by values like 0.0000000000002 (more than just > the ones I listed, perhaps a few hundred. The end gives the same error. > > Traceback (most recent call last): > File "./mymods.py", line 118, in ? > newi=h[key]['NEWI'] > KeyError: 'NEWI' > > I can still attach what the screen has, if that'll help. Let's take a different approach: print len(h) for key in h.keys(): try: newi=h[key]['NEWI'] except KeyError: print key That will tell us how many items are in h and whether we have few or many of them that have the KeyError. -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From hunter92383 at gmail.com Sun Jul 8 19:44:53 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 8 Jul 2007 10:44:53 -0700 Subject: [Tutor] object names In-Reply-To: References: <674d5ce60707080921k35129e17v84b36fde75e30529@mail.gmail.com> Message-ID: <674d5ce60707081044p18c6d99bp70d2ff0fe2821bfb@mail.gmail.com> ugh, i guess what I need is just to name variables, not objects. var_1 var_2 and so on. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070708/9f032e92/attachment.htm From sarliz73 at yahoo.com Sun Jul 8 21:02:13 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Sun, 8 Jul 2007 12:02:13 -0700 (PDT) Subject: [Tutor] Key Error In-Reply-To: Message-ID: <570691.38917.qm@web35108.mail.mud.yahoo.com> I appologize...but what is, 'grep'? I'm at the end of my rope, which right now looks about as sturdy as string (and I don't mean a string buffer either)!!! Okay, where to go from here... Again, as I mentioned there may be holes in what I'm giving but that's because 1). segments of this program do work, and I don't want to overload this list with my Python problems (and believe me, I have enough to probably keep you kind, knowledgable folks busy for weeks!) and 2). I don't always know if I'm giving you all enough information to decipher my mess, or too much information. I believe 'NEWI' is supposed to be a new subkey that will hold a value called 'newind.' But if I can't get the program to initialize this 'NEWI' then I don't know how any values can come from it. Thanks anyways... I'll keep digging, Sara "Sara Johnson" wrote > Probably best if I skip the example and show what code I do have: > ~~~~~~~~~~~ > for key in h.keys(): > wssd=h[key]['WSSD'] > wspd=h[key]['WSPD'] > wmax=h[key]['WMAX'] > newi=h[key]['NEWI'] > if wssd<-989. or wspd<-989. or wmax<-989.: break > if wspd==0.: break > ~~~~~~~~~~~~~~~~~ > Where the "newi" = "abcd" that I showed before. OK, Then that is telling us that h is a dictionary containing further dictionaries inside. The error tells us that at least one of the dictionaries does not have a key 'NEWI' If this code is supposed to be production strength it is not of good quality. It should either be defending these dictionary accesses with a try/except block or it should be using the get() method of the dictionary to force a default value. (The tests at the end are poorly written too. If one of my team produced code like this I'd be having strong words with them!) Which is the best solution will depend on the situation... > I have no where else in my code anything pertaining to > these 4 keys. Might I suggest grep? :-) > The first 3 were there, and produce no errors. I am making > adjustments to an existing script. I only have C programming > knowledge I hope you have at least basic Python too? Otherwise even reading the code will be difficult. While Python is easy to read thats a strictly relative measure! > so my thought was that it "newi" was just a variable that > needed to be assigned. newi is indeed a "just a variable" that is being assigned a value, but the value does not exist. This is a data error, your problems lie in the initialisation of the dictionaries coupled to the vulnerability of the code to this kind of error. > You'll notice the parameters below (i.e., if wssd < -989 ) but > there is obviously nothing for "newi" at the moment. Indeed, but there may be further on. Its certainly not involved in any of these tests. > The program's only error at the moment seems to be this line: > > newi=h[key]['NEWI'] The program has several errors IMHO but the one that is causing the interpreter to complain is due to non existent data. You need to find why that data is missing. Or, you could find a valid default value and assign that, either through a try/except block or by uysing a get() instead of key access. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld --------------------------------- Get the Yahoo! toolbar and be alerted to new email wherever you're surfing. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070708/c3fcc7b9/attachment.htm From rabidpoobear at gmail.com Sun Jul 8 22:14:26 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 08 Jul 2007 15:14:26 -0500 Subject: [Tutor] backslashes In-Reply-To: <857e4c3d0707080954i46bf31e5r9135e18bcbcbb74f@mail.gmail.com> References: <857e4c3d0707080954i46bf31e5r9135e18bcbcbb74f@mail.gmail.com> Message-ID: <469145A2.10802@gmail.com> max . wrote: > hello i am writing a simple password tester that uses a word list and > am running into some problems when i read the words from a text file > they are written to the screen with a backslash at the end and i cant > seem to find a way to get rid of them > > here is the script: > > __name__="dictionary password tester" > __author__="max baseman (dos.fool at gmail.com )" > __version__="0.1" > __discription__="tests a password against a dictonary" > ############################################################# > > print > print > password=raw_input("password >") > passlist=open("/Users/max/passlist.rtf","r") # passlist is just a list > of 50,000 words This is almost definitely the problem. .rtf is 'rich text formatting' which, depending on which program wrote it (word pad / Microsoft Word / etc) contains various degrees of markup / formatting mixed in with the text. If you want straight text, don't try to process the rtf and remove the formatting. Just save your file as a .txt (or anything else - just so long as the program that's actually saving it knows to save it as straight ascii without any markup.) > guesses=0 > for line in passlist: > line=line.replace('\ ','') #heres what i was trying now > guesses=guesses+1 > line=line.lower() > print line > if line==password: > print > print > print"you password was",line,"and it took",guesses,"guesses" > break > > > > > > p.s i am about to look up how to type to python and not show the text > for the password bit but if anyone knows please explain > any help would be great thanks try this link: http://docs.python.org/lib/module-getpass.html HTH, -Luke From dkuhlman at rexx.com Sun Jul 8 22:16:14 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 8 Jul 2007 13:16:14 -0700 Subject: [Tutor] backslashes In-Reply-To: <857e4c3d0707080954i46bf31e5r9135e18bcbcbb74f@mail.gmail.com> References: <857e4c3d0707080954i46bf31e5r9135e18bcbcbb74f@mail.gmail.com> Message-ID: <20070708201614.GA23635@cutter.rexx.com> On Sun, Jul 08, 2007 at 10:54:51AM -0600, max . wrote: > hello i am writing a simple password tester that uses a word list and am > running into some problems when i read the words from a text file they are > written to the screen with a backslash at the end and i cant seem to find a > way to get rid of them > In Python, the backslash is a character escape character. In order to include a backslash in a string, use a double backslash. Here is some example code:: In [1]: s1 = 'abcd\\efg\\' In [2]: s1 Out[2]: 'abcd\\efg\\' In [3]: len(s1) Out[3]: 9 In [4]: s1.replace('\\', '') Out[4]: 'abcdefg' Notice the length of the string (before removing the backslashes). Each apparently double backslash actually has a length of 1. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From rabidpoobear at gmail.com Sun Jul 8 22:18:29 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 08 Jul 2007 15:18:29 -0500 Subject: [Tutor] object names In-Reply-To: <674d5ce60707081044p18c6d99bp70d2ff0fe2821bfb@mail.gmail.com> References: <674d5ce60707080921k35129e17v84b36fde75e30529@mail.gmail.com> <674d5ce60707081044p18c6d99bp70d2ff0fe2821bfb@mail.gmail.com> Message-ID: <46914695.6030006@gmail.com> elis aeris wrote: > ugh, i guess what I need is just to name variables, not objects. > > > var_1 > var_2 > > and so on. Did you read what Alan said? He gave you a way to do this without using separate variables. There are many problems associated with creating variable names dynamically, and you haven't given us a reason why you need to do this. We're not withholding information from you to be egregious, we're doing it for your own good. You most likely don't need to do this, and we gave you a perfectly viable alternative in 99% of cases. Hope you read this, -Luke From bgailer at alum.rpi.edu Sun Jul 8 23:34:15 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 08 Jul 2007 14:34:15 -0700 Subject: [Tutor] Key Error In-Reply-To: <91c4f0860707081027y5f637823w87e1a7df3f8b1cf1@mail.gmail.com> References: <362062.566.qm@web35103.mail.mud.yahoo.com> <469111F3.90308@alum.rpi.edu> <91c4f0860707081011g48bff9c7gaceb1d55752fd570@mail.gmail.com> <46911CE3.4090107@alum.rpi.edu> <91c4f0860707081027y5f637823w87e1a7df3f8b1cf1@mail.gmail.com> Message-ID: <46915857.9070302@alum.rpi.edu> Sara Johnson wrote: > Should I temporarily comment out the other values (i.e., WSSD, > WSPD...)? I'm getting an error now that says: > > File "./mymods.py", line 122 > if wssd<-989. or wspd<-989. or wmax<-989.: break > ^ > SyntaxError: invalid syntax Please post (always) the surrounding code. The error is likely due to whatever is on the preceding line. Here's your original code: for key in h.keys(): wssd=h[key]['WSSD'] wspd=h[key]['WSPD'] wmax=h[key]['WMAX'] newi=h[key]['NEWI'] if wssd<-989. or wspd<-989. or wmax<-989.: break if wspd==0.: break I was suggesting you replace all of that with: print len(h) for key in h.keys(): try: newi=h[key]['NEWI'] except KeyError: print key Keep in mind that Python uses indentation to convey structure instead of braces (like C). -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From bgailer at alum.rpi.edu Sun Jul 8 23:41:05 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 08 Jul 2007 14:41:05 -0700 Subject: [Tutor] Key Error In-Reply-To: <91c4f0860707081018p68b69e4ax146db0c68547c125@mail.gmail.com> References: <362062.566.qm@web35103.mail.mud.yahoo.com> <469111F3.90308@alum.rpi.edu> <91c4f0860707081018p68b69e4ax146db0c68547c125@mail.gmail.com> Message-ID: <469159F1.3060007@alum.rpi.edu> Sara Johnson wrote: > On how the 'h' was created.... > > Well, it appears 'h' is referenced in a few spots in this code. It > looks like initially, at least, a dictionary 'h' is created and some h > keys and sub keys follow, obviously from the purpose of this project > (having to do with pickling), h is assigned: > > h=cPickle.load(inf) > > Is this because of the sub keys that follow? This means that some (same or other) program created h, "pickled" it and most likely wrote it to a file. So that program is failing in some way to create the correct keys for the dictionaries that comprise the values of h. > Could this be why I'm not able to create 'NEWI'? Again note you are not trying to create anything. newi=h[key]['NEWI'] is attempting to reference an existing key, and the key does not exist. > > Sorry if I'm missing something or not answering your question, I'm > highly confused! Of course you are. Going into a totally new realm with just C under your belt. If you'd like, give me a call. We might be able to cover more ground faster on the phone. -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From pierre.cutellic at gmail.com Sun Jul 8 23:44:31 2007 From: pierre.cutellic at gmail.com (pierre cutellic) Date: Sun, 8 Jul 2007 23:44:31 +0200 Subject: [Tutor] launching mayavi2 via SPE? Message-ID: <3c8b20230707081444q69650f8ct1f9d4c920b00770b@mail.gmail.com> hi, i just started to work with scipy and i would like to know the basic example code to launch or script mayavi2???? because i can't get anything with the documentation given on the scipy.orgsite :( cheers pierre -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070708/f86c9a62/attachment-0001.html From keridee at jayco.net Sun Jul 8 20:55:20 2007 From: keridee at jayco.net (Tiger12506) Date: Sun, 8 Jul 2007 18:55:20 -0000 Subject: [Tutor] how long? References: <468BE95C.8070401@kostyrka.org> Message-ID: <017901c7c191$8c9ebb20$b8fce004@JSLAPTOP> > Thorsten Kampe wrote: >> * Ben Waldin (Tue, 3 Jul 2007 19:46:42 +1200) >>> How long will it take until I successfully create my own working program >>> that is useful? I have crated the address book ones in the tutors and >>> just want to know how long it takes before I start to create my own >>> thought up programs that will be useful. Thanks Ben >> >> Approximately ten days, four hours and six minutes >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor Hmmm... I'd say it depends on whether or not you can... 'create my own thought up programs', much more than how long it takes. Hey! I have an idea! Why don't you write a python program that can calculate just how long it takes for you to do that? I'd guess that's what Thorsten Kampe has done. ;-) Factors involved in the algorithm: 1) How quickly you develop creative ideas (women usually do this better - My mother walks into a craft store, looks at an ugly little doll and exclaims, "Oooh! I know just what to do with that!") 2) How "useful" those ideas are - i.e. How many drawings you have compared to started projects 3) How motivated you are to finish them - ex. how crowded your workbench is compared to how many projects you have finished. 4) How effectively you translate thoughts into words, that is, how well you can articulate the language you are working in. (Be it English, Spanish, French, German, Python, C/C++, etc.) 5) Hmmm... I can't think of a "Five". That means I must be lacking a little in #1. ;-) Let's see... Once you've accumulated a bunch of data about yourself, your habits, your hobbies, the 4 factors i listed, etc, etc, etc... Then all you have to do is do a weighted calculation averaging these together... Hmmm... you'll need a test case too, so you will have to accumulate data on other people to see how long it takes them (based on their abilities because different people have different capacities for learning). Oh. And you will have to determine just what useful means to you. Collect a lot of data on that, being sure that you compare what you think is useful against what other people think is useful. Average it all up and come up with some sort of result. Just always keep in mind what you're aiming for, your goal (which in this case is to find how long it takes to write useful programs). LOL. Do you really think that anyone on this list can tell you how long it will take? Only *you* know how long it will take *you* to write what *you* think is a useful program. Jacob S. From keridee at jayco.net Sun Jul 8 21:08:31 2007 From: keridee at jayco.net (Tiger12506) Date: Sun, 8 Jul 2007 19:08:31 -0000 Subject: [Tutor] How can I escape a pound symbol in my script? References: <231662.89425.qm@web52504.mail.re2.yahoo.com> <468E394E.1070606@timgolden.me.uk> Message-ID: <01d101c7c193$645da340$b8fce004@JSLAPTOP> > ron wrote: >> in the US, # is a symbol for weight, not currency. > > I didn't know that; I assumed it was only > used for ordinal numbering (as in Item #3). > > # How do you write out, with a quick symbol, "I'm going to >> buy 3# of potatoes? This - #3 - means Number 3 This - 3# - means 3 pounds in weight. This is the true reason why (most) Americans call it a pound sign. Back in the days of typewriters when the key change may have been a reason, most Americans did not type. (That was for secretary women ;-) Sometimes you will see the "pound sign" on old, old recipes, but it is not used anymore. Only a novelty now. In fact, most English teachers in America are young enough now that using the # sign for pound will generate a syntax error. (that usage has been deprecated) They've all upgraded to the new version of English. English v1900.1001.2.2 or something like that. ;-) > Assuming that "you" is us Brits, then: > > 3lb That is the official way in America also. But technically (as I learned in some Physics courses) it's supposed to be succeeded by '.' whereas metric units are NOT. Picky, picky people, aren't they? sigh. Jacob S. From alan.gauld at btinternet.com Mon Jul 9 01:17:24 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Jul 2007 00:17:24 +0100 Subject: [Tutor] Key Error References: <570691.38917.qm@web35108.mail.mud.yahoo.com> Message-ID: "Sara Johnson" wrote > I apologize...but what is, 'grep'? The General Regular Expression Parser - at least that's one of the explanations. (Another is that it is the ed search command, and there are at least two more, it's part of the Unix mythology, debated for at least 30 years! :-) More pragmatically it is the standard Unix tool for searching text files for strings. Its available on other OS too thanks to GNU. Thus grep "NEWI" *.py will find all the occurences of NEWI in your python files. (grep -f will list only the files containing it.) If you use emacs or vi as your editor you can get the editor to step through the results in the same way as you step through the compilation errors after a make... You can search for sophisticated regex patterns and include or exclude patterns etc. grep should be a basic tool of any programmer regardless of language used or OS. > But if I can't get the program to initialize this 'NEWI' then > I don't know how any values can come from it. Thats the critical factor here. You need to initialise the dictionary in the first place. I notice from another post tat its being loaded from a pickle file. Try looking to see where it gets "dumped" to the file, that might help (grep again!) If the dump only happens when the program closes down then maybe just writing some default values on the first load of the program will do - thats where the get() method comes in again... It looks suspiciuously to me as if this NEWI key is some extra feature thats been added to the code and the initialisation code has not been updated to cope. Thats a common error especially in programs where the initialisation is in another program that only got run once a long time ago! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From keridee at jayco.net Sun Jul 8 21:44:13 2007 From: keridee at jayco.net (Tiger12506) Date: Sun, 8 Jul 2007 19:44:13 -0000 Subject: [Tutor] help with translating a c function to a python function References: <384c93600707050940i75d2bd72kd66bbe0356c010b7@mail.gmail.com><384c93600707051029i6b6c5dd1lf5e5f20431b2fc77@mail.gmail.com> Message-ID: <021b01c7c198$644a5010$b8fce004@JSLAPTOP> >> i have a c function from some modbus documentation that i need to >> translate into python. >> unsigned short CRC16(puchMsg, usDataLen) >> unsigned char *puchMsg ; >> unsigned short usDataLen ; >> { >> unsigned char uchCRCHi = 0xFF ; >> unsigned char uchCRCLo = 0xFF ; >> unsigned uIndex ; >> while (usDataLen??) >> { >> uIndex = uchCRCHi ^ *puchMsgg++ ; >> uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ; >> uchCRCLo = auchCRCLo[uIndex] ; >> } >> return (uchCRCHi << 8 | uchCRCLo) ; >> } I found this link which may provide some insight into what's going on here. (google "modbus CRC16") http://www.modbustools.com/modbus_crc16.htm This proves to me that auchCRCHi is a lookup table that you do not have access to. Happily :-) that link provides the table. Hmmm... let's see, the difficult C stuff... *puchMsgg++ means to return the current character in a string, and then increment the pointer, so that when the C code encounters *puchMsgg++ again it reads the next character, increments, etc. You can emulate this with an index and array notation in python. ^ , << , and | are all bitwise operators, and python uses all of these in the same way as C '^' means XOR exclusive OR. 0101 ^ 0011 = 0110 i.e. 5 ^ 3 = 6 '<< ' means left - shift 0010 << 2 = 1000 i.e. a << b = a * (2**b) '|' means OR. 0101 ^ 0011 = 0111 i.e. 5 ^ 3 = 7 puchMsgg is basically a string and all the unsigned stuff are (very roughly) integers. HTH, Jacob S. From jim at well.com Mon Jul 9 03:01:27 2007 From: jim at well.com (jim stockford) Date: Sun, 8 Jul 2007 18:01:27 -0700 Subject: [Tutor] Key Error In-Reply-To: References: <362062.566.qm@web35103.mail.mud.yahoo.com> Message-ID: On Jul 8, 2007, at 9:45 AM, Alan Gauld wrote: > (The tests at the end > are poorly written too. If one of my team produced code like > this I'd be having strong words with them!) If you'd be willing to share your strong words, I'd be grateful to learn better alternatives. From sarliz73 at yahoo.com Mon Jul 9 03:27:30 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Sun, 8 Jul 2007 18:27:30 -0700 (PDT) Subject: [Tutor] Key Error In-Reply-To: Message-ID: <548099.22121.qm@web35105.mail.mud.yahoo.com> If this is in reference to the code that I listed. I have no experience with Python so I may have left something off unknowingly which resulted in him questioning whatever was there. The strong words probably should be directed at me for not knowing what I'm doing. jim stockford wrote: On Jul 8, 2007, at 9:45 AM, Alan Gauld wrote: > (The tests at the end > are poorly written too. If one of my team produced code like > this I'd be having strong words with them!) If you'd be willing to share your strong words, I'd be grateful to learn better alternatives. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- We won't tell. Get more on shows you hate to love (and love to hate): Yahoo! TV's Guilty Pleasures list. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070708/d793defb/attachment.htm From nephish at gmail.com Mon Jul 9 03:34:04 2007 From: nephish at gmail.com (shawn bright) Date: Sun, 8 Jul 2007 20:34:04 -0500 Subject: [Tutor] help with translating a c function to a python function In-Reply-To: <021b01c7c198$644a5010$b8fce004@JSLAPTOP> References: <384c93600707050940i75d2bd72kd66bbe0356c010b7@mail.gmail.com> <384c93600707051029i6b6c5dd1lf5e5f20431b2fc77@mail.gmail.com> <021b01c7c198$644a5010$b8fce004@JSLAPTOP> Message-ID: <384c93600707081834s2c7a036n8fd09503de15b81b@mail.gmail.com> Hey thanks, i finally did get a function working. i posted it on www.bitsbam.com i did guess that the puchMsg++ ment that it was iterating through the bytes of an array. And Kent and Alan helped me get through the other parts. I am glad for all this help, because this is an issue that comes up increasingly often. so i am also glad for the email archiving by gmail. he he thanks all, shawn On 7/8/07, Tiger12506 wrote: > > > >> i have a c function from some modbus documentation that i need to > >> translate into python. > > >> unsigned short CRC16(puchMsg, usDataLen) > >> unsigned char *puchMsg ; > >> unsigned short usDataLen ; > >> { > >> unsigned char uchCRCHi = 0xFF ; > >> unsigned char uchCRCLo = 0xFF ; > >> unsigned uIndex ; > >> while (usDataLen??) > >> { > >> uIndex = uchCRCHi ^ *puchMsgg++ ; > >> uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ; > >> uchCRCLo = auchCRCLo[uIndex] ; > >> } > >> return (uchCRCHi << 8 | uchCRCLo) ; > >> } > > I found this link which may provide some insight into what's going on > here. > (google "modbus CRC16") > > http://www.modbustools.com/modbus_crc16.htm > > This proves to me that auchCRCHi is a lookup table that you do not have > access to. Happily :-) that link provides the table. > > Hmmm... let's see, the difficult C stuff... *puchMsgg++ means to return > the > current character in a string, and then increment the pointer, so that > when > the C code encounters *puchMsgg++ again it reads the next character, > increments, etc. You can emulate this with an index and array notation in > python. > > ^ , << , and | are all bitwise operators, and python uses all of these > in the same way as C > > '^' means XOR exclusive OR. > 0101 ^ 0011 = 0110 i.e. 5 ^ 3 = 6 > > '<< ' means left - shift > 0010 << 2 = 1000 i.e. a << b = a * (2**b) > > '|' means OR. > 0101 ^ 0011 = 0111 i.e. 5 ^ 3 = 7 > > puchMsgg is basically a string > and all the unsigned stuff are (very roughly) integers. > > HTH, > Jacob S. > > _______________________________________________ > 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/20070708/5b78077a/attachment-0001.html From sarliz73 at yahoo.com Mon Jul 9 03:41:45 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Sun, 8 Jul 2007 18:41:45 -0700 (PDT) Subject: [Tutor] Bundle help! In-Reply-To: <46811E98.2070401@tds.net> Message-ID: <595920.19878.qm@web35111.mail.mud.yahoo.com> I brought this up with Kent a little while ago... >>>If you have a list of pairs of (name, percentage) then you should be >>>able to sort it directly with the sort() method of the list. For >>>example: >>>In [3]: data = [ ('Kent', 50), ('Sara', 80), ('Fred', 20) ] >>>In [4]: data.sort() >>>In [5]: data >>>Out[5]: [('Fred', 20), ('Kent', 50), ('Sara', 80)] >Use append() to add more data, then sort again to get it in order: >>>In [6]: data.append(('Joe', 90)) >>>In [7]: data.sort() >>>In [8]: data >>>Out[8]: [('Fred', 20), ('Joe', 90), ('Kent', 50), ('Sara', 80)] What happens if I need to sort alphabetical and numerically? I guess in this case it would be.... ('Fred', 20), ('Joe', 50), ('Kent', 80), ('Sara', 90) I'm taking the original list and the original values i.e., ('Fred', 20), ('Joe', 90), ('Kent', 80)... and switching it so that it reads in both ways... List 1, [('Fred', 20), ('Joe', 90), ('Kent', 50), ('Sara', 80)] List 2, ('Fred', 20), ('Joe', 50), ('Kent', 80), ('Sara', 90)] How would I do that so I wind up with both lists? I have two lists now, but if I try and reorder them they just reverse in alphabetical order without affecting the second value (the number). Thanks! --------------------------------- Boardwalk for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's economy) at Yahoo! Games. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070708/f88e21cd/attachment.htm From alan.gauld at btinternet.com Mon Jul 9 09:22:05 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Jul 2007 08:22:05 +0100 Subject: [Tutor] Key Error References: <362062.566.qm@web35103.mail.mud.yahoo.com> Message-ID: "jim stockford" wrote >> (The tests at the end are poorly written too. > > If you'd be willing to share your strong words, I'd > be grateful to learn better alternatives. OK, The strong words referred to the entire piece and the biggest error was the lack of try/except or get(). However the tests are badly done IMHO for several reasons, namely: if wssd<-989. or wspd<-989. or wmax<-989.: break if wspd==0.: break 1) Both sets of tests result in a break so the last test should be combined with the others in a single line. (as a sub point I'd also prefer to see both tests on wspd placed together for ease of maintenance) 2) The values are floating point but the programmer has lazily omited the end zero which makes it very hard to spot the trailing decimal point. 3) The last equality test is inherently unreliable when using floating point values since if the value were derived by calciulation it might be 'nearly zero', the best way to check equality for floats is to test within a range. (If this case is guaranteed safe I would expect a comment to explain why, because it's such an unusual situation...) 4) The spacing between the < and minus sign is non existent which could lead to the combination being read as a <- arrow sign. Now inPyton that doesn't mean anything but in other languages does, so a reader not familiar with Python (like our OP) might be misdirected, whereas a simple space would remove any doubt. Some might also object to the break being on the same line as the test but personally I don't object to that. But the points above all have real impact on legibility, maintainability and, potentially, reliability. We wouldn't normally expect to see such pickiness in this list because its aimed at beginners, but if this is production code, and from the look of it, in the telecomms market - which usually demands very high standards, then the quality should be much higher. I'd prefer the tests to be written like this: e = 0.0000000000001 if -e <= wspd <= e or wspd < -989.0 or wssd < -989.0 or wmax < -989.0: break Its more typing and more room but less ambiguous and easier to read IMHO. Alan G. From alan.gauld at btinternet.com Mon Jul 9 09:26:32 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Jul 2007 08:26:32 +0100 Subject: [Tutor] Bundle help! References: <46811E98.2070401@tds.net> <595920.19878.qm@web35111.mail.mud.yahoo.com> Message-ID: "Sara Johnson" wrote >>Use append() to add more data, then sort again to get it in order: >>>>In [6]: data.append(('Joe', 90)) >>>>In [7]: data.sort() >>>>In [8]: data >>>>Out[8]: [('Fred', 20), ('Joe', 90), ('Kent', 50), ('Sara', 80)] > > What happens if I need to sort alphabetical and numerically? You can supply your own comparison function to the sort routine. You can also just specify the key to sort by for simple cases. > I'm taking the original list and the original values > i.e., ('Fred', 20), ('Joe', 90), ('Kent', 80)... and switching it > so that it reads in both ways... > List 1, [('Fred', 20), ('Joe', 90), ('Kent', 50), ('Sara', 80)] > List 2, ('Fred', 20), ('Joe', 50), ('Kent', 80), ('Sara', 90)] But you lost me here. You seem to be switching the values in the tuples around and its not clear to me by what criteria. HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dperlman at wisc.edu Mon Jul 9 17:53:41 2007 From: dperlman at wisc.edu (David Perlman) Date: Mon, 09 Jul 2007 08:53:41 -0700 Subject: [Tutor] Bundle help! In-Reply-To: <595920.19878.qm@web35111.mail.mud.yahoo.com> References: <595920.19878.qm@web35111.mail.mud.yahoo.com> Message-ID: <1A2A43EE-1598-407D-AC6F-7775DE379396@wisc.edu> I think what you want to do is start from the beginning with two separate lists, sort each one however you want, and then either join them with zip() or simply reference them as (list1[n], list2[n]). I believe there's also a way to use zip() to separate your list of tuples into separate lists, but I don't know how off the top of my head. You can find out if you follow these instructions though: Go to http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&group=comp.lang.py enter 'zip inverse', and check search Python only. On Jul 8, 2007, at 6:41 PM, Sara Johnson wrote: > How would I do that so I wind up with both lists? I have two lists > now, but if I try and reorder them they just reverse in > alphabetical order without affecting the second value (the number). > -- -dave---------------------------------------------------------------- All I ask is that the kind of unsolvable that it turns out to be has respectable precedents. -Jerry Fodor From sarliz73 at yahoo.com Mon Jul 9 18:54:13 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Mon, 9 Jul 2007 09:54:13 -0700 (PDT) Subject: [Tutor] Bundle help! In-Reply-To: Message-ID: <235766.24467.qm@web35113.mail.mud.yahoo.com> Sorry to be so confusing. Just realized a dumb mistake I made. It doesn't need to be resorted alphabetically and numerically. I need one list alphabetical and one numerical. (Alphabetical) List 1, [('Fred', 20), ('Joe', 90), ('Kent', 50), ('Sara', 80)] (Numerical) List 2, [('Fred', 20), ('Kent', 50), ('Sara', 80) ('Joe', 90)] It looks like these are appended together, but to re-sort, how do I (not sure if this is a word) "unappend" them? Thanks, Sara Alan Gauld wrote: "Sara Johnson" wrote >>Use append() to add more data, then sort again to get it in order: >>>>In [6]: data.append(('Joe', 90)) >>>>In [7]: data.sort() >>>>In [8]: data >>>>Out[8]: [('Fred', 20), ('Joe', 90), ('Kent', 50), ('Sara', 80)] > > What happens if I need to sort alphabetical and numerically? You can supply your own comparison function to the sort routine. You can also just specify the key to sort by for simple cases. > I'm taking the original list and the original values > i.e., ('Fred', 20), ('Joe', 90), ('Kent', 80)... and switching it > so that it reads in both ways... > List 1, [('Fred', 20), ('Joe', 90), ('Kent', 50), ('Sara', 80)] > List 2, ('Fred', 20), ('Joe', 50), ('Kent', 80), ('Sara', 90)] But you lost me here. You seem to be switching the values in the tuples around and its not clear to me by what criteria. --------------------------------- Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070709/74fea07f/attachment.html From dperlman at wisc.edu Mon Jul 9 19:08:23 2007 From: dperlman at wisc.edu (David Perlman) Date: Mon, 09 Jul 2007 10:08:23 -0700 Subject: [Tutor] Bundle help! In-Reply-To: <235766.24467.qm@web35113.mail.mud.yahoo.com> References: <235766.24467.qm@web35113.mail.mud.yahoo.com> Message-ID: <75FA1944-31FD-4E19-AD84-2129F7FB973C@wisc.edu> Maybe this reference will help: http://xahlee.org/perl-python/sort_list.html Just the first part of the discussion there. On Jul 9, 2007, at 9:54 AM, Sara Johnson wrote: > Sorry to be so confusing. Just realized a dumb mistake I made. It > doesn't need to be resorted alphabetically and numerically. I need > one list alphabetical and one numerical. > > > (Alphabetical) List 1, [('Fred', 20), ('Joe', 90), ('Kent', 50), > ('Sara', 80)] > > (Numerical) List 2, [('Fred', 20), ('Kent', 50), ('Sara', 80) > ('Joe', 90)] > > > It looks like these are appended together, but to re-sort, how do I > (not sure if this is a word) "unappend" them? > -- -dave---------------------------------------------------------------- All I ask is that the kind of unsolvable that it turns out to be has respectable precedents. -Jerry Fodor From sarliz73 at yahoo.com Mon Jul 9 19:32:34 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Mon, 9 Jul 2007 10:32:34 -0700 (PDT) Subject: [Tutor] Bundle help! In-Reply-To: <1A2A43EE-1598-407D-AC6F-7775DE379396@wisc.edu> Message-ID: <640762.57538.qm@web35109.mail.mud.yahoo.com> Sorry, just needing to clarify. As I may have eluded to in other posts, this is sort of a script that was written and I'm making modifications to. Due to my serious lack of experience, I'm afraid to rewrite anything. However, would I accomplish the same result by copying the lists, then breaking them apart with zip()? I haven't used that before, but I'm willing to try it as long as I don't ruin what's already been done. Unfortunately, the link you posted didn't bring up anything. I tried to search google groups and got a bunch of asian text (using comp.lang.py). Again, sorry for my lack of experience here. I do speak C somewhat. Guess I should sign this: HTDI...(hope that didn't irritate!) Sara David Perlman wrote: I think what you want to do is start from the beginning with two separate lists, sort each one however you want, and then either join them with zip() or simply reference them as (list1[n], list2[n]). I believe there's also a way to use zip() to separate your list of tuples into separate lists, but I don't know how off the top of my head. You can find out if you follow these instructions though: Go to http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&group=comp.lang.py enter 'zip inverse', and check search Python only. On Jul 8, 2007, at 6:41 PM, Sara Johnson wrote: > How would I do that so I wind up with both lists? I have two lists > now, but if I try and reorder them they just reverse in > alphabetical order without affecting the second value (the number). > -- -dave---------------------------------------------------------------- All I ask is that the kind of unsolvable that it turns out to be has respectable precedents. -Jerry Fodor _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Pinpoint customers who are looking for what you sell. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070709/68fc1da1/attachment.htm From alan.gauld at btinternet.com Mon Jul 9 19:53:45 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Jul 2007 18:53:45 +0100 Subject: [Tutor] Bundle help! References: <1A2A43EE-1598-407D-AC6F-7775DE379396@wisc.edu> <640762.57538.qm@web35109.mail.mud.yahoo.com> Message-ID: "Sara Johnson" wrote > this is sort of a script that was written and I'm making > modifications to. Due to my serious lack of experience, > I'm afraid to rewrite anything. This is probably a long shot given the code you've posted so far, but I don't suppose there are any design documents available? Structure charets, class diagrams? Even plain text or pseudo code? In an ideal world it would be possible to find the faulty function without having to read any code, but few projects are that well documented. But then again few projects have nothing! If you can find it it might tell you at a high level how the code hangs together. > However, would I accomplish the same result by copying > the lists, then breaking them apart with zip()? I'm not sure zip is the best tool for breaking lists apart, but I'm no expert with it. But its easy to do with a simple loop if you are dealing with a list of tuples: list1 = [] list2 = [] for item in theList: list1.append(item[0]) list2.append(item[1]) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From tnoyeaux at msn.com Mon Jul 9 22:11:20 2007 From: tnoyeaux at msn.com (Tony Noyeaux) Date: Mon, 9 Jul 2007 16:11:20 -0400 Subject: [Tutor] Resource request Message-ID: I am looking for a good online resource for the "def Menu" and/or "elif choice" commands. Any help would be much appreciated. _________________________________________________________________ Don't get caught with egg on your face. Play Chicktionary!?? http://club.live.com/chicktionary.aspx?icid=chick_wlmailtextlink -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070709/a388cfde/attachment.html From alan.gauld at btinternet.com Mon Jul 9 22:24:46 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Jul 2007 21:24:46 +0100 Subject: [Tutor] Resource request References: Message-ID: "Tony Noyeaux" wrote > I am looking for a good online resource for > > the "def Menu" def is the command for defining a function. Menu, in this vcase, is the name of the function being defined. You will find functions explained in the Modules and Functions topic of my tutorial. > and/or "elif choice" commands. I'm not sure why you think its a case of and/or? You need to know about elif quite apart from, and in addition to, functions. The use of if/elif/else is described in the branching topic of my tutorial. Given your questions it sounds like you are a beginner to programming in general, not just Python. In which case you should consider going through any of the tutorials listed here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers possibly mine! :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From keridee at jayco.net Mon Jul 9 19:22:52 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 9 Jul 2007 17:22:52 -0000 Subject: [Tutor] Fastest way to iterate through a file References: <468050D5.3020403@tds.net><674d5ce60707011334n68ae9565ka7525740108d6e17@mail.gmail.com><674d5ce60707051430u127ef70dp606fda6d5dae1440@mail.gmail.com> Message-ID: <016e01c7c24d$cc0071c0$28fce004@JSLAPTOP> It seems to me that what you need is this. http://www.python.net/crew/mhammond/win32/Downloads.html I think the key that you are missing here is that python does not include functions that you ask without downloading something special. Check the link, download those extensions, and read the documents included with them. Particularly this section: - Python for... |_ Win32 API |_ Modules |_ win32api HTH, Jacob S. >>I need some of a something to be imported into python > > Maybe. > >> these are the functions I need, anyway know anything that might do >> any of >> the following? > > Assuming you are still talking about Windows XP... > >> suppose the class' name is autowindow: > > What kind of class? No such class exists so are you > proposing to create it? Is it based on a Windows object? > > Remember python is a programming language not a GUI toolkit. > If you want to do things to a GUI you need a toolkit. It might > be linked to the native Win32 API through winall or ctypes or > it might be a cross platform toolkit like Tkinter or wxPython, > but its not part of Python. > >> autowindow.gainfocus(handle) >> put the window of that handle into focus. > > The Win32 SetFocus function does that. > >> import autowindow >> autowindow.imagechecksum() >> autowindow.imagechecksum("c:\image\image.bmp") >> autowindow.areachecksum() >> >> sum = autowindow.areachecksum(x1,y1,x2,y2) absolute screen >> coordinate > > Its unlikely any GUI toolkit will do that, it sounds more like > a job for a graphics toolkit like PIL. > >> autowindow.getmousepos() > > Mouse events carry the x/y coordinates. > Just trap any mouse move and it will tell you where it is. > >> autowindow.restart() >> autowindow.shutdown() > > This is hardware dependant, some computers won;t allow it. > But on Windows you can try using the API as described on this page > (which I found with a simple google search on Win32 restart shutdown) > > http://blogs.msdn.com/brad_mccabe/archive/2005/03/02/383542.aspx > >> autowindow.winexist() >> true/false = autowindow.winexist() >> handle or window name. (no class wanted!) > > FindWindow will effectively do this. > >> autowindow.listwindows() > > EnumWindows does this for you > > We discussed both of these recently. > >> autowindow.GainFocus() > > You already asked for this. > >> autowindow.KeyboardEvent(text) > > Yep, all toolkits allow you to trap a keyboard event. > Most distinguish between key down and key up as well > as the generic keypress. > > Or if you want to simulate a keyboard event you can use > PostMessage. Again we discussed this recently. > >> autowindow.KeyboardEvent("Python rocks!", keyholddelay ) >> keyholddelay = miliseconds. > > No idea what this is supposed to be/do. > >> autowindow.mouseclick(button, clicks) >> autowindow.MouseEvent(x, y, button, clicks) >> autowindow.mousemove() >> autowindow.mousemove(x,y, speed) >> autowindow.winMove(x, y) >> autowindow.winResize(x, y) >> autowindow.winMinimize() >> autowindow.winMaximize() >> autowindow.winClose() > > These are all standard event types. > >> they all take handle > > And if you want to simulate them use PostMessage > >> autowindow.listwindows() >> autowindow.listwindows("window name") >> returns a list of handles if multiple > > You are repeating yourself again. > >> autowindow.hotkey() >> autowindow.hotkey(keyboard key, function) >> keyboard key = any key on keyboard >> function = function to start > > Not sure, there may be a Windows function for this but > I haven't seen it... > >> auntwindow.run ( /source/exe.exe, "image.bmp" ) > > Try ExecFile > or WinExec > >> autowindow.msgbox("window name", "window message", box_number ) > > Standard windows MsgBox function > > Have you actually tried looking for these on MSDN for yourself. > They are standard windows functions. They are mapped into Python > by the toolkirs but the basic functions are pure windows and > documented in MSDN. > > Recall I recommended reading the web page on how to ask smart > questions? One of the key points is not to ask the same questions > multiple times of the same audience - and especially not in the > same message! > > Also provide some context abvout why you need the information. > What you are trying to achieve etc. Othewise you will get the same > level of vagueness back that you provide. > > -- > 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 > From hunter92383 at gmail.com Tue Jul 10 00:51:52 2007 From: hunter92383 at gmail.com (elis aeris) Date: Mon, 9 Jul 2007 15:51:52 -0700 Subject: [Tutor] file methods Message-ID: <674d5ce60707091551n572fd651k690256bb6f9d6e6e@mail.gmail.com> python 3.9 File Objects of Python Library Reference from the document i know that if I want to open a text file I do: f = open("text.txt", "r+") and thus create f as an file object i can then use. however, i don't understand these functions .readline .readlines .read .xlinesread I have a file like this one: command = func_babara parameter_1 = 300 parameter_2 = 300 parameter_3 = 50 parameter_4 = 0 parameter_5 = 0 parameter_6 = 0 ,as you see, i need to process it one line at a time and use this .ini file as a configuration file. how do I use those functions, I don't understand the libarry reference. also, I need to output lines like above to text.txt, how do I do it? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070709/268067b4/attachment.html From rabidpoobear at gmail.com Tue Jul 10 00:57:36 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 09 Jul 2007 17:57:36 -0500 Subject: [Tutor] file methods In-Reply-To: <674d5ce60707091551n572fd651k690256bb6f9d6e6e@mail.gmail.com> References: <674d5ce60707091551n572fd651k690256bb6f9d6e6e@mail.gmail.com> Message-ID: <4692BD60.3030504@gmail.com> elis aeris wrote: > python 3.9 File Objects of Python Library Reference > > > > from the document i know that if I want to open a text file I do: > > f = open("text.txt", "r+") > > and thus create f as an file object i can then use. > > however, i don't understand these functions > > .readline > .readlines > .read > .xlinesread > > I have a file like this one: > > command = func_babara > parameter_1 = 300 > parameter_2 = 300 > parameter_3 = 50 > parameter_4 = 0 > parameter_5 = 0 > parameter_6 = 0 > > > ,as you see, i need to process it one line at a time and use this .ini > file as a configuration file. > > how do I use those functions, I don't understand the libarry reference. > > also, I need to output lines like above to text.txt, how do I do it? elis - have you looked into any of the tutorials that people have referred you to? It appears that you aren't putting forth the effort to learn Python, and you're just presenting us with any issues you need to solve (I.E. getting us to do it for you). Personally, I don't have any desire to help you when I get the impression that you aren't trying to learn at all. -Luke From john at fouhy.net Tue Jul 10 01:00:56 2007 From: john at fouhy.net (John Fouhy) Date: Tue, 10 Jul 2007 11:00:56 +1200 Subject: [Tutor] file methods In-Reply-To: <674d5ce60707091551n572fd651k690256bb6f9d6e6e@mail.gmail.com> References: <674d5ce60707091551n572fd651k690256bb6f9d6e6e@mail.gmail.com> Message-ID: <5e58f2e40707091600o6248cc92q36131a55ee9e3462@mail.gmail.com> On 10/07/07, elis aeris wrote: > from the document i know that if I want to open a text file I do: > > f = open("text.txt", "r+") > > and thus create f as an file object i can then use. > > however, i don't understand these functions > > .readline > .readlines > .read > .xlinesread The best way to find out what the functions do is to experiment with them. eg: >>> f = open('text.txt', 'r') >>> f.readlines() and look at the output. However, that said, the modern way to read a file one line at a time is: f = open('text.txt', 'r') for line in f: # do something with line This will set the variable 'line' to each line of the file in turn. -- John. From bhaaluu at gmail.com Tue Jul 10 02:54:54 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 9 Jul 2007 20:54:54 -0400 Subject: [Tutor] file methods In-Reply-To: <5e58f2e40707091600o6248cc92q36131a55ee9e3462@mail.gmail.com> References: <674d5ce60707091551n572fd651k690256bb6f9d6e6e@mail.gmail.com> <5e58f2e40707091600o6248cc92q36131a55ee9e3462@mail.gmail.com> Message-ID: Greetings, On 7/9/07, John Fouhy wrote: > > The best way to find out what the functions do is to experiment with them. > > eg: > > >>> f = open('text.txt', 'r') > >>> f.readlines() > > and look at the output. I like that idea. I made a simple english plain text file, thus: first line second line third line and named it text.txt. I start the Python interactive interpreter: >>> >>> open('text.txt').read() 'first line\nsecond line\nthird line\n' >>> len(open('text.txt').read()) 34 >>> file=open('text.txt').read() >>> print file first line second line third line >>> file.readlines() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'str' object has no attribute 'readlines' > However, that said, the modern way to read a file one line at a time is: > > f = open('text.txt', 'r') > for line in f: > # do something with line > > This will set the variable 'line' to each line of the file in turn. >>> for line in file: . . . print line . . . f i r s t l i n e s e c o n d l i n e t h i r d l i n e >>> > > -- > John. >>> Ctrl-D Oh well, back to the tutorials.... 8^D -- bhaaluu at gmail dot com From john at fouhy.net Tue Jul 10 03:04:20 2007 From: john at fouhy.net (John Fouhy) Date: Tue, 10 Jul 2007 13:04:20 +1200 Subject: [Tutor] file methods In-Reply-To: References: <674d5ce60707091551n572fd651k690256bb6f9d6e6e@mail.gmail.com> <5e58f2e40707091600o6248cc92q36131a55ee9e3462@mail.gmail.com> Message-ID: <5e58f2e40707091804j51dfe202g426c13bfe0ac4428@mail.gmail.com> On 10/07/07, bhaaluu wrote: > >>> file.readlines() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'str' object has no attribute 'readlines' This error here is caused by this earlier statement: > >>> file=open('text.txt').read() 'file' is now a string, not a file-like object. This also causes the behaviour you get when iterating 'for line in file'... -- John. From billburns at pennswoods.net Tue Jul 10 04:00:28 2007 From: billburns at pennswoods.net (Bill Burns) Date: Mon, 09 Jul 2007 22:00:28 -0400 Subject: [Tutor] Bundle help! In-Reply-To: <235766.24467.qm@web35113.mail.mud.yahoo.com> References: <235766.24467.qm@web35113.mail.mud.yahoo.com> Message-ID: <4692E83C.6020806@pennswoods.net> [Sara Johnson] > Sorry to be so confusing. Just realized a dumb mistake I made. It > doesn't need to be resorted alphabetically and numerically. I need one > list alphabetical and one numerical. > > > (Alphabetical) List 1, [('Fred', 20), ('Joe', 90), ('Kent', 50), > ('Sara', 80)] > > (Numerical) List 2, [('Fred', 20), ('Kent', 50), ('Sara', 80) ('Joe', 90)] > I didn't keep track of the thread very well, so I don't know if you have one single list or two separate lists?? I'll assume you have a single list and you want to create two new lists sorted differently: # Single 'Master List'. masterList = [('Sara', 80), ('Kent', 50), ('Joe', 90), ('Fred', 20)] # Create a list for our alpha sort. alphaList = list(masterList) # Simply calling sort() will sort it alphabetically. alphaList.sort() print 'Alphabetical List: ', alphaList def sortByNum(tup): # Helper function. return tup[1] # Create a list for our numerical sort. numList = list(masterList) # sort() can take an optional key parameter, which allows us to define # our own sorting method. This sort() calls the sortByNum() function, # which I've defined to only look at the 2nd item in the tuple (the # numerical portion. numList.sort(key=sortByNum) print 'Numerical List: ', numList # Or you could also use a lambda in place of the separate # function def, which would eliminate sortByNum() completely. #~ numList.sort(key=lambda tup: tup[1]) #~ print 'Numerical List: ', numList # And another method using the operator module... #~ import operator #~ numList.sort(key=operator.itemgetter(1)) #~ print 'Numerical List: ', numList HTH, Bill From alan.gauld at btinternet.com Tue Jul 10 09:15:26 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Jul 2007 08:15:26 +0100 Subject: [Tutor] file methods References: <674d5ce60707091551n572fd651k690256bb6f9d6e6e@mail.gmail.com><5e58f2e40707091600o6248cc92q36131a55ee9e3462@mail.gmail.com> Message-ID: "bhaaluu" wrote >> The best way to find out what the functions do is to experiment >> with them. >> >> eg: >> >> >>> f = open('text.txt', 'r') >> >>> f.readlines() >> >> and look at the output. > > I like that idea. I made a simple english plain text file, thus: > > first line > second line > third line > > and named it text.txt. > > I start the Python interactive interpreter: >>>> > >>>> open('text.txt').read() > 'first line\nsecond line\nthird line\n' And this is where your problems start. You are not creating a file object that you can use, instead you are immediately calling read)() which reads the whole file as a string. All the subsequent operations you do are to the string not the file. If you look at Johns origonal example he first created a file object, f, and then experimented with the methods Alan G. From alan.gauld at btinternet.com Tue Jul 10 09:23:44 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Jul 2007 08:23:44 +0100 Subject: [Tutor] file methods References: <674d5ce60707091551n572fd651k690256bb6f9d6e6e@mail.gmail.com> Message-ID: "elis aeris" wrote > python 3.9 File Objects of Python Library Reference > Learning to program from the reference manual is possible, especially if you use the interpreter to experiment as John has suggested. But it will be much faster and less error prone if you just work through oine of the beginners tutorials. They will all explain how to access files. > from the document i know that if I want to open a text file I do: > > f = open("text.txt", "r+") Usually you don't want the + sign which means "read and write". You open a file to read or to write, very rarely do you open it to read and write at the same time, that's frought with difficulty, especially for a beginner. Thus the best way to open a file is either f = open('text.txt','r') # to read it f = open('text.txt','w') # to create a new file and write to it > and thus create f as an file object i can then use. > > however, i don't understand these functions > > .readline This reads a line of the file > .readlines this reads all of the lines in the file into a list > .read this reads the whole file as a single string > .xlinesread I assume you mean xreadlines? Thats pretty much not needed nowadays, it used to be a more memory efficient version of readlines > I have a file like this one: > > command = func_babara > parameter_1 = 300 > parameter_2 = 300 > parameter_3 = 50 > parameter_4 = 0 > parameter_5 = 0 > parameter_6 = 0 > > > ,as you see, i need to process it one line at a time and use this > .ini file > as a configuration file. OK, Just use readlines to read each line and process it. Or as John mentions just iterate over the file directly. > how do I use those functions, I don't understand the libarry > reference. Read one of the tutorials, such as the Handling Files topic in my tutorial. > also, I need to output lines like above to text.txt, how do I do > it? Use the write methods, you have only looked at the read ones from your list above. Again see the Handling Files topic in my tutorial, or indeed any other beginners tutiorial. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From patoot_rulz at hotmail.com Tue Jul 10 09:55:51 2007 From: patoot_rulz at hotmail.com (Dave Pata) Date: Tue, 10 Jul 2007 17:55:51 +1000 Subject: [Tutor] font colours Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070710/30cd09fe/attachment.html From patoot_rulz at hotmail.com Tue Jul 10 10:37:45 2007 From: patoot_rulz at hotmail.com (Dave Pata) Date: Tue, 10 Jul 2007 18:37:45 +1000 Subject: [Tutor] GUI backgrounds using Tk Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070710/f72d0fb4/attachment-0001.htm From bhaaluu at gmail.com Tue Jul 10 14:24:36 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 10 Jul 2007 08:24:36 -0400 Subject: [Tutor] file methods In-Reply-To: <5e58f2e40707091804j51dfe202g426c13bfe0ac4428@mail.gmail.com> References: <674d5ce60707091551n572fd651k690256bb6f9d6e6e@mail.gmail.com> <5e58f2e40707091600o6248cc92q36131a55ee9e3462@mail.gmail.com> <5e58f2e40707091804j51dfe202g426c13bfe0ac4428@mail.gmail.com> Message-ID: Greetings, On 7/9/07, John Fouhy wrote: > On 10/07/07, bhaaluu wrote: > > >>> file.readlines() > > Traceback (most recent call last): > > File "", line 1, in ? > > AttributeError: 'str' object has no attribute 'readlines' > > This error here is caused by this earlier statement: > > > >>> file=open('text.txt').read() > > 'file' is now a string, not a file-like object. This also causes the > behaviour you get when iterating 'for line in file'... > > -- > John. > Thank you for the clarification. One pitfall of experimentation as a Noob is in not knowing enough to figure out what or why errors are generated. Thus, this Tutor list is very helpful. I really appreciate the feedback. So, in summary: file = open('text.txt', 'r') makes 'file' a "file object". and file = open('text.txt').read() makes 'file' hold 'text.txt' as a string. If 'file' is an 'object', I guess it is easier to use the "methods" .readline(), .readlines() ,.read(), and .xlinesread(), on it? Whereas, if 'file' is a string, those "methods" can't be used on it? I'm still struggling with the oop terminology, so please be gentle. =) As regards the terminology: a problem for Me is that the OOP terms for Python are usually explained in terms of other OOP languages. I would certainly welcome an introduction to OOP for Python that explains OOP without referring to any other OOP language. Python is my first OOP language, and the references to what the concepts are called in other OOP languages are just plain confusing at times. My modus operandi : Read from a Python tutorial. Type in the examples and run them. Read more, type more, run more. Read the Python Tutor mailing list.... Evidently, in Python, the main programming paradigm is: object.attribute AND in Python, "everything is an object." Cheers! 8^D -- bhaaluu at gmail dot com From Mike.Hansen at atmel.com Tue Jul 10 16:27:16 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Tue, 10 Jul 2007 08:27:16 -0600 Subject: [Tutor] file methods In-Reply-To: <674d5ce60707091551n572fd651k690256bb6f9d6e6e@mail.gmail.com> References: <674d5ce60707091551n572fd651k690256bb6f9d6e6e@mail.gmail.com> Message-ID: <57B026980605A64F9B23484C5659E32E8F511C@poccso.US.ad.atmel.com> > -----Original Message----- >[...] > I have a file like this one: > > command = func_babara > parameter_1 = 300 > parameter_2 = 300 > parameter_3 = 50 > parameter_4 = 0 > parameter_5 = 0 > parameter_6 = 0 > > > ,as you see, i need to process it one line at a time and use > this .ini file as a configuration file. > Take a look at the ConfigParser module. It can read ini files easily. Mike From aymchaos at yahoo.com Tue Jul 10 16:27:08 2007 From: aymchaos at yahoo.com (Mihai Iacob) Date: Tue, 10 Jul 2007 07:27:08 -0700 (PDT) Subject: [Tutor] Integer to binary Message-ID: <839688.18500.qm@web32714.mail.mud.yahoo.com> Hello, Is there a function that converts from integer to binary (or a module that handles this)? The only thing close to it that i found in the manual is the binascii module but i can't get it to work. Thanks ____________________________________________________________________________________ Shape Yahoo! in your own image. Join our Network Research Panel today! http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 From rdm at rcblue.com Tue Jul 10 17:38:18 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 10 Jul 2007 08:38:18 -0700 Subject: [Tutor] Integer to binary In-Reply-To: <839688.18500.qm@web32714.mail.mud.yahoo.com> References: <839688.18500.qm@web32714.mail.mud.yahoo.com> Message-ID: <20070710153833.70C151E4003@bag.python.org> At 07:27 AM 7/10/2007, Mihai Iacob wrote: >Hello, > >Is there a function that converts from integer to >binary (or a module that handles this)? > >The only thing close to it that i found in the manual >is the binascii module but i can't get it to work. Here's one: def base10ToBaseN(n, base=2): """converts base 10 integer n to base 2-9 integer as string""" if n == 0: return '0' sign = '-' if n<0 else '' num = abs(n) seq = [] while (num != 0): (num, bit) = divmod(num, base) seq.append(str(bit)) seq.append(sign) return ''.join(reversed(seq)) Dick Moores From dkuhlman at rexx.com Tue Jul 10 18:08:09 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 10 Jul 2007 09:08:09 -0700 Subject: [Tutor] file methods In-Reply-To: References: <674d5ce60707091551n572fd651k690256bb6f9d6e6e@mail.gmail.com> <5e58f2e40707091600o6248cc92q36131a55ee9e3462@mail.gmail.com> <5e58f2e40707091804j51dfe202g426c13bfe0ac4428@mail.gmail.com> Message-ID: <20070710160809.GB21020@cutter.rexx.com> On Tue, Jul 10, 2007 at 08:24:36AM -0400, bhaaluu wrote: > Thank you for the clarification. > One pitfall of experimentation as a Noob is in not knowing enough to > figure out what or why errors are generated. Thus, this Tutor list is very > helpful. I really appreciate the feedback. > You might consider installing and using IPython instead of the standard Python interactive prompt. At the IPython prompt, the question mark operator gives help. For example, notice the "f.read?", below. In [25]: f = open('test_lxml.py', 'r') In [26]: f.read? Type: builtin_function_or_method Base Class: String Form: Namespace: Interactive Docstring: read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. IPython is at: http://ipython.scipy.org/moin/ Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From alan.gauld at btinternet.com Tue Jul 10 19:12:10 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Jul 2007 18:12:10 +0100 Subject: [Tutor] Integer to binary References: <839688.18500.qm@web32714.mail.mud.yahoo.com> Message-ID: "Mihai Iacob" wrote > Is there a function that converts from integer to > binary (or a module that handles this)? Remember that integers are binary. Thats how they are stored. What I think you want is something that will represent an integer as a string of 1s and 0s. Something like the hex function which returns the hex string version of a number? Sadly, and I don't understand why, it doesn't exist in the standard library. But its easy to build your own. Here is one, Dick has provided another more general form: def bin(n): digits = ['000','001','010','011','100','101','110','111'] num = oct(int(n)) result = "" for d in num: result += digits[int(d)] return result.lstrip('0') NB There's a bug in handling negative numbers! HTH, Alan G. From alan.gauld at btinternet.com Tue Jul 10 19:14:03 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Jul 2007 18:14:03 +0100 Subject: [Tutor] GUI backgrounds using Tk References: Message-ID: "Dave Pata" wrote > I was wondering if anyone knows how to insert graphic images, > such as JPEG and BMP, into a simple Tk GUI and use them > as the background. Any help will be appreciated. since its for homework onl;y hints are allowed. You need to look at the Image object in Tk and insert one of those into your GUI Alan G From tnoyeaux at msn.com Tue Jul 10 19:37:34 2007 From: tnoyeaux at msn.com (Tony Noyeaux) Date: Tue, 10 Jul 2007 13:37:34 -0400 Subject: [Tutor] Code query..works in IDLE but not DrPython editor Message-ID: Simple Random code. import randomprint random.choice(['Apple', 'Pear', 'Shrimp', 'Death', 'Life']) Works in IDLE gui, no problem. Gives me a random pick no problem. When i changed to DrPython, to continue building parts of my code.. it won't take that code. Gives me this error. C:/Python/pythonw.exe -u "C:/Python25/random.py"Traceback (most recent call last): File "C:/Python25/random.py", line 1, in import random File "C:\Python25\random.py", line 2, in print random.choice(['Apple', 'Pear', 'Shrimp', 'Death', 'Life'])AttributeError: 'module' object has no attribute 'choice' ... not sure why one editor would work, and while the other won't?.. any suggestions. Looking for some insight. _________________________________________________________________ See what you?re getting into?before you go there. http://newlivehotmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070710/0641681a/attachment.htm From dkuhlman at rexx.com Tue Jul 10 20:58:59 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 10 Jul 2007 11:58:59 -0700 Subject: [Tutor] Code query..works in IDLE but not DrPython editor In-Reply-To: References: Message-ID: <20070710185859.GA29954@cutter.rexx.com> On Tue, Jul 10, 2007 at 01:37:34PM -0400, Tony Noyeaux wrote: > > Simple Random code. > > > import randomprint random.choice(['Apple', 'Pear', 'Shrimp', 'Death', 'Life']) > > > Works in IDLE gui, no problem. Gives me a random pick no problem. > > When i changed to DrPython, to continue building parts of my code.. it won't take that code. > > Gives me this error. > > C:/Python/pythonw.exe -u "C:/Python25/random.py"Traceback (most recent call last): File "C:/Python25/random.py", line 1, in import random File "C:\Python25\random.py", line 2, in print random.choice(['Apple', 'Pear', 'Shrimp', 'Death', 'Life'])AttributeError: 'module' object has no attribute 'choice' > > ... not sure why one editor would work, and while the other > won't?.. any suggestions. Check the path and notice where random comes from under both DrPython and Idle: import sys print sys.path import random print random It might be that DrPython is finding a different module random from that which Idle finds. I was tripped by a similar error. Idle and IPython both have my bin directory on sys.path (I'm on Linux), while standard Python does not. IPython was finding one of my modules in the bin directory, whereas standard Python found it under lib/python2.5/site-packages. Hope this helps. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From alan.gauld at btinternet.com Tue Jul 10 21:55:17 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Jul 2007 20:55:17 +0100 Subject: [Tutor] Code query..works in IDLE but not DrPython editor References: Message-ID: "Tony Noyeaux" wrote > import randomprint random.choice(['Apple', 'Pear', 'Shrimp', > 'Death', 'Life']) Your formatting is a little strange as seen above but... > Works in IDLE gui, no problem. Do you mean the interactive shell in IDLE? Or are you actually comparing like for like? In other words are you running a file in IDLE? > Gives me this error. > ...snip ... > File "C:/Python25/random.py", line 1, in import random This says that you are importing random from a file called random.py I suspect this means that you called your own file the same as the module and when Python tries to import random it sees your file first - and imports itself. > AttributeError: 'module' object has no attribute 'choice' And because your file doesn't define a choice function it gives an error. Try renaming your file to myrandom or somesuch. Guessing, but it seems a fair guess. Alan G. From dos.fool at gmail.com Tue Jul 10 22:01:57 2007 From: dos.fool at gmail.com (max .) Date: Tue, 10 Jul 2007 14:01:57 -0600 Subject: [Tutor] writing over text Message-ID: <857e4c3d0707101301p15939f11nbbef840b55505b8d@mail.gmail.com> hello i am writing a population script and was wondering if i can just keep writing to the same line instead of printing a new line every second thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070710/24a70e04/attachment.html From alan.gauld at btinternet.com Tue Jul 10 22:08:17 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Jul 2007 21:08:17 +0100 Subject: [Tutor] font colours References: Message-ID: "Dave Pata" wrote > I am currently doing an assignment for school using python > and im at the stage of make it look good and i need more > colours. More colours rarely means it looks good, just garish! Good UI's are built by following style guidelines that allow the user to configure the colors which means the programmer sticks to the standard options - that means it should look OK even in shades of grey!. (Or he makes the UI skinnable which is a whole new can of worms!) However, if you insist, the Tkinter colours are to some extent OS dependant and the names are those used by the X server on Unix type systems. However its probably easier to specify colors as RRGGBB hex string values (for 256 colours). For ex: fg = '#FFAA33' bg = '#1177CC' Write a small simple canvas application withb a loop and timer to see the colours available... And finally if you insist on taking control of colours at least do it through a config file that the users can change it. This is particularly important if colour-blind users might be using the app - what looks good to you might be unreadable to them!. > P.S I dont know if this has any effect on matters but > i am using the Tkinter toolkit. Yes, it does make a difference. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Jul 10 22:13:14 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Jul 2007 21:13:14 +0100 Subject: [Tutor] writing over text References: <857e4c3d0707101301p15939f11nbbef840b55505b8d@mail.gmail.com> Message-ID: "max ." wrote > hello i am writing a population script and was wondering if i can > just keep > writing to the same line instead of printing a new line every second Depending on the terminal type you can use control codes to move the cursor. Thus on most Unix terminals you can use Ctrl-U to delete the line, thus if you wriote a Ctrl-U character before each line and suppress the newline at the end it will appear that all output is on a single line. On a DOS ANSI terminal I can't recall the Ctrl code used, but it is possible. Another option is to use the curses module which allows you to specify the screen coordinates where you write. A similar module is available for DOS on the web - I think I saw it on the vaults of Parnassus. HTH, Alan G. From bgailer at alum.rpi.edu Tue Jul 10 22:17:07 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 10 Jul 2007 13:17:07 -0700 Subject: [Tutor] writing over text In-Reply-To: <857e4c3d0707101301p15939f11nbbef840b55505b8d@mail.gmail.com> References: <857e4c3d0707101301p15939f11nbbef840b55505b8d@mail.gmail.com> Message-ID: <4693E943.7070409@alum.rpi.edu> max . wrote: > hello i am writing a population script and was wondering if i can > just keep writing to the same line instead of printing a new line > every second import time for i in range(5): print chr(13), i, time.sleep(1) # chr(13) = carriage return, and the trailing , suppresses the newline. -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From dos.fool at gmail.com Tue Jul 10 22:53:47 2007 From: dos.fool at gmail.com (max .) Date: Tue, 10 Jul 2007 14:53:47 -0600 Subject: [Tutor] writing over text In-Reply-To: <4693E943.7070409@alum.rpi.edu> References: <857e4c3d0707101301p15939f11nbbef840b55505b8d@mail.gmail.com> <4693E943.7070409@alum.rpi.edu> Message-ID: <857e4c3d0707101353u41f8cb2dvceb3e56e43052d66@mail.gmail.com> thank you so much :) On 7/10/07, Bob Gailer wrote: > > max . wrote: > > hello i am writing a population script and was wondering if i can > > just keep writing to the same line instead of printing a new line > > every second > import time > for i in range(5): > print chr(13), i, > time.sleep(1) > > # chr(13) = carriage return, and the trailing , suppresses the newline. > > -- > Bob Gailer > 510-978-4454 Oakland, CA > 919-636-4239 Chapel Hill, NC > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070710/70dd6a7a/attachment.htm From washakie at gmail.com Tue Jul 10 23:22:11 2007 From: washakie at gmail.com (John) Date: Tue, 10 Jul 2007 23:22:11 +0200 Subject: [Tutor] An interesting case... of east vs. west Message-ID: I was trying to read in a tab delimited file i was given with lat and lon, the thing is I needed decimal lat, and decimal long... well, anyway I think you can see what my problem was: for i in range(0,344) y=d[i][2].split('\xb0') x=d[i][3].split('\xb0') ydeg,ymin=y[0].strip(),y[1].rstrip('\' N').rstrip("\' S") xdeg,xmin=x[0].strip(),x[1].rstrip("\' E").rstrip("\' W") if re.search('\ZW','x[1]') xmin=-1*xmin if re.search('\ZS','y[1]') ymin=-1*ymin declat=int(ydeg)+(float(ymin)/60) declon=int(xdeg)+(float(xmin)/60) The thing is, it isn't terribly robust (I'm not even positive it's working correctly!!). For instance, as you might have guessed I was given Lat and Lon in the following format: STNA 45? 49' N 08? 38' E STNB 46? 58' 19? 33' E STNC 53?33' -9?54' STND 51?32' N 12?54' W Some indicating north or some, and some not. This wasn't a concern, as I knew they were all North. However, the West / East issue is another story. Anyone have a more elegant solution? -john -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070710/37fa8ab3/attachment.html From washakie at gmail.com Wed Jul 11 00:06:00 2007 From: washakie at gmail.com (John) Date: Wed, 11 Jul 2007 00:06:00 +0200 Subject: [Tutor] An interesting case... of east vs. west In-Reply-To: References: Message-ID: Just a quick follow up.. it doesn't work :s There are definitely some problems... ideas are welcome! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070711/d4cd6193/attachment.html From rabidpoobear at gmail.com Wed Jul 11 00:12:26 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 10 Jul 2007 17:12:26 -0500 Subject: [Tutor] An interesting case... of east vs. west In-Reply-To: References: Message-ID: <4694044A.30605@gmail.com> John wrote: > Just a quick follow up.. it doesn't work :s > > There are definitely some problems... ideas are welcome! I have an idea: use a regular expression :D Unfortunately, I don't have the knowledge of these down well enough to just spout one off OTOH, and I've got somewhere I have to be, but I believe that you could use regexps to solve this quite easily. Good luck, and hopefully someone more helpful will chime in. -Luke From washakie at gmail.com Wed Jul 11 00:35:09 2007 From: washakie at gmail.com (John) Date: Wed, 11 Jul 2007 00:35:09 +0200 Subject: [Tutor] An interesting case... of east vs. west In-Reply-To: References: Message-ID: Luke, Albert: Thanks.. yes I'm thinking re is what I need... and using negative values for west, and positive for east is our convention. The problem I have is that not all the data was provided in that format, so I'm in the process of converting... There are a number of problems with my original post. For one, the conversion to decimal fails if given a negative number (i.e. -9 30' in my approach becomes 8.5 when it should be 9.5). So, to get around that I need to use abs, and add some if cases to convert it back to negative.. Anyway, still working through this... On 7/11/07, Albert Weiss wrote: > > > John: One way to handle the situation of longitude is to make everything > west of the Greenwich meridan a negative value until -180 degrees and > everything east of Greenwich a positive value. HTH. > Albert > > > > > *John * > Sent by: tutor-bounces at python.org > > 07/10/2007 04:22 PM > To > tutor at python.org cc > Subject > [Tutor] An interesting case... of east vs. west > > > > > I was trying to read in a tab delimited file i was given with lat and lon, > the thing is I needed decimal lat, and decimal long... well, anyway I think > you can see what my problem was: > > for i in range(0,344) > y=d[i][2].split('\xb0') > x=d[i][3].split('\xb0') > ydeg,ymin=y[0].strip(),y[1].rstrip('\' N').rstrip("\' S") > xdeg,xmin=x[0].strip(),x[1].rstrip("\' E").rstrip("\' W") > if re.search('\ZW','x[1]') xmin=-1*xmin > if re.search('\ZS','y[1]') ymin=-1*ymin > declat=int(ydeg)+(float(ymin)/60) > declon=int(xdeg)+(float(xmin)/60) > > The thing is, it isn't terribly robust (I'm not even positive it's working > correctly!!). For instance, as you might have guessed I was given Lat and > Lon in the following format: > STNA 45? 49' N 08? 38' E > STNB 46? 58' 19? 33' E > STNC 53?33' -9?54' > STND 51?32' N 12?54' W > > Some indicating north or some, and some not. This wasn't a concern, as I > knew they were all North. However, the West / East issue is another story. > Anyone have a more elegant solution? > > -john > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Five 1.4.1, Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)], PIL 1.1.6 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070711/068a5412/attachment.htm From tinoloc at gmail.com Wed Jul 11 00:37:48 2007 From: tinoloc at gmail.com (Tino Dai) Date: Tue, 10 Jul 2007 18:37:48 -0400 Subject: [Tutor] An interesting case... of east vs. west In-Reply-To: References: Message-ID: On 7/10/07, John wrote: > > I was trying to read in a tab delimited file i was given with lat and lon, > the thing is I needed decimal lat, and decimal long... well, anyway I think > you can see what my problem was: > > for i in range(0,344) > y=d[i][2].split('\xb0') > x=d[i][3].split('\xb0') > ydeg,ymin=y[0].strip(),y[1].rstrip('\' N').rstrip("\' S") > xdeg,xmin=x[0].strip(),x[1].rstrip("\' E").rstrip("\' W") > if re.search('\ZW','x[1]') xmin=-1*xmin > if re.search('\ZS','y[1]') ymin=-1*ymin > declat=int(ydeg)+(float(ymin)/60) > declon=int(xdeg)+(float(xmin)/60) > > The thing is, it isn't terribly robust (I'm not even positive it's working > correctly!!). For instance, as you might have guessed I was given Lat and > Lon in the following format: > STNA 45? 49' N 08? 38' E > STNB 46? 58' 19? 33' E > STNC 53?33' -9?54' > STND 51?32' N 12?54' W > > > Off the top of my head regex=re.compile("STD[A-Z] (\d+)[ ]?(\d+)'[ ]?N?[ ]?\-?(\d+)[ ]?(\d+)' [EW]") m = re.search(regex,linesOfFile) print m.group(1) That should work, but you might need to massage the regex a little HTH, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070710/46f36038/attachment.html From tinoloc at gmail.com Wed Jul 11 00:51:30 2007 From: tinoloc at gmail.com (Tino Dai) Date: Tue, 10 Jul 2007 18:51:30 -0400 Subject: [Tutor] Question about lambda and new.instancemethod Message-ID: Hi Everybody, I have been working on a parser for myself. I want to create methods on the fly with the information that I get from a file. Here is my question: class configure: <.....stuff deleted......> def parseGlobal(self,projectName,section,project): for element in section.childNodes: if not element.nodeName == "#text": self.glblFunc["get" + project.getAttribute("name").encode("ascii").capitalize() + element.nodeName.encode("ascii").capitalize()] = \ lambda self : element.firstChild.data.encode("ascii") <...and later on...> def addMethod(instName,funcDict): for k,v in funcDict.iteritems(): instName.__dict__[k]=new.instancemethod(v,instName,'configure') The instance name and funcDict (which is the populated self.glblFunc) get sent up to addMethod. This is supposed to create a new method within the instance of my class. Instead, I get a AttributeError exception thrown. So, I check the code using inspect.getsource, and for all of the new methods that I create, I get ' + element.nodeName.encode("ascii").capitalize()] = lambda self : sys.stdout.write(element.firstChild.data.encode("ascii"))\n\n' instead of lambda self : sys.stdout.write(element.firstChild.data.encode("ascii") Could anybody tell me why this is happening or do you need some more code Thanks, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070710/50a5c192/attachment.htm From washakie at gmail.com Wed Jul 11 01:09:11 2007 From: washakie at gmail.com (John) Date: Wed, 11 Jul 2007 01:09:11 +0200 Subject: [Tutor] An interesting case... of east vs. west In-Reply-To: References: Message-ID: A little closer, this seems to work, but it's not catching the 'W' or 'S' cases to make it negative... for i in range(0,20): y=d[i][2].split('\xb0') x=d[i][3].split('\xb0') ydeg,ymin=int(y[0].rstrip()),float(y[1].strip('\' N')) xdeg,xmin=int(x[0].rstrip()),float(x[1].rstrip("\' E").rstrip("\' W")) if re.search('\Z W','x[1]'): xdeg=-1*xdeg if re.search('\Z S','y[1]'): ydeg=-1*ydeg declat=abs(ydeg)+ymin/60 declon=abs(xdeg)+xmin/60 if ydeg < 0: declat=declat*-1 if xdeg < 0: declon=declon*-1 elv=int(d[i][4].strip('m')) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070711/2fec694a/attachment.html From carroll at tjc.com Wed Jul 11 01:17:38 2007 From: carroll at tjc.com (Terry Carroll) Date: Tue, 10 Jul 2007 16:17:38 -0700 (PDT) Subject: [Tutor] back on bytes In-Reply-To: Message-ID: On Sat, 7 Jul 2007, Alan Gauld wrote: > I'm intrigued as to why people are using weird combinations > of math to manipulate bitstrings given that Python has a full > set of bitwise operators. Surely it is easier and more obvious > to simply shift the bits right or left using >> and << and use > bitwise and/or operations than do all this multiplication and > addition malarky. That's a fair point. I guess it's all in how the problem shows up to you. This felt like arbitrary-base arithmetic to me, not bit manipulation. To recap, what I had was a 32-bit string, representing a 28-bit number. The high-order bit of each byte was a zero. The task is essentially to suck out these four bits and then shmush the remaining 28 bits together to get the integer value. When I encountered this, it looked to me like a number encoded in base-128: counting from the right, the first byte is in units of 128**0 (i.e., 1); the second in units of 128**1 (i.e., 128); the third, 128**2 (16384); and the leftmost, 128**3 (2097152). So it just made sense to me to write it that way: def ID3TagLength(s): """ Given a 4-byte string s, decode as ID3 tag length """ return (ord(s[0]) * 0x200000 + ord(s[1]) * 0x4000 + ord(s[2]) * 0x80 + ord(s[3]) ) I expressed the factors in hex, because I think that the sequence 0x200000, 0x4000, 0x80 is clearer and appears to be less of a "magic number" sequence than 2097152, 16384, 128. I figured I'd still understand it if I had to look at it a couple months later. Now that you mention it, I certainly could have done it bitwise: def ID3TagLengthBitwise(s): """ Given a 4-byte string s, decode as ID3 tag length """ return (ord(s[0]) << 21 | ord(s[1]) << 14 | ord(s[2]) << 7 | ord(s[3]) ) It just didn't occur to me, and the first one worked right off. > (Its also a lot faster!) Could be. But the arithmetic approach immediately worked, and this sort of field only appears a few times in any particular MP3 file, so it wasn't in any way a bottleneck. It never occurred to me to try to optimize it. I doubt any speed-up would have been perceptible. (On the other hand, I'm the guy who always microwaves his food in multiples of 11 seconds, so I don't have to move my finger all the way down to the "0" button. Go figure.) > If you are going to > operate at the bit level why not use the bit level operations? In my case, this didn't feel like operating at the bit level; it felt like doing arbitrary-base arithmetic. I will add, however, that my approach would fail in Sean's context. In my context, the upper bit in each byte is a zero; in Sean's, it's used to signify something unrelated to the numeric value. So Sean's going to have to AND the high-order bit to zero anyway, so bitwise all the way is a logical approach. I think if I'd been working in that context, the problem would have showed up to me as a bit manipulation problem, and not as an arbitrary-base arithmetic problem. From alan.gauld at btinternet.com Wed Jul 11 01:21:08 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Jul 2007 00:21:08 +0100 Subject: [Tutor] An interesting case... of east vs. west References: Message-ID: "John" wrote > you can see what my problem was: > > for i in range(0,344) > y=d[i][2].split('\xb0') > x=d[i][3].split('\xb0') > ... > declon=int(xdeg)+(float(xmin)/60) The first thing I'd suggest is not to try to do it all in one step. Break it into chunks and write helper functions for each part, that will be much easier to debug. I think you want a parser to extract the lat and lon values as a tuple. A function to tidy up the lat and another to do the lons. Finally a ms to decimal convertor. Your top loop then becomes: coords = [] for line in file(...): lat,lon = getLatLon(line) lat = latTidy() lon = lonTidy() coords.append((asDec(lat),asDec(lon))) To produce a list of coord tuples in decimal format. Now, can you solve the 4 sub problems? A regex may help with the first one. The second and third will need knowlege of each possible format The fourth is a straightforward math exercise HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From washakie at gmail.com Wed Jul 11 03:50:26 2007 From: washakie at gmail.com (John) Date: Wed, 11 Jul 2007 03:50:26 +0200 Subject: [Tutor] An interesting case... of east vs. west In-Reply-To: References: Message-ID: I will work with this further, and report back once I find Alan's method... but for now, this seems to work: for i in range(0,20): y=d[i][2].split('\xb0') x=d[i][3].split('\xb0') ydeg,ymin=int(y[0].rstrip()),float(y[1].strip('\' N')) xdeg,xmin=int(x[0].rstrip()),float(x[1].rstrip("\' E").rstrip("\' W")) if re.search("W",x[1]): xdeg=-1*xdeg if re.search("S",y[1]): ydeg=-1*ydeg declat=abs(ydeg)+ymin/60 declon=abs(xdeg)+xmin/60 if ydeg < 0: declat=declat*-1 if xdeg < 0: declon=declon*-1 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070711/9413b161/attachment.htm From sarliz73 at yahoo.com Wed Jul 11 06:37:33 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Tue, 10 Jul 2007 21:37:33 -0700 (PDT) Subject: [Tutor] Bundle help! In-Reply-To: Message-ID: <978334.94503.qm@web35102.mail.mud.yahoo.com> Alan Gauld wrote: "Sara Johnson" wrote > this is sort of a script that was written and I'm making > modifications to. Due to my serious lack of experience, > I'm afraid to rewrite anything. This is probably a long shot given the code you've posted so far, but I don't suppose there are any design documents available? Structure charets, class diagrams? Even plain text or pseudo code? Not sure I follow what you mean by those specific documents or diagrams, but I do have the output and the sample code. Seems like it would be easy to just enter it all in and get that output, except for the different files I've had to include ("chmod" command on various scripts). Not sure if I've described that correctly. Nonetheless, I've had to bundle this and pickle that and create 3 different files plus one script. Only close on one of those. If you are talking about the output on this one step, I can put it into a text file and attach it. Again my fear is that whatever I do to make that happen will eventually lead to the other outputs as well. In an ideal world it would be possible to find the faulty function without having to read any code, but few projects are that well documented. But then again few projects have nothing! If you can find it it might tell you at a high level how the code hangs together. I'm not sure zip is the best tool for breaking lists apart, but I'm no expert with it. But its easy to do with a simple loop if you are dealing with a list of tuples: list1 = [] list2 = [] for item in theList: list1.append(item[0]) list2.append(item[1]) I will give this a try and some of the other suggestions I have received. Thanks again! --------------------------------- Choose the right car based on your needs. Check out Yahoo! Autos new Car Finder tool. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070710/e57082fb/attachment-0001.html From therealcaffeine at gmail.com Wed Jul 11 07:59:34 2007 From: therealcaffeine at gmail.com (Brian Hicks) Date: Tue, 10 Jul 2007 23:59:34 -0600 Subject: [Tutor] Making Incremental Filenames Message-ID: <469471C6.7050003@gmail.com> Hi, I'm making a webcam automation script (for a project 365 photo thing) and I can't figure out how to increment the filename every time the script saves an image. I'm using this snippet of code to count the tiles in the directory: filecount = len(os.walk("C:\Users\Username\Desktop").next()[2]) This returns 4 in my case. I tried using os.path.join to join "C:\Users\Username\Pictures\365\day",filecount (which is 4),".jpg" so I can save it using the webcam library I have, but that throws a rather serious looking error, which is like this: Traceback (most recent call last): File "", line 1, in filename = os.path.join("C:\Users\Brian\Desktop\day",file_count,".jpg") File "C:\Python25\lib\ntpath.py", line 67, in join elif isabs(b): File "C:\Python25\lib\ntpath.py", line 53, in isabs s = splitdrive(s)[1] File "C:\Python25\lib\ntpath.py", line 119, in splitdrive if p[1:2] == ':': TypeError: 'int' object is unsubscriptable I think I need to be looking into converting filecount to a string somehow instead of an integer, but once again I'm not sure how and all I've tried has given me errors. Please help? -Brian Hicks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070710/05a95cec/attachment.htm From john at fouhy.net Wed Jul 11 08:07:36 2007 From: john at fouhy.net (John Fouhy) Date: Wed, 11 Jul 2007 18:07:36 +1200 Subject: [Tutor] Making Incremental Filenames In-Reply-To: <469471C6.7050003@gmail.com> References: <469471C6.7050003@gmail.com> Message-ID: <5e58f2e40707102307t42b8fbb0q50c188f19e5a8d4a@mail.gmail.com> On 11/07/07, Brian Hicks wrote: > Hi, I'm making a webcam automation script (for a project 365 photo thing) > and I can't figure out how to increment the filename every time the script > saves an image. I'm using this snippet of code to count the tiles in the > directory: [...] > This returns 4 in my case. I tried using os.path.join to join > "C:\Users\Username\Pictures\365\day",filecount (which is > 4),".jpg" so I can save it using the webcam library I have, but that throws > a rather serious looking error, which is like this: os.path.join is unlikely to be what you want. You use os.path.join to join separate chunks of path together, where each bit is complete on its own. For example, os.path.join("C:\Foo", "bar") would produce "C:\Foo\bar" (note the backslash between Foo and bar). The goal is to provide a platform-independent way of joining pathnames together, so you don't have to figure out whether to use '/' or '\' or something else. You need string formatting -- the % operator. Try this: filename = "C:\\Users\\Username\\Pictures\\365\\day%d.jpg" % filecount Or even: filename = "C:\\Users\\Username\\Pictures\\365\\day%3d.jpg" % filecount (this will give you 001, 002, ...) Check the python docs (library reference, under "Sequence types") for more information. -- John. From rabidpoobear at gmail.com Wed Jul 11 08:13:37 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 11 Jul 2007 01:13:37 -0500 Subject: [Tutor] Making Incremental Filenames In-Reply-To: <469471C6.7050003@gmail.com> References: <469471C6.7050003@gmail.com> Message-ID: <46947511.7030004@gmail.com> Brian Hicks wrote: > Hi, I'm making a webcam automation script (for a project 365 photo > thing) and I can't figure out how to increment the filename every time > the script saves an image. I'm using this snippet of code to count > the tiles in the directory: > > filecount = len(os.walk("C:\Users\Username\Desktop").next()[2]) > > > This returns 4 in my case. I tried using os.path.join to join > "C:\Users\Username\Pictures\365\day",filecount (which is 4),".jpg" so > I can save it using the webcam library I have, but that throws a > rather serious looking error, which is like this: > > Traceback (most recent call last): > File "", line 1, in > filename = > os.path.join("C:\Users\Brian\Desktop\day",file_count,".jpg") > File "C:\Python25\lib\ntpath.py", line 67, in join > elif isabs(b): > File "C:\Python25\lib\ntpath.py", line 53, in isabs > s = splitdrive(s)[1] > File "C:\Python25\lib\ntpath.py", line 119, in splitdrive > if p[1:2] == ':': > TypeError: 'int' object is unsubscriptable > > I think I need to be looking into converting filecount to a string > somehow instead of an integer, but once again I'm not sure how and all > I've tried has given me errors. Please help? Certainly :) the problem lies in your use of os.path.join. This joins paths, as the name implies. Therefore, 'Myworkingdirectory','myfilename','.jpg' will not result in 'Myworkingdirectorymyfilename.jpg' but 'Myworkingdirectory/myfilename/.jpg' or r'Myworkingdirectory\myfilename\.jpg' if you're on Windows. The purpose of this function in the os module is because directories in paths are denoted by different characters ('\\' or r'\' on Windoze, '/' on Unix variants) so it enables you to use the same path, subdirectory/subsubdirectory/myfile.ext subdirectory\subsubdirectory\myfile.ext on whatever OS you're on without you having to worry about it. But since you're trying to join a string, an int, and a string together, the os.path.join function is complaining on the integer. Even if you converted this to an integer, you wouldn't get the result you want. In Python, you can perform string concatenation the same way you perform addition. F.E. 'hello ' + 'world' is the same thing as 'hello world' so you have a few options... you can go the + route, but this requires everything to be strings: 'myfilepath/myfilename' + str(file_count) + '.jpg' or you could go the string substitution route: 'myfilepath/myfilename%s.jpg' % file_count Note that you could use %i if you are certain it's an integer, but I usually just use %s for everything (maybe that's bad ;) Or, as John Fouhy pointed out (I wouldn't have written this e-mail if I'd received his before starting this one) you can use the %d. Also, just a future warning: If you want to substitute a bunch of things into a string, like 'hello, my name is %s and I like your cat, %s.' you can't just do 'hello, my name is %s and I like your cat, %s.' % 'john' , 'freckles' you'd have to do 'hello, my name is %s and I like your cat, %s.' % ('john', 'freckles') because the substitution expects either a single argument or a tuple containing all of the values to be substituted. HTH, -Luke > > -Brian Hicks > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Wed Jul 11 09:13:58 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Jul 2007 08:13:58 +0100 Subject: [Tutor] Bundle help! References: <978334.94503.qm@web35102.mail.mud.yahoo.com> Message-ID: "Sara Johnson" wrote > but I don't suppose there are any design documents available? > Structure charts, class diagrams? Even plain text or pseudo > code? > > Not sure I follow what you mean by those specific documents > or diagrams, I guess that answers the question! :-) I mean, are there any design documents that describe how the code works? Where the various pieces are defined, which functions get called by which other functions etc. As I said, in a well run project it should be possible to figure out which function is faulty (and have a good idea what exactly is faulty with it) without ever looking at code(*) . Some examples of software design notations can be found here: http://www.smartdraw.com/tutorials/software/index.htm There is no shortage of tools, just a willingnmess to use them! ( JSD and DFDs are best (IMHO) for non OOP and UML is best for OOP.) (*)This is about 3 or 4 times faster (= cheaper) than reading code! Unfortunately very few projects take the time to produce good maintenance documents and therefore pay a huge price in maintenance and enhancement costs over the years. (Maintenance accounts for 80% of a projects total software costs!) My first programming manager always maintained that a programmners first priority was to produce code that was easy to maintain, even above performance and rapid delivery. Having been team leader on two maintenance projects since then, I heartily concur! Alan G. From aweiss at unlnotes.unl.edu Wed Jul 11 00:14:45 2007 From: aweiss at unlnotes.unl.edu (Albert Weiss) Date: Tue, 10 Jul 2007 17:14:45 -0500 Subject: [Tutor] An interesting case... of east vs. west In-Reply-To: Message-ID: John: One way to handle the situation of longitude is to make everything west of the Greenwich meridan a negative value until -180 degrees and everything east of Greenwich a positive value. HTH. Albert John Sent by: tutor-bounces at python.org 07/10/2007 04:22 PM To tutor at python.org cc Subject [Tutor] An interesting case... of east vs. west I was trying to read in a tab delimited file i was given with lat and lon, the thing is I needed decimal lat, and decimal long... well, anyway I think you can see what my problem was: for i in range(0,344) y=d[i][2].split('\xb0') x=d[i][3].split('\xb0') ydeg,ymin=y[0].strip(),y[1].rstrip('\' N').rstrip("\' S") xdeg,xmin=x[0].strip(),x[1].rstrip("\' E").rstrip("\' W") if re.search('\ZW','x[1]') xmin=-1*xmin if re.search('\ZS','y[1]') ymin=-1*ymin declat=int(ydeg)+(float(ymin)/60) declon=int(xdeg)+(float(xmin)/60) The thing is, it isn't terribly robust (I'm not even positive it's working correctly!!). For instance, as you might have guessed I was given Lat and Lon in the following format: STNA 45? 49' N 08? 38' E STNB 46? 58' 19? 33' E STNC 53?33' -9?54' STND 51?32' N 12?54' W Some indicating north or some, and some not. This wasn't a concern, as I knew they were all North. However, the West / East issue is another story. Anyone have a more elegant solution? -john _______________________________________________ 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/20070710/4c37d247/attachment.html From kp8 at mac.com Wed Jul 11 13:24:17 2007 From: kp8 at mac.com (kevin parks) Date: Wed, 11 Jul 2007 20:24:17 +0900 Subject: [Tutor] Module imports In-Reply-To: References: Message-ID: <2412B4B1-5C8F-4D1C-A6E3-218240554EB1@mac.com> With sincere apologies for such a basic question, and one i will admit that i asked once before, moons ago. But even after googling around a bit i don't understand what the right answer is, or if i once did, can't recall it now.. I have a script, let's call it foo.py This script loads several modules from the standard library and a home brewed module that has a bunch code that i often reuse in it. For example it might have: # -- foo.py -- # -- batteries included import random import sys import time # -- homebrewed import kp [... code here ..] That is fine and in this script i will call and use various things from the random, sys, and time modules. but my kp module also uses happens to call on certain things from the random, time, and sys modules and so kp.py also has import random import sys import time Now so far this seems to be working fine and without error (as far as i can tell). However, shouldn't i only be importing random, sys and time once? and if so, where? in foo.py or kp.py? It was explained to me that it is fine to import random, sys and time in both, and that only the first import uses up memory, and subsequent attempts to import the same module don't really cost anything and just add a reference in the namespace. but isn't loading it in both modules confusing and bad .... additionally in this case which import is actually being used (or does this not even matter?) the one in kp.py or in foo.py? For some reason i feel like i should understand how and why this works a little better in order to avoid overlap and conflict in what is becoming a bit more involved intermingling of modules and scripts. or alternately you all can chime in and say "dude, get over it, multiple and overlapping imports are not a big deal in python, you are worrying about nothing, and making a problem where there is none! Get on with your life." haha best, kevin From tinoloc at gmail.com Wed Jul 11 16:38:20 2007 From: tinoloc at gmail.com (Tino Dai) Date: Wed, 11 Jul 2007 10:38:20 -0400 Subject: [Tutor] Question about code reviews Message-ID: Hi there, Do you know of any service or person that could do a code review for me? Thanks, -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070711/1fe57382/attachment.html From jrmorrisnc at gmail.com Wed Jul 11 17:03:18 2007 From: jrmorrisnc at gmail.com (John Morris) Date: Wed, 11 Jul 2007 11:03:18 -0400 Subject: [Tutor] Question regarding syntax Message-ID: <6216eba0707110803u733a0e71ga6d4dac3078a37ae@mail.gmail.com> I'm editing some code from Mailman and seeing: legend = _("%(hostname)s Mailing Lists") Can anyone tell me what the _( means in that context? Thanks, John -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070711/52e3a42b/attachment.htm From nephish at gmail.com Wed Jul 11 17:10:39 2007 From: nephish at gmail.com (shawn bright) Date: Wed, 11 Jul 2007 10:10:39 -0500 Subject: [Tutor] storm anyone? Message-ID: <384c93600707110810qfdb0765g66e45b971ce9f62a@mail.gmail.com> Hey there all, i got the news that storm was released as open source. Storm is a db orm for python. i have a downloaded package and i would like to play with it, but it does not come with any install instructions. i found the package here https://storm.canonical.com/FrontPage there is a makefile in the top level folder, so should i use gcc and try to 'make' 'make install' or is that not necessarily the way to go here? thanks for any tips shawn -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070711/952bfd66/attachment.htm From noufal at airtelbroadband.in Wed Jul 11 17:31:16 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Wed, 11 Jul 2007 21:01:16 +0530 Subject: [Tutor] Module imports In-Reply-To: <2412B4B1-5C8F-4D1C-A6E3-218240554EB1@mac.com> References: <2412B4B1-5C8F-4D1C-A6E3-218240554EB1@mac.com> Message-ID: <4694F7C4.5090308@airtelbroadband.in> kevin parks wrote: > With sincere apologies for such a basic question, and one i will > admit that i asked once before, moons ago. But even after googling > around a bit i don't understand what the right answer is, or if i > once did, can't recall it now.. [..] > > For some reason i feel like i should understand how and why this > works a little better in order to avoid overlap and conflict in what > is becoming a bit more involved intermingling of modules and scripts. I don't think you need to worry. The python primitive "id" returns a unique identifier for it's argument (I recall reading the it's the memory location of the object). Anyway, I have a module called foo.py which has this import sys print id(sys) Then I start python and do this import sys print id(sys) 3084566644 import foo 3084566644 id(foo.sys) 3084566644 sys is foo.sys True So, it is the same object. You don't have to worry. Peace. -- ~noufal From dkuhlman at rexx.com Wed Jul 11 17:34:35 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 11 Jul 2007 08:34:35 -0700 Subject: [Tutor] Module imports In-Reply-To: <2412B4B1-5C8F-4D1C-A6E3-218240554EB1@mac.com> References: <2412B4B1-5C8F-4D1C-A6E3-218240554EB1@mac.com> Message-ID: <20070711153435.GA73342@cutter.rexx.com> On Wed, Jul 11, 2007 at 08:24:17PM +0900, kevin parks wrote: > but my kp module also uses happens to call on certain things from the > random, time, and sys modules and so kp.py also has > > import random > import sys > import time > > Now so far this seems to be working fine and without error (as far as > i can tell). However, shouldn't i only be importing random, sys and > time once? and if so, where? in foo.py or kp.py? No need to worry. You *are* only importing each module once. Python checks, and only imports a module if it has not already been imported. Here is a quote from the section on the import statement in the Python language reference. "The system maintains a table of modules that have been or are being initialized, indexed by module name. This table is accessible as sys.modules. When a module name is found in this table, step (1) is finished. If not, a search for a module definition is started. When a module is found, it is loaded. Details of the module searching and loading process are implementation and platform specific. It generally involves searching for a `built-in'' module with the given name and then searching a list of locations given as sys.path." -- http://docs.python.org/ref/import.html You can prove this to yourself by writing a tiny module with a print statement at top level (outside any function or class definition), then importing it twice. The print statement should only write out its message one time. This has consequences, by the way. Calculations that performed at a top level in a module are performed only once, for example. > > It was explained to me that it is fine to import random, sys and time > in both, and that only the first import uses up memory, and > subsequent attempts to import the same module don't really cost > anything and just add a reference in the namespace. but isn't loading > it in both modules confusing and bad .... additionally in this case > which import is actually being used (or does this not even matter?) > the one in kp.py or in foo.py? > No. It's not bad. It's considered good practice. And, considered the opposite. If we were required to only import each module once, then before I added an import statement to my code, I'd have to check every other module I import and every module imported by those modules etc. for duplicates. > For some reason i feel like i should understand how and why this > works a little better in order to avoid overlap and conflict in what > is becoming a bit more involved intermingling of modules and scripts. > > or alternately you all can chime in and say "dude, get over it, > multiple and overlapping imports are not a big deal in python, you > are worrying about nothing, and making a problem where there is > none! Get on with your life." haha It is not that you should "try not to worry". It's that you are doing things the way you are intended to. And, you are probably in sync with the cosmos, too. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From dkuhlman at rexx.com Wed Jul 11 18:00:35 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 11 Jul 2007 09:00:35 -0700 Subject: [Tutor] Question regarding syntax In-Reply-To: <6216eba0707110803u733a0e71ga6d4dac3078a37ae@mail.gmail.com> References: <6216eba0707110803u733a0e71ga6d4dac3078a37ae@mail.gmail.com> Message-ID: <20070711160035.GB73342@cutter.rexx.com> On Wed, Jul 11, 2007 at 11:03:18AM -0400, John Morris wrote: > I'm editing some code from Mailman and seeing: > > legend = _("%(hostname)s Mailing Lists") > The outter parenthese are a function call. The underscore is a name that has a callable as a value, I suppose. I believe that the value of the name underscore is the last expression evaluated, but I'm not sure. Mailman is a great product. But that bit of code is not, I think, very good code. In Python explicitness is a virtue, and the use of the underscore is implicit and is not very Pythonic. By the way, The inner parentheses are a formatting operation. %(x)s will be replaced by the value of x in Example: vals = {'animal': 'dog'} "Rover is a big %(animal)s." % vals "%(animal)s" will be replaced by "dog". When you use this form, the value on the right of the formatting operator must be a dictionary. More from the library reference: When the right argument is a dictionary (or other mapping type), then the formats in the string must include a parenthesised mapping key into that dictionary inserted immediately after the "%" character. The mapping key selects the value to be formatted from the mapping. For example: >>> print '%(language)s has %(#)03d quote types.' % \ {'language': "Python", "#": 2} Python has 002 quote types. -- http://docs.python.org/lib/typesseq-strings.html Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From jrmorrisnc at gmail.com Wed Jul 11 18:31:36 2007 From: jrmorrisnc at gmail.com (John Morris) Date: Wed, 11 Jul 2007 12:31:36 -0400 Subject: [Tutor] Question regarding syntax In-Reply-To: <20070711160035.GB73342@cutter.rexx.com> References: <6216eba0707110803u733a0e71ga6d4dac3078a37ae@mail.gmail.com> <20070711160035.GB73342@cutter.rexx.com> Message-ID: <6216eba0707110931l49062086rd1d8cb86d091ad4f@mail.gmail.com> On 7/11/07, Dave Kuhlman wrote: > > On Wed, Jul 11, 2007 at 11:03:18AM -0400, John Morris wrote: > > I'm editing some code from Mailman and seeing: > > > > legend = _("%(hostname)s Mailing Lists") > > > > The outer parentheses are a function call. The underscore > is a name that has a callable as a value, I suppose. I > believe that the value of the name underscore is the last > expression evaluated, but I'm not sure. Right... Thanks, I figured it was something like that but it was not something I'd encountered. so if _ = foo then bar = _("test") is equivalent to bar = foo("test") Mailman is a great product. But that bit of code is not, I think, > very good code. In Python explicitness is a virtue, and the use of > the underscore is implicit and is not very Pythonic. Agreed. The _ stuff is reminiscent of Perl $_, @_ and friends. I'd go miles personally to avoid that usage, personally. I have done the whole 'import this' and mightily strive to grok it all properly on a regular basis. ;-) By the way, The inner parentheses are a formatting operation. > %(x)s will be replaced by the value of x in Example: > > vals = {'animal': 'dog'} > "Rover is a big %(animal)s." % vals > > "%(animal)s" will be replaced by "dog". When you use this form, > the value on the right of the formatting operator must be a > dictionary. More from the library reference: > > When the right argument is a dictionary (or other mapping type), > then the formats in the string must include a parenthesised mapping > key into that dictionary inserted immediately after the "%" > character. The mapping key selects the value to be formatted from > the mapping. For example: > > >>> print '%(language)s has %(#)03d quote types.' % \ > {'language': "Python", "#": 2} > Python has 002 quote types. > > -- http://docs.python.org/lib/typesseq-strings.html Thanks for this too, though it's more completeness than I needed (just wondered if _( was "special" usage or what. Kudos on an excellent reply. So, any really good tutorials on FP and map, filter, zip, lambda ? I'm trying to wrap my mind around those better... Thanks much! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070711/31ab1992/attachment.html From chi at chimeric.de Wed Jul 11 18:17:42 2007 From: chi at chimeric.de (Michael Klier) Date: Wed, 11 Jul 2007 18:17:42 +0200 Subject: [Tutor] Question regarding syntax In-Reply-To: <20070711160035.GB73342@cutter.rexx.com> References: <6216eba0707110803u733a0e71ga6d4dac3078a37ae@mail.gmail.com> <20070711160035.GB73342@cutter.rexx.com> Message-ID: <20070711161742.GE10405@shipdown.de> Dave Kuhlman wrote: > On Wed, Jul 11, 2007 at 11:03:18AM -0400, John Morris wrote: > > I'm editing some code from Mailman and seeing: > > > > legend = _("%(hostname)s Mailing Lists") > > I am no python pro but I guess that funtction _() ist just a wrapper function around gettext.gettext from the gettext module (used for localization). I`ve seen that in lots of places and I think that`s common practise (don`t beat me if I am wrong ;-)). > Mailman is a great product. But that bit of code is not, I think, > very good code. Even the python gettext docs [1] use it that way. [1] http://docs.python.org/lib/node732.html Kind Regards Michael -- Michael Klier mail: chi at chimeric.de www: http://www.chimeric.de icq: 206179334 jabber: chi at jabber.shipdown.de key: http://downloads.chimeric.de/chi.asc key-id: 0x8308F551 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20070711/ceb29548/attachment.pgp From brunson at brunson.com Wed Jul 11 20:33:43 2007 From: brunson at brunson.com (Eric Brunson) Date: Wed, 11 Jul 2007 12:33:43 -0600 Subject: [Tutor] Question regarding syntax In-Reply-To: <20070711161742.GE10405@shipdown.de> References: <6216eba0707110803u733a0e71ga6d4dac3078a37ae@mail.gmail.com> <20070711160035.GB73342@cutter.rexx.com> <20070711161742.GE10405@shipdown.de> Message-ID: <46952287.3000404@brunson.com> Michael Klier wrote: > Dave Kuhlman wrote: > >> On Wed, Jul 11, 2007 at 11:03:18AM -0400, John Morris wrote: >> >>> I'm editing some code from Mailman and seeing: >>> >>> legend = _("%(hostname)s Mailing Lists") >>> >>> > > I am no python pro but I guess that funtction _() ist just a wrapper > function around gettext.gettext from the gettext module (used for > localization). I`ve seen that in lots of places and I think that`s > common practise (don`t beat me if I am wrong ;-)). > > >> Mailman is a great product. But that bit of code is not, I think, >> very good code. >> > > Even the python gettext docs [1] use it that way. > > [1] http://docs.python.org/lib/node732.html > > I've seen it before, too. From the example in the manual I imagine it's more convention than anything hard and fast, probably to make the string stand out more than the function call since it's essentially just doing a translation. However, by assigning gettext.getttext to the local variable '_', you do avoid a module lookup every time it's used. It's useful when you do something like this (contrived example): import math f = math.cos for x in range(0, 100000): print x, f(x) From hunter92383 at gmail.com Wed Jul 11 21:13:18 2007 From: hunter92383 at gmail.com (elis aeris) Date: Thu, 12 Jul 2007 03:13:18 +0800 Subject: [Tutor] I/O error (?) Message-ID: <674d5ce60707111213q6fea7f03pbddf8710e992bd3@mail.gmail.com> number_1 = 1 number_2 = 2 number_3 = 3 number_4 = 4 number_5 = 5 number_6 = 6 f = open("data.ini", "w") f.write("[1]") f.write("\n") f.write("command" + "=" + "mousemove\n") f.write("parameter_" + str(number_1) + "=" + " 500\n") f.write("parameter_" + str(number_2) + "=" + " 500\n") f.write("parameter_" + str(number_3) + "=" + " 500\n") f.write("parameter_" + str(number_4) + "=" + " 500\n") f.write("parameter_" + str(number_5) + "=" + " 500\n") f.write("parameter_" + str(number_6) + "=" + " 500\n") I am not sure why this wouldn't work, but this actually doesn't output at all. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070712/88de5934/attachment.html From andre.roberge at gmail.com Wed Jul 11 21:21:47 2007 From: andre.roberge at gmail.com (Andre Roberge) Date: Wed, 11 Jul 2007 16:21:47 -0300 Subject: [Tutor] Question regarding syntax In-Reply-To: <46952287.3000404@brunson.com> References: <6216eba0707110803u733a0e71ga6d4dac3078a37ae@mail.gmail.com> <20070711160035.GB73342@cutter.rexx.com> <20070711161742.GE10405@shipdown.de> <46952287.3000404@brunson.com> Message-ID: <7528bcdd0707111221t634b972exb0206b54fe0c7ac4@mail.gmail.com> On 7/11/07, Eric Brunson wrote: > Michael Klier wrote: > > Dave Kuhlman wrote: > > > >> On Wed, Jul 11, 2007 at 11:03:18AM -0400, John Morris wrote: > >> > >>> I'm editing some code from Mailman and seeing: > >>> > >>> legend = _("%(hostname)s Mailing Lists") > >>> > >>> > > > > I am no python pro but I guess that funtction _() ist just a wrapper > > function around gettext.gettext from the gettext module (used for > > localization). I`ve seen that in lots of places and I think that`s > > common practise (don`t beat me if I am wrong ;-)). > > > > > >> Mailman is a great product. But that bit of code is not, I think, > >> very good code. > >> > > > > Even the python gettext docs [1] use it that way. > > > > [1] http://docs.python.org/lib/node732.html > > > > > > I've seen it before, too. From the example in the manual I imagine it's > more convention than anything hard and fast, probably to make the string > stand out more than the function call since it's essentially just doing > a translation. > It is a standard convention. Lots of tools are built on the assumption that translatable strings are going to be enclosed in _(...) These tools extract the strings from programs, and put them in files (.po) that are easily editable by human translators. This convention is *not* limited to Python. Andr? > However, by assigning gettext.getttext to the local variable '_', you do > avoid a module lookup every time it's used. It's useful when you do > something like this (contrived example): > > import math > > f = math.cos > for x in range(0, 100000): > print x, f(x) > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Wed Jul 11 21:31:44 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Jul 2007 20:31:44 +0100 Subject: [Tutor] Question regarding syntax References: <6216eba0707110803u733a0e71ga6d4dac3078a37ae@mail.gmail.com><20070711160035.GB73342@cutter.rexx.com> <6216eba0707110931l49062086rd1d8cb86d091ad4f@mail.gmail.com> Message-ID: "John Morris" wrote > So, any really good tutorials on FP and map, filter, zip, lambda ? > I'm trying to wrap my mind around those better... You can try my FP topic in my tutor. Its not the last word but there are an excellent series of FP articles on the IBM Python 'blog' by David Mertz -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Jul 11 21:41:58 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Jul 2007 20:41:58 +0100 Subject: [Tutor] I/O error (?) References: <674d5ce60707111213q6fea7f03pbddf8710e992bd3@mail.gmail.com> Message-ID: "elis aeris" wrote > number_1 = 1 > number_2 = 2 > number_3 = 3 > number_4 = 4 > number_5 = 5 > number_6 = 6 > > f = open("data.ini", "w") > f.write("[1]") > f.write("\n") > f.write("command" + "=" + "mousemove\n") > f.write("parameter_" + str(number_1) + "=" + " 500\n") > f.write("parameter_" + str(number_2) + "=" + " 500\n") > f.write("parameter_" + str(number_3) + "=" + " 500\n") > f.write("parameter_" + str(number_4) + "=" + " 500\n") > f.write("parameter_" + str(number_5) + "=" + " 500\n") > f.write("parameter_" + str(number_6) + "=" + " 500\n") This is horribly inefficient and redundant. Howeever to answer your question first... > I am not sure why this wouldn't work, but this actually > doesn't output at all. You need to close the file after wrioting to force Python to flush its memory buffers to disk. (You can also use the flush method if you need to keep the file open for some reason) However you could write your code much more easily as: f = open('data.ini','w') f.write("[1]\ncommand=mousemove\n") for n in range(1,7): f.write("parameter_%d=500\n" % n) f.close() Or if you must use named values: numbers = [1,2,3,4,5,6] f = open('data.ini','w') f.write("[1]\ncommand=mousemove\n") for n in numbers: f.write("parameter_%d=500\n" % n) f.close() You are creating a lot of extra work for yourself by trying to use dynamic variables and not gaining anything. Also, as someone else mentioned, if you want to create config files there is a standard Python module that can help. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From stickster at gmail.com Wed Jul 11 21:47:20 2007 From: stickster at gmail.com (Paul W. Frields) Date: Wed, 11 Jul 2007 15:47:20 -0400 Subject: [Tutor] _ function In-Reply-To: References: Message-ID: <1184183240.3467.7.camel@localhost.localdomain> > > On Wed, Jul 11, 2007 at 11:03:18AM -0400, John Morris wrote: > > > I'm editing some code from Mailman and seeing: > > > > > > legend = _("%(hostname)s Mailing Lists") > > > > > > > The outter parenthese are a function call. The underscore > > is a name that has a callable as a value, I suppose. I > > believe that the value of the name underscore is the last > > expression evaluated, but I'm not sure. FWIW, I think that by convention _ is an alias for a translation function. In other words, this message is marked as one that is translatable. I'm only guessing, but I've run into this in some UI code in Python I've seen. By the way, I would like to say that I am somewhat of a newbie to Python, and also that I really appreciate the knowledge I've picked up on this list thus far. To all those of you who take time out of your busy day to answer questions, thank you! -- Paul W. Frields, RHCE http://paul.frields.org/ gpg fingerprint: 3DA6 A0AC 6D58 FEC4 0233 5906 ACDB C937 BD11 3717 Fedora Project: http://fedoraproject.org/wiki/PaulWFrields irc.freenode.net: stickster @ #fedora-docs, #fedora-devel, #fredlug -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part Url : http://mail.python.org/pipermail/tutor/attachments/20070711/b8e7650c/attachment-0001.pgp From hunter92383 at gmail.com Wed Jul 11 21:55:49 2007 From: hunter92383 at gmail.com (elis aeris) Date: Thu, 12 Jul 2007 03:55:49 +0800 Subject: [Tutor] I/O error (?) In-Reply-To: References: <674d5ce60707111213q6fea7f03pbddf8710e992bd3@mail.gmail.com> Message-ID: <674d5ce60707111255s24a931b3u4ee9f159ee0e087c@mail.gmail.com> oh in this case they actually aren't possible to be listized, because they are just place holders for quite a number of other names of variables and stuff :) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070712/bf620ae8/attachment.html From rabidpoobear at gmail.com Wed Jul 11 22:14:37 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 11 Jul 2007 15:14:37 -0500 Subject: [Tutor] I/O error (?) In-Reply-To: <674d5ce60707111255s24a931b3u4ee9f159ee0e087c@mail.gmail.com> References: <674d5ce60707111213q6fea7f03pbddf8710e992bd3@mail.gmail.com> <674d5ce60707111255s24a931b3u4ee9f159ee0e087c@mail.gmail.com> Message-ID: <46953A2D.2020508@gmail.com> elis aeris wrote: > oh in this case they actually aren't possible to be listized, because > they are just place holders for quite a number of other names of > variables and stuff :) That is untrue. You can put any variables into a list that you want. For example: x = 'hello' b = 42 abba = 0xABBA Then you can do this: mylist = [x,b,abba] and print from the list. -Luke From hunter92383 at gmail.com Wed Jul 11 22:26:37 2007 From: hunter92383 at gmail.com (elis aeris) Date: Thu, 12 Jul 2007 04:26:37 +0800 Subject: [Tutor] I/O error (?) In-Reply-To: <46953A2D.2020508@gmail.com> References: <674d5ce60707111213q6fea7f03pbddf8710e992bd3@mail.gmail.com> <674d5ce60707111255s24a931b3u4ee9f159ee0e087c@mail.gmail.com> <46953A2D.2020508@gmail.com> Message-ID: <674d5ce60707111326j79edb59by53adccd53a79badf@mail.gmail.com> no, no, the values are coming from all over the place, so having to remember which member of the list that function is tied to may be more of a headache I get the technique though On 7/12/07, Luke Paireepinart wrote: > > elis aeris wrote: > > oh in this case they actually aren't possible to be listized, because > > they are just place holders for quite a number of other names of > > variables and stuff :) > That is untrue. > You can put any variables into a list that you want. > For example: > x = 'hello' > b = 42 > abba = 0xABBA > > Then you can do this: > mylist = [x,b,abba] > and print from the list. > > -Luke > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070712/b0ca8566/attachment.htm From hunter92383 at gmail.com Wed Jul 11 22:28:13 2007 From: hunter92383 at gmail.com (elis aeris) Date: Thu, 12 Jul 2007 04:28:13 +0800 Subject: [Tutor] strange output Message-ID: <674d5ce60707111328o5f542934i60a72c66b4293ab@mail.gmail.com> def mousemove(): f.write("command" + " =" + " mousemove\n") f.write("parameter_" + str(number_1) + "=" + " 500\n") f.write("parameter_" + str(number_2) + "=" + " 500\n") f.write("parameter_" + str(number_3) + "=" + " 500\n") f.write("parameter_" + str(number_4) + "=" + " 500\n") f.write("parameter_" + str(number_5) + "=" + " 500\n") f.write("parameter_" + str(number_6) + "=" + " 500\n") f = open("data.ini", "w") mousemove() f.close() even though this part is skippe number_1 = 100 number_2 = 200 number_3 = 300 number_4 = 400 number_5 = 500 number_6 = 600 it doesn't say something like undefined functions and instead it would print the numbers fine. strange eh? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070712/66663eb8/attachment.html From samar.mohamed at agfa.com Wed Jul 11 22:00:46 2007 From: samar.mohamed at agfa.com (samar.mohamed at agfa.com) Date: Wed, 11 Jul 2007 16:00:46 -0400 Subject: [Tutor] please add me Message-ID: Please add me to the mailing list Samar Mohamed -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070711/b0e55044/attachment.htm From hunter92383 at gmail.com Wed Jul 11 22:51:00 2007 From: hunter92383 at gmail.com (elis aeris) Date: Thu, 12 Jul 2007 04:51:00 +0800 Subject: [Tutor] green brackets? Message-ID: <674d5ce60707111351g7b44eabm2a05c82d57be7b9e@mail.gmail.com> def mousemove(x,y): f.write("n\") f.write("command" + " =" + " mousemove\n") f.write("parameter_1 = " + str(x) + "\n") f.write("parameter_2 = " + str(y) + "\n") f.write("n\") for some reason that last bracket of the 2nd and last line line in IDLE are green.\ why is that? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070712/204de6c8/attachment.htm From rabidpoobear at gmail.com Wed Jul 11 22:55:42 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 11 Jul 2007 15:55:42 -0500 Subject: [Tutor] green brackets? In-Reply-To: <674d5ce60707111351g7b44eabm2a05c82d57be7b9e@mail.gmail.com> References: <674d5ce60707111351g7b44eabm2a05c82d57be7b9e@mail.gmail.com> Message-ID: <469543CE.4080008@gmail.com> elis aeris wrote: > def mousemove(x,y): > f.write("n\") n\ and \n are different. n\ means "an n character and then an escaped character" because the n\ was followed by a ", then the string literally contains n\" for example, "my momma always said \"life is like a box of chocolates. you never know what you gonna get.\"" will be the following string: my momma always said "life is like a box of chocolates. you never know what you gonna get." The reason they're "green" in IDLE is because there is no end " for the string, since the \" is interpreted as "put the quotation mark into the string instead of stopping the string here" > f.write("command" + " =" + " mousemove\n") > f.write("parameter_1 = " + str(x) + "\n") > f.write("parameter_2 = " + str(y) + "\n") > f.write("n\") > > for some reason that last bracket of the 2nd and last line line in > IDLE are green.\ > why is that? -Luke From nuin at genedrift.org Wed Jul 11 22:56:34 2007 From: nuin at genedrift.org (Paulo Nuin) Date: Wed, 11 Jul 2007 16:56:34 -0400 Subject: [Tutor] green brackets? In-Reply-To: <674d5ce60707111351g7b44eabm2a05c82d57be7b9e@mail.gmail.com> References: <674d5ce60707111351g7b44eabm2a05c82d57be7b9e@mail.gmail.com> Message-ID: <46954402.4010909@genedrift.org> Hi f.write("n\") should be f.write("\n") Paulo elis aeris wrote: > def mousemove(x,y): > f.write("n\") > f.write("command" + " =" + " mousemove\n") > f.write("parameter_1 = " + str(x) + "\n") > f.write("parameter_2 = " + str(y) + "\n") > f.write("n\") > > > > > > for some reason that last bracket of the 2nd and last line line in > IDLE are green.\ > why is that? > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From hunter92383 at gmail.com Wed Jul 11 22:57:15 2007 From: hunter92383 at gmail.com (elis aeris) Date: Thu, 12 Jul 2007 04:57:15 +0800 Subject: [Tutor] green brackets? In-Reply-To: <46954402.4010909@genedrift.org> References: <674d5ce60707111351g7b44eabm2a05c82d57be7b9e@mail.gmail.com> <46954402.4010909@genedrift.org> Message-ID: <674d5ce60707111357x67ea3adcm1516f8209a6a8e32@mail.gmail.com> @_@ i see On 7/12/07, Paulo Nuin wrote: > > Hi > > f.write("n\") should be > > f.write("\n") > > Paulo > > elis aeris wrote: > > def mousemove(x,y): > > f.write("n\") > > f.write("command" + " =" + " mousemove\n") > > f.write("parameter_1 = " + str(x) + "\n") > > f.write("parameter_2 = " + str(y) + "\n") > > f.write("n\") > > > > > > > > > > > > for some reason that last bracket of the 2nd and last line line in > > IDLE are green.\ > > why is that? > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > 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/20070712/38c4e09b/attachment.html From washakie at gmail.com Wed Jul 11 23:05:05 2007 From: washakie at gmail.com (John) Date: Wed, 11 Jul 2007 23:05:05 +0200 Subject: [Tutor] green brackets? In-Reply-To: <674d5ce60707111357x67ea3adcm1516f8209a6a8e32@mail.gmail.com> References: <674d5ce60707111351g7b44eabm2a05c82d57be7b9e@mail.gmail.com> <46954402.4010909@genedrift.org> <674d5ce60707111357x67ea3adcm1516f8209a6a8e32@mail.gmail.com> Message-ID: This is how you put a newline or linebreak in a string: \n -just adding that for someone's search later on, since 'newline' and 'linebreak' hadn't been mentioned yet ;) (Should I be doing something else!?) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070711/6cadfd15/attachment.htm From alan.gauld at btinternet.com Wed Jul 11 23:15:59 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Jul 2007 22:15:59 +0100 Subject: [Tutor] I/O error (?) References: <674d5ce60707111213q6fea7f03pbddf8710e992bd3@mail.gmail.com> <674d5ce60707111255s24a931b3u4ee9f159ee0e087c@mail.gmail.com> Message-ID: "elis aeris" wrote > oh in this case they actually aren't possible to be listized, > because they > are just place holders for quite a number of other names of > variables and > stuff :) OK, But you could still use a dictionary and get the same effect... Alan G. From alan.gauld at btinternet.com Wed Jul 11 23:17:32 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Jul 2007 22:17:32 +0100 Subject: [Tutor] please add me References: Message-ID: You need to add yourself. Go to the Python web site, Community, Mailing Lists. Navigate to the tutor list and fill in the registration form. HTH, Alan G. wrote in message news:OFC7C941BC.EFBC0C0C-ON85257315.006DE442-85257315.006DEF07 at agfa.com... > Please add me to the mailing list > > Samar Mohamed -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Wed Jul 11 23:22:33 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Jul 2007 22:22:33 +0100 Subject: [Tutor] strange output References: <674d5ce60707111328o5f542934i60a72c66b4293ab@mail.gmail.com> Message-ID: "elis aeris" wrote in message news:674d5ce60707111328o5f542934i60a72c66b4293ab at mail.gmail.com... > def mousemove(): > f.write("command" + " =" + " mousemove\n") > f.write("parameter_" + str(number_1) + "=" + " 500\n") > f.write("parameter_" + str(number_2) + "=" + " 500\n") > f.write("parameter_" + str(number_3) + "=" + " 500\n") > f.write("parameter_" + str(number_4) + "=" + " 500\n") > f.write("parameter_" + str(number_5) + "=" + " 500\n") > f.write("parameter_" + str(number_6) + "=" + " 500\n") > > > f = open("data.ini", "w") > mousemove() > f.close() > > > > > even though this part is skippe > > number_1 = 100 > number_2 = 200 > number_3 = 300 > number_4 = 400 > number_5 = 500 > number_6 = 600 > Are you doing this in a file or using the >>> prompt? If its at the >>> prompt then it will remember the number_1 values from earlier. If you are saying you now have a file without the number_1 stuff and just the function above then that is indeed odd! Alan g. From rabidpoobear at gmail.com Wed Jul 11 23:25:12 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 11 Jul 2007 16:25:12 -0500 Subject: [Tutor] please add me In-Reply-To: References: Message-ID: <46954AB8.6000600@gmail.com> Alan Gauld wrote: > You need to add yourself. > Technically, he doesn't need to add himself. We could just add his e-mail address for him. But that might violate some ToS or something. -Luke From rabidpoobear at gmail.com Wed Jul 11 23:27:19 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 11 Jul 2007 16:27:19 -0500 Subject: [Tutor] strange output In-Reply-To: References: <674d5ce60707111328o5f542934i60a72c66b4293ab@mail.gmail.com> Message-ID: <46954B37.1010303@gmail.com> Alan Gauld wrote: > "elis aeris" wrote in message > news:674d5ce60707111328o5f542934i60a72c66b4293ab at mail.gmail.com... > >> def mousemove(): >> f.write("command" + " =" + " mousemove\n") >> f.write("parameter_" + str(number_1) + "=" + " 500\n") >> f.write("parameter_" + str(number_2) + "=" + " 500\n") >> f.write("parameter_" + str(number_3) + "=" + " 500\n") >> f.write("parameter_" + str(number_4) + "=" + " 500\n") >> f.write("parameter_" + str(number_5) + "=" + " 500\n") >> f.write("parameter_" + str(number_6) + "=" + " 500\n") >> >> >> f = open("data.ini", "w") >> mousemove() >> f.close() >> >> >> >> >> even though this part is skippe >> >> number_1 = 100 >> number_2 = 200 >> number_3 = 300 >> number_4 = 400 >> number_5 = 500 >> number_6 = 600 >> >> > > Are you doing this in a file or using the >>> prompt? > If its at the >>> prompt then it will remember the number_1 values > from earlier. If you are saying you now have a file without the > number_1 stuff and just the function above then that is indeed odd! > Also, IDLE without a subprocess will keep modules and such around, and since those are just objects, I suspect it keeps local variables too, until you restart IDLE. -Luke From alan.gauld at btinternet.com Wed Jul 11 23:20:55 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Jul 2007 22:20:55 +0100 Subject: [Tutor] I/O error (?) References: <674d5ce60707111213q6fea7f03pbddf8710e992bd3@mail.gmail.com><674d5ce60707111255s24a931b3u4ee9f159ee0e087c@mail.gmail.com><46953A2D.2020508@gmail.com> <674d5ce60707111326j79edb59by53adccd53a79badf@mail.gmail.com> Message-ID: "elis aeris" wrote > no, no, the values are coming from all over the place, so having to > remember > which member of the list that function is tied to may be more of a > headache That makes sense provided you are using more decriptive names that number_1 etc. Thats just as hard to remember as the index of a list! But if they have decent names then its a fair point. Alan G. From keridee at jayco.net Wed Jul 11 19:48:29 2007 From: keridee at jayco.net (Tiger12506) Date: Wed, 11 Jul 2007 17:48:29 -0000 Subject: [Tutor] I/O error (?) References: <674d5ce60707111213q6fea7f03pbddf8710e992bd3@mail.gmail.com><674d5ce60707111255s24a931b3u4ee9f159ee0e087c@mail.gmail.com><46953A2D.2020508@gmail.com> <674d5ce60707111326j79edb59by53adccd53a79badf@mail.gmail.com> Message-ID: <00a501c7c3e3$b483d680$26fce004@JSLAPTOP> > no, no, the values are coming from all over the place, so having to > remember > which member of the list that function is tied to may be more of a > headache > > I get the technique though Would you do us a huge favor in helping you and send us your code, the code where these values are coming from all over the place? Perhaps we can help come up with a much more efficient solution. I personally read this sentence and thought maybe that you have found one of the uses of dynamic variables, but this still seems unlikely. If you have not found one of those uses, then my gut is telling me that you are approaching this from the wrong angle. However, I can't tell for sure. And since the other suggestions do not seem to suit your tastes (see above quote) then perhaps we can save you a lot of typing/work by showing you another way. JS From carroll at tjc.com Thu Jul 12 02:47:49 2007 From: carroll at tjc.com (Terry Carroll) Date: Wed, 11 Jul 2007 17:47:49 -0700 (PDT) Subject: [Tutor] How do you install EGG files (was: storm anyone? In-Reply-To: <384c93600707110810qfdb0765g66e45b971ce9f62a@mail.gmail.com> Message-ID: On Wed, 11 Jul 2007, shawn bright wrote: > Hey there all, > i got the news that storm was released as open source. Storm is a db orm for > python. > i have a downloaded package and i would like to play with it, but it does > not come with any install instructions. > i found the package here https://storm.canonical.com/FrontPage > there is a makefile in the top level folder, so should i use gcc and try to > 'make' 'make install' or is that not necessarily the way to go here? Yeah, the docs at https://storm.canonical.com/Install leave a little bit to be desired. I see it comes in an EGG format, which is just a ZIP file. What will (I think) work is to open the EGG file with your favorite unzipper and unzip into your site-packages directory (making sure to use the directory names from the EGG file). Just for the heck of it, I tried this out. Before the unzipping: >>> import storm Traceback (most recent call last): File "", line 1, in ImportError: No module named storm Then I unzipped as described above: >>> import storm >>> dir(storm) ['Undef', 'UndefType', '__builtins__', '__doc__', '__file__', '__name__', '__path__'] >>> print storm.__doc__ None >>> print storm.__path__ ['C:\\Python25\\lib\\site-packages\\storm'] >>> So that seems to work. But the larger question is, "What do I do with an EGG file?" I know there's a more straightforward way of having Python process an EGG file, just as Java processes a JAR file. I've just never had to learn it. I'm retitling this thread in the hopes that someone who knows will assist; then I'll learn something, too. From brunson at brunson.com Thu Jul 12 02:51:21 2007 From: brunson at brunson.com (Eric Brunson) Date: Wed, 11 Jul 2007 18:51:21 -0600 Subject: [Tutor] How do you install EGG files In-Reply-To: References: Message-ID: <46957B09.3060203@brunson.com> Terry Carroll wrote: > On Wed, 11 Jul 2007, shawn bright wrote: > > >> Hey there all, >> i got the news that storm was released as open source. Storm is a db orm for >> python. >> i have a downloaded package and i would like to play with it, but it does >> not come with any install instructions. >> i found the package here https://storm.canonical.com/FrontPage >> there is a makefile in the top level folder, so should i use gcc and try to >> 'make' 'make install' or is that not necessarily the way to go here? >> > > Yeah, the docs at https://storm.canonical.com/Install leave a little bit > to be desired. > > I see it comes in an EGG format, which is just a ZIP file. What will (I > think) work is to open the EGG file with your favorite unzipper and unzip > into your site-packages directory (making sure to use the directory names > from the EGG file). > > Just for the heck of it, I tried this out. Before the unzipping: > > >>>> import storm >>>> > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named storm > > Then I unzipped as described above: > > >>>> import storm >>>> dir(storm) >>>> > ['Undef', 'UndefType', '__builtins__', '__doc__', '__file__', '__name__', > '__path__'] > >>>> print storm.__doc__ >>>> > None > >>>> print storm.__path__ >>>> > ['C:\\Python25\\lib\\site-packages\\storm'] > > > So that seems to work. > > But the larger question is, "What do I do with an EGG file?" I know > there's a more straightforward way of having Python process an EGG file, > just as Java processes a JAR file. I've just never had to learn it. > > I'm retitling this thread in the hopes that someone who knows will assist; > then I'll learn something, too. > Add the full path of the egg to a .pth file in a directory in your python path. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From hunter92383 at gmail.com Thu Jul 12 02:54:51 2007 From: hunter92383 at gmail.com (elis aeris) Date: Thu, 12 Jul 2007 08:54:51 +0800 Subject: [Tutor] making aaa.txt in notepad focused. Message-ID: <674d5ce60707111754t3661904at620d3389a88fcdc0@mail.gmail.com> import time from ctypes import * # Load up the Win32 APIs we need to use. GetForegroundWindow = windll.user32.GetForegroundWindow foreground_window = GetForegroundWindow() this is a part of a code I from a separate project. I am trying to find out it's possible to do this: handle = gesomethingfromthefocusedwindow() later when I want to do this: handle.gainfocus() and zap that window to the front! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070712/6f9989fe/attachment-0001.htm From carroll at tjc.com Thu Jul 12 03:01:11 2007 From: carroll at tjc.com (Terry Carroll) Date: Wed, 11 Jul 2007 18:01:11 -0700 (PDT) Subject: [Tutor] How do you install EGG files In-Reply-To: <46957B09.3060203@brunson.com> Message-ID: On Wed, 11 Jul 2007, Eric Brunson wrote: > Add the full path of the egg to a .pth file in a directory in your > python path. Cool, thanks. To Shawn: So all I did was create a text file called "myeggs.pth" in my site-packages directory, with the following content: >cat c:\Python25\Lib\site-packages\myeggs.pth C:\Documents and Settings\tcarroll\My Documents\Installs\Storm\storm-0.9-py2.5.egg And it worked. From billburns at pennswoods.net Thu Jul 12 04:12:41 2007 From: billburns at pennswoods.net (Bill Burns) Date: Wed, 11 Jul 2007 22:12:41 -0400 Subject: [Tutor] making aaa.txt in notepad focused. In-Reply-To: <674d5ce60707111754t3661904at620d3389a88fcdc0@mail.gmail.com> References: <674d5ce60707111754t3661904at620d3389a88fcdc0@mail.gmail.com> Message-ID: <46958E19.6000002@pennswoods.net> elis aeris wrote: > import time > from ctypes import * > > # Load up the Win32 APIs we need to use. > GetForegroundWindow = windll.user32.GetForegroundWindow > > > foreground_window = GetForegroundWindow() > > > > > > this is a part of a code I from a separate project. > > > I am trying to find out it's possible to do this: > > handle = gesomethingfromthefocusedwindow() > > later when I want to do this: > > handle.gainfocus() > > > and zap that window to the front! > So you have a text file open with Notepad? And the file is 'aaa.txt' and you want Notepad to be active (have the focus)? If so, try this: from ctypes import windll user32 = windll.user32 SW_RESTORE = 9 hwnd = user32.FindWindowA(None, 'aaa.txt - Notepad') if hwnd: user32.ShowWindow(hwnd, SW_RESTORE) user32.SetForegroundWindow(hwnd) Bill From hunter92383 at gmail.com Thu Jul 12 04:21:05 2007 From: hunter92383 at gmail.com (elis aeris) Date: Thu, 12 Jul 2007 10:21:05 +0800 Subject: [Tutor] making aaa.txt in notepad focused. In-Reply-To: <46958E19.6000002@pennswoods.net> References: <674d5ce60707111754t3661904at620d3389a88fcdc0@mail.gmail.com> <46958E19.6000002@pennswoods.net> Message-ID: <674d5ce60707111921y650ff0b4ka001425d8aa9a74@mail.gmail.com> is it possible to do patial window title? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070712/9c315086/attachment.html From dos.fool at gmail.com Thu Jul 12 07:08:55 2007 From: dos.fool at gmail.com (max .) Date: Wed, 11 Jul 2007 23:08:55 -0600 Subject: [Tutor] curses Message-ID: <857e4c3d0707112208j6fb7d957he1d648f148854828@mail.gmail.com> hello all sorry but i just cant seem to get my head around curses iv read a few of the tuts out there and get what there saying but i cant write my own if any one can point me in the right direction easer is better i only need something very simple right now just writting and refreshing thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070711/73191524/attachment.htm From alan.gauld at btinternet.com Thu Jul 12 09:29:33 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Jul 2007 08:29:33 +0100 Subject: [Tutor] curses References: <857e4c3d0707112208j6fb7d957he1d648f148854828@mail.gmail.com> Message-ID: "max ." wrote > hello all sorry but i just cant seem to get my head around curses I know the feeling it took me a while too. > iv read a few of the tuts out there and get what there saying > but i cant write my own Can you tell us a) What OS are you using - Curses only really works on Linux/Unix style systems in my experience. b) Which particular curses tutorial did you read? c) What you are trying to do d) What code have you tried? And how does it fail? Its a lot easier for us to address specific questions than to try to write a generic introduction to curses.Especially when several of those already exist. The thinghs you find hard to understand might not be the same things I struggled with... The key things to remember are to initialise the screen first and restore it last: import curses # curses needs to initialize the screen # so that it can control it. screen = curses.initscr() # rest of program here... # create viewports/windows etc# manipulate cursor, write text...curses.endwin() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From strider1551 at gmail.com Thu Jul 12 13:14:34 2007 From: strider1551 at gmail.com (Adam A. Zajac) Date: Thu, 12 Jul 2007 07:14:34 -0400 Subject: [Tutor] Question about code reviews In-Reply-To: References: Message-ID: <20070712071434.5b04fef8@lavos> > Do you know of any service or person that could do a code review > for me? Perhaps if you were more specific about what you are looking for in the review? If you merely want something to check your code for possible errors and how well you stick to standards, then look into pylint or pychecker. From connorsml at gmail.com Thu Jul 12 14:04:55 2007 From: connorsml at gmail.com (Michael Connors) Date: Thu, 12 Jul 2007 13:04:55 +0100 Subject: [Tutor] python syntax: underscore Message-ID: Hi, I was following the thread on about the _("xx") thingy. Since then I played around a bit with underscores at the console and it seems to me that if you execute code with a return value but you dont save the result, then _ is a pointer to this value. Is that correct? >>4 4 >>print _ 4 So if I do this, >>_ = 10 >>4 4 >>print _ 10 What is this _ used for? If I assign something to the underscore, will it cause strange things to happen later? (Just curiosity) Regards, -- Michael -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070712/d7dc9390/attachment.htm From taserian at gmail.com Thu Jul 12 15:08:22 2007 From: taserian at gmail.com (taserian) Date: Thu, 12 Jul 2007 09:08:22 -0400 Subject: [Tutor] How to improve Message-ID: <70dbc4d40707120608k376c5a9r1d3c43811d8f6bd2@mail.gmail.com> I've been programming for years before encountering Pythoin, but in much more verbose languages, and I appreciate the fact that Python is so terse and still accomplishes so much. Still, I have difficulty thinking in Python, and tend to revert to longer programs for what seems to be simple tasks. Sometimes it's because I'm just not aware of a library function, but many times it's because there's just some elegant way to solve my kludge. As an exercise in Python, I decided to solve a toy problem called "interleave". The idea is that I want to determine how many words in the English language are decomposable into two words by taking it apart one letter at a time. So the word "theorems" could be decomposed into "term" and "hoes" (original word = abababab, decomposed words = aaaa and bbbb, with all letters in the same order as in the original word). I'd like to see how I could improve the program below for this, and make it more Python-ish. = = = = START def decompose(longword): word1 = longword[0::2] word2 = longword[1::2] return (word1, word2) wordlengthlist = [None] * 31 for i in range(0,len(wordlengthlist)): wordlengthlist[i] = [] results = [] for lineread in open("word.list"): for word in lineread.split(): if len(word)<31: wordlengthlist[len(word)].append(word) outfile = open('InterleaveEnglishYAWL.txt', 'w') for x in range(4, 31): print x for i in wordlengthlist[x]: twowords = decompose(i) word1 = twowords[0] word2 = twowords[1] if word1 in wordlengthlist[len(word1)] and word2 in wordlengthlist[len(word2)]: outfile.write("(" + word1 + ", " + word2 + ", " + i + ")\n") print (word1, word2, i) outfile.close(); = = = = END Tony R. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070712/30841107/attachment.html From stickster at gmail.com Thu Jul 12 15:25:24 2007 From: stickster at gmail.com (Paul W. Frields) Date: Thu, 12 Jul 2007 09:25:24 -0400 Subject: [Tutor] python syntax: underscore In-Reply-To: References: Message-ID: <1184246724.3878.2.camel@localhost.localdomain> On Thu, 2007-07-12 at 13:04 +0100, Michael Connors wrote: > Hi, > I was following the thread on about the _("xx") thingy. > Since then I played around a bit with underscores at the console and > it seems to me that if you execute code with a return value but you > dont save the result, then _ is a pointer to this value. > > Is that correct? http://docs.python.org/ref/id-classes.html '''The special identifier "_" is used in the interactive interpreter to store the result of the last evaluation; it is stored in the __builtin__ module. When not in interactive mode, "_" has no special meaning and is not defined.''' -- Paul W. Frields, RHCE http://paul.frields.org/ gpg fingerprint: 3DA6 A0AC 6D58 FEC4 0233 5906 ACDB C937 BD11 3717 Fedora Project: http://fedoraproject.org/wiki/PaulWFrields irc.freenode.net: stickster @ #fedora-docs, #fedora-devel, #fredlug From alan.gauld at btinternet.com Thu Jul 12 16:28:39 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Jul 2007 15:28:39 +0100 Subject: [Tutor] How to improve References: <70dbc4d40707120608k376c5a9r1d3c43811d8f6bd2@mail.gmail.com> Message-ID: "taserian" wrote > I'd like to see how I could improve the program below for this, and > make it > more Python-ish. > > = = = = START > > def decompose(longword): > word1 = longword[0::2] > word2 = longword[1::2] > return (word1, word2) This seems OK to me. > wordlengthlist = [None] * 31 > for i in range(0,len(wordlengthlist)): > wordlengthlist[i] = [] But this could be done using a list comprehension: wordlengthlist = [[] for i in range(31)) > results = [] > > for lineread in open("word.list"): > for word in lineread.split(): > if len(word)<31: > wordlengthlist[len(word)].append(word) > > outfile = open('InterleaveEnglishYAWL.txt', 'w') > > for x in range(4, 31): > print x > for i in wordlengthlist[x]: > twowords = decompose(i) > word1 = twowords[0] > word2 = twowords[1] the three lines above can be done as word1,word2 = decompose(i) > if word1 in wordlengthlist[len(word1)] and word2 in > wordlengthlist[len(word2)]: > outfile.write("(" + word1 + ", " + word2 + ", " + i + > ")\n") > print (word1, word2, i) > > outfile.close(); > > = = = = END Those are the only significant changes I wouldmake. Alan G. From tinoloc at gmail.com Thu Jul 12 19:48:34 2007 From: tinoloc at gmail.com (Tino Dai) Date: Thu, 12 Jul 2007 13:48:34 -0400 Subject: [Tutor] Question about code reviews In-Reply-To: <20070712071434.5b04fef8@lavos> References: <20070712071434.5b04fef8@lavos> Message-ID: On 7/12/07, Adam A. Zajac wrote: > > > Do you know of any service or person that could do a code review > > for me? > > Perhaps if you were more specific about what you are looking for in the > review? If you merely want something to check your code for possible > errors and how well you stick to standards, then look into pylint or > pychecker. > > Actually, I'm looking for two things: I can do stuff with python, but a) is there a better way to do it? b) What in python don't I know that I don't know. Does that make sense? -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070712/a4198ebc/attachment.html From glingl at aon.at Thu Jul 12 20:00:03 2007 From: glingl at aon.at (Gregor Lingl) Date: Thu, 12 Jul 2007 20:00:03 +0200 Subject: [Tutor] How to improve In-Reply-To: <70dbc4d40707120608k376c5a9r1d3c43811d8f6bd2@mail.gmail.com> References: <70dbc4d40707120608k376c5a9r1d3c43811d8f6bd2@mail.gmail.com> Message-ID: <46966C23.4030300@aon.at> taserian schrieb: > I've been programming for years before encountering Pythoin, but in > much more verbose languages, and I appreciate the fact that Python is > so terse and still accomplishes so much. Still, I have difficulty > thinking in Python, and tend to revert to longer programs for what > seems to be simple tasks. Sometimes it's because I'm just not aware of > a library function, but many times it's because there's just some > elegant way to solve my kludge. > > As an exercise in Python, I decided to solve a toy problem called > "interleave". The idea is that I want to determine how many words in > the English language are decomposable into two words by taking it > apart one letter at a time. So the word "theorems" could be decomposed > into "term" and "hoes" (original word = abababab, decomposed words = > aaaa and bbbb, with all letters in the same order as in the original > word). > > I'd like to see how I could improve the program below for this, and > make it more Python-ish. > Hi taserian, I've just produced an alternative solution of your problem (based on your ideas). The main difference is, that I use a wordlength-dictionary. This version has the advantage, that it doesn't make an assumption about the max word length. I don't consider it to be an improvement, just an example that uses different language elements of Python in some places. Hope you enjoy it. ==== START wordlengthdict = {} for word in open("wordlist.txt").read().split(): wordlengthdict.setdefault(len(word),[]).append(word) outfile = open('InterleaveEnglishYAWL.txt', 'w') for l in sorted(wordlengthdict.keys()): print l for w in wordlengthdict[l]: wordtriple = (w1, w2, dummy) = w[0::2], w[1::2], w if w1 in wordlengthdict.get(len(w1),[]) and w2 in wordlengthdict.get(len(w2),[]): outfile.write("(%s, %s, %s)\n" % wordtriple) print wordtriple outfile.close(); ==== END Best regards, Gregor > = = = = START > > def decompose(longword): > word1 = longword[0::2] > word2 = longword[1::2] > return (word1, word2) > > wordlengthlist = [None] * 31 > for i in range(0,len(wordlengthlist)): > wordlengthlist[i] = [] > results = [] > > for lineread in open("word.list"): > for word in lineread.split(): > if len(word)<31: > wordlengthlist[len(word)].append(word) > > outfile = open('InterleaveEnglishYAWL.txt', 'w') > > for x in range(4, 31): > print x > for i in wordlengthlist[x]: > twowords = decompose(i) > word1 = twowords[0] > word2 = twowords[1] > if word1 in wordlengthlist[len(word1)] and word2 in > wordlengthlist[len(word2)]: > outfile.write("(" + word1 + ", " + word2 + ", " + i + ")\n") > print (word1, word2, i) > > outfile.close(); > > = = = = END > > Tony R. > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From keridee at jayco.net Thu Jul 12 17:06:24 2007 From: keridee at jayco.net (Tiger12506) Date: Thu, 12 Jul 2007 15:06:24 -0000 Subject: [Tutor] Question about code reviews References: <20070712071434.5b04fef8@lavos> Message-ID: <034501c7c496$3a502d60$f5fce004@JSLAPTOP> >> >> > Do you know of any service or person that could do a code review >> > for me? >> >> Perhaps if you were more specific about what you are looking for in the >> review? If you merely want something to check your code for possible >> errors and how well you stick to standards, then look into pylint or >> pychecker. >> >> Actually, I'm looking for two things: > > I can do stuff with python, but a) is there a better way to do it? b) What > in python don't I know that I don't know. Does that make sense? > > -Tino I'm sure there are some people on the list who wouldn't mind reviewing some of your code and giving suggestions. Perhaps you would benefit by providing links? From queprime at gmail.com Thu Jul 12 22:19:56 2007 From: queprime at gmail.com (Que Prime) Date: Thu, 12 Jul 2007 13:19:56 -0700 Subject: [Tutor] Question Message-ID: <17285ccf0707121319r7a23792fp387919c137232057@mail.gmail.com> I'm trying to create a program that creates a file and write the number for each line. Here is what I have so far but can't seem to get the loop and write correct. Thanks in advance. print "Creating txt file" tfile = open("25.txt", "w") for i in range(25): x = int(1) tfile.writelines("x\n") x += 1 tfile.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070712/ee215152/attachment.html From alan.gauld at btinternet.com Thu Jul 12 22:54:24 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Jul 2007 21:54:24 +0100 Subject: [Tutor] Question References: <17285ccf0707121319r7a23792fp387919c137232057@mail.gmail.com> Message-ID: "Que Prime" wrote > Here is what I have so far but can't seem to get the loop and > write correct. I suspect you have used another language before and Python's for loop is foxing you. > print "Creating txt file" > tfile = open("25.txt", "w") > > for i in range(25): > x = int(1) You don;t need to convert to an int, i is already an int. But worse, you are here converting the number 1 to an int every time through the loop. I don't think thats what you want! range(25) will produce a list of numbers from 0 to 24. The for loop will set i to each number in turn. > tfile.writelines("x\n") And writelines expects a list of strings but you are giving it one string. You only need write() here. And of course you don't need x so you can just write the string version of i: str(i) plus a new line (\n) > x += 1 And you don't need this at all because the loop will automatically get the next number. > tfile.close() Try those changes, it should simplify things significantly. You might find a quick read through my loops and file handling topics useful too. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dkuhlman at rexx.com Fri Jul 13 01:26:08 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 12 Jul 2007 16:26:08 -0700 Subject: [Tutor] Here is newbie doc on how to implement generators Message-ID: <20070712232608.GA59300@cutter.rexx.com> I find iterators and generators fascinating. So, in order to try to understand them better myself, I've written up some notes. I'm hoping that these notes might help someone new to the generators and iterators in Python. You can find it here: http://www.rexx.com/~dkuhlman/python_comments.html http://www.rexx.com/~dkuhlman/python_comments.html#iterators-and-generators I'll appreciate any comments and suggestions that might help me improve it. Please pass the above link along to anyone you think it might help. And, I have a question -- If you look at the example of the iterative (non-recursive) generator (the Doubler class), you will see that it walks a list, not a tree. That's because I was *not* able to figure out how to implement a non-recursive tree walk generator. I found examples showing non-recursive/iterative solutions to how to walk a *binary* tree. Those examples are at: Lib/test/test_generator.py # in the Python distribution http://en.wikipedia.org/wiki/Inorder_tree_walk But, I could not find a example that shows a non-recursive way to walk a tree in which each node has an arbitrary number of children. Alas, I could not write that non-recursive tree walk. The recusive walk is easy and clean. So, maybe I should not worry about the non-recursive approach. Still, it really bothers me that I could not do it. So, if you know where there are some examples, that would help me improve my notes on iterators and generators, please give me a link. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From jrmorrisnc at gmail.com Fri Jul 13 02:06:51 2007 From: jrmorrisnc at gmail.com (John Morris) Date: Thu, 12 Jul 2007 20:06:51 -0400 Subject: [Tutor] Question regarding syntax In-Reply-To: <7528bcdd0707111221t634b972exb0206b54fe0c7ac4@mail.gmail.com> References: <6216eba0707110803u733a0e71ga6d4dac3078a37ae@mail.gmail.com> <20070711160035.GB73342@cutter.rexx.com> <20070711161742.GE10405@shipdown.de> <46952287.3000404@brunson.com> <7528bcdd0707111221t634b972exb0206b54fe0c7ac4@mail.gmail.com> Message-ID: <6216eba0707121706j76d87caav825f27ef358503d3@mail.gmail.com> On 7/11/07, Andre Roberge wrote: > > > It is a standard convention. Lots of tools are built on the > assumption that translatable strings are going to be enclosed in > _(...) > These tools extract the strings from programs, and put them in files > (.po) that are easily editable by human translators. > > This convention is *not* limited to Python. So, it's used as a marker to allow for easy language portability for internal text strings? I did not know that. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070712/d66c76a2/attachment.htm From john at fouhy.net Fri Jul 13 02:39:40 2007 From: john at fouhy.net (John Fouhy) Date: Fri, 13 Jul 2007 12:39:40 +1200 Subject: [Tutor] Here is newbie doc on how to implement generators In-Reply-To: <20070712232608.GA59300@cutter.rexx.com> References: <20070712232608.GA59300@cutter.rexx.com> Message-ID: <5e58f2e40707121739m6422fb0fib6ad685a9d1364b0@mail.gmail.com> On 13/07/07, Dave Kuhlman wrote: > And, I have a question -- If you look at the example of the > iterative (non-recursive) generator (the Doubler class), you will > see that it walks a list, not a tree. That's because I was *not* > able to figure out how to implement a non-recursive tree walk > generator. You should just be able to use a stack -- push the children onto a stack, then pop them off and walk through them. Here's an example, using tuples and lists as a basic tree data type: ####### treetest.py ######### TREE = (0, [(1, [(2, [(3, []), (4, []), (5, [(6, []), (7, []), (8, []), (9, []), ]), (10, [(11, []), (12, []), ]), ]), (13, [(14, []), (15, []), (16, [])]), (17, []), (18, []), ]), (19, []), (20, []), ]) def walkTree(tree): # stack to hold nodes as we walk through stack = [] stack.append(tree) while stack: value, children = stack.pop() for child in reversed(children): # reverse children to get the right order. stack.append(child) yield value if __name__ == '__main__': for value in walkTree(TREE): print value ####### treetest.py ######### HTH! -- John. From billburns at pennswoods.net Fri Jul 13 02:41:22 2007 From: billburns at pennswoods.net (Bill Burns) Date: Thu, 12 Jul 2007 20:41:22 -0400 Subject: [Tutor] making aaa.txt in notepad focused. In-Reply-To: <674d5ce60707111921y650ff0b4ka001425d8aa9a74@mail.gmail.com> References: <674d5ce60707111754t3661904at620d3389a88fcdc0@mail.gmail.com> <46958E19.6000002@pennswoods.net> <674d5ce60707111921y650ff0b4ka001425d8aa9a74@mail.gmail.com> Message-ID: <4696CA32.1080303@pennswoods.net> elis aeris wrote: > is it possible to do patial window title? Partial window title? ;-) Sure, have a look at this thread: http://aspn.activestate.com/ASPN/Mail/Message/python-win32/3012629 and take a look at pywinauto, as well: http://sourceforge.net/projects/pywinauto https://lists.sourceforge.net/lists/listinfo/pywinauto-users Bill From dos.fool at gmail.com Fri Jul 13 04:16:06 2007 From: dos.fool at gmail.com (max baseman) Date: Thu, 12 Jul 2007 20:16:06 -0600 Subject: [Tutor] curses Message-ID: <8D9227EB-A9EB-4813-AA6A-1B5AA6D7A73D@gmail.com> ok after reading a few tutorials i think i know enough to write my program here it is not commented yet though sorry: import curses from time import sleep scr=vurses.initscr() population=0 seconds=0 try: scr.nodelay(1) scr.leaveok(0) max_y, max_x = scr.getmaxyx() while scr.getch()== -1: sleep(1) seconds=seconds+1 population=population+2.5 scr.addstr(0,0,"seconds:",seconds") # i would like to get this bottom left but didn't know how scr.sddch(1,0,population) # here is ware i think I'm having problems also would like this to be centered scr.clear() scr.refresh() finaly: curses.endwin() but i get the error: traceback (most recent call last): file "population.py", line 15, in scr.addch(1,0,population) TypeError: argument 1 or 3 must be a ch or an int thank you From alan.gauld at btinternet.com Fri Jul 13 08:22:08 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jul 2007 07:22:08 +0100 Subject: [Tutor] curses References: <8D9227EB-A9EB-4813-AA6A-1B5AA6D7A73D@gmail.com> Message-ID: "max baseman" wrote > scr.sddch(1,0,population) # here is ware i think I'm having problems > also would like this to be centered Try this: scr.addchr(max_x/2,max_y/2, str(population)[0]) > traceback (most recent call last): > file "population.py", line 15, in > scr.addch(1,0,population) > TypeError: argument 1 or 3 must be a ch or an int You can pass the chr directly in which case the first arg is a char. Or you can provide a position as you are doing in which case the third arg must be a char. But populatio is an int so you need to convert it. see above. Alan G. From alan.gauld at btinternet.com Fri Jul 13 08:27:32 2007 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 13 Jul 2007 06:27:32 +0000 (GMT) Subject: [Tutor] Question Message-ID: <465674.2212.qm@web86104.mail.ukl.yahoo.com> Including the list... ----- Original Message ---- From: Que Prime To: Alan Gauld > Thank you Alan, but I'm still having difficulty. > I think you mean this but there must be something that I'm misunderstanding. > > print "Creating txt file" > tfile = open("25.txt", "w") > for i in range(25): > tfile.write i: > str (i)(\n) > tfile.close() Close, but you are still making it too difficult :-) Try tfile.write(str(i)+'\n') OR tfile.write( "d\n" % i) HTH, Alan G. On 7/12/07, Alan Gauld wrote: "Que Prime" wrote > Here is what I have so far but can't seem to get the loop and > write correct. I suspect you have used another language before and Python's for loop is foxing you. > print "Creating txt file" > tfile = open("25.txt", "w") > > for i in range(25): > x = int(1) You don;t need to convert to an int, i is already an int. But worse, you are here converting the number 1 to an int every time through the loop. I don't think thats what you want! range(25) will produce a list of numbers from 0 to 24. The for loop will set i to each number in turn. > tfile.writelines("x\n") And writelines expects a list of strings but you are giving it one string. You only need write() here. And of course you don't need x so you can just write the string version of i: str(i) plus a new line (\n) > x += 1 And you don't need this at all because the loop will automatically get the next number. > tfile.close() Try those changes, it should simplify things significantly. You might find a quick read through my loops and file handling topics useful too. -- 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/20070713/ca208b79/attachment-0001.htm From rabidpoobear at gmail.com Fri Jul 13 09:20:43 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 13 Jul 2007 02:20:43 -0500 Subject: [Tutor] Question In-Reply-To: <465674.2212.qm@web86104.mail.ukl.yahoo.com> References: <465674.2212.qm@web86104.mail.ukl.yahoo.com> Message-ID: <469727CB.5050100@gmail.com> > Try > > tfile.write(str(i)+'\n') > > OR > > tfile.write( "d\n" % i) Alan meant tfile.write("%d\n" % i) of course ;) -Luke From linden at bluewin.ch Fri Jul 13 11:05:38 2007 From: linden at bluewin.ch (linden at bluewin.ch) Date: Fri, 13 Jul 2007 09:05:38 +0000 (GMT) Subject: [Tutor] (no subject) Message-ID: <9145740.953001184317538070.JavaMail.webmail@ps13zhb.bluewin.ch> Hello, The attached code makes a number of colored rectangles visible in a canvas. Each rectangle should match with a pre-recorded sound file (in .wav or other format) containing the pronunciation of a letter of the alphabet in a given language. For instance, the first rectangle, in white, should correspond to the sound "a" (let's say, in Spanish) and it should be heard once the cursor is inside the rectangle. This can easily be done with the "PlaySound" command of "winsound". It is less obvious to find the proper binding event that will both play the sound "a" and show the corresponding sign (or letter) "a", preferably in a blinking mode, after a short time interval within the rectangle. Can someone suggest a possible solution to this problem? Moreover, as the complete set of rectangles should, in principle, represent all sounds of a given language, it also should be possible to generate any word in that language by moving the cursor from one rectangle to the other - just as a teacher would move a pointer to similar signs if they were shown on a blackboard. For instance, in order to produce the word "amigo" (if we stick to our Spanish example) she first would point at the white rectangle, then at another rectangle (not shown here) corresponding to the sound and the sign "m", then at a third one for "i", and so on until the whole word has been formed. The word itself (and, in fact, entire sentences) could be heard after having been pre-recorded in a lexical database. The user could then be asked to write the letter, word or phrase he/she has just heard in a text area below the set of rectangles. He/she could also be asked to repeat the same sounds (letter, word and sentences) in order to receive a corrected feed-back, provided some voice recognition and synthesis devices were available. The functionalities I am trying to implement for this purpose (aside from the more traditional ones of resetting, erasing text and quitting the program) are those that will enable the user to hear a sound (letter, word or whole sentence), write what he/she has heard in a text area, repeat it and wait for a corrected answer through a voice recognition and synthesis process. Can this be done in Python? Thank you in advance for any suggestion or answer, even partial, to my question. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: rectkinter.py Url: http://mail.python.org/pipermail/tutor/attachments/20070713/57f1a635/attachment.asc From rdm at rcblue.com Fri Jul 13 12:51:26 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 13 Jul 2007 03:51:26 -0700 Subject: [Tutor] Importing question Message-ID: <20070713105142.7E9741E4006@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070713/9a51e8fa/attachment.htm From janos.juhasz at VELUX.com Fri Jul 13 13:03:04 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Fri, 13 Jul 2007 13:03:04 +0200 Subject: [Tutor] Tutor Digest, Vol 41, Issue 47 In-Reply-To: Message-ID: Hi Linden, > Date: Fri, 13 Jul 2007 09:05:38 +0000 (GMT) > From: "linden at bluewin.ch" > Subject: [Tutor] (no subject) > To: tutor at python.org > Message-ID: > <9145740.953001184317538070.JavaMail.webmail at ps13zhb.bluewin.ch> > Content-Type: text/plain; charset="utf-8" > The functionalities I am trying to implement for this purpose > (aside from the more traditional ones of resetting, erasing text and > quitting the program) are those that will enable the user to hear a > sound (letter, word or whole sentence), write what he/she has heard > in a text area, repeat it and wait for a corrected answer through a > voice recognition and synthesis process. Can this be done in Python? > Thank you in advance for any suggestion or answer, even > partial, to my question. About speech recognition in python take a look on this link: http://win32com.goermezer.de/content/view/143/188/ And this is a working sample about the MS voice API http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114216 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070713/059de7b5/attachment.htm From tinoloc at gmail.com Fri Jul 13 14:52:43 2007 From: tinoloc at gmail.com (Tino Dai) Date: Fri, 13 Jul 2007 08:52:43 -0400 Subject: [Tutor] Question about code reviews In-Reply-To: <034501c7c496$3a502d60$f5fce004@JSLAPTOP> References: <20070712071434.5b04fef8@lavos> <034501c7c496$3a502d60$f5fce004@JSLAPTOP> Message-ID: On 7/12/07, Tiger12506 wrote: > > >> > >> > Do you know of any service or person that could do a code review > >> > for me? > >> > >> Perhaps if you were more specific about what you are looking for in the > >> review? If you merely want something to check your code for possible > >> errors and how well you stick to standards, then look into pylint or > >> pychecker. > >> > >> Actually, I'm looking for two things: > > > > I can do stuff with python, but a) is there a better way to do it? b) > What > > in python don't I know that I don't know. Does that make sense? > > > > -Tino > > I'm sure there are some people on the list who wouldn't mind reviewing > some > of your code and giving suggestions. Perhaps you would benefit by > providing > links? Sure, I'm working on getting two of my modules from a tightly coupled state to a loosely couple state. After that, I will post some of my code for the list to see. Thanks, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070713/4621ae7a/attachment.html From rfquerin at gmail.com Fri Jul 13 16:45:09 2007 From: rfquerin at gmail.com (Richard Querin) Date: Fri, 13 Jul 2007 10:45:09 -0400 Subject: [Tutor] eyeD3 module installation on XP Message-ID: <7d81675b0707130745h5017b76bgb43f50a23548c7f3@mail.gmail.com> I'm interested in writing a small app - or attempting to ;) - which will involve using the eyeD3 python module to process id3 tags of a given set of files. There are source downloads as well as downloads for various linux distros, which is fine. However I also might want to work on this in XP. I'm not sure how to install this on a Windows system. The install instructions in the source code download describe the normal ./configure, make, make install which I've used several times before when installing stuff on my home linux box, but I'm not sure these will work on my Xp system. Any pointers on how to go about installing this module? There's a file called 'setup.py.in' as well. Not sure what that does.. Are there any id3 tag processing modules other than eyeD3 that I should be looking at? Thanks. From brunson at brunson.com Fri Jul 13 16:56:49 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 13 Jul 2007 08:56:49 -0600 Subject: [Tutor] Importing question In-Reply-To: <20070713105142.7E9741E4006@bag.python.org> References: <20070713105142.7E9741E4006@bag.python.org> Message-ID: <469792B1.2090202@brunson.com> Dick Moores wrote: > At http://wiki.python.org/moin/SimplePrograms I found this code: > > ============================================ > import itertools > > def iter_primes(): > # an iterator of all numbers between 2 and +infinity > numbers = itertools.count(2) > > # generate primes forever > while True: > # get the first number from the iterator (always a prime) > prime = numbers.next() > yield prime > > # this code iteratively builds up a chain of > # filters...slightly tricky, but ponder it a bit > numbers = itertools.ifilter(prime.__rmod__, numbers) > > for p in iter_primes(): > if p > 1000: > break > print p > ==================================================== > > It works for me in Win XP, Python 2.5. > > However, in trying to dig into the code to understand it, I'm not able > to find itertools.py, even though itertools is found in the docs at < > http://www.python.org/doc/2.4/lib/module-itertools.html>. > A search of my Python25 directory doesn't turn up an itertools.py. > > So my question is, how does the first line of the code work? /Where > /is itertools? On my Fedora 7 system it is in /usr/lib/python2.5/lib-dynload/itertoolsmodule.so. Note the difference in naming for built in binary objects. > > Thanks, > > Dick Moores > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From brunson at brunson.com Fri Jul 13 16:59:55 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 13 Jul 2007 08:59:55 -0600 Subject: [Tutor] Here is newbie doc on how to implement generators In-Reply-To: <20070712232608.GA59300@cutter.rexx.com> References: <20070712232608.GA59300@cutter.rexx.com> Message-ID: <4697936B.1090604@brunson.com> Dave Kuhlman wrote: > I find iterators and generators fascinating. So, in order to try > to understand them better myself, I've written up some notes. I'm > hoping that these notes might help someone new to the generators > and iterators in Python. You can find it here: > > http://www.rexx.com/~dkuhlman/python_comments.html > http://www.rexx.com/~dkuhlman/python_comments.html#iterators-and-generators > > I'll appreciate any comments and suggestions that might help me > improve it. > > Please pass the above link along to anyone you think it might help. > > And, I have a question -- If you look at the example of the > iterative (non-recursive) generator (the Doubler class), you will > see that it walks a list, not a tree. That's because I was *not* > able to figure out how to implement a non-recursive tree walk > generator. > > I found examples showing non-recursive/iterative solutions to how > to walk a *binary* tree. Those examples are at: > > Lib/test/test_generator.py # in the Python distribution > http://en.wikipedia.org/wiki/Inorder_tree_walk > > But, I could not find a example that shows a non-recursive way to > walk a tree in which each node has an arbitrary number of children. > If you store your tree data in an adjacency list iteration becomes trivial. > Alas, I could not write that non-recursive tree walk. The recusive > walk is easy and clean. So, maybe I should not worry about the > non-recursive approach. Still, it really bothers me that I could > not do it. > > So, if you know where there are some examples, that would help me > improve my notes on iterators and generators, please give me a > link. > > Dave > > > > From rdm at rcblue.com Fri Jul 13 17:13:49 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 13 Jul 2007 08:13:49 -0700 Subject: [Tutor] Importing question In-Reply-To: <4697924C.8050705@brunson.com> References: <20070713105142.7E9741E4006@bag.python.org> <4697924C.8050705@brunson.com> Message-ID: <20070713151359.80E561E400C@bag.python.org> At 07:55 AM 7/13/2007, Eric Brunson wrote: >Dick Moores wrote: >>At http://wiki.python.org/moin/SimplePrograms I found this code: >> >>============================================ >>import itertools >> >>def iter_primes(): >> # an iterator of all numbers between 2 and +infinity >> numbers = itertools.count(2) >> >> # generate primes forever >> while True: >> # get the first number from the iterator (always a prime) >> prime = numbers.next() >> yield prime >> >> # this code iteratively builds up a chain of >> # filters...slightly tricky, but ponder it a bit >> numbers = itertools.ifilter(prime.__rmod__, numbers) >> >>for p in iter_primes(): >> if p > 1000: >> break >> print p >>==================================================== >> >>It works for me in Win XP, Python 2.5. >> >>However, in trying to dig into the code to understand it, I'm not >>able to find itertools.py, even though itertools is found in the >>docs at < http://www.python.org/doc/2.4/lib/module-itertools.html>. >>A search of my Python25 directory doesn't turn up an itertools.py. >> >>So my question is, how does the first line of the code work? /Where >>/is itertools? > >On my Fedora 7 system it is in >/usr/lib/python2.5/lib-dynload/itertoolsmodule.so. Hm. I have no lib-dyload, nor an itertoolsmodule. Dick >Note the difference in naming for built in binary modules. From rdm at rcblue.com Fri Jul 13 17:25:33 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 13 Jul 2007 08:25:33 -0700 Subject: [Tutor] class question Message-ID: <20070713152816.D09CB1E400A@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070713/bb563ca1/attachment.htm From Mike.Hansen at atmel.com Fri Jul 13 17:52:44 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Fri, 13 Jul 2007 09:52:44 -0600 Subject: [Tutor] curses In-Reply-To: <8D9227EB-A9EB-4813-AA6A-1B5AA6D7A73D@gmail.com> References: <8D9227EB-A9EB-4813-AA6A-1B5AA6D7A73D@gmail.com> Message-ID: <57B026980605A64F9B23484C5659E32E8F52E5@poccso.US.ad.atmel.com> > > ok after reading a few tutorials i think i know enough to write my > program > here it is > not commented yet though sorry: > For me, I need to put comments in while I'm coding or I'll never put them in. I _try_ to put in a doc string for every class and function/method. With Python being so readable, I don't put comments that explain what I'm doing, but I _try_ to put comments on why I'm doing something. I'm sure I could do better at commenting my code. "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live." Even if the code you are writing is supposed to be a one off that will never be used again(famous last words), it's best to keep up the practice of commenting your code. Mike From hunter92383 at gmail.com Fri Jul 13 18:10:13 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 14 Jul 2007 00:10:13 +0800 Subject: [Tutor] how do I input " as part of a string? Message-ID: <674d5ce60707130910u68561c19t5046cf27dcf8d842@mail.gmail.com> how do I input " as part of a string? f.write("my "car" has been a great one for me") I am trying to write the above lines into a file, including the " as part of a the single string how do I do that? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070714/387344c6/attachment.html From hunter92383 at gmail.com Fri Jul 13 18:22:35 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 14 Jul 2007 00:22:35 +0800 Subject: [Tutor] how do I input " as part of a string? In-Reply-To: <674d5ce60707130910u68561c19t5046cf27dcf8d842@mail.gmail.com> References: <674d5ce60707130910u68561c19t5046cf27dcf8d842@mail.gmail.com> Message-ID: <674d5ce60707130922l31560aaahee1b6b645d160481@mail.gmail.com> also, why does the interpreter restart when I run this? f = open("data.ini","w") f.write("yeahppe") f.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070714/eda125a4/attachment.html From tktucker at gmail.com Fri Jul 13 18:27:47 2007 From: tktucker at gmail.com (Tom Tucker) Date: Fri, 13 Jul 2007 12:27:47 -0400 Subject: [Tutor] how do I input " as part of a string? In-Reply-To: <674d5ce60707130922l31560aaahee1b6b645d160481@mail.gmail.com> References: <674d5ce60707130910u68561c19t5046cf27dcf8d842@mail.gmail.com> <674d5ce60707130922l31560aaahee1b6b645d160481@mail.gmail.com> Message-ID: <2a278ffe0707130927r3e3b4531g940f9f9bfd5242f1@mail.gmail.com> Try escaping the quotes. >>> f = open("data.ini","w") >>> f.write("my \"car\" has been a great one for me") >>> f.close() ~ >cat data.ini my "car" has been a great one for me On 7/13/07, elis aeris wrote: > > also, why does the interpreter restart when I run this? > > > > f = open("data.ini","w") > > f.write("yeahppe") > > f.close() > _______________________________________________ > 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/20070713/e7ee0ff3/attachment.htm From keridee at jayco.net Fri Jul 13 14:30:43 2007 From: keridee at jayco.net (Tiger12506) Date: Fri, 13 Jul 2007 12:30:43 -0000 Subject: [Tutor] (no subject) References: <9145740.953001184317538070.JavaMail.webmail@ps13zhb.bluewin.ch> Message-ID: <004401c7c549$a58352c0$39fde004@JSLAPTOP> If you just draw rectangles, you would have to track the mouse cursor and check to see if it's within the boundaries of a rectangle manually. I suggest using buttons. It will be easier to know when the mouse is over them. > Hello, > > The attached code makes a number of colored rectangles visible > in a canvas. Each rectangle should match with a pre-recorded sound > file (in .wav or other format) containing the pronunciation of a > letter of the alphabet in a given language. For instance, the first > rectangle, in white, should correspond to the sound "a" (let's say, > in Spanish) and it should be heard once the cursor is inside the > rectangle. This can easily be done with the "PlaySound" command of > "winsound". It is less obvious to find the proper binding event that > will both play the sound "a" and show the corresponding sign (or > letter) "a", preferably in a blinking mode, after a short time > interval within the rectangle. > > Can someone suggest a possible solution to this problem? > > Moreover, as the complete set of rectangles should, in > principle, represent all sounds of a given language, it also should > be possible to generate any word in that language by moving the > cursor from one rectangle to the other - just as a teacher would move > a pointer to similar signs if they were shown on a blackboard. For > instance, in order to produce the word "amigo" (if we stick to our > Spanish example) she first would point at the white rectangle, then > at another rectangle (not shown here) corresponding to the sound and > the sign "m", then at a third one for "i", and so on until the whole > word has been formed. > > The word itself (and, in fact, entire sentences) could be > heard after having been pre-recorded in a lexical database. The user > could then be asked to write the letter, word or phrase he/she has > just heard in a text area below the set of rectangles. He/she could > also be asked to repeat the same sounds (letter, word and sentences) > in order to receive a corrected feed-back, provided some voice > recognition and synthesis devices were available. > > The functionalities I am trying to implement for this purpose > (aside from the more traditional ones of resetting, erasing text and > quitting the program) are those that will enable the user to hear a > sound (letter, word or whole sentence), write what he/she has heard > in a text area, repeat it and wait for a corrected answer through a > voice recognition and synthesis process. Can this be done in Python? > > Thank you in advance for any suggestion or answer, even > partial, to my question. > > > > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From keridee at jayco.net Fri Jul 13 14:35:02 2007 From: keridee at jayco.net (Tiger12506) Date: Fri, 13 Jul 2007 12:35:02 -0000 Subject: [Tutor] class question References: <20070713152816.D09CB1E400A@bag.python.org> Message-ID: <005301c7c54a$3fcba170$39fde004@JSLAPTOP> > ======================================= > class BankAccount(object): > def __init__(self, initial_balance=0): > self.balance = initial_balance > def deposit(self, amount): > self.balance += amount > def withdraw(self, amount): > self.balance -= amount > def overdrawn(self): > return self.balance < 0 > my_account = BankAccount(15) > my_account.withdraw(5) > print my_account.balance > ========================================= > > This prints the expected "10". > > My question is, of what use can "overdrawn" be put? If I change the > withdrawal amount to 25, it prints the expected "-10", whether the class > contains the "overdrawn" function or not. > > Thanks, > > Dick Moores A very good question. Now I have one for you. What does your bank do when you try to withdraw money? First, it checks to see if you have the money in your account. If you do, it subtracts that out of your balance. Whoever wrote that code failed to do the check within the withdraw function. ======================================= class BankAccount(object): def __init__(self, initial_balance=0): self.balance = initial_balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): if self.overdrawn(): raise "Insufficient Funds Error" self.balance -= amount def overdrawn(self): return self.balance < 0 my_account = BankAccount(15) my_account.withdraw(5) print my_account.balance ========================================= JS From humbolt at comcast.net Fri Jul 13 18:35:12 2007 From: humbolt at comcast.net (Robert H. Haener IV) Date: Fri, 13 Jul 2007 12:35:12 -0400 Subject: [Tutor] how do I input " as part of a string? In-Reply-To: <2a278ffe0707130927r3e3b4531g940f9f9bfd5242f1@mail.gmail.com> References: <674d5ce60707130910u68561c19t5046cf27dcf8d842@mail.gmail.com> <674d5ce60707130922l31560aaahee1b6b645d160481@mail.gmail.com> <2a278ffe0707130927r3e3b4531g940f9f9bfd5242f1@mail.gmail.com> Message-ID: <4697A9C0.5070904@comcast.net> Tom Tucker wrote: > Try escaping the quotes. > >>>> f = open("data.ini","w") >>>> f.write("my \"car\" has been a great one for me") >>>> f.close() > > ~ >cat data.ini > my "car" has been a great one for me Tom beat me to posting that, see here for more information on escape sequences in Python: http://docs.python.org/ref/strings.html -Robert From hunter92383 at gmail.com Fri Jul 13 18:44:43 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 14 Jul 2007 00:44:43 +0800 Subject: [Tutor] interpreter restarts Message-ID: <674d5ce60707130944h4bc161e6k6942b119a1d71566@mail.gmail.com> why deos the interpreter restarts with this? f = open("data.ini","w") f.write("yeahppe") f.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070714/f356939d/attachment.html From hunter92383 at gmail.com Fri Jul 13 18:53:22 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 14 Jul 2007 00:53:22 +0800 Subject: [Tutor] how do I input " as part of a string? In-Reply-To: <4697A9C0.5070904@comcast.net> References: <674d5ce60707130910u68561c19t5046cf27dcf8d842@mail.gmail.com> <674d5ce60707130922l31560aaahee1b6b645d160481@mail.gmail.com> <2a278ffe0707130927r3e3b4531g940f9f9bfd5242f1@mail.gmail.com> <4697A9C0.5070904@comcast.net> Message-ID: <674d5ce60707130953x194fc93cve1d54290490a7ca2@mail.gmail.com> def winlist(title): f.write("winlist(\"title\")") how about if "title" is a variable? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070714/e42d75fb/attachment.htm From humbolt at comcast.net Fri Jul 13 19:40:55 2007 From: humbolt at comcast.net (Robert H. Haener IV) Date: Fri, 13 Jul 2007 13:40:55 -0400 Subject: [Tutor] how do I input " as part of a string? In-Reply-To: <674d5ce60707130953x194fc93cve1d54290490a7ca2@mail.gmail.com> References: <674d5ce60707130910u68561c19t5046cf27dcf8d842@mail.gmail.com> <674d5ce60707130922l31560aaahee1b6b645d160481@mail.gmail.com> <2a278ffe0707130927r3e3b4531g940f9f9bfd5242f1@mail.gmail.com> <4697A9C0.5070904@comcast.net> <674d5ce60707130953x194fc93cve1d54290490a7ca2@mail.gmail.com> Message-ID: <4697B927.8090409@comcast.net> elis aeris wrote: > def winlist(title): > f.write("winlist(\"title\")") > > > > how about if "title" is a variable? I assume, from your example, that you want to write the value of the variable 'title' enclosed in quotation marks. We once again use an escape sequence to output quotation marks, but this example also utilizes string formatting to convert the value of 'title' to a string and place it between the quotation marks in the output: def winlist(title): f.write("\"%s\"" % title) Please note that I have never used the write function before, but I just ran a quick test with the python interpreter and that appears to be valid code. For more information on string formatting, see here: http://docs.python.org/lib/typesseq-strings.html -Robert From hunter92383 at gmail.com Fri Jul 13 19:44:09 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 14 Jul 2007 01:44:09 +0800 Subject: [Tutor] how do I input " as part of a string? In-Reply-To: <4697B927.8090409@comcast.net> References: <674d5ce60707130910u68561c19t5046cf27dcf8d842@mail.gmail.com> <674d5ce60707130922l31560aaahee1b6b645d160481@mail.gmail.com> <2a278ffe0707130927r3e3b4531g940f9f9bfd5242f1@mail.gmail.com> <4697A9C0.5070904@comcast.net> <674d5ce60707130953x194fc93cve1d54290490a7ca2@mail.gmail.com> <4697B927.8090409@comcast.net> Message-ID: <674d5ce60707131044u767d1c84h29baf059ae24eb27@mail.gmail.com> this one doesn't work; did I misread your string? f = open("data.ini","w") title = "taitle" f.write('title is \"%title\"\n ') f.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070714/f1e39a81/attachment-0001.htm From humbolt at comcast.net Fri Jul 13 19:51:41 2007 From: humbolt at comcast.net (Robert H. Haener IV) Date: Fri, 13 Jul 2007 13:51:41 -0400 Subject: [Tutor] how do I input " as part of a string? In-Reply-To: <674d5ce60707131044u767d1c84h29baf059ae24eb27@mail.gmail.com> References: <674d5ce60707130910u68561c19t5046cf27dcf8d842@mail.gmail.com> <674d5ce60707130922l31560aaahee1b6b645d160481@mail.gmail.com> <2a278ffe0707130927r3e3b4531g940f9f9bfd5242f1@mail.gmail.com> <4697A9C0.5070904@comcast.net> <674d5ce60707130953x194fc93cve1d54290490a7ca2@mail.gmail.com> <4697B927.8090409@comcast.net> <674d5ce60707131044u767d1c84h29baf059ae24eb27@mail.gmail.com> Message-ID: <4697BBAD.6010302@comcast.net> elis aeris wrote: > this one doesn't work; did I misread your string? > > f = open("data.ini","w") > > title = "taitle" > > f.write('title is \"%title\"\n ') > > > f.close() Yes, you misread my string. The correct form of the above would be as follows: f = open("data.ini","w") title = "taitle" f.write('title is \"%s\"\n' % title) f.close() -Robert From queprime at gmail.com Fri Jul 13 20:04:17 2007 From: queprime at gmail.com (Que Prime) Date: Fri, 13 Jul 2007 11:04:17 -0700 Subject: [Tutor] String or Re Message-ID: <17285ccf0707131104i366106d0ud50a193d6c70c1a3@mail.gmail.com> I'm working on the following code to read a log file and output lines containing '10.52.10.10' but am unsure of whether to use a regular expression or string to achive this. Can someone please enlighten me? Thank you. infile = open("in.txt","r") outfile = open("out.txt", "w") for line in infile: if line #contains '10.52.10.10': outfile.write(line) ofile.close() wfile.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070713/d72c6fd6/attachment.htm From hunter92383 at gmail.com Fri Jul 13 20:20:41 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 14 Jul 2007 02:20:41 +0800 Subject: [Tutor] how do I input " as part of a string? In-Reply-To: <4697BBAD.6010302@comcast.net> References: <674d5ce60707130910u68561c19t5046cf27dcf8d842@mail.gmail.com> <674d5ce60707130922l31560aaahee1b6b645d160481@mail.gmail.com> <2a278ffe0707130927r3e3b4531g940f9f9bfd5242f1@mail.gmail.com> <4697A9C0.5070904@comcast.net> <674d5ce60707130953x194fc93cve1d54290490a7ca2@mail.gmail.com> <4697B927.8090409@comcast.net> <674d5ce60707131044u767d1c84h29baf059ae24eb27@mail.gmail.com> <4697BBAD.6010302@comcast.net> Message-ID: <674d5ce60707131120w4053edf5o65a6302eeed51b04@mail.gmail.com> def send(string): f.write("send( \"%s\"\n' % string )" ) f = open ("data.ini") send("string is very nice and all those things are pretty cool") this one is wrong, i guess i didn't ask you how to add things after this \"%s\"\n' % title) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070714/02cfcaa9/attachment.html From alan.gauld at btinternet.com Fri Jul 13 20:36:44 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jul 2007 19:36:44 +0100 Subject: [Tutor] Question References: <465674.2212.qm@web86104.mail.ukl.yahoo.com> <469727CB.5050100@gmail.com> Message-ID: "Luke Paireepinart" wrote in message news:469727CB.5050100 at gmail.com... > >> Try >> >> tfile.write(str(i)+'\n') >> >> OR >> >> tfile.write( "d\n" % i) > Alan meant tfile.write("%d\n" % i) of course ;) Which is why we should always include the list on replies! Thanks for catching that one Luke Alan G. From arunkumarpg at gmail.com Fri Jul 13 20:38:44 2007 From: arunkumarpg at gmail.com (Arun Kumar PG) Date: Sat, 14 Jul 2007 00:08:44 +0530 Subject: [Tutor] time.mktime(time.gmtime(time tuple from any timezone)) always will be the same ? Message-ID: <3cffff920707131138me4622b5u2a2a95ff1d1106c7@mail.gmail.com> Guys, May be a dumb question but I am a bit confused (may be coz working over 24 hours for the last couple days:)). so the question is: No matter which timezone I am in if i say time.gmtime(time.mktime(( datetime.date().timetuple()))) I will always get the same value. - right ? thx for answering this dumbo question but i need a break! -- Cheers, - A -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070714/7ac386b9/attachment.htm From carroll at tjc.com Fri Jul 13 20:39:29 2007 From: carroll at tjc.com (Terry Carroll) Date: Fri, 13 Jul 2007 11:39:29 -0700 (PDT) Subject: [Tutor] interpreter restarts In-Reply-To: <674d5ce60707130944h4bc161e6k6942b119a1d71566@mail.gmail.com> Message-ID: On Sat, 14 Jul 2007, elis aeris wrote: > why deos the interpreter restarts with this? > > f = open("data.ini","w") > > f.write("yeahppe") > > f.close() Not sure. It certainly doesn't, for me. >>> f = open("data.ini","w") >>> f.write("yeahppe") >>> f.close() >>> U:\>cat data.ini yeahppe From alan.gauld at btinternet.com Fri Jul 13 20:38:53 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jul 2007 19:38:53 +0100 Subject: [Tutor] interpreter restarts References: <674d5ce60707130944h4bc161e6k6942b119a1d71566@mail.gmail.com> Message-ID: "elis aeris" wrote > why deos the interpreter restarts with this? Which interpreter? Command prompt python? IDLE? PythonWin? PyCrust? And are you running them line by line manually or is the code in a file? > f = open("data.ini","w") > > f.write("yeahppe") > > f.close() Works OK for me in PyCrust and the vanilla interpreter. Alan G. From alan.gauld at btinternet.com Fri Jul 13 20:40:50 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jul 2007 19:40:50 +0100 Subject: [Tutor] String or Re References: <17285ccf0707131104i366106d0ud50a193d6c70c1a3@mail.gmail.com> Message-ID: "Que Prime" wrote > I'm working on the following code to read a log file and output > lines > containing '10.52.10.10' but am unsure of whether to use a regular > expression or string to achive this. I tend to only use regex for patterns. If its a fixed string the standard methods are usually easier and faster. > infile = open("in.txt","r") > outfile = open("out.txt", "w") > > for line in infile: > if line #contains '10.52.10.10': try using if '10.52.10.10' in line: > outfile.write(line) > > > ofile.close() > wfile.close() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From carroll at tjc.com Fri Jul 13 20:45:32 2007 From: carroll at tjc.com (Terry Carroll) Date: Fri, 13 Jul 2007 11:45:32 -0700 (PDT) Subject: [Tutor] String or Re In-Reply-To: <17285ccf0707131104i366106d0ud50a193d6c70c1a3@mail.gmail.com> Message-ID: On Fri, 13 Jul 2007, Que Prime wrote: > I'm working on the following code to read a log file and output lines > containing '10.52.10.10' but am unsure of whether to use a regular > expression or string to achive this. > for line in infile: > if line #contains '10.52.10.10': > outfile.write(line) I wouldn't go with regular expressions here. Try this: for line in infile: if line.find("10.52.10.11") != -1: outfile.write(line) From dkuhlman at rexx.com Fri Jul 13 20:46:57 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 13 Jul 2007 11:46:57 -0700 Subject: [Tutor] Here is newbie doc on how to implement generators In-Reply-To: <5e58f2e40707121739m6422fb0fib6ad685a9d1364b0@mail.gmail.com> References: <20070712232608.GA59300@cutter.rexx.com> <5e58f2e40707121739m6422fb0fib6ad685a9d1364b0@mail.gmail.com> Message-ID: <20070713184657.GA22487@cutter.rexx.com> On Fri, Jul 13, 2007 at 12:39:40PM +1200, John Fouhy wrote: > On 13/07/07, Dave Kuhlman wrote: > > And, I have a question -- If you look at the example of the > > iterative (non-recursive) generator (the Doubler class), you will > > see that it walks a list, not a tree. That's because I was *not* > > able to figure out how to implement a non-recursive tree walk > > generator. > > You should just be able to use a stack -- push the children onto a > stack, then pop them off and walk through them. > > Here's an example, using tuples and lists as a basic tree data type: > > ####### treetest.py ######### > > TREE = (0, [(1, [(2, [(3, []), > (4, []), > (5, [(6, []), > (7, []), > (8, []), > (9, []), > ]), > (10, [(11, []), > (12, []), > ]), > ]), > (13, [(14, []), > (15, []), > (16, [])]), > (17, []), > (18, []), > ]), > (19, []), > (20, []), > ]) > > def walkTree(tree): > # stack to hold nodes as we walk through > stack = [] > stack.append(tree) > > while stack: > value, children = stack.pop() > for child in reversed(children): # reverse children to get > the right order. > stack.append(child) > yield value > > if __name__ == '__main__': > for value in walkTree(TREE): > print value > > ####### treetest.py ######### John - That is so cool. I can't believe that it is so simple and elegant. I thought that a stack was involved in the solution, but I could not figure out how to use it. Thanks. And, to extend this a bit more, here are two slightly modified versions of your solution that implement classes whose instances are iterators. # # Version #1 -- This version has a next() method, as required by # the iterator protocol. # class Node(object): def __init__(self, value='', children=None): self.value = chr(value + 97) * 3 if children is None: children = [] else: self.children = children def walk_tree(self): # stack to hold nodes as we walk through stack = [] stack.append(self) while stack: node = stack.pop() # reverse children to get the right order. stack.extend(reversed(node.children)) yield node def __iter__(self): self.iterator = self.walk_tree() return self def next(self): return self.iterator.next() # # Version #2 -- This version does not have a next() method, but # the iterators returned by __iter__() do have a next(). # class Node(object): def __init__(self, value='', children=None): self.value = chr(value + 97) * 3 if children is None: children = [] else: self.children = children def walk_tree(self): # stack to hold nodes as we walk through stack = [] stack.append(self) while stack: node = stack.pop() # reverse children to get the right order. stack.extend(reversed(node.children)) yield node def __iter__(self): return self.walk_tree() # # Create some data. # TREE = Node(0, [Node(1, [Node(2, [Node(3, []), Node(4, []), Node(5, [Node(6, []), Node(7, []), Node(8, []), Node(9, []), ]), Node(10, [Node(11, []), Node(12, []), ]), ]), Node(13, [Node(14, []), Node(15, []), Node(16, [])]), Node(17, []), Node(18, []), ]), Node(19, []), Node(20, []), ]) # # Here is a function to exercise the iterator. # def test(): for node in TREE: print 'value: %s' % (node.value, ) Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From hunter92383 at gmail.com Fri Jul 13 20:46:59 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 14 Jul 2007 02:46:59 +0800 Subject: [Tutor] interpreter restarts In-Reply-To: References: <674d5ce60707130944h4bc161e6k6942b119a1d71566@mail.gmail.com> Message-ID: <674d5ce60707131146g85e3d99sd9d6bb6435652709@mail.gmail.com> IDLE On 7/14/07, Alan Gauld wrote: > > > "elis aeris" wrote > > > why deos the interpreter restarts with this? > > Which interpreter? > Command prompt python? IDLE? PythonWin? > PyCrust? > > And are you running them line by line manually > or is the code in a file? > > > f = open("data.ini","w") > > > > f.write("yeahppe") > > > > f.close() > > Works OK for me in PyCrust and the vanilla interpreter. > > 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/20070714/42c7f1c9/attachment.html From hunter92383 at gmail.com Fri Jul 13 20:47:14 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 14 Jul 2007 02:47:14 +0800 Subject: [Tutor] interpreter restarts In-Reply-To: <674d5ce60707131146g85e3d99sd9d6bb6435652709@mail.gmail.com> References: <674d5ce60707130944h4bc161e6k6942b119a1d71566@mail.gmail.com> <674d5ce60707131146g85e3d99sd9d6bb6435652709@mail.gmail.com> Message-ID: <674d5ce60707131147o3e2a78e1xb33fcfa4dea3dc30@mail.gmail.com> from a file, i click run from the IDLE interpreter On 7/14/07, elis aeris wrote: > > IDLE > > On 7/14/07, Alan Gauld wrote: > > > > > > "elis aeris" wrote > > > > > why deos the interpreter restarts with this? > > > > Which interpreter? > > Command prompt python? IDLE? PythonWin? > > PyCrust? > > > > And are you running them line by line manually > > or is the code in a file? > > > > > f = open("data.ini","w") > > > > > > f.write("yeahppe") > > > > > > f.close () > > > > Works OK for me in PyCrust and the vanilla interpreter. > > > > 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/20070714/c1e810a7/attachment.htm From carroll at tjc.com Fri Jul 13 20:58:18 2007 From: carroll at tjc.com (Terry Carroll) Date: Fri, 13 Jul 2007 11:58:18 -0700 (PDT) Subject: [Tutor] String or Re In-Reply-To: Message-ID: On Fri, 13 Jul 2007, Terry Carroll wrote: > Try this: > > for line in infile: > if line.find("10.52.10.11") != -1: > outfile.write(line) No, don't. Alan's solution is much nicer. From rdm at rcblue.com Fri Jul 13 21:04:28 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 13 Jul 2007 12:04:28 -0700 Subject: [Tutor] class question In-Reply-To: <005301c7c54a$3fcba170$39fde004@JSLAPTOP> References: <20070713152816.D09CB1E400A@bag.python.org> <005301c7c54a$3fcba170$39fde004@JSLAPTOP> Message-ID: <20070713190435.A746E1E400A@bag.python.org> At 05:35 AM 7/13/2007, Tiger12506 wrote: > > ======================================= > > class BankAccount(object): > > def __init__(self, initial_balance=0): > > self.balance = initial_balance > > def deposit(self, amount): > > self.balance += amount > > def withdraw(self, amount): > > self.balance -= amount > > def overdrawn(self): > > return self.balance < 0 > > my_account = BankAccount(15) > > my_account.withdraw(5) > > print my_account.balance > > ========================================= > > > > This prints the expected "10". > > > > My question is, of what use can "overdrawn" be put? If I change the > > withdrawal amount to 25, it prints the expected "-10", whether the class > > contains the "overdrawn" function or not. > > > > Thanks, > > > > Dick Moores > >A very good question. Now I have one for you. What does your bank do when >you try to withdraw money? First, it checks to see if you have the money in >your account. If you do, it subtracts that out of your balance. Whoever >wrote that code failed to do the check within the withdraw function. > >======================================= >class BankAccount(object): > def __init__(self, initial_balance=0): > self.balance = initial_balance > def deposit(self, amount): > self.balance += amount > def withdraw(self, amount): > if self.overdrawn(): > raise "Insufficient Funds Error" > self.balance -= amount > def overdrawn(self): > return self.balance < 0 >my_account = BankAccount(15) >my_account.withdraw(5) >print my_account.balance >========================================= But when I run that with a withdrawal of 25, it still prints only "-10". How have you involved the "overdrawn" function? Dick From christopher.henk at gm.com Fri Jul 13 21:35:37 2007 From: christopher.henk at gm.com (christopher.henk at gm.com) Date: Fri, 13 Jul 2007 15:35:37 -0400 Subject: [Tutor] class question In-Reply-To: <20070713190435.A746E1E400A@bag.python.org> Message-ID: However if you try to withdraw any money after you took out the $25 it would raise the error. The overdrawn function checks if you are in the negatives. Since the balance is checked before the money is taken out, there is no error when you take out the $25. If you wan the error to be raised whenever you go negative simply switch the withdrawal and the function call in withdraw def withdraw(self, amount): self.balance -= amount if self.overdrawn(): raise "Insufficient Funds Error" and if you don't want the money taken out if there is insufficient funds, just add the withdrawn amount back: def withdraw(self, amount): self.balance -= amount if self.overdrawn(): self.balance += amount raise "Insufficient Funds Error, no money withdrawn" Chris Henk Allison Transmission phone: 317.242.2569 fax: 317.242.3469 e-mail: christopher.henk at gm.com Dick Moores Sent by: tutor-bounces at python.org 07/13/2007 03:04 PM To Tiger12506 , cc Subject Re: [Tutor] class question At 05:35 AM 7/13/2007, Tiger12506 wrote: > > ======================================= > > class BankAccount(object): > > def __init__(self, initial_balance=0): > > self.balance = initial_balance > > def deposit(self, amount): > > self.balance += amount > > def withdraw(self, amount): > > self.balance -= amount > > def overdrawn(self): > > return self.balance < 0 > > my_account = BankAccount(15) > > my_account.withdraw(5) > > print my_account.balance > > ========================================= > > > > This prints the expected "10". > > > > My question is, of what use can "overdrawn" be put? If I change the > > withdrawal amount to 25, it prints the expected "-10", whether the class > > contains the "overdrawn" function or not. > > > > Thanks, > > > > Dick Moores > >A very good question. Now I have one for you. What does your bank do when >you try to withdraw money? First, it checks to see if you have the money in >your account. If you do, it subtracts that out of your balance. Whoever >wrote that code failed to do the check within the withdraw function. > >======================================= >class BankAccount(object): > def __init__(self, initial_balance=0): > self.balance = initial_balance > def deposit(self, amount): > self.balance += amount > def withdraw(self, amount): > if self.overdrawn(): > raise "Insufficient Funds Error" > self.balance -= amount > def overdrawn(self): > return self.balance < 0 >my_account = BankAccount(15) >my_account.withdraw(5) >print my_account.balance >========================================= But when I run that with a withdrawal of 25, it still prints only "-10". How have you involved the "overdrawn" function? Dick _______________________________________________ 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/20070713/9f5b5455/attachment.html From challman at gmail.com Fri Jul 13 21:50:49 2007 From: challman at gmail.com (Chris Hallman) Date: Fri, 13 Jul 2007 15:50:49 -0400 Subject: [Tutor] Python on Windows with SSH for Cisco devices Message-ID: <9f68812f0707131250n2308ab1ai28d2c6bdf5f92259@mail.gmail.com> Has anyone successfully used Python on Windows with SSH connections to Cisco devices? I'm referring to using a Python module (Paramiko, pyssh though not actively developed, Twisted.conch, etc.) and not shelling out via Pexpect (doesn't work on Windows) or Plink. I need to connect to hundreds of Cisco routers/switches so that I can run numerous commands to gather data. Here is a snippet of my Telnet commands that I need working via SSH: self.tn.write("wr\n") (index, match, read) = self.tn.expect(["OK"], 15) if not match: self.tn.write("yes\n") time.sleep(random.uniform(0,2)) self.tn.write("copy tf runn\n") self.tn.read_until("host []?", 7) time.sleep(random.uniform(0,2)) self.tn.write("192.168.136.51\n") self.tn.read_until("filename []?", 7) time.sleep(random.uniform(0,2)) self.tn.write(self.filename +"\n") time.sleep(random.uniform(0,2)) self.tn.read_until("[running-config]?", 7) time.sleep(random.uniform(0,2)) self.tn.write("\n") I've been able to get the following to work, but the TCP connection closes after each command: import paramiko client = paramiko.SSHClient() # ignore host keys for the test client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy()) client.connect('host####', 22, 'user####', 'passw####') (stdin, stdout, stderr) = client.exec_command('sh ver | i IOS') print stdout.read() I've read that I can use a dummy channel (not sure the difference between a channel and a TCP connection) to keep the connection active. I've read the docs and I've searched the net, but I can't seem to find a good example that helps. Programming isn't my day job so I'm not that great at it. Any help would be great. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070713/e8f32cfb/attachment-0001.html From rdm at rcblue.com Fri Jul 13 22:03:54 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 13 Jul 2007 13:03:54 -0700 Subject: [Tutor] class question In-Reply-To: References: <20070713190435.A746E1E400A@bag.python.org> Message-ID: <20070713200405.9F0F71E400A@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070713/0c30a00c/attachment.htm From andreas at kostyrka.org Fri Jul 13 22:07:20 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 13 Jul 2007 22:07:20 +0200 Subject: [Tutor] Python on Windows with SSH for Cisco devices Message-ID: <3W1s3KklPZrj.BfscclNH@heaven.kostyrka.org> I haven't done anything like that as I don't use Windows for anything serious. But I see basically no problem, as at least some of the packages you've mentioned are portable to marginal OSes like Windows *g* So my tip would be, start implementing, I personally would probably stick to conch for many concurrent sessions, and come back (or use the twisted list) when you encounter troubles. Andreas -- Urspr?ngl. Mitteil. -- Betreff: [Tutor] Python on Windows with SSH for Cisco devices Von: "Chris Hallman" Datum: 13.07.2007 19:51 Has anyone successfully used Python on Windows with SSH connections to Cisco devices? I'm referring to using a Python module (Paramiko, pyssh though not actively developed, Twisted.conch, etc.) and not shelling out via Pexpect (doesn't work on Windows) or Plink. I need to connect to hundreds of Cisco routers/switches so that I can run numerous commands to gather data. Here is a snippet of my Telnet commands that I need working via SSH: self.tn.write("wr\n") (index, match, read) = self.tn.expect(["OK"], 15) if not match: self.tn.write("yes\n") time.sleep(random.uniform(0,2)) self.tn.write("copy tf runn\n") self.tn.read_until("host []?", 7) time.sleep(random.uniform(0,2)) self.tn.write("192.168.136.51\n") self.tn.read_until("filename []?", 7) time.sleep(random.uniform(0,2)) self.tn.write(self.filename +"\n") time.sleep(random.uniform(0,2)) self.tn.read_until("[running-config]?", 7) time.sleep(random.uniform(0,2)) self.tn.write("\n") I've been able to get the following to work, but the TCP connection closes after each command: import paramiko client = paramiko.SSHClient() # ignore host keys for the test client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy()) client.connect('host####', 22, 'user####', 'passw####') (stdin, stdout, stderr) = client.exec_command('sh ver | i IOS') print stdout.read() I've read that I can use a dummy channel (not sure the difference between a channel and a TCP connection) to keep the connection active. I've read the docs and I've searched the net, but I can't seem to find a good example that helps. Programming isn't my day job so I'm not that great at it. Any help would be great. Thanks! _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Fri Jul 13 23:50:35 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jul 2007 22:50:35 +0100 Subject: [Tutor] Importing question References: <20070713105142.7E9741E4006@bag.python.org> Message-ID: "Dick Moores" wrote in > import itertools > > def iter_primes(): > # an iterator of all numbers between 2 and +infinity > numbers = itertools.count(2) > ... > It works for me in Win XP, Python 2.5. > > However, in trying to dig into the code to understand it, > I'm not able to find itertools.py, Thats because its a compiled C module not implemented in Python. You probably won't find a sys.py either. If you do >>> print itertools You'll see its actually built-in. So you need to look at the C source to see how it is written! Alan G From alan.gauld at btinternet.com Sat Jul 14 00:00:00 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jul 2007 23:00:00 +0100 Subject: [Tutor] how do I input " as part of a string? References: <674d5ce60707130910u68561c19t5046cf27dcf8d842@mail.gmail.com> Message-ID: "elis aeris" wrote > how do I input " as part of a string? > > f.write("my "car" has been a great one for me") > > I am trying to write the above lines into a file, including > the " as part of a the single string As you say in the subject the qurstion is how to get a quote into a string. The fact you are writing to a file is irrelevant so lets get that out of the way and look at how you print a string with a quote in it. I actually mention one approach in the Simple Sequences topic of my tutorial - the very first hands on topic. You might find it helpful to read that through. But basically you can include one kind of quote inside another, like this: >>> s = 'This has a " inside' >>> s2 = "But this has a ' in it" >>> s3 = '''And this has both " and ' characters''' >>> s4 = """and so does this: ' ", see?""" And I can print all of them: >>> for x in s,s2,s3,s4: print x Another way to include a quote is to "escape" it, that is precede it with a \ character, like this: >>> s5 = "This has \" in it despite having \" as its quote sign" HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From keridee at jayco.net Fri Jul 13 20:07:01 2007 From: keridee at jayco.net (Tiger12506) Date: Fri, 13 Jul 2007 18:07:01 -0000 Subject: [Tutor] interpreter restarts References: <674d5ce60707130944h4bc161e6k6942b119a1d71566@mail.gmail.com><674d5ce60707131146g85e3d99sd9d6bb6435652709@mail.gmail.com> <674d5ce60707131147o3e2a78e1xb33fcfa4dea3dc30@mail.gmail.com> Message-ID: <011101c7c578$a0a53f00$4cfce004@JSLAPTOP> Interesting... This is something very strange. I've been able to reproduce the phenomenon that elis described. Here's how to reproduce the error. 1) Open a new edit window in IDLE 2) type in code - do NOT save 3) Select Run Module from the Run menu 4) Save file when prompted When the IDLE shell opens, it will show RESTART as if you were to have actually restarted the shell. If you run an already saved file, the shell does not restart. I am curious why this occurs also. JS From alan.gauld at btinternet.com Sat Jul 14 00:04:29 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jul 2007 23:04:29 +0100 Subject: [Tutor] how do I input " as part of a string? References: <674d5ce60707130910u68561c19t5046cf27dcf8d842@mail.gmail.com><674d5ce60707130922l31560aaahee1b6b645d160481@mail.gmail.com><2a278ffe0707130927r3e3b4531g940f9f9bfd5242f1@mail.gmail.com><4697A9C0.5070904@comcast.net><674d5ce60707130953x194fc93cve1d54290490a7ca2@mail.gmail.com><4697B927.8090409@comcast.net><674d5ce60707131044u767d1c84h29baf059ae24eb27@mail.gmail.com><4697BBAD.6010302@comcast.net> <674d5ce60707131120w4053edf5o65a6302eeed51b04@mail.gmail.com> Message-ID: "elis aeris" wrote > def send(string): > f.write("send( \"%s\"\n' % string )" ) > > f = open ("data.ini") > > send("string is very nice and all those things are pretty cool") > > this one is wrong, i guess i didn't ask you how to add things after > this Whats "wrong" about it. It should write out send( \"string is very nice and all those things are pretty cool\"\n' ) > \"%s\"\n' % title) Does this have any relevance or is it just a curt n paste error? -- 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 Jul 14 00:12:05 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jul 2007 23:12:05 +0100 Subject: [Tutor] class question References: <20070713190435.A746E1E400A@bag.python.org> <20070713200405.9F0F71E400A@bag.python.org> Message-ID: "Dick Moores" wrote > Thanks. You've clarified it for me completely. > > Your second way seems to make more sense. > And instead of raising the error, why not just print it: Because that would make the class much less reusable. It would be limited to applications using stdout. A GUI banking program would be unable to use the BankAccount class. But by raising an exception the user gets to decide what to do, either pop up a dialog, print a message or send an email to the banks client. Its a primary design goal for reuse to de-couple business logic - like the bank account - from the user interface. There is a bit more discussion around this in my Case Study topic where I convert it from command line to GUI and again in my InterProcess Comms topic where I turn the AddressBook into a client-server app. 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 Jul 14 00:17:51 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jul 2007 23:17:51 +0100 Subject: [Tutor] interpreter restarts References: <674d5ce60707130944h4bc161e6k6942b119a1d71566@mail.gmail.com><674d5ce60707131146g85e3d99sd9d6bb6435652709@mail.gmail.com> <674d5ce60707131147o3e2a78e1xb33fcfa4dea3dc30@mail.gmail.com> Message-ID: "elis aeris" wrote > from a file, i click run from the IDLE interpreter OK, Thats just normal IDLE behaviour. The Python shell restarts so your module doesn't pick up any junk lying around from the previous run. Alan G. From alan.gauld at btinternet.com Sat Jul 14 00:21:35 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jul 2007 23:21:35 +0100 Subject: [Tutor] time.mktime(time.gmtime(time tuple from any timezone))always will be the same ? References: <3cffff920707131138me4622b5u2a2a95ff1d1106c7@mail.gmail.com> Message-ID: "Arun Kumar PG" wrote > May be a dumb question but I am a bit confused (may be coz working > over 24 > hours for the last couple days:)). so the question is: > > No matter which timezone I am in if i say > time.gmtime(time.mktime(( > datetime.date().timetuple()))) I will always get the same value. - > right ? Hopefully. There is a slight chance that odd things will happen around the international dateline - Timezones are funny things and devilishly hard to get exactly right in all situations, but by and large gmtime will allways return the UTC (aka GMT) time Alan G From alan.gauld at btinternet.com Sat Jul 14 00:26:15 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Jul 2007 23:26:15 +0100 Subject: [Tutor] interpreter restarts References: <674d5ce60707130944h4bc161e6k6942b119a1d71566@mail.gmail.com><674d5ce60707131146g85e3d99sd9d6bb6435652709@mail.gmail.com><674d5ce60707131147o3e2a78e1xb33fcfa4dea3dc30@mail.gmail.com> <011101c7c578$a0a53f00$4cfce004@JSLAPTOP> Message-ID: "Tiger12506" wrote > If you run an already saved file, the shell does not restart. > I am curious why this occurs also. It does it for me, I get a restart banner every time I run a file, saved or not. Alan G From alan.gauld at btinternet.com Sat Jul 14 00:36:14 2007 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 13 Jul 2007 22:36:14 +0000 (GMT) Subject: [Tutor] Fw: curses Message-ID: <333026.47642.qm@web86105.mail.ukl.yahoo.com> Returning to the list.... ----- Forwarded Message ---- > From: max baseman > To: Alan Gauld > hmm but now i get a error on the same line scr.addch(max_x/2, max_y/ > 2, str(population)[0]) > _curses.error addch() returned ERR Thats because you are writing outside the screen boundaries. My mistake, the order of the params is y,x not x,y so it should have been: scr.addchr(max_y/2,max_x/2, str(population)[0]) Apologies, Alan G. From humbolt at comcast.net Sat Jul 14 01:07:23 2007 From: humbolt at comcast.net (Robert H. Haener IV) Date: Fri, 13 Jul 2007 19:07:23 -0400 Subject: [Tutor] how do I input " as part of a string? In-Reply-To: <674d5ce60707131120w4053edf5o65a6302eeed51b04@mail.gmail.com> References: <674d5ce60707130910u68561c19t5046cf27dcf8d842@mail.gmail.com> <674d5ce60707130922l31560aaahee1b6b645d160481@mail.gmail.com> <2a278ffe0707130927r3e3b4531g940f9f9bfd5242f1@mail.gmail.com> <4697A9C0.5070904@comcast.net> <674d5ce60707130953x194fc93cve1d54290490a7ca2@mail.gmail.com> <4697B927.8090409@comcast.net> <674d5ce60707131044u767d1c84h29baf059ae24eb27@mail.gmail.com> <4697BBAD.6010302@comcast.net> <674d5ce60707131120w4053edf5o65a6302eeed51b04@mail.gmail.com> Message-ID: <469805AB.5040401@comcast.net> elis aeris wrote: > def send(string): > f.write("send( \"%s\"\n' % string )" ) > > > > > f = open ("data.ini") > > send("string is very nice and all those things are pretty cool") > > > > > > this one is wrong, i guess i didn't ask you how to add things after this > > > \"%s\"\n' % title) It appears that you have a fundamental misunderstanding of how to define a function, your code calls the function in the definition of the function: def send(string): f.write("send(...)") Do you see how the function depends on itself in order to define itself? This is the same mistake you made in a earlier message (the one you sent a little over 6 hours ago), in my response to that message I corrected the mistake but forgot to point it out. Here is the corrected version of your example, note that I have changed the opening quote of f.write() to a singe quote in order to avoid confusion with regard to the escaped double quotes: def send(string): f.write('\"%s\"\n' % string) f = open("data.ini","w") send("string is very nice and all those things are pretty cool") -Robert From keridee at jayco.net Fri Jul 13 21:09:04 2007 From: keridee at jayco.net (Tiger12506) Date: Fri, 13 Jul 2007 19:09:04 -0000 Subject: [Tutor] class question References: <20070713190435.A746E1E400A@bag.python.org> <20070713205329.B3D8A3A1975@mognet2.onlyinternet.net> Message-ID: <015901c7c581$4b4c8eb0$4cfce004@JSLAPTOP> > Your second way seems to make more sense. And instead of raising the > error, why not just print it: There is a very good reason for this and it's important that you understand it to write good code. If you use a print statement, you break the benefit of encapsulation. If you were to use that class in a GUI application, for example, you would never know if the account had become overdrawn. Only by using an exception could you use that class effectively in both circumstances, and in the same way! a = BankAccount() try: a.withdraw(50) except: notify_error() Where notify error depends on how you want to communicate that information to the end-user. (messagebox, display, stdout, stderr, file, etc) JS From rdm at rcblue.com Sat Jul 14 01:11:28 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 13 Jul 2007 16:11:28 -0700 Subject: [Tutor] class question In-Reply-To: References: <20070713190435.A746E1E400A@bag.python.org> <20070713200405.9F0F71E400A@bag.python.org> Message-ID: <20070713231139.8B2621E4013@bag.python.org> At 03:12 PM 7/13/2007, Alan Gauld wrote: >"Dick Moores" wrote > > > Thanks. You've clarified it for me completely. > > > > Your second way seems to make more sense. > > And instead of raising the error, why not just print it: > >Because that would make the class much less reusable. >It would be limited to applications using stdout. A GUI >banking program would be unable to use the BankAccount >class. But by raising an exception the user gets to decide >what to do, either pop up a dialog, print a message or send >an email to the banks client. > >Its a primary design goal for reuse to de-couple business >logic - like the bank account - from the user interface. > >There is a bit more discussion around this in my >Case Study topic where I convert it from command >line to GUI and again in my InterProcess Comms topic >where I turn the AddressBook into a client-server app. Thanks, Alan. I'll check it out. Dick From keridee at jayco.net Fri Jul 13 21:15:05 2007 From: keridee at jayco.net (Tiger12506) Date: Fri, 13 Jul 2007 19:15:05 -0000 Subject: [Tutor] class question References: <20070713190435.A746E1E400A@bag.python.org><20070713205329.B3D8A3A1975@mognet2.onlyinternet.net> <015901c7c581$4b4c8eb0$4cfce004@JSLAPTOP> Message-ID: <001901c7c582$227594e0$4cfce004@JSLAPTOP> Ooops, didn't see Alan's post before I sent this... JS >> Your second way seems to make more sense. And instead of raising the >> error, why not just print it: > > There is a very good reason for this and it's important that you > understand > it to write good code. If you use a print statement, you break the benefit > of encapsulation. > > If you were to use that class in a GUI application, for example, you would > never know if the account had become overdrawn. Only by using an exception > could you use that class effectively in both circumstances, and in the > same > way! > > a = BankAccount() > try: > a.withdraw(50) > except: > notify_error() > > Where notify error depends on how you want to communicate that information > to the end-user. (messagebox, display, stdout, stderr, file, etc) > > JS From rdm at rcblue.com Sat Jul 14 01:18:59 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 13 Jul 2007 16:18:59 -0700 Subject: [Tutor] Importing question In-Reply-To: References: <20070713105142.7E9741E4006@bag.python.org> Message-ID: <20070713231914.511AB1E400B@bag.python.org> At 02:50 PM 7/13/2007, Alan Gauld wrote: >"Dick Moores" wrote in > > > > import itertools > > > > def iter_primes(): > > # an iterator of all numbers between 2 and +infinity > > numbers = itertools.count(2) > > ... > > > It works for me in Win XP, Python 2.5. > > > > However, in trying to dig into the code to understand it, > > I'm not able to find itertools.py, > >Thats because its a compiled C module not implemented >in Python. You probably won't find a sys.py either. > >If you do > > >>> print itertools > > >You'll see its actually built-in. > >So you need to look at the C source to see how it is written! Ah. and >>> import math >>> print math Thanks, Alan! Dick From encorejane at gmail.com Thu Jul 12 23:52:07 2007 From: encorejane at gmail.com (encore jane) Date: Thu, 12 Jul 2007 14:52:07 -0700 Subject: [Tutor] Platform-independent Excel reader Message-ID: <000301c7c4ce$e4e13520$5301a8c0@MD1918> Hi, Does anyone know about a good native Excel file reader that is platform independent? Thanks, AJ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070712/de67359f/attachment.htm From Darren at newspyn.com Fri Jul 13 19:13:14 2007 From: Darren at newspyn.com (Darren Williams) Date: Fri, 13 Jul 2007 13:13:14 -0400 Subject: [Tutor] CGI error Message-ID: <001201c7c571$19a839a0$7801a8c0@YOURFD474B1D4C> Hi all I have a Windows hosting account with lunarpages.com and am having a bit of trouble with CGI. I have enabled both CGI and Python in the control panel and made sure the permissions for all my CGI scripts are set to both readable and executable for all users but I keep getting the same 'The specified CGI application misbehaved by not returning a complete set of HTTP headers' error. The script that i'm trying to execute (example_7.1.py) - Code: [Download] 1.. #!/usr/bin/python 2.. 3.. # Import the CGI module 4.. import cgi 5.. 6.. # Required header that tells the browser how to render the HTML. 7.. print "Content-Type: text/html\n\n" 8.. 9.. # Define function to generate HTML form. 10.. def generate_form(): 11.. print "\n" 12.. print "\n" 13.. print "\tInfo Form\n" 14.. print "\n" 15.. print "\n" 16.. print "\t

Please, enter your name and age.

\n" 17.. print "\t\n" 18.. print "\t\t\n" 20.. print "\t\t\n" 22.. print "\t\t\n" 24.. print "\t
Name:
Age:
\n" 25.. print "\t\n" 27.. print "\t\n" 28.. print "\t\n" 29.. print "\n" 30.. print "\n" 31.. 32.. # Define function display data. 33.. def display_data(name, age): 34.. print "\n" 35.. print "\n" 36.. print "\tInfo Form\n" 37.. print "\n" 38.. print "\n" 39.. print name, ", you are", age, "years old." 40.. print "\n" 41.. print "\n" 42.. 43.. # Define main function. 44.. def main(): 45.. form = cgi.FieldStorage() 46.. if (form.has_key("action") and form.has_key("name") \ 47.. and form.has_key("age")): 48.. if (form["action"].value == "display"): 49.. display_data(form["name"].value, form["age"].value) 50.. else: 51.. generate_form() 52.. 53.. # Call main function. 54.. main() 55.. And the server log - #Software: Microsoft Internet Information Services 6.0 #Version: 1.0 #Date: 2007-07-13 12:11:28 #Fields: date time s-sitename s-computername s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs-version cs(User-Agent) cs(Cookie) cs(Referer) cs-host sc-status sc-substatus sc-win32-status sc-bytes cs-bytes time-taken 2007-07-13 12:11:27 W3SVC12090 ARCTURUS 209.200.254.99 GET /Index.aspx - 80 - 74.14.92.189 HTTP/1.1 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.8.1.4)+Gecko/20070515+Firefox/2.0.0.4 - - newspyn.com 200 0 0 995 403 593 2007-07-13 12:11:27 W3SVC12090 ARCTURUS 209.200.254.99 GET /Images/ComingSoon.png - 80 - 74.14.92.189 HTTP/1.1 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.8.1.4)+Gecko/20070515+Firefox/2.0.0.4 - http://newspyn.com/ newspyn.com 404 0 2 1819 374 93 2007-07-13 12:11:30 W3SVC12090 ARCTURUS 209.200.254.99 GET /Images/development.bmp - 80 - 74.14.92.189 HTTP/1.1 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.8.1.4)+Gecko/20070515+Firefox/2.0.0.4 - http://newspyn.com/ newspyn.com 200 0 0 1000335 375 2984 2007-07-13 12:11:30 W3SVC12090 ARCTURUS 209.200.254.99 GET /favicon.ico - 80 - 74.14.92.189 HTTP/1.1 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.8.1.4)+Gecko/20070515+Firefox/2.0.0.4 - - newspyn.com 404 0 2 1819 334 93 2007-07-13 12:11:51 W3SVC12090 ARCTURUS 209.200.254.99 GET /cgi-bin/example_1.1.cgi - 80 - 74.14.92.189 HTTP/1.1 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.8.1.4)+Gecko/20070515+Firefox/2.0.0.4 - - newspyn.com 404 0 3 1819 426 93 2007-07-13 12:12:05 W3SVC12090 ARCTURUS 209.200.254.99 GET /cgi-bin - 80 - 74.14.92.189 HTTP/1.1 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.8.1.4)+Gecko/20070515+Firefox/2.0.0.4 - - newspyn.com 404 0 2 1819 410 109 #Software: Microsoft Internet Information Services 6.0 #Version: 1.0 #Date: 2007-07-13 13:03:04 #Fields: date time s-sitename s-computername s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs-version cs(User-Agent) cs(Cookie) cs(Referer) cs-host sc-status sc-substatus sc-win32-status sc-bytes cs-bytes time-taken 2007-07-13 13:03:04 W3SVC12090 ARCTURUS 209.200.254.99 GET /cgi-bin/example_1.1.cgi - 80 - 74.14.92.189 HTTP/1.1 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.8.1.4)+Gecko/20070515+Firefox/2.0.0.4 - - newspyn.com 404 0 3 1819 426 218 #Software: Microsoft Internet Information Services 6.0 #Version: 1.0 #Date: 2007-07-13 13:30:37 #Fields: date time s-sitename s-computername s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs-version cs(User-Agent) cs(Cookie) cs(Referer) cs-host sc-status sc-substatus sc-win32-status sc-bytes cs-bytes time-taken 2007-07-13 13:30:37 W3SVC12090 ARCTURUS 209.200.254.99 GET /cgi-bin/example_1.1.cgi - 80 - 74.14.92.189 HTTP/1.1 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.8.1.4)+Gecko/20070515+Firefox/2.0.0.4 - - newspyn.com 502 2 0 417 426 421 2007-07-13 13:36:22 W3SVC12090 ARCTURUS 209.200.254.99 GET /cgi-bin/example_7.1.cgi - 80 - 74.14.92.189 HTTP/1.1 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.8.1.4)+Gecko/20070515+Firefox/2.0.0.4 - - newspyn.com 502 2 0 417 426 281 #Software: Microsoft Internet Information Services 6.0 #Version: 1.0 #Date: 2007-07-13 14:33:25 #Fields: date time s-sitename s-computername s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs-version cs(User-Agent) cs(Cookie) cs(Referer) cs-host sc-status sc-substatus sc-win32-status sc-bytes cs-bytes time-taken 2007-07-13 14:33:25 W3SVC12090 ARCTURUS 209.200.254.99 GET /cgi-bin/example_7.1.cgi - 80 - 74.14.92.189 HTTP/1.1 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.8.1.4)+Gecko/20070515+Firefox/2.0.0.4 - - newspyn.com 502 2 0 417 452 406 #Software: Microsoft Internet Information Services 6.0 #Version: 1.0 #Date: 2007-07-13 15:31:18 #Fields: date time s-sitename s-computername s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs-version cs(User-Agent) cs(Cookie) cs(Referer) cs-host sc-status sc-substatus sc-win32-status sc-bytes cs-bytes time-taken 2007-07-13 15:31:18 W3SVC12090 ARCTURUS 209.200.254.99 GET /cgi-bin/example_7.1.py - 80 - 74.14.92.189 HTTP/1.1 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.8.1.4)+Gecko/20070515+Firefox/2.0.0.4 - - newspyn.com 502 2 0 417 425 6546 #Software: Microsoft Internet Information Services 6.0 #Version: 1.0 #Date: 2007-07-13 16:00:27 #Fields: date time s-sitename s-computername s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs-version cs(User-Agent) cs(Cookie) cs(Referer) cs-host sc-status sc-substatus sc-win32-status sc-bytes cs-bytes time-taken 2007-07-13 16:00:26 W3SVC12090 ARCTURUS 209.200.254.99 GET /cgi-bin/example_7.1.py - 80 - 74.14.92.189 HTTP/1.1 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.8.1.4)+Gecko/20070515+Firefox/2.0.0.4 - - newspyn.com 502 2 0 417 451 421 #Software: Microsoft Internet Information Services 6.0 #Version: 1.0 #Date: 2007-07-13 16:34:43 #Fields: date time s-sitename s-computername s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs-version cs(User-Agent) cs(Cookie) cs(Referer) cs-host sc-status sc-substatus sc-win32-status sc-bytes cs-bytes time-taken 2007-07-13 16:34:43 W3SVC12090 ARCTURUS 209.200.254.99 GET /cgi-bin/example_7.1.py - 80 - 74.14.92.189 HTTP/1.1 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.8.1.4)+Gecko/20070515+Firefox/2.0.0.4 - - newspyn.com 502 2 0 417 451 406 2007-07-13 16:37:07 W3SVC12090 ARCTURUS 209.200.254.99 GET /cgi-bin/example_7.1.py - 80 - 74.14.92.189 HTTP/1.1 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.8.1.4)+Gecko/20070515+Firefox/2.0.0.4 - - newspyn.com 502 2 0 417 451 343 Thanks in advance for any help -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070713/bea40533/attachment.html -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 174 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070713/bea40533/attachment-0001.gif From kent37 at tds.net Sat Jul 14 04:18:44 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 13 Jul 2007 22:18:44 -0400 Subject: [Tutor] Importing question In-Reply-To: <20070713105142.7E9741E4006@bag.python.org> References: <20070713105142.7E9741E4006@bag.python.org> Message-ID: <46983284.6030902@tds.net> Dick Moores wrote: > At http://wiki.python.org/moin/SimplePrograms I found this code: > > ============================================ > import itertools > > def iter_primes(): > # an iterator of all numbers between 2 and +infinity > numbers = itertools.count(2) > > # generate primes forever > while True: > # get the first number from the iterator (always a prime) > prime = numbers.next() > yield prime > > # this code iteratively builds up a chain of > # filters...slightly tricky, but ponder it a bit > numbers = itertools.ifilter(prime.__rmod__, numbers) > > for p in iter_primes(): > if p > 1000: > break > print p > ==================================================== > > It works for me in Win XP, Python 2.5. > > However, in trying to dig into the code to understand it, I'm not able > to find itertools.py, even though itertools is found in the docs at < > http://www.python.org/doc/2.4/lib/module-itertools.html>. > A search of my Python25 directory doesn't turn up an itertools.py. > > So my question is, how does the first line of the code work? /Where /is > itertools? You can find out where any module is located using its __file__ attribute. This works for modules written in C, too. On my (Mac OSX) computer: In [2]: itertools.__file__ Out[2]: '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload/itertools.so' Kent From hunter92383 at gmail.com Sat Jul 14 04:48:06 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 14 Jul 2007 10:48:06 +0800 Subject: [Tutor] how do I input " as part of a string? In-Reply-To: <469805AB.5040401@comcast.net> References: <674d5ce60707130910u68561c19t5046cf27dcf8d842@mail.gmail.com> <674d5ce60707130922l31560aaahee1b6b645d160481@mail.gmail.com> <2a278ffe0707130927r3e3b4531g940f9f9bfd5242f1@mail.gmail.com> <4697A9C0.5070904@comcast.net> <674d5ce60707130953x194fc93cve1d54290490a7ca2@mail.gmail.com> <4697B927.8090409@comcast.net> <674d5ce60707131044u767d1c84h29baf059ae24eb27@mail.gmail.com> <4697BBAD.6010302@comcast.net> <674d5ce60707131120w4053edf5o65a6302eeed51b04@mail.gmail.com> <469805AB.5040401@comcast.net> Message-ID: <674d5ce60707131948r5cd75edew7ddb2afdd3c7c7e5@mail.gmail.com> I actually meant to type send, because the text file is then going to read by auto it 3, which has the function send I use that functions this way because I have this for sale , for that, unless someone wants to make 100USd, I have to write a application interface between the two, which is what I am doing. # opens autoit3source.au3 to write f = open ("sc.au3", "w") # au3 send("text") def send(string): f.write('\"%s\"\n' % string) to restate my question, this is what I need: how do I do this? variable = taitle f.write(texttexttexttext'\"%s\"\n' % variable textextexte ) ? as in, I not only need to include " in between, I also need to input text string before and after the variable. an example http://www.autoitscript.com/autoit3/docs/functions/MsgBox.htm MsgBox ( 0, "title", "text" ) 0 means it's a vanilla popbox with "ok" other numbers could mean , ignore, cancel and so forth. how I want to use it organge = 5 f.write( "there are orange "florida" oranges on the counter") :) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070714/638e425c/attachment.html From hunter92383 at gmail.com Sat Jul 14 04:54:22 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 14 Jul 2007 10:54:22 +0800 Subject: [Tutor] interpreter restarts In-Reply-To: References: <674d5ce60707130944h4bc161e6k6942b119a1d71566@mail.gmail.com> <674d5ce60707131146g85e3d99sd9d6bb6435652709@mail.gmail.com> <674d5ce60707131147o3e2a78e1xb33fcfa4dea3dc30@mail.gmail.com> <011101c7c578$a0a53f00$4cfce004@JSLAPTOP> Message-ID: <674d5ce60707131954j7994c224kb33bdb7d8a367e37@mail.gmail.com> ohhh, you are the greatest :)) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070714/85ffc819/attachment.htm From rabidpoobear at gmail.com Sat Jul 14 05:17:46 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 13 Jul 2007 22:17:46 -0500 Subject: [Tutor] (no subject) In-Reply-To: <9145740.953001184317538070.JavaMail.webmail@ps13zhb.bluewin.ch> References: <9145740.953001184317538070.JavaMail.webmail@ps13zhb.bluewin.ch> Message-ID: <4698405A.8050908@gmail.com> linden at bluewin.ch wrote: > Hello, > Hi, welcome to the list. Please use meaningful subject lines in the future. -Luke From tinoloc at gmail.com Sat Jul 14 05:18:57 2007 From: tinoloc at gmail.com (Tino Dai) Date: Fri, 13 Jul 2007 23:18:57 -0400 Subject: [Tutor] eyeD3 module installation on XP In-Reply-To: <7d81675b0707130745h5017b76bgb43f50a23548c7f3@mail.gmail.com> References: <7d81675b0707130745h5017b76bgb43f50a23548c7f3@mail.gmail.com> Message-ID: On 7/13/07, Richard Querin wrote: > > I'm interested in writing a small app - or attempting to ;) - which > will involve using the eyeD3 python module to process id3 tags of a > given set of files. > > There are source downloads as well as downloads for various linux > distros, which is fine. However I also might want to work on this in > XP. I'm not sure how to install this on a Windows system. The install > instructions in the source code download describe the normal > ./configure, make, make install which I've used several times before > when installing stuff on my home linux box, but I'm not sure these > will work on my Xp system. > > Any pointers on how to go about installing this module? There's a file > called 'setup.py.in' as well. Not sure what that does.. Hi Richard, It seems that the setup.py.in and the setup.py are exact the same each for the version variable. The setup.py.in is from which the setup.py module is generated in the configure process. And the setup.py will be used in the make install process. The easiest way of getting it to work on XP is to download cygwin and run it in that. Another option is that you could hand run the make file. There doesn't seem to be any files that need to be compiled, so you would be ok there. Other than that. Good Luck. HTH, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070713/b5cbf6e0/attachment.html From rabidpoobear at gmail.com Sat Jul 14 05:21:04 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 13 Jul 2007 22:21:04 -0500 Subject: [Tutor] Tutor Digest, Vol 41, Issue 47 In-Reply-To: References: Message-ID: <46984120.50806@gmail.com> J?nos Juh?sz wrote: > > Hi Linden, Hi Janos. The text of your e-mail is tiny. I can't read it. Does this have something to do with HTML formatting, perhaps? People on the list generally prefer plain text, but if it's unavoidable, that's fine. It's just less accessible, and therefore less likely that you'll get a meaningful response. Just thought I'd bring the issue to your attention, in case you didn't realize. -Luke From rabidpoobear at gmail.com Sat Jul 14 05:26:39 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 13 Jul 2007 22:26:39 -0500 Subject: [Tutor] CGI error In-Reply-To: <001201c7c571$19a839a0$7801a8c0@YOURFD474B1D4C> References: <001201c7c571$19a839a0$7801a8c0@YOURFD474B1D4C> Message-ID: <4698426F.9040006@gmail.com> Darren Williams wrote: > Hi all Smile > > I have a Windows hosting account with lunarpages.com and am having a > bit of trouble with CGI. I have enabled both CGI and Python in the > control panel and made sure the permissions for all my CGI scripts are > set to both readable and executable for all users but I keep getting > the same 'The specified CGI application misbehaved by not returning a > complete set of HTTP headers' error. > > The script that i'm trying to execute (example_7.1.py) - > > > Code: [Download > ] > > 1. |#!/usr/bin/python| > 2. > > 3. # Import the CGI module > 4. import cgi > 5. > > 6. # Required header that tells the browser how to render the HTML. > 7. print "Content-Type: text/html\n\n" > Darren - are you sure this line is being executed? I have a suspicion that something to do with CGI in IIS (I have no idea, I've never used IIS) might be calling your functions directly and not running this module? I'm not sure, that's sort of how it works in Apache - mod_python calls a specific function inside a specific module, or something like that. Additionally, try adding '\r\n\r\n' instead of '\n\n' because, as it's IIS, which is a microsoft product, it might require the MS-style newline rather than the unix-style. > > 1. > > > 2. # Define function to generate HTML form. > 3. def generate_form(): > 4. print "\n" > 5. print "\n" > > [snip more code] > > And the server log - > > [snip server log] > > Thanks in advance for any help Smile Sure! Hope I helped somewhat, or at least sparked an idea. -Luke From rabidpoobear at gmail.com Sat Jul 14 05:49:57 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 13 Jul 2007 22:49:57 -0500 Subject: [Tutor] how do I input " as part of a string? In-Reply-To: <674d5ce60707131948r5cd75edew7ddb2afdd3c7c7e5@mail.gmail.com> References: <674d5ce60707130910u68561c19t5046cf27dcf8d842@mail.gmail.com> <674d5ce60707130922l31560aaahee1b6b645d160481@mail.gmail.com> <2a278ffe0707130927r3e3b4531g940f9f9bfd5242f1@mail.gmail.com> <4697A9C0.5070904@comcast.net> <674d5ce60707130953x194fc93cve1d54290490a7ca2@mail.gmail.com> <4697B927.8090409@comcast.net> <674d5ce60707131044u767d1c84h29baf059ae24eb27@mail.gmail.com> <4697BBAD.6010302@comcast.net> <674d5ce60707131120w4053edf5o65a6302eeed51b04@mail.gmail.com> <469805AB.5040401@comcast.net> <674d5ce60707131948r5cd75edew7ddb2afdd3c7c7e5@mail.gmail.com> Message-ID: <469847E5.6020300@gmail.com> elis aeris wrote: > I actually meant to type send, because the text file is then going to > read by auto it 3, which > has the function send > > I use that functions this way because I have this > > for sale , for that, unless someone wants to make 100USd, I have to > write a application interface between the two, which is what I am doing. So instead of taking the time to learn Python, which would've made this an easy project, you are just going to keep trying stuff until something works? And you're getting us to help you to brute-force this problem, when the actual purpose of this list is to help people learn python? I don't see any reason why I should continue to reply to you, or why anyone else should, for that matter. It's frustrating that this deluge of messages from you, that you could honestly solve yourself in a few minutes if you had any desire whatsoever to learn, is getting in the way of people who are actually trying to learn. Not only by way of taking up the exceptional tutors' (Alan, Kent, etc) time reading and rereading the same problem you have over and over, that is slightly different, but also that I (and likely others) get pretty peeved when you aren't picking up on the obvious hints that everyone's dropping that you should stop working on this project until you learn the fundamentals of programming in Python. I feel my time has been wasted, because every e-mail I send to you that has constructive advice, you just ignore. Answers, answers, solutions, solutions! That's not what we do here! We give you hints and guidance so you can solve the problems yourself, so that you can _understand_ them, and so that you will know how to solve the next problem that arises that is similar. Yet all I've seen from you is slightly different problems cropping up over and over, and obvious fundamental lack of understanding not only of the method in which to implement a solution to a problem, but also in formulating a solution in the first place. The previous e-mail of this nature I wrote was significantly less coarse, but more detailed in the manner in which you could proceed, so that you would learn properly, and it went ignored. Do I have your attention? (Apologies to Alan et. al. for my tactlessness.) -Luke From rabidpoobear at gmail.com Sat Jul 14 05:52:19 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 13 Jul 2007 22:52:19 -0500 Subject: [Tutor] interpreter restarts In-Reply-To: References: <674d5ce60707130944h4bc161e6k6942b119a1d71566@mail.gmail.com><674d5ce60707131146g85e3d99sd9d6bb6435652709@mail.gmail.com> <674d5ce60707131147o3e2a78e1xb33fcfa4dea3dc30@mail.gmail.com> Message-ID: <46984873.3010404@gmail.com> Alan Gauld wrote: > "elis aeris" wrote > > >> from a file, i click run from the IDLE interpreter >> > > OK, Thats just normal IDLE behaviour. The Python shell > restarts so your module doesn't pick up any junk lying > around from the previous run. > But there's an exception to that - if you right-click a file in Windoze and 'edit' it, IDLE won't open up its subprocess, and as such, it can't restart the interpreter session because it's running in the same process as IDLE, and to restart the interpreter would mean restarting IDLE. Boy, that 'edit with idle' thing sure does cause some problems, don't it? :) -Luke From dale.pearl at gmail.com Sat Jul 14 06:19:50 2007 From: dale.pearl at gmail.com (Dale Pearl) Date: Fri, 13 Jul 2007 21:19:50 -0700 Subject: [Tutor] Platform-independent Excel reader In-Reply-To: <000301c7c4ce$e4e13520$5301a8c0@MD1918> References: <000301c7c4ce$e4e13520$5301a8c0@MD1918> Message-ID: <747edb7f0707132119j657def07y4aa35b226d97a51@mail.gmail.com> how about google docs? On 7/12/07, encore jane wrote: > > Hi, > > Does anyone know about a good native Excel file reader that is platform > independent? > > Thanks, > > AJ > > _______________________________________________ > 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/20070713/52803194/attachment.htm From billburns at pennswoods.net Sat Jul 14 06:36:08 2007 From: billburns at pennswoods.net (Bill Burns) Date: Sat, 14 Jul 2007 00:36:08 -0400 Subject: [Tutor] Platform-independent Excel reader In-Reply-To: <000301c7c4ce$e4e13520$5301a8c0@MD1918> References: <000301c7c4ce$e4e13520$5301a8c0@MD1918> Message-ID: <469852B8.2080602@pennswoods.net> encore jane wrote: > Hi, > > Does anyone know about a good native Excel file reader that is platform > independent? > > Thanks, > > AJ > Take a look at this, it's platform independent and reads excel files :-) http://cheeseshop.python.org/pypi/xlrd Bill From hunter92383 at gmail.com Sat Jul 14 08:15:53 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 14 Jul 2007 14:15:53 +0800 Subject: [Tutor] how do I input " as part of a string? In-Reply-To: <469847E5.6020300@gmail.com> References: <674d5ce60707130910u68561c19t5046cf27dcf8d842@mail.gmail.com> <4697A9C0.5070904@comcast.net> <674d5ce60707130953x194fc93cve1d54290490a7ca2@mail.gmail.com> <4697B927.8090409@comcast.net> <674d5ce60707131044u767d1c84h29baf059ae24eb27@mail.gmail.com> <4697BBAD.6010302@comcast.net> <674d5ce60707131120w4053edf5o65a6302eeed51b04@mail.gmail.com> <469805AB.5040401@comcast.net> <674d5ce60707131948r5cd75edew7ddb2afdd3c7c7e5@mail.gmail.com> <469847E5.6020300@gmail.com> Message-ID: <674d5ce60707132315l30217ba9l7492ac1d560eed32@mail.gmail.com> understood. On 7/14/07, Luke Paireepinart wrote: > > elis aeris wrote: > > I actually meant to type send, because the text file is then going to > > read by auto it 3, which > > has the function send > > > > I use that functions this way because I have this > > < > http://rentacoder.com/RentACoder/misc/BidRequests/ShowBidRequest.asp?lngBidRequestId=719268 > > > > for sale , for that, unless someone wants to make 100USd, I have to > > write a application interface between the two, which is what I am doing. > So instead of taking the time to learn Python, which would've made this > an easy project, you are just going to keep trying stuff until something > works? > And you're getting us to help you to brute-force this problem, when the > actual purpose of this list is to help people learn python? > I don't see any reason why I should continue to reply to you, or why > anyone else should, for that matter. > It's frustrating that this deluge of messages from you, that you could > honestly solve yourself in a few minutes if you had any desire > whatsoever to learn, is getting in the way of people who are actually > trying to learn. Not only by way of taking up the exceptional tutors' > (Alan, Kent, etc) time reading and rereading the same problem you have > over and over, that is slightly different, but also that I (and likely > others) get pretty peeved when you aren't picking up on the obvious > hints that everyone's dropping that you should stop working on this > project until you learn the fundamentals of programming in Python. > > I feel my time has been wasted, because every e-mail I send to you that > has constructive advice, you just ignore. > Answers, answers, solutions, solutions! > That's not what we do here! > We give you hints and guidance so you can solve the problems yourself, > so that you can _understand_ them, and so that you will know how to > solve the next problem that arises that is similar. Yet all I've seen > from you is slightly different problems cropping up over and over, and > obvious fundamental lack of understanding not only of the method in > which to implement a solution to a problem, but also in formulating a > solution in the first place. > > The previous e-mail of this nature I wrote was significantly less > coarse, but more detailed in the manner in which you could proceed, so > that you would learn properly, and it went ignored. Do I have your > attention? > > (Apologies to Alan et. al. for my tactlessness.) > -Luke > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070714/3f2da307/attachment.html From hunter92383 at gmail.com Sat Jul 14 08:38:38 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sat, 14 Jul 2007 14:38:38 +0800 Subject: [Tutor] tutor In-Reply-To: <674d5ce60707132332u57819d11kffccfb358311e7de@mail.gmail.com> References: <674d5ce60707132332u57819d11kffccfb358311e7de@mail.gmail.com> Message-ID: <674d5ce60707132338t3b6d208bu15be93f457c413e6@mail.gmail.com> please think about your first programming class, and then think about how long it took the prof to teach the concept of array. yes, it's about a week, if he is really good. python is a very young language, prefered by professionals of its simplicity, as such, the number of character of the document divided by the actual code has a very high ratio, because its well written document of people who know multiple languages, I have to as what appears to be the same question over and over because Ican't read the documents. it's too cryptic. and as I go, i just come across dumb problem like: how I want to use it organge = 5 f.write( "there are orange "florida" oranges on the counter") yes i know that i have asked about how to include a qutation mark and I have asked about how to include a variable, but separately. i know it 's less than 3 " , but i don't know where entertain my frustration. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070714/6cee6258/attachment.htm From alan.gauld at btinternet.com Sat Jul 14 08:54:34 2007 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 14 Jul 2007 06:54:34 +0000 (GMT) Subject: [Tutor] Fw: Fw: curses Message-ID: <19374.53916.qm@web86111.mail.ukl.yahoo.com> Following my own advice.... ----- Forwarded Message ---- From: ALAN GAULD To: max baseman Sent: Saturday, 14 July, 2007 7:53:43 AM Subject: Re: [Tutor] Fw: curses Max, You need to send questions to the tutor list not just me. Make sure you use Reply All or at least that tutor at python.org is included. The advantages of having many eyes reading your question is that you increase both speed and accuracy of results. In addition it keeps the answers available to all so others with the same problem in the future can use a search engine to find them. Now, on this topic... ----- Original Message ---- From: max baseman To: ALAN GAULD Sent: Saturday, 14 July, 2007 1:39:11 AM Subject: Re: [Tutor] Fw: curses > hmmm so sorry to keep bothering you but now i get no error thats good > but also no display just a blinking curser in top right and if i type > it shows their one letter at a time It worked for me but you do need to do a scr.refresh() each time to make it visible.. Alan G. On Jul 13, 2007, at 4:36 PM, ALAN GAULD wrote: > Returning to the list.... > > > ----- Forwarded Message ---- >> From: max baseman >> To: Alan Gauld >> hmm but now i get a error on the same line scr.addch(max_x/2, max_y/ >> 2, str(population)[0]) >> _curses.error addch() returned ERR > > Thats because you are writing outside the screen boundaries. > My mistake, the order of the params is y,x not x,y so it should > have been: > > scr.addchr(max_y/2,max_x/2, str(population)[0]) > > Apologies, > > Alan G. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sat Jul 14 08:58:20 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 14 Jul 2007 07:58:20 +0100 Subject: [Tutor] Importing question References: <20070713105142.7E9741E4006@bag.python.org> <46983284.6030902@tds.net> Message-ID: "Kent Johnson" wrote > You can find out where any module is located using its __file__ > attribute. This works for modules written in C, too. But not on Windoze. If it's built-in there is no __file__ attribute. But the print trick tells you if it's builtin and if it's not __file__ works. Alan G. From alan.gauld at btinternet.com Sat Jul 14 09:04:56 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 14 Jul 2007 08:04:56 +0100 Subject: [Tutor] tutor References: <674d5ce60707132332u57819d11kffccfb358311e7de@mail.gmail.com> <674d5ce60707132338t3b6d208bu15be93f457c413e6@mail.gmail.com> Message-ID: "elis aeris" wrote > because its well written document of people who know multiple > languages, I > have to as what appears to be the same question over and over > because > Ican't read the documents. The official tutor is designed for experienced programmers. There are many beginners tutors too. Try some of the ones here http://wiki.python.org/moin/BeginnersGuide/NonProgrammers until you find one you like and then go through it. It will only take a day of your time to cover all the basics but it will be well invested. Slightly more advanced bt shorter tutors are here: http://wiki.python.org/moin/BeginnersGuide/Programmers -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bhaaluu at gmail.com Sat Jul 14 14:54:24 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Sat, 14 Jul 2007 08:54:24 -0400 Subject: [Tutor] tutor In-Reply-To: References: <674d5ce60707132332u57819d11kffccfb358311e7de@mail.gmail.com> <674d5ce60707132338t3b6d208bu15be93f457c413e6@mail.gmail.com> Message-ID: Greetings, I have found that this Python Book has been helpful: http://ibiblio.org/obp/thinkCS/python/english2e.tgz How to Think Like a Computer Scientist Learning with Python by Allen B. Downey, Jeffrey Elkner and Chris Meyers Printed copies now available from Green Tea Press. One of the most fundamental steps in designing a computer program is to be able to state the problem clearly and unambiguously and to gain a clear understanding of what is required for its solution. The objective here is to eliminate unimportant aspects and zero in on the root problem (most computer programs solve a problem). >From my own experiences, I've found that some people are able to learn from books with minimal outside help, some can learn from books with maximum outside help, and others can't learn from books at all, they need to have their hands held from the first step to the final destination. The later usually don't make it too far after the first journey. As for myself, I am a hobbyist programmer who enjoys computer programming much in the same way that others enjoy doing cryptix and crossword puzzles. I'm usually able to learn from books with minimal help. Even so, in the beginning, the documentation for a new computer programming language is somewhat difficult to follow. So, I stick with the tutorials that are easier to understand until I can gain enough experience to understand the documentation. I also use Internet search engines to look for relevant code snippets. I can often learn how to solve a particular problem by studying source code that is already working, and modifying it to suit myself. http://www.google.com/codesearch/advanced_code_search I really don't know how to advise someone who can't read. Computer programming is a a literate activity. If one can't read, a book is no good. If one can't read, then advice from a programmer's mailing list will probably go unnoticed. If money ($ USD) is no object, perhaps a good suggestion is: Enroll in a Summer Computer Programming Camp! Yeah, that's the ticket! 8^D Can anyone recommend a good Summer Python Computer Programming Camp? 42! -- bhaaluu at gmail dot com On 7/14/07, Alan Gauld wrote: > > "elis aeris" wrote > > > because its well written document of people who know multiple > > languages, I > > have to as what appears to be the same question over and over > > because > > Ican't read the documents. > > The official tutor is designed for experienced programmers. > There are many beginners tutors too. Try some of the ones here > > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > until you find one you like and then go through it. It will only > take a day of your time to cover all the basics but it will be > well invested. > > Slightly more advanced bt shorter tutors are here: > > http://wiki.python.org/moin/BeginnersGuide/Programmers > > > -- > 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 > From tnoyeaux at msn.com Sat Jul 14 15:57:06 2007 From: tnoyeaux at msn.com (Tony Noyeaux) Date: Sat, 14 Jul 2007 09:57:06 -0400 Subject: [Tutor] Newbie Project part 2... Message-ID: Thanks to all the tutors,... your advice has been invaluable todate,.. the learning continues. The code below..asks the user to pick one of 3 options,.. once they choose,... a random result happens based on their choice. --------------------------------------------------------- import randomprint "\t\t\t\tLife Simulator"print "You have just turned 18 years old. Your life awaits,... choices to be made.."print "\na)Army,\nb)Navy,\nc)Airforce"job=raw_input("What will u join?") if job == "a": print random.choice(["You win Silver star", "You are killed in action"])elif job == "b": print random.choice(["You fall overboard", "You command you're own battleship"])elif job == "c": print random.choice(["You get shot down", "You become wing commander"]) raw_input("\n\nPress Enter to quit.")---------------------------------------------------------------------- This works fine. I am having trouble coding in the 2nd question,.. and all subsequent questions. The next Question.. has to be a result of the random result. So, if they choose .. b).. and they join the navy,... random result,..."you command battleship results"... then,... a specific question,... with, and abc responce,.. will trigger. Obviosly,. there will be alot of responces to all the different options stored. Just trying to get the framework working which i have not been able to sucessfully accomplish yet. So for the sake of the example, the user chose B)Navy ---> You command battleship random resulted... Then this question appeared. "Will you reenlist for another four years"? random results of "You are Promoted to Secretary of the Navy", "You lose a leg in a torpedo attack". All the actual responces and random results are just examples to get the structure and code working. I am hoping to be able to print a summary of each happening ... as results are generated. So the user can see their own personal story build.. based on their responces etc. Thanks again for the insights you've given todate. Tony Noyeaux _________________________________________________________________ Local listings, incredible imagery, and driving directions - all in one place! Find it! http://maps.live.com/?wip=69&FORM=MGAC01 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070714/31c64f06/attachment.htm From dos.fool at gmail.com Sat Jul 14 16:08:28 2007 From: dos.fool at gmail.com (max baseman) Date: Sat, 14 Jul 2007 08:08:28 -0600 Subject: [Tutor] curses Message-ID: <7EBB61A9-66E5-4669-AF0C-2247C222CBE9@gmail.com> hello all sorry to bother I'm working on my first curses program ive been wanting to learn curses for a while now and now that a have a lop top with fedora core running in run level 3 ware im trying to program all the tools i'll use but curses will be my only gui ALAN has been helping me with this program import curses from time import sleep scr=curses.initscr() population=0 seconds=0 try: scr.nodelay(1) scr.leaveok(0) max_y, max_x = scr.getmaxyx() while 1: sleep(1) second=seconds=+1 population=population+2.5 scr.addstr(0,0,"seconds",seconds) scr.addch,max_y/2, max_x/2, str(population)[0] scr.refresh() finally: curses.endwin() depending on ware i run this i get different results on may mac OSX 10.4 i only get a wired second thing in the top left corner that looks like this secooes and when i run this on fedora core 6 i get the seconds word in top left but no number and i get a single digit in the midle that changes i think the single digit is part of population but not all i cant find out what is wrong any help would be great :) From mwalsh at groktech.org Sat Jul 14 17:44:01 2007 From: mwalsh at groktech.org (Martin Walsh) Date: Sat, 14 Jul 2007 10:44:01 -0500 Subject: [Tutor] CGI error In-Reply-To: <001201c7c571$19a839a0$7801a8c0@YOURFD474B1D4C> References: <001201c7c571$19a839a0$7801a8c0@YOURFD474B1D4C> Message-ID: <4698EF41.2060002@groktech.org> Hi Darren, Darren Williams wrote: > Hi all Smile > > I have a Windows hosting account with lunarpages.com and am having a bit > of trouble with CGI. I have enabled both CGI and Python in the control > panel and made sure the permissions for all my CGI scripts are set to > both readable and executable for all users but I keep getting the same > 'The specified CGI application misbehaved by not returning a complete > set of HTTP headers' error. Have you tried to run the script from the command line? If the code provided below is accurate and has not been changed by your mail client, then it will raise an IndentationError, and the script will exit before printing the Content-type header. > The script that i'm trying to execute (example_7.1.py) - > 32. # Define function display data. > 33. def display_data(name, age): Here is an improper indent ... > 34. print "\n" > 35. print "\n" > 36. print "\tInfo Form\n" > 37. print "\n" > 38. print "\n" > 39. print name, ", you are", age, "years old." > 40. print "\n" > 41. print "\n" > 42. > 43. # Define main function. > 44. def main(): ... and here ... > 45. form = cgi.FieldStorage() > 46. if (form.has_key("action") and form.has_key("name") \ > 47. and form.has_key("age")): > 48. if (form["action"].value == "display"): > 49. display_data(form["name"].value, form["age"].value) > 50. else: > 51. generate_form() > 52. > 53. # Call main function. > 54. main() ... and here ... HTH, Marty From stickster at gmail.com Sat Jul 14 19:25:44 2007 From: stickster at gmail.com (Paul W. Frields) Date: Sat, 14 Jul 2007 13:25:44 -0400 Subject: [Tutor] tutor In-Reply-To: References: <674d5ce60707132332u57819d11kffccfb358311e7de@mail.gmail.com> <674d5ce60707132338t3b6d208bu15be93f457c413e6@mail.gmail.com> Message-ID: <1184433944.26776.7.camel@localhost.localdomain> On Sat, 2007-07-14 at 08:54 -0400, bhaaluu wrote: > Greetings, > > I have found that this Python Book has been helpful: > > http://ibiblio.org/obp/thinkCS/python/english2e.tgz > > How to Think Like a Computer Scientist > Learning with Python > > by Allen B. Downey, Jeffrey Elkner and Chris Meyers > Printed copies now available from Green Tea Press. This book is excellent for people who are new to the whole concept of programming. (That includes ideas like arrays, loops, etc.) At least one of the authors is a high school teacher who works, or used to work, not too far from where I live -- although I don't know him personally. You can also just read it online at: http://ibiblio.org/obp/thinkCS/python/english2e/html/ -- Paul W. Frields, RHCE http://paul.frields.org/ gpg fingerprint: 3DA6 A0AC 6D58 FEC4 0233 5906 ACDB C937 BD11 3717 Fedora Project: http://fedoraproject.org/wiki/PaulWFrields irc.freenode.net: stickster @ #fedora-docs, #fedora-devel, #fredlug -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part Url : http://mail.python.org/pipermail/tutor/attachments/20070714/6905841a/attachment.pgp From alan.gauld at btinternet.com Sat Jul 14 21:14:55 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 14 Jul 2007 20:14:55 +0100 Subject: [Tutor] tutor References: <674d5ce60707132332u57819d11kffccfb358311e7de@mail.gmail.com><674d5ce60707132338t3b6d208bu15be93f457c413e6@mail.gmail.com> Message-ID: Hi, > books with maximum outside help, and others can't learn from books > at all, they need to have their hands held from the first step to > the > final destination. IMO Anyone in that position is never going to be able to program at any level of competency. Its a simple fact that to program at anything beyond the most basic level you will need to read manuals/references etc. If you can't read and learn you will struggle to learn enough of anything to progress. > and crossword puzzles. I'm usually able to learn from books with > minimal help. Even so, in the beginning, the documentation for a > new computer programming language is somewhat difficult to follow. I'm intrigued by that statement. What do you find challenging? Once you learn one language and understand the basic concepts then learning a new language is usually a very straightforward process. After all there are relatively few new things to learn: How the basic control strucctures are done: Sequences (including overall program structure) Loops Branches Modules( ie. procedures/functions, later to include OOP if relevant) How I/O is done - reading input and writing output, and file handling Data structures supported: numbers, strings, boolean, collections Those can usually be learnt in a morning and after that its a matter of gaining experience writing (and reading) code. I generally expect someone at work (not a hobbyist) to be fairly fluent in a new language within a week. I would never send someone who can program on a training course for a new language (except for C++!) > use Internet search engines to look for relevant code snippets. This is fine but has a danger that you wind up stitching together snippets without really understanding how they work. This leads to a debugging nightmare! > I can often learn how to solve a particular problem by studying > source code that is already working, and modifying it to suit > myself. > > http://www.google.com/codesearch/advanced_code_search That is the best way to do it IMHO. It ensures you pick up language idioms, find interesting shortcuts and once you start to see whays to improve the code you know you've pretty much got on top of things! > Computer programming is a a literate activity. If one can't > read, a book is no good. Indeed. Some folks tried to introduce purely visual programming some years ago but the limitations of not using text were so high that most efforts would up in a strange hybrid experience of limited value. (One such experiment was Borland's ObjectWindows - did anyone else ever use that?) -- 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 Jul 14 21:38:58 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 14 Jul 2007 20:38:58 +0100 Subject: [Tutor] Newbie Project part 2... References: Message-ID: "Tony Noyeaux" wrote in --------------------------------------------------------- import random print "\t\t\t\tLife Simulator" print "You have just turned 18 years old. Your life awaits,... choices to be made.." print "\na)Army,\nb)Navy,\nc)Airforce" job=raw_input("What will u join?") if job == "a": print random.choice(["You win Silver star", "You are killed in action"]) elif job == "b": print random.choice(["You fall overboard", "You command you're own battleship"]) elif job == "c": print random.choice(["You get shot down", "You become wing commander"]) raw_input("\n\nPress Enter to quit.") ---------------------------------------------------------------------- > This works fine. > > I am having trouble coding in the 2nd question,.. and all subsequent > questions. > > The next Question.. has to be a result of the random result. I suggested using a nested dictionary structure to hold the questions. Did you try that? It should make this a relatively trivial problem. I'll show the structure for the example you have given so far: questions: {'Q': {""" You have just turned 18 years old. Your life awaits,... choices to be made.. """ : ['Army', 'Navy', 'Airforce']} {'a': { 'Q': {#army questions here} } 'b': { 'Q': {''What kind of ship?': ['battleship','carrier','tug']}, 'a': { # battleship questions}, 'b': { # carrier questions}, 'c': { # tug questions } } 'c': { 'Q': {# airforce Q here} } } Obviously keeping the structure clear is critical to success and a good programmers editor will help balance the braces/quotes etc You can extend the structure to have multiple questions at each stage by simply putting each questoon/answer dictionary in a list. You could also break the structure to ease layout so for example three separate instances, one per service. You could even encapsulate it in a class (I would!) You are essentially building a tree structure and then navigating down it in a part-random, part-deterministic manner. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bhaaluu at gmail.com Sat Jul 14 22:14:51 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Sat, 14 Jul 2007 16:14:51 -0400 Subject: [Tutor] tutor In-Reply-To: References: <674d5ce60707132332u57819d11kffccfb358311e7de@mail.gmail.com> <674d5ce60707132338t3b6d208bu15be93f457c413e6@mail.gmail.com> Message-ID: Greetings, I'm enjoying this discussion. On 7/14/07, Alan Gauld wrote: > Hi, > > > books with maximum outside help, and others can't learn from books > > at all, they need to have their hands held from the first step to > > the > > final destination. > > IMO Anyone in that position is never going to be able to program > at any level of competency. Its a simple fact that to program at > anything beyond the most basic level you will need to read > manuals/references etc. If you can't read and learn you will > struggle to learn enough of anything to progress. Reading and comprehension are fundamental skills. I can show someone how to cut a wooden board with a saw, and join the pieces with a hammer and 10p nails, to make a bookcase. That doesn't require reading. They just need to watch me, then do it themselves until they get it right. It takes a little time to learn if they've never done it before, but it doesn't require reading. They can load books on the bookshelf. That doesn't make them literate. If they want to build anything more complicated than a bookshelf, then reading is a handy skill to have! But computer programming requires reading. The programmer has to be able to read in order to write a program. Why? Because documenting a program is something that every programmer should do, and if you can't read, how can you possibly WRITE documentation? =) > > > and crossword puzzles. I'm usually able to learn from books with > > minimal help. Even so, in the beginning, the documentation for a > > new computer programming language is somewhat difficult to follow. > > I'm intrigued by that statement. What do you find challenging? All of it seems complicated at first because I'm not familiar with the nuances of the new language. As you've noted, the language docs are written for experienced programmers, and may not be suitable for learning from. As I gain familiarity with the language, things that seemed over my head when I first started, start to make sense. I didn't understand anything at all when reading the OOP docs. Why? I'm completely new to OOP, and I don't have a good grasp of the vocabulary yet. However, as I'm reading more, and doing more examples, I'm feeling more comfortable with the documentation. That is not to say that I understand it yet. But it isn't quite as difficult to read the docs as it was, say, a week ago. As a hobbyist, I do my programming in my spare time. I do not have a CS background. Sometimes, documentation assumes a certain level of understanding. Often, I'm never able to understand certain things. > > Once you learn one language and understand the basic concepts > then learning a new language is usually a very straightforward > process. > After all there are relatively few new things to learn: > > How the basic control strucctures are done: > Sequences (including overall program structure) > Loops > Branches > Modules( ie. procedures/functions, later to include OOP if > relevant) > > How I/O is done - reading input and writing output, and file handling > > Data structures supported: > numbers, strings, boolean, collections > > Those can usually be learnt in a morning and after that > its a matter of gaining experience writing (and reading) code. Not everyone can pick things up as fast as some people do. I usually start out slowly. But the things I do learn, I try to learn well. I type in a lot of code, and I run a lot of code that others have written, to see what it will do. I agree that the basics are pretty much the same for most computer programming languages. One of the first languages I learned was a dialect of Lisp, a functional programming language called Logo. I was pleased to find a Logo interpreter written in Python a couple of days ago. What a treasure! =) [Only a hobbyist like me might think so?] (For more information about Logo, see: http://www.cs.berkeley.edu/~bh/ ) > > I generally expect someone at work (not a hobbyist) to be fairly > fluent in a new language within a week. I would never send > someone who can program on a training course for a new > language (except for C++!) I would expect nothing less from a professional programmer! Why the exception for C++ ? > > > use Internet search engines to look for relevant code snippets. > > This is fine but has a danger that you wind up stitching > together snippets without really understanding how they > work. This leads to a debugging nightmare! Yeah, I know, right? =) I got into the computer programming hobby shortly after buying my first computer. I'd download code snippets from BBSes and run them on MS-DOS. It could be very dangerous! Plus those ancient Borland compilers... > > > I can often learn how to solve a particular problem by studying > > source code that is already working, and modifying it to suit > > myself. > > > > http://www.google.com/codesearch/advanced_code_search > > That is the best way to do it IMHO. It ensures you pick up > language idioms, find interesting shortcuts and once you > start to see whays to improve the code you know you've > pretty much got on top of things! This is okay if you already know how to program a little bit. However, if you really don't understand the fundamental concepts of computer programming, it probably won't help much. Plus, this way requires that the student know HOW TO READ! =) Yes, we're back to that little snafu again... reading (and comprehension). > > > Computer programming is a a literate activity. If one can't > > read, a book is no good. > > Indeed. Some folks tried to introduce purely visual > programming some years ago but the limitations of > not using text were so high that most efforts would up > in a strange hybrid experience of limited value. > (One such experiment was Borland's ObjectWindows - did > anyone else ever use that?) Was that the one that used objects like old flowchart symbols to design a program? I may have seen pictures of it somewhere, but never actually saw it in person. =) > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld BTW, your book is helpful as well! Happy (Python) Programming! -- bhaaluu at gmail dot com From alan.gauld at btinternet.com Sat Jul 14 23:35:57 2007 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 14 Jul 2007 21:35:57 +0000 (GMT) Subject: [Tutor] tutor Message-ID: <223412.21805.qm@web86101.mail.ukl.yahoo.com> > > I'm intrigued by that statement. What do you find challenging? > > All of it seems complicated at first because I'm not familiar with the > nuances of the new language. ....I do not have a CS background. That's one of the reasons I wrote my tutor. It became obvious to me that most web tutors assumed a CS training. I decided I neded to define the CS terminology and as much of the theory as was necessary to understand the other tutors. Kind of like the meat of my first year computing course at uni' but accessible to non-CS folks. > > Those can usually be learnt in a morning and after that > > its a matter of gaining experience writing (and reading) code. > > Not everyone can pick things up as fast as some people do. True, but if you already understand the concepts its usually pretty easy to translate them to a new language. You don;t need to remember the new syntax, just create your own short reference card. I find most lamnguages can be represented on a single side of A4/Letter paper. Not the whole language but enough to tackle basic problems and start getting some hands on experience. Thats the level I mean by a morning. > One of the first languages I learned was a dialect of Lisp, a > functional programming language called Logo. Logo is great, I first used it on an old CP/M 8 bit Micro. The syntax is easy and yet extensible, with less parens than Lisp. I even had a Windows version (ie it could write GUI programs not just run in a window!) MSWLogo, for a while, and an OOP version (objectlogo). The comp.lang.logo newsgroup still has a little bit of traffic, I sometimes drop by for old times sake! Last time I looked a version of MSWLogo had been produced for XP... > > fluent in a new language within a week. I would never send > > someone who can program on a training course for a new > > language (except for C++!) > > Why the exception for C++ ? C++ is a really tricky language. Not only is it huge but there are lots of real sneaky gotchas lurking that only long periods of painful debugging will reveal without training. The biggest problem is that C++ creates zillions of temporary objects which sometimes don't get deleted thus chewing up memory (no garbage collection). also the rules around multiple inheritance and member data access are arcane beyond telling. For example: class X { private: int foo; protected: int bar; public: int baz; } class C: public X{....} class D: protected X {...} class E: private X {...} C *c = new(C) D *d = new(D) E *e = new(E) Now tell me which attributes are visible 1) to the methods of C,D,E and 2) to the users of the instances c,d,e. And thats only single inheritance! Too much power and flexibility leads to too many permutations. > > (One such experiment was Borland's ObjectWindows - did > > anyone else ever use that?) > > Was that the one that used objects like old flowchart symbols > to design a program? I may have seen pictures of it somewhere, > but never actually saw it in person. =) That's the one. It was quite powerful with very easy database access mechanisms (but without a loop construct!) but ultimately so finnicky to use that you were a lot quicker writing code. As soon as Delphi appeared ObjectWindows died a quiet but surprisingly prolonged death Alan G. From john at fouhy.net Sun Jul 15 03:39:06 2007 From: john at fouhy.net (John Fouhy) Date: Sun, 15 Jul 2007 13:39:06 +1200 Subject: [Tutor] Platform-independent Excel reader In-Reply-To: <000301c7c4ce$e4e13520$5301a8c0@MD1918> References: <000301c7c4ce$e4e13520$5301a8c0@MD1918> Message-ID: <5e58f2e40707141839i3b010ffo60fb18fb034c54cd@mail.gmail.com> On 13/07/07, encore jane wrote: > Does anyone know about a good native Excel file reader that is platform > independent? I have had success with pyExcelerator: http://sourceforge.net/projects/pyexcelerator -- John. From dos.fool at gmail.com Sun Jul 15 05:55:22 2007 From: dos.fool at gmail.com (max baseman) Date: Sat, 14 Jul 2007 21:55:22 -0600 Subject: [Tutor] reading random line from a file Message-ID: <76A18CD7-378E-4A9A-9DB4-67AD379D368D@gmail.com> im writing a quick quote reader that spits out a random quote from a show but cant get it to pick randomly i tried a=randrange(820)+1 text.readline(a) and i would prefer not having to bring evryline into the program then picking like for line in text.readlines(): lines.append(text) ... any help would be great thanks From rabidpoobear at gmail.com Sun Jul 15 06:06:54 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 14 Jul 2007 23:06:54 -0500 Subject: [Tutor] reading random line from a file In-Reply-To: <76A18CD7-378E-4A9A-9DB4-67AD379D368D@gmail.com> References: <76A18CD7-378E-4A9A-9DB4-67AD379D368D@gmail.com> Message-ID: <46999D5E.5020509@gmail.com> max baseman wrote: > im writing a quick quote reader that spits out a random quote from a > show but cant get it to pick randomly > i tried > a=randrange(820)+1 > text.readline(a) > > and i would prefer not having to bring evryline into the program then > picking like > > for line in text.readlines(): > lines.append(text) > You don't have to read the lines in this way. Just do lines = text.readlines() directly. There's no way that you can just directly read a specific line without reading in the rest of the file, because Python doesn't know beforehand where newlines are located inside of the file. So even if this were possible, it would still read in all of the file up to and including the line you want, so that it could count the number of newlines. Why is it a problem to input it all at once? -Luke From john at fouhy.net Sun Jul 15 06:08:01 2007 From: john at fouhy.net (John Fouhy) Date: Sun, 15 Jul 2007 16:08:01 +1200 Subject: [Tutor] reading random line from a file In-Reply-To: <76A18CD7-378E-4A9A-9DB4-67AD379D368D@gmail.com> References: <76A18CD7-378E-4A9A-9DB4-67AD379D368D@gmail.com> Message-ID: <5e58f2e40707142108r6be0d476v2db94d46b7d48846@mail.gmail.com> On 15/07/07, max baseman wrote: > im writing a quick quote reader that spits out a random quote from a > show but cant get it to pick randomly > i tried > a=randrange(820)+1 > text.readline(a) > > and i would prefer not having to bring evryline into the program then > picking like The 'fortune' program in unix/linux produces random quotes from a quote file. As I understand it, it builds separate index files for each input file. I'm not sure exactly how it works, but I would guess the index files contain byte offsets for the start and end of each quote. So you would read the whole index file (which will be much shorter than the main quote file), select one at random, then use .seek() and .read() to read just the bytes you are interested in from the main file. -- John. From alan.gauld at btinternet.com Sun Jul 15 08:38:29 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 15 Jul 2007 07:38:29 +0100 Subject: [Tutor] reading random line from a file References: <76A18CD7-378E-4A9A-9DB4-67AD379D368D@gmail.com> Message-ID: "max baseman" wrote > im writing a quick quote reader that spits out a random quote from a > show but cant get it to pick randomly You can either get theclines to be the same length and use a random index to seek() to the start of the line you want. Or you can build a separate index file which records where each line starts and randomly select one of thiose. But that requires that the quotes file is only changed programmatically so that the index file can be rebuilt each time you add/delete a quote. (Or you build an indexing program) Its much easier (unless the file is huge) to just use readlines() HTH Alan G. From andreas at kostyrka.org Sun Jul 15 08:41:40 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sun, 15 Jul 2007 08:41:40 +0200 Subject: [Tutor] reading random line from a file Message-ID: Well he could implement the indexing into his program and check mtimes to decide if he needs to reindex. But yes, as long the file fits into memory, readlines (or list(file("quotes,txt")) makes more sense. Andreas -- Urspr?ngl. Mitteil. -- Betreff: Re: [Tutor] reading random line from a file Von: "Alan Gauld" Datum: 15.07.2007 06:39 "max baseman" wrote > im writing a quick quote reader that spits out a random quote from a > show but cant get it to pick randomly You can either get theclines to be the same length and use a random index to seek() to the start of the line you want. Or you can build a separate index file which records where each line starts and randomly select one of thiose. But that requires that the quotes file is only changed programmatically so that the index file can be rebuilt each time you add/delete a quote. (Or you build an indexing program) Its much easier (unless the file is huge) to just use readlines() HTH Alan G. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From rabidpoobear at gmail.com Sun Jul 15 09:00:30 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 15 Jul 2007 02:00:30 -0500 Subject: [Tutor] reading random line from a file In-Reply-To: <3E202D96-8B0C-4E39-BFA1-5E000A524B3A@gmail.com> References: <76A18CD7-378E-4A9A-9DB4-67AD379D368D@gmail.com> <46999D5E.5020509@gmail.com> <3E202D96-8B0C-4E39-BFA1-5E000A524B3A@gmail.com> Message-ID: <4699C60E.2070107@gmail.com> max baseman wrote: > cool thanks > > oh for performance eventualy i would like the file to contain many quotes Using readlines isn't exactly going to cause a performance bottleneck. I used the following code #make the file.py f = file("temp.txt","w") x = 100000 while x > 0: f.write("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n") x -= 1 f.close() #------- this creates a file with a whole lot of lines of 'a's. 100,000 lines, to be exact, and 4,200,000 bytes. In other words, this is a fair approximation for if you had, say, 25,000 quotes (since your quotes are likely to be, on average, longer than the amount of 'a's I used.) I think you'll agree that that's quite a few quotes. Now how long does it take to use readlines() on this file? #test performance.py import timeit string = "f = file('temp.txt','r');f.readlines();f.close()" temp = timeit.Timer(stmt=string) print "1000 iterations took: " + str(temp.timeit(1000)) #----- what this code does is opens, reads all the text of the file, and closes the file. We call timeit with 1000 as the argument, so it repeats this process 1000 times. The output of this program on my machine is: 1000 iterations took: 51.0771701431 In other words, if you have 25,000 quotes, you could read all of them into memory in 51.07717/1000 (approximately) or 0.05107 seconds. And I'm skeptical that you would even have that many quotes. So, like i said before, I doubt this will cause any significant performance problem in pretty much any normal situation. Also, by the way - please reply to me on-list so that others get the benefit of our conversations. -Luke From ranpra at gmail.com Sun Jul 15 09:46:37 2007 From: ranpra at gmail.com (Pradeep Kumar) Date: Sun, 15 Jul 2007 11:46:37 +0400 Subject: [Tutor] Searching Algorithm Message-ID: <76b198110707150046u7c7800c3mad6734e84d1c4500@mail.gmail.com> Hi All, I have a bulk of data in .txt, SQL Server 2000, .xls file(s) either in structured or without I want to search specific data in it. How I can. Any fastest algorithm for searching data (like google style) Pradeep -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070715/90b2351b/attachment.htm From sarliz73 at yahoo.com Sun Jul 15 19:16:51 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Sun, 15 Jul 2007 10:16:51 -0700 (PDT) Subject: [Tutor] Bundle help! In-Reply-To: <75FA1944-31FD-4E19-AD84-2129F7FB973C@wisc.edu> Message-ID: <578720.35371.qm@web35111.mail.mud.yahoo.com> Thanks to everyone for your help and quick responses! Has anyone heard of the "bundle method?" Some of you have already said you didn't. I wonder why it's included as part of my code/instructions. I'm trying to accomplish what I 'think' they want with the other questions I've posed here. Here's my instruction: ================ #SUB-TASK 1: Fix the above to print/write only the keys with >0% missing, sorted alphabetically #by the key. (No need to use the "bundle method" for that). But ALSO append the #same information to outfile2, sorted by worst offender. (Use bundle for that). ======================== Just curious, but in this link (' http://xahlee.org/perl-python/sort_list.html ') you mentioned, what does the "re" part mean? At first I thought it was the name of the list or 'return' but that's included later. *************** def myComp (x,y): import re def getNum(str): return float(re.findall(r'\d+',str)[0]) return cmp(getNum(x),getNum(y)) li.sort(myComp) print li # returns ['web7-s.jpg', 'my23i.jpg', 'fris88large.jpg', 'my283.jpg'] Thanks, Sara ********* David Perlman wrote: Maybe this reference will help: http://xahlee.org/perl-python/sort_list.html Just the first part of the discussion there. --------------------------------- We won't tell. Get more on shows you hate to love (and love to hate): Yahoo! TV's Guilty Pleasures list. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070715/3e649aaa/attachment.html From tnoyeaux at msn.com Sun Jul 15 19:47:30 2007 From: tnoyeaux at msn.com (Tony Noyeaux) Date: Sun, 15 Jul 2007 13:47:30 -0400 Subject: [Tutor] Newbie Project part 2... Message-ID: Thanks for your reply Alan. Reorganizing the data into a dictionary format, not sure i understood your structure below, but understood the need to reorg my data into dictionaries. Was wondering it would work if i created two dictionaries; One say,... results, the other questions. Reorganizing the data something like this. Using an alpha key for the results, and a numeric key for the questions. If i go to this kind of format, would i a be able to still use random code with it effectively?, as i mix and max dictionary events. random.choice .. only seemed to give me the key and not the definition... not sure how to phrase that code. The learning continues... thanks again. If this structure would lend itself to what i'm trying to do,.. will then try and rebuild the questions into the structure. questions = {"111":"Army,Navy or Air Force",\"112":"Leave the Service, Get Desk Job, Become trainer",\"113":"etc1?",\"114":"etc2?",\} results = {"aaa":"You die",\"aab":"You are wounded",\"aac":"You lose a leg",\"aad":"You lose an eye",\"aae":"You lose an arm",\"aaf":"You are awarded the bronze star",\"aag":"You are promoted to General",\"aah":"You ship sinks",\"aag":"You are busted out of the army",\"aah":"You plane is shot down",\} ---> > Message: 7> Date: Sat, 14 Jul 2007 20:38:58 +0100> From: "Alan Gauld" > Subject: Re: [Tutor] Newbie Project part 2...> To: tutor at python.org> Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1";> reply-type=original> > > "Tony Noyeaux" wrote in> ---------------------------------------------------------> import random> print "\t\t\t\tLife Simulator"> print "You have just turned 18 years old. Your life awaits,... choices > to be made.."> print "\na)Army,\nb)Navy,\nc)Airforce"> job=raw_input("What will u join?")> if job == "a":> print random.choice(["You win Silver star", "You are killed in > action"])> elif job == "b":> print random.choice(["You fall overboard", "You command you're own > battleship"])> elif job == "c":> print random.choice(["You get shot down", "You become wing > commander"])> > raw_input("\n\nPress Enter to quit.")> ----------------------------------------------------------------------> > > This works fine.> >> > I am having trouble coding in the 2nd question,.. and all subsequent > > questions.> >> > The next Question.. has to be a result of the random result.> > I suggested using a nested dictionary structure to hold the questions.> Did you try that? It should make this a relatively trivial problem.> > I'll show the structure for the example you have given so far:> > questions: {'Q':> {"""> You have just turned 18 years old.> Your life awaits,... choices to be made..> """ : ['Army', 'Navy', 'Airforce']}> {'a':> { 'Q': {#army questions here}> }> 'b':> {> 'Q': {''What kind of ship?': > ['battleship','carrier','tug']},> 'a': { # battleship questions},> 'b': { # carrier questions},> 'c': { # tug questions }> }> 'c':> { 'Q': {# airforce Q here}> }> }> > Obviously keeping the structure clear is critical to success and> a good programmers editor will help balance the braces/quotes etc> > You can extend the structure to have multiple questions at each> stage by simply putting each questoon/answer dictionary in a list.> You could also break the structure to ease layout so for example> three separate instances, one per service. You could> even encapsulate it in a class (I would!)> > You are essentially building a tree structure and then navigating> down it in a part-random, part-deterministic manner.> > -- > 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> > > End of Tutor Digest, Vol 41, Issue 56> ************************************* _________________________________________________________________ PC Magazine?s 2007 editors? choice for best web mail?award-winning Windows Live Hotmail. http://imagine-windowslive.com/hotmail/?locale=en-us&ocid=TXT_TAGHM_migration_HMWL_mini_pcmag_0707 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070715/586bf522/attachment.htm From sarliz73 at yahoo.com Sun Jul 15 19:54:52 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Sun, 15 Jul 2007 10:54:52 -0700 (PDT) Subject: [Tutor] Bundle help! In-Reply-To: <4692E83C.6020806@pennswoods.net> Message-ID: <386641.76328.qm@web35102.mail.mud.yahoo.com> Regarding my early question on bundle. Not sure if this makes any sense, but I noticed where else it's used. If this looks funny, remember that I did not write it (and therefore do not entirely understand it). I'm only editing it according to some specific guidelines. >>>for key in h.keys(): >>>bundle=(h[key]['TA9M'],key) #bundle is a tuple, (a list would also be ok) >>>if bundle[0]>0.: >>>allt.append(bundle) Thanks, Sara --------------------------------- Boardwalk for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's economy) at Yahoo! Games. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070715/9ed49ee5/attachment.html From bgailer at alum.rpi.edu Sun Jul 15 23:05:05 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 15 Jul 2007 14:05:05 -0700 Subject: [Tutor] Newbie Project part 2... In-Reply-To: References: Message-ID: <469A8C01.4040501@alum.rpi.edu> Here's a list-based alternative: tree = [ ["You have just turned 18 years old. Your life awaits,... choices to be made..", ["Army", ["win Silver star", ["reenlist", [] # next lower level... ], ["retire", [] ] ], ["killed in action", ["burial", [] ], ["cremation", [] ] ] ], ["Navy", ["fall overboard", ["sink", [], ], ["swim", [] ] ], ["command battleship", ["be a hero", [] ], ["undergo mutiny", [] ] ] ] ] ] import random print "\t\t\t\tLife Simulator" currentList = tree while True: currentList = random.choice(currentList) print currentList[0] question = "" for position, item in enumerate(currentList[1:]): question += "\n" + str(position + 1) + ") " + (item[0]) while True: try: ans = int(raw_input(question)) except KeyboardInterrupt: break except: print "Please enter a number." continue if ans < 1 or ans > len(currentList): print "Please enter a number between 1 and %s." % len(currentList) continue currentList = currentList[ans] break From bhaaluu at gmail.com Mon Jul 16 00:01:12 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Sun, 15 Jul 2007 18:01:12 -0400 Subject: [Tutor] Bundle help! In-Reply-To: <578720.35371.qm@web35111.mail.mud.yahoo.com> References: <75FA1944-31FD-4E19-AD84-2129F7FB973C@wisc.edu> <578720.35371.qm@web35111.mail.mud.yahoo.com> Message-ID: Hi! http://docs.python.org/lib/module-re.html Regular Expressions module. On 7/15/07, Sara Johnson wrote: > ======================== > > Just curious, but in this link (' > http://xahlee.org/perl-python/sort_list.html ') you > mentioned, what does the "re" part mean? At first I thought it was the name > of the list or 'return' but that's included later. > > > *************** > > def myComp (x,y): > import re > def getNum(str): return float(re.findall(r'\d+',str)[0]) > return cmp(getNum(x),getNum(y)) > > li.sort(myComp) > print li # returns ['web7-s.jpg', 'my23i.jpg', 'fris88large.jpg', > 'my283.jpg'] > > Thanks, > Sara Someone recently showed this to me: $ python >>> import re >>> dir(re) ['DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'U', 'UNICODE', 'VERBOSE', 'X', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'compile', 'engine', 'error', 'escape', 'findall', 'finditer', 'match', 'purge', 'search', 'split', 'sub', 'subn', 'template'] >>> dir(re.match) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] All those quoted things that the dir() function spit out are in the module. >>> dir(re.match.__doc__) 'Try to apply the pattern at the start of the string, returning\n a match object, or None if no match was found.' You can find all sorts of stuff like this. It's somewhat cryptic at first, but with the above documentation in hand, you can figure it out eventually. =) -- bhaaluu at gmail dot com From rondosxx at yahoo.com Mon Jul 16 00:12:15 2007 From: rondosxx at yahoo.com (ron) Date: Sun, 15 Jul 2007 15:12:15 -0700 (PDT) Subject: [Tutor] loop example from 'Learning to Program' Message-ID: <69132.92546.qm@web52504.mail.re2.yahoo.com> Here's the code and error message: ____________________________________________________________________________________ Be a PS3 game guru. Get your game face on with the latest PS3 news and previews at Yahoo! Games. http://videogames.yahoo.com/platform?platform=120121 From rabidpoobear at gmail.com Mon Jul 16 00:19:47 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 15 Jul 2007 17:19:47 -0500 Subject: [Tutor] loop example from 'Learning to Program' In-Reply-To: <69132.92546.qm@web52504.mail.re2.yahoo.com> References: <69132.92546.qm@web52504.mail.re2.yahoo.com> Message-ID: <469A9D83.7090409@gmail.com> ron wrote: > Here's the code and error message: > Where? Is it *gasp* invisdible? > > > > > ____________________________________________________________________________________ > Be a PS3 game guru. > Get your game face on with the latest PS3 news and previews at Yahoo! Games. > http://videogames.yahoo.com/platform?platform=120121 > You know, gmail doesn't have ads online and it doesn't tack these ads onto your messages. Think about it ;) -Luke From rondosxx at yahoo.com Mon Jul 16 00:20:16 2007 From: rondosxx at yahoo.com (ron) Date: Sun, 15 Jul 2007 15:20:16 -0700 (PDT) Subject: [Tutor] loop example from 'Learning to Program' Message-ID: <652731.11239.qm@web52503.mail.re2.yahoo.com> So I'm starting to work my way through Alan's online book, reading, then typing in code and seeing it work. The following is a snippet of code in the Loops section. I'm getting an error message. Here's the code and error message: myList = [1,2,3,4] for index in range(len(myList)): myList[index] += 1 print myList File "", line 3 print myList ^ SyntaxError: invalid syntax can someone tell me what the syntax error is, and how to correct it? my thanks, ron ____________________________________________________________________________________ Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase. http://farechase.yahoo.com/ From rabidpoobear at gmail.com Mon Jul 16 00:24:02 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 15 Jul 2007 17:24:02 -0500 Subject: [Tutor] loop example from 'Learning to Program' In-Reply-To: <652731.11239.qm@web52503.mail.re2.yahoo.com> References: <652731.11239.qm@web52503.mail.re2.yahoo.com> Message-ID: <469A9E82.3030400@gmail.com> ron wrote: > So I'm starting to work my way through Alan's online > book, reading, then typing in code and seeing it work. > The following is a snippet of code in the Loops > section. I'm getting an error message. > > Here's the code and error message: > > myList = [1,2,3,4] > for index in range(len(myList)): > myList[index] += 1 > print myList > > File "", line 3 > print myList > ^ > SyntaxError: invalid syntax > Did you create a new file with this in it, or did you try to type it into the interpreter? Is this exactly what you typed? > can someone tell me what the syntax error is, and how > to correct it? > There's nothing wrong with the code. Let's try to figure out what else it could be. -Luke From rondosxx at yahoo.com Mon Jul 16 00:36:40 2007 From: rondosxx at yahoo.com (ron) Date: Sun, 15 Jul 2007 15:36:40 -0700 (PDT) Subject: [Tutor] loop example from 'Learning to Program' In-Reply-To: <469A9E82.3030400@gmail.com> Message-ID: <597343.58933.qm@web52505.mail.re2.yahoo.com> ok, this code is written with vi: #/usr/bin/env python #foreach.py myList = [1,2,3,4] for index in range(len(myList)): myList[index] += 1 print myList ~ here's the result: ~$ ./foreach.py ./foreach.py: line 3: myList: command not found ./foreach.py: line 4: syntax error near unexpected token `(' ./foreach.py: line 4: `for index in range(len(myList)):' I think I liked the first result better! thanks again, ron ____________________________________________________________________________________ Park yourself in front of a world of choices in alternative vehicles. Visit the Yahoo! Auto Green Center. http://autos.yahoo.com/green_center/ From rabidpoobear at gmail.com Mon Jul 16 00:39:05 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 15 Jul 2007 17:39:05 -0500 Subject: [Tutor] loop example from 'Learning to Program' In-Reply-To: <597343.58933.qm@web52505.mail.re2.yahoo.com> References: <597343.58933.qm@web52505.mail.re2.yahoo.com> Message-ID: <469AA209.9030702@gmail.com> ron wrote: > ok, this code is written with vi: > > #/usr/bin/env python > This should be #! not just #, that makes it a regular comment. > #foreach.py > > myList = [1,2,3,4] > for index in range(len(myList)): > myList[index] += 1 > print myList > ~ > > here's the result: > > ~$ ./foreach.py > You have to run the code like this: python foreach.py So that python is executing the code instead of bash. HTH, -Luke From rondosxx at yahoo.com Mon Jul 16 00:48:29 2007 From: rondosxx at yahoo.com (ron) Date: Sun, 15 Jul 2007 15:48:29 -0700 (PDT) Subject: [Tutor] loop example from 'Learning to Program' In-Reply-To: <469AA209.9030702@gmail.com> Message-ID: <556475.20994.qm@web52503.mail.re2.yahoo.com> thanks Luke, you folks are awesome! ____________________________________________________________________________________ Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz From kent37 at tds.net Mon Jul 16 04:13:30 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 15 Jul 2007 22:13:30 -0400 Subject: [Tutor] Question about code reviews In-Reply-To: References: <20070712071434.5b04fef8@lavos> Message-ID: <469AD44A.6040901@tds.net> Tino Dai wrote: > Actually, I'm looking for two things: > > I can do stuff with python, but a) is there a better way to do it? b) > What in python don't I know that I don't know. Does that make sense? Reading other people's code is another good way to learn both of these. I found reading the printed Python Cookbook to be an excellent way to learn a lot about how Python is actually written by skilled coders. Kent From kent37 at tds.net Mon Jul 16 04:13:37 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 15 Jul 2007 22:13:37 -0400 Subject: [Tutor] Module imports In-Reply-To: <2412B4B1-5C8F-4D1C-A6E3-218240554EB1@mac.com> References: <2412B4B1-5C8F-4D1C-A6E3-218240554EB1@mac.com> Message-ID: <469AD451.8080009@tds.net> kevin parks wrote: > It was explained to me that it is fine to import random, sys and time > in both, and that only the first import uses up memory, and > subsequent attempts to import the same module don't really cost > anything and just add a reference in the namespace. but isn't loading > it in both modules confusing and bad It is actually required to import a module everywhere you want to use it. Noufal and Dave have explained that the actual loading of the module only happens once. Another thing import does is to introduce the name of the imported module into the namespace of the importing module. In order to be able to refer, for example, to sys.maxint, the sys module must be bound to the name 'sys'. That binding is done by the import statement. So if you didn't import sys in a module that used it you would get NameErrors when you tried to access attributes of the sys module. Kent From janos.juhasz at VELUX.com Mon Jul 16 13:08:01 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Mon, 16 Jul 2007 13:08:01 +0200 Subject: [Tutor] ADO problem In-Reply-To: Message-ID: Dear All, I have a good sample about using ADO to reach windows active directory. import win32com.client c = win32com.client.Dispatch("ADODB.Connection") c.Open("Provider=ADSDSOObject") rs,rc=c.Execute(""" SELECT name, description, department >From 'LDAP://DC=VELUX, DC=ORG' where objectClass='user' and name='*.ferbau' and department = 'IT' order by name """) while not rs.EOF: print rs.Fields[0].Value, rs.Fields[1].Value rs.MoveNext() It print the next result: IT (u'\xc1kos Szab\xf3',) IT (u'Szabolcs K\xe1m\xe1n',) ... So rs.Fields[1] is a tuple. I tried to turn it to get the first item from this tuple like this while not rs.EOF: print rs.Fields[0].Value, rs.Fields[1][0].Value rs.MoveNext() But it gives the next error Traceback (most recent call last): File "D:\devel\python\admin\AD_ADO.py", line 13, in ? print rs.Fields[0].Value, rs.Fields[1][0].Value File "c:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 228, in __getitem__ raise TypeError, "This object does not support enumeration" TypeError: This object does not support enumeration How can I print that unicode string? J?nos Juh?sz From mail at timgolden.me.uk Mon Jul 16 14:16:54 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 16 Jul 2007 13:16:54 +0100 Subject: [Tutor] ADO problem In-Reply-To: References: Message-ID: <469B61B6.3080309@timgolden.me.uk> J?nos Juh?sz wrote: > while not rs.EOF: > print rs.Fields[0].Value, rs.Fields[1].Value > rs.MoveNext() > > It print the next result: > IT (u'\xc1kos Szab\xf3',) > IT (u'Szabolcs K\xe1m\xe1n',) > ... > > So rs.Fields[1] is a tuple. Well, here's the most obvious thing: By the look of it: rs.Fields[1] is *not* a tuple. It's an instance of some sort. rs.Fields[1].Value *is* a tuple. So something like this: rs.Fields[1].Value[0] should work. I'm not quite clear why that second field returns a tuple while the first one doesn't. (Assuming you have reproduced the code and output faithfully). To do this specific thing, you might find it easier to use a module wrapper: http://tgolden.sc.sabren.com/python/active_directory.html where your query would become something like (untested): import active_directory for user in active_directory.search ( objectClass="User", name="*.ferbeau", department="IT" ): print user.name, user.description, user.department Hope that helps somewhat. TJG From jason.massey at gmail.com Mon Jul 16 15:05:11 2007 From: jason.massey at gmail.com (Jason Massey) Date: Mon, 16 Jul 2007 08:05:11 -0500 Subject: [Tutor] Bundle help! In-Reply-To: References: <75FA1944-31FD-4E19-AD84-2129F7FB973C@wisc.edu> <578720.35371.qm@web35111.mail.mud.yahoo.com> Message-ID: <7e3eab2c0707160605y2464d817ia954272e06b26abc@mail.gmail.com> A nice tutorial on using regular expressions in Python: http://www.amk.ca/python/howto/regex/ On 7/15/07, bhaaluu wrote: > > Hi! > > http://docs.python.org/lib/module-re.html > > Regular Expressions module. > > On 7/15/07, Sara Johnson wrote: > > ======================== > > > > Just curious, but in this link (' > > http://xahlee.org/perl-python/sort_list.html ') you > > mentioned, what does the "re" part mean? At first I thought it was the > name > > of the list or 'return' but that's included later. > > > > > > *************** > > > > def myComp (x,y): > > import re > > def getNum(str): return float(re.findall(r'\d+',str)[0]) > > return cmp(getNum(x),getNum(y)) > > > > li.sort(myComp) > > print li # returns ['web7-s.jpg', 'my23i.jpg', 'fris88large.jpg', > > 'my283.jpg'] > > > > Thanks, > > Sara > > Someone recently showed this to me: > > $ python > > >>> import re > > >>> dir(re) > > ['DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', > 'U', 'UNICODE', > 'VERBOSE', 'X', '__all__', '__builtins__', '__doc__', '__file__', > '__name__', 'compile', > 'engine', 'error', 'escape', 'findall', 'finditer', 'match', 'purge', > 'search', 'split', 'sub', > 'subn', 'template'] > > >>> dir(re.match) > > ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', > '__getattribute__', '__hash__', '__init__', '__module__', '__name__', > '__new__', > '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', > 'func_closure', > 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', > 'func_name'] > > All those quoted things that the dir() function spit out are in the > module. > > >>> dir(re.match.__doc__) > > 'Try to apply the pattern at the start of the string, returning\n > a match object, or None if no match was found.' > > You can find all sorts of stuff like this. It's somewhat cryptic at first, > but with the above documentation in hand, you can figure it out > eventually. =) > > -- > bhaaluu at gmail dot 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/20070716/fce07243/attachment.htm From taserian at gmail.com Mon Jul 16 15:26:29 2007 From: taserian at gmail.com (taserian) Date: Mon, 16 Jul 2007 09:26:29 -0400 Subject: [Tutor] How to improve In-Reply-To: <46966C23.4030300@aon.at> References: <70dbc4d40707120608k376c5a9r1d3c43811d8f6bd2@mail.gmail.com> <46966C23.4030300@aon.at> Message-ID: <70dbc4d40707160626pdde7613p6354488751b4e200@mail.gmail.com> Thank you both, Alan and Gregor. Sorry I didn't reply earlier; just a bit overwhelmed with a family situation over here. Alan, looks like I'll have to go over list comprehension as a way to initialize variables. I recall when I first started programming this, I tried wordlist = [] * 31, completely overlooking the fact that all of the list were in fact the same, and when debugging finding that my wordlist had been copied 31 times! Gregor, I like your version since you don't have to constrain the list artificially, as I did. For this problem in particular, the longest interlaced word I could find was 11 characters long, and the longer you go, the less probable it is that you'll find one. 31 seemed like a good enough value, but I'll probably change my version to look like yours. Thanks again, guys! Tony R. On 7/12/07, Gregor Lingl wrote: > > taserian schrieb: > > I've been programming for years before encountering Pythoin, but in > > much more verbose languages, and I appreciate the fact that Python is > > so terse and still accomplishes so much. Still, I have difficulty > > thinking in Python, and tend to revert to longer programs for what > > seems to be simple tasks. Sometimes it's because I'm just not aware of > > a library function, but many times it's because there's just some > > elegant way to solve my kludge. > > > > As an exercise in Python, I decided to solve a toy problem called > > "interleave". The idea is that I want to determine how many words in > > the English language are decomposable into two words by taking it > > apart one letter at a time. So the word "theorems" could be decomposed > > into "term" and "hoes" (original word = abababab, decomposed words = > > aaaa and bbbb, with all letters in the same order as in the original > > word). > > > > I'd like to see how I could improve the program below for this, and > > make it more Python-ish. > > > Hi taserian, > > I've just produced an alternative solution of your problem > (based on your ideas). The main difference is, that I use > a wordlength-dictionary. This version has the advantage, that > it doesn't make an assumption about the max word length. > I don't consider it to be an improvement, just an example > that uses different language elements of Python in some places. > Hope you enjoy it. > > ==== START > > wordlengthdict = {} > > for word in open("wordlist.txt").read().split(): > wordlengthdict.setdefault(len(word),[]).append(word) > > outfile = open('InterleaveEnglishYAWL.txt', 'w') > > for l in sorted(wordlengthdict.keys()): > print l > for w in wordlengthdict[l]: > wordtriple = (w1, w2, dummy) = w[0::2], w[1::2], w > if w1 in wordlengthdict.get(len(w1),[]) and w2 in > wordlengthdict.get(len(w2),[]): > outfile.write("(%s, %s, %s)\n" % wordtriple) > print wordtriple > > outfile.close(); > > ==== END > > Best regards, > Gregor > > > = = = = START > > > > def decompose(longword): > > word1 = longword[0::2] > > word2 = longword[1::2] > > return (word1, word2) > > > > wordlengthlist = [None] * 31 > > for i in range(0,len(wordlengthlist)): > > wordlengthlist[i] = [] > > results = [] > > > > for lineread in open("word.list"): > > for word in lineread.split(): > > if len(word)<31: > > wordlengthlist[len(word)].append(word) > > > > outfile = open('InterleaveEnglishYAWL.txt', 'w') > > > > for x in range(4, 31): > > print x > > for i in wordlengthlist[x]: > > twowords = decompose(i) > > word1 = twowords[0] > > word2 = twowords[1] > > if word1 in wordlengthlist[len(word1)] and word2 in > > wordlengthlist[len(word2)]: > > outfile.write("(" + word1 + ", " + word2 + ", " + i + ")\n") > > print (word1, word2, i) > > > > outfile.close(); > > > > = = = = END > > > > Tony R. > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > 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/20070716/0af62b1e/attachment.html From bhaaluu at gmail.com Mon Jul 16 16:28:15 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 16 Jul 2007 10:28:15 -0400 Subject: [Tutor] tutor In-Reply-To: <223412.21805.qm@web86101.mail.ukl.yahoo.com> References: <223412.21805.qm@web86101.mail.ukl.yahoo.com> Message-ID: Greetings Alan, et al, On 7/14/07, ALAN GAULD wrote: > > > What do you find challenging? I find _ALL OF IT_ [computer programming] challenging. Perhaps that is why computer programming is my hobby. If it wasn't challenging, it wouldn't hold my interest for very long. Part of my hobby is collecting used-books about computer programming. I have shelves filled with books about BASIC, Pascal, C, C++, Intel 8086 Assembly, Perl, and a smattering of others. I think I've maybe read one of them from cover to cover. Otherwise, I use them for the examples they contain. They are a library of code snippets in various languages. I have several old computers with various OSes on them, that have various old compilers and interpreters installed. What does this have to do with Python? First of all, Python is the latest 'flavor' of programming language that I'm trying to learn. One of the best things about learning Python is this list: Excerpts from: http://mail.python.org/mailman/listinfo/tutor ------------------------------------ 1. Tutor -- Discussion for learning programming with Python. 2. This [Tutor] list is for folks who want to ask questions regarding how to learn computer programming with the Python [programming] language. 3. ...[M]any feel [Python] is a good first language, because it makes it easy to express the fundamental concepts of programming such as data structures and algorithms with a syntax which many find easy to read and write. 4. Folks interested in learning about programming with Python are encouraged to join, as are folks interested in helping others learn. While the list is called tutor, anyone, whether novice or expert, can answer questions. 5. If individuals wish to start off-line conversations about a particular concept and become one-on-one tutor/tutee, that's fine. If either party wants to summarize what they learned for others to benefit, that's fine too. ----------------------------------------------- Re:#1. This is a mailing list devoted to "learning programming". Specifically, the Python language is used to learn programming. Re:#2. People who are interested in learning HOW TO program a computer may ask questions on this list. They are encouraged to ask their questions, using the Python programming language. Re:#3. Pyhton is considered a good 'first language' to learn. It doesn't have to be your first language, but if it is, it is probably a good one to start with. Why? Because the concepts of computer programming are considered by many people to be easy to grasp and express in the Python language. Re:#4. Anyone can answer other's questions, even if they are novices. The list is 'inclusive'. Anyone, no matter what their level of experience is, is invited to join and participate in the discussions. Re:#5. The discussions can take place on-list, or off-list. If they take place off-list, participants are encouraged to post a summary of what they've learned, so others can benefit from the off-list discussion. Whew! That is way cool! That probably means that you probabl;y won't hear too much "RTFM" on this list, right? =) However, one of the NICE things about Python is that there is an abundance of documentation written at every imaginable level, available online, for free (or for whatever it costs you to be online). Sometimes, "RTFM" [Read The Fine Manual] is an appropriate first answer to a question. However, just the reply, "RTFM", usually isn't enough... most experienced programmers are aware that many less experienced programmers probably aren't very familiar with the exisiting documentation yet. In fact, it is quite possible that a new user to the Tutor list is ALSO a new computer user, AND new to the Internet, who is also interested in learning how to program their new machine. (After all, the most fascinating thing about computers is: they are programmable.) So, an "RTFM" reply (if deemed appropriate as an answer to a question), is usually accompanied by a link to where The Fine Manual is located, ie. a viable URL [Web address]. A Noob, or Newbie can be Anyone! If a person continues learning throughout their lifespan, then they will always be a Noob at something. No one is born just knowing everything, automatically. However, some have been gifted with more raw intelligence than others, and they usually learn more quickly than someone who isn't as gifted. Those people are encouraged to stay on the list and help others learn Python, even as they are learning more advanced aspects of the language. So, after all that is said and done.... the question seems to be: How do we ask and answer questions on the Tutor list, so as not to be flamed? (Asbestos underwear are mighty uncomfortable!) 1. It is usually considered good Network "ettiquette" to read a FAQ [Frequently Asked Questions] about a mailing list before, or shortly after joining the mailing list. The FAQ for Tutor is located at: ____________ and is maintained by: _____________. 2. It is usually considered good mailing list "ettiquette" to either read some of the archives of the mailing list, OR, to read the daily postings of the mailing list for awhile, BEFORE posting to the list. The archives for Tutor are located here: http://mail.python.org/pipermail/tutor/ and a searchable archive of the list is located here: http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor Why? Well, for one thing, you get a "feel" for the list, and also get to know who some of the people on the list are. 3. On the Tutor list, a "good" question has at least the following information: A. Platform you're working on: a. Operating System? b. Version of Python? i. IDE? ii. other? B. State the problem you're trying to solve. C. Include some Python source code. 4. When answering a question on the Tutor list, a good answer should contain the following information: A. If deemed appropriate, OR, if "RTFM" is the knee-jerk reaction: include a viable URL (a viable URL doesn't get a 404) to the reference you are recommending. a. If the page you are recommending is huge, give enough info for the person to find the information in the web page. B. Avoid the overuse of acronyms, unless you explain what the acronym stands for, somewhere in the answer. C. Verbose answers are ususally better than terse answers. 5. Encourage people to solve their own programming problem. This is part of the "learning computer programming" nature of the list. =) What else? I'm sure there is way more. I'm still looking for a Python Programming Summer Camp in my area. 8^D -- bhaaluu at gmail dot com From zmachinez at gmail.com Mon Jul 16 17:25:14 2007 From: zmachinez at gmail.com (z machinez) Date: Mon, 16 Jul 2007 11:25:14 -0400 Subject: [Tutor] Basic DB question Message-ID: Hi All, I am just starting out with Python and was hoping someone could point me in the direction of reading materials for working with RDBMS? In particular, I am working with two various relational databases. One of which stores real-time data for trading. In Python I am planning on building various time series models to collate historical tick data and real-time data. As I am very new to Python, I was hoping someone could recommend some docs/books. I have read up on the DBAPI, but do not think this is what I need. I might be wrong though. Thanks in advance for the help. Z. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070716/55b720a1/attachment.htm From carroll at tjc.com Mon Jul 16 18:03:25 2007 From: carroll at tjc.com (Terry Carroll) Date: Mon, 16 Jul 2007 09:03:25 -0700 (PDT) Subject: [Tutor] eyeD3 module installation on XP In-Reply-To: <7d81675b0707130745h5017b76bgb43f50a23548c7f3@mail.gmail.com> Message-ID: On Fri, 13 Jul 2007, Richard Querin wrote: > Any pointers on how to go about installing this module? There's a file > called 'setup.py.in' as well. Not sure what that does.. Richard; I'm stumped. Can you try version 0.6.10? See why below. I'm using eyeD3-0.6.10, so I know it's possible to install on XP. I took your question as an opportunity to upgrade to eyeD3-0.6.14, planning to write down how I did it an respond to your message. No joy. I think the appropriate sequence is config / setup build / setup install ; But I can't get it working. (BTW, I have Cygwin installed, which is where I get my "sh" command). When I did the "sh configure", I got: F:\installs\Python\eyed3\eyeD3-0.6.14>sh configure checking whether make sets $(MAKE)... yes checking for python... /cygdrive/c/Python25//python checking if /cygdrive/c/Python25//python is version 2.3 or greater... yes configure: creating ./config.status config.status: creating Makefile config.status: WARNING: Makefile.in seems to ignore the --datarootdir setting config.status: creating setup.py config.status: error: cannot find input file: etc/eyeD3.spec.in I think that warning and error are fatal to the install. When I try to setup build, I get: F:\installs\Python\eyed3\eyeD3-0.6.14>python setup.py build running build running build_py error: package directory 'src\eyeD3' does not exist So, bottom line, I think the warning message: Makefile.in seems to ignore the --datarootdir setting is the key. I just retried the configure in the .10 version and did *not* get this error: F:\installs\Python\eyed3\eyeD3-0.6.10>sh configure checking whether make sets $(MAKE)... yes checking for python... /cygdrive/c/Python25//python checking if /cygdrive/c/Python25//python is version 2.3 or greater... yes configure: creating ./config.status config.status: creating Makefile config.status: creating setup.py config.status: creating etc/eyeD3.spec config.status: creating src/eyeD3/__init__.py config.status: creating doc/eyeD3.1 You might want to try downloading .10 instead of the current release and see if that works for you. See http://eyed3.nicfit.net/releases/ Sorry I can't help more. From andreas at kostyrka.org Mon Jul 16 18:11:40 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 16 Jul 2007 18:11:40 +0200 Subject: [Tutor] Basic DB question In-Reply-To: References: Message-ID: <469B98BC.5090708@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 DBAPI is an interface standard describing what you can expect in a database access module, like psycopg. Andreas z machinez wrote: > Hi All, > > I am just starting out with Python and was hoping someone could point me > in the direction of reading materials for working with RDBMS? In > particular, I am working with two various relational databases. One of > which stores real-time data for trading. In Python I am planning on > building various time series models to collate historical tick data and > real-time data. As I am very new to Python, I was hoping someone could > recommend some docs/books. > > I have read up on the DBAPI, but do not think this is what I need. I > might be wrong though. > > Thanks in advance for the help. > > Z. > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGm5i8HJdudm4KnO0RAgxtAKDLosrBW+t1pRHdo9EBH+V8TreSwQCg6A9a oNXWmoAk25u7GxiiVeO4YdU= =D7JY -----END PGP SIGNATURE----- From D3IBZ at hotmail.com Mon Jul 16 18:38:29 2007 From: D3IBZ at hotmail.com (Darren Williams) Date: Mon, 16 Jul 2007 12:38:29 -0400 Subject: [Tutor] CGI Calculator Message-ID: Hi all, I am a Python convert coming from a JavaScript background (as you can probably tell) and am currently writing my first application using Python which will be a calculator for an online game I used to play (thought it would be a decent first project) but am not sure on the syntax for referencing an HTML form input field, I tried this (which returns an error) - XHTML form - DopeWars Junkie Calculator

Coat Size:

Used Pockets:

Lab Space:

Total Junkies:

Dealer Visits Remaining:

junkieCalc.py - #!/usr/bin/env python import cgi def main(): print "Content-type: text/html\n" form = cgi.FieldStorage() if form.has_key("coatSize") and form.has_key("usedPockets") and form.has_key("labSpace") and form.has_key("totalJunkies") and form.has_key("DVR") and form["coatSize"].value != "" and form["usedPockets"].value != "" and form["labSpace"].value != "" and form["totalJunkies"].value != "" and form["DVR"].value != "": Tokens = 0 while usedPockets > (totalJunkies - labSpace) * 17: Tokens = Tokens + 1 usedPockets = (usedPockets - totalJunkies + labSpace) * 17 totalJunkies = totalJunkies + 1 print "Tokens" else: print "Try again" main() This is the error i'm getting - Traceback (most recent call last): File "D:\inetpub\vhosts\newspyn.com\cgi-bin\JunkieCalc.py", line 23, in ? main() File "D:\inetpub\vhosts\newspyn.com\cgi-bin\JunkieCalc.py", line 10, in main while usedPockets > (totalJunkies - labSpace) * 17: UnboundLocalError: local variable 'usedPockets' referenced before assignment Thanks in advance for any help :) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070716/990edd43/attachment.html From brunson at brunson.com Mon Jul 16 18:50:19 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 16 Jul 2007 10:50:19 -0600 Subject: [Tutor] CGI Calculator In-Reply-To: References: Message-ID: <469BA1CB.6020204@brunson.com> Darren Williams wrote: > Hi all, > > I am a Python convert coming from a JavaScript background Welcome to Python, Darren. > (as you can probably tell) and am currently writing my first > application using Python which will be a calculator for an online game > I used to play (thought it would be a decent first project) but am not > sure on the syntax for referencing an HTML form input field, I tried > this (which returns an error) - > > XHTML form - > > > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> > > > DopeWars Junkie Calculator > > >
>
>

Coat Size: >

Used Pockets: >

Lab Space: >

Total Junkies: name="totalJunkies"> >

Dealer Visits Remaining: name="DVR"> >

>

> > > > junkieCalc.py - > > #!/usr/bin/env python > > import cgi > > def main(): > print "Content-type: text/html\n" > form = cgi.FieldStorage() > if form.has_key("coatSize") and form.has_key("usedPockets") and > form.has_key("labSpace") and form.has_key("totalJunkies") and > form.has_key("DVR") and form["coatSize"].value != "" and > form["usedPockets"].value != "" and form["labSpace"].value != "" and > form["totalJunkies"].value != "" and form["DVR"].value != "": > Tokens = 0 > while usedPockets > (totalJunkies - labSpace) * 17: > Tokens = Tokens + 1 > usedPockets = (usedPockets - totalJunkies + labSpace) * 17 > totalJunkies = totalJunkies + 1 > print "Tokens" > else: > print "Try again" > > main() > > This is the error i'm getting - > > Traceback (most recent call last): File > "D:\inetpub\vhosts\newspyn.com\cgi-bin\JunkieCalc.py", line 23, in ? > main() File "D:\inetpub\vhosts\newspyn.com\cgi-bin\JunkieCalc.py", > line 10, in main while usedPockets > (totalJunkies - labSpace) * 17: > UnboundLocalError: local variable 'usedPockets' referenced before > assignment So, you get an error on line 10, which is: while usedPockets > (totalJunkies - labSpace) * 17: and it says that your variable is referenced before assignment. Have you assigned a value to it? In your intro you ask how to reference an HTML form field, well you're already doing it in your if statement: form["labSpace"].value, so if you want a local variable named usedPockets, you should assign a value to it, like: usedPockets = form["usedPockets"].value As an aside, a nice tool for helping debug CGI scripts is the CGI Traceback module. Add this as the first line of the program (after the shebang line, before the import cgi: import cgitb; cgitb.enable() Hope that helps, e. > > Thanks in advance for any help :) > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rfquerin at gmail.com Mon Jul 16 19:00:25 2007 From: rfquerin at gmail.com (Richard Querin) Date: Mon, 16 Jul 2007 13:00:25 -0400 Subject: [Tutor] eyeD3 module installation on XP In-Reply-To: References: <7d81675b0707130745h5017b76bgb43f50a23548c7f3@mail.gmail.com> Message-ID: <7d81675b0707161000w13f15cbax77d33b3c84a5d3c2@mail.gmail.com> Sorry Tino, Missed your response completely. Your advice on using cygwin was spot-on. I hadn't thought of using that. Per my response to Terry, I've got the .10 version up and running now. Thanks. RQ From rfquerin at gmail.com Mon Jul 16 19:01:12 2007 From: rfquerin at gmail.com (Richard Querin) Date: Mon, 16 Jul 2007 13:01:12 -0400 Subject: [Tutor] Fwd: eyeD3 module installation on XP In-Reply-To: <7d81675b0707160958y752823a7o31c06f6b96949585@mail.gmail.com> References: <7d81675b0707130745h5017b76bgb43f50a23548c7f3@mail.gmail.com> <7d81675b0707160958y752823a7o31c06f6b96949585@mail.gmail.com> Message-ID: <7d81675b0707161001o177736a2r148dd36d1762e8b@mail.gmail.com> On 7/16/07, Terry Carroll wrote: > You might want to try downloading .10 instead of the current release and > see if that works for you. See http://eyed3.nicfit.net/releases/ > > Sorry I can't help more. Nope. That's fine. Based on your response I was able to upgrade my Cygwin (didn't have the make utility installed) and then was able to download the .10 version and it's installed and working here right now. Awesome. I won't be doing much coding here at work but I like to dabble now and then ;). I'll (hopefully) be able to install the .deb package without problem on my ubuntu box at home. Thanks a lot. RQ From D3IBZ at hotmail.com Mon Jul 16 19:52:46 2007 From: D3IBZ at hotmail.com (Darren Williams) Date: Mon, 16 Jul 2007 13:52:46 -0400 Subject: [Tutor] CGI Calculator References: <469BA1CB.6020204@brunson.com> Message-ID: Ok, now i've modified my script but am getting another error, i've commented a few useless (hopefully) lines out - #!/usr/bin/env python import cgitb; cgitb.enable() import cgi def main(): print "Content-type: text/html\n" form = cgi.FieldStorage() # if form.has_key("coatSize") and form.has_key("usedPockets") and form.has_key("labSpace") and form.has_key("totalJunkies") and form.has_key("DVR") and form["coatSize"].value != "" and form["usedPockets"].value != "" and form["labSpace"].value != "" and form["totalJunkies"].value != "" and form["DVR"].value != "": Tokens = 0 coatSize = form["coatSize"].value usedPockets = form["usedPockets"].value labSpace = form["labSpace"].value totalJunkies = form["totalJunkies"].value DVR = form["DVR"].value while usedPockets > totalJunkies - labSpace * 17: Tokens = Tokens + 1 usedPockets = (usedPockets - totalJunkies + labSpace) * 17 totalJunkies = totalJunkies + 1 print "Tokens" # else: # print "Try again" main() Here's the error using the CGI Traceback Module - D:\inetpub\vhosts\newspyn.com\cgi-bin\JunkieCalc.py 21 print "Tokens" 22 # else: 23 # print "Try again... beeyatch" 24 25 main() main = D:\inetpub\vhosts\newspyn.com\cgi-bin\JunkieCalc.py in main() 15 DVR = form["DVR"].value 16 17 while usedPockets > totalJunkies - labSpace * 17: 18 Tokens = Tokens + 1 19 usedPockets = (usedPockets - totalJunkies + labSpace) * 17 usedPockets = '192000', totalJunkies = '200', labSpace = '0' TypeError: unsupported operand type(s) for -: 'str' and 'str' args = ("unsupported operand type(s) for -: 'str' and 'str'",) It's confused me - it says I can't subtract a string from a string but then gives the value's of the variables (that I randomly entered into the form) at the bottom - usedPockets = '192000', totalJunkies = '200', labSpace = '0' Thanks in advance for any help :) ----- Original Message ----- From: "Eric Brunson" To: "Darren Williams" Cc: Sent: Monday, July 16, 2007 12:50 PM Subject: Re: [Tutor] CGI Calculator > Darren Williams wrote: >> Hi all, >> I am a Python convert coming from a JavaScript background > > Welcome to Python, Darren. > >> (as you can probably tell) and am currently writing my first application >> using Python which will be a calculator for an online game I used to play >> (thought it would be a decent first project) but am not sure on the >> syntax for referencing an HTML form input field, I tried this (which >> returns an error) - >> XHTML form - >> >> > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> >> >> >> DopeWars Junkie Calculator >> >> >>
>>
> action="http://newspyn.com/cgi-bin/JunkieCalc.py"> >>

Coat Size: >>

Used Pockets: > name="usedPockets"> >>

Lab Space: >>

Total Junkies: > name="totalJunkies"> >>

Dealer Visits Remaining: > name="DVR"> >>

>>

>> >> >> junkieCalc.py - >> #!/usr/bin/env python >> import cgi >> def main(): >> print "Content-type: text/html\n" >> form = cgi.FieldStorage() >> if form.has_key("coatSize") and form.has_key("usedPockets") and >> form.has_key("labSpace") and form.has_key("totalJunkies") and >> form.has_key("DVR") and form["coatSize"].value != "" and >> form["usedPockets"].value != "" and form["labSpace"].value != "" and >> form["totalJunkies"].value != "" and form["DVR"].value != "": >> Tokens = 0 >> while usedPockets > (totalJunkies - labSpace) * 17: >> Tokens = Tokens + 1 >> usedPockets = (usedPockets - totalJunkies + labSpace) * 17 >> totalJunkies = totalJunkies + 1 >> print "Tokens" >> else: >> print "Try again" >> main() >> This is the error i'm getting - >> Traceback (most recent call last): File >> "D:\inetpub\vhosts\newspyn.com\cgi-bin\JunkieCalc.py", line 23, in ? >> main() File "D:\inetpub\vhosts\newspyn.com\cgi-bin\JunkieCalc.py", line >> 10, in main while usedPockets > (totalJunkies - labSpace) * 17: >> UnboundLocalError: local variable 'usedPockets' referenced before >> assignment > > So, you get an error on line 10, which is: > > while usedPockets > (totalJunkies - labSpace) * 17: > > and it says that your variable is referenced before assignment. Have you > assigned a value to it? In your intro you ask how to reference an HTML > form field, well you're already doing it in your if statement: > form["labSpace"].value, so if you want a local variable named usedPockets, > you should assign a value to it, like: usedPockets = > form["usedPockets"].value > > > As an aside, a nice tool for helping debug CGI scripts is the CGI > Traceback module. Add this as the first line of the program (after the > shebang line, before the import cgi: > > import cgitb; cgitb.enable() > > Hope that helps, > e. > >> Thanks in advance for any help :) >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > From brunson at brunson.com Mon Jul 16 20:01:32 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 16 Jul 2007 12:01:32 -0600 Subject: [Tutor] CGI Calculator In-Reply-To: References: <469BA1CB.6020204@brunson.com> Message-ID: <469BB27C.3000402@brunson.com> Darren Williams wrote: > Ok, now i've modified my script but am getting another error, i've > commented a few useless (hopefully) lines out - > > #!/usr/bin/env python > > import cgitb; cgitb.enable() > import cgi > > [snip] > 17 while usedPockets > totalJunkies - labSpace * 17: > > 18 Tokens = Tokens + 1 > > 19 usedPockets = (usedPockets - totalJunkies + > labSpace) * 17 > > usedPockets = '192000', totalJunkies = '200', labSpace = '0' > > TypeError: unsupported operand type(s) for -: 'str' and 'str' > args = ("unsupported operand type(s) for -: 'str' and 'str'",) > What does "dog" - "cat" mean? Similarly, what does "100" - "12" mean? It's not the same in Python as 100 - 12, because those are numbers, "100" and "12" are strings which happen to represent numbers. You need to coerce those strings into integers, maybe like this: usedPockets = int(form["usedPockets"].value) When you do that, you'll probably need to catch any exception that could occur if the string can't be converted. > > > It's confused me - it says I can't subtract a string from a string but > then gives the value's of the variables (that I randomly entered into > the form) at the bottom - usedPockets = '192000', totalJunkies = > '200', labSpace = '0' > From D3IBZ at hotmail.com Mon Jul 16 20:39:46 2007 From: D3IBZ at hotmail.com (Darren Williams) Date: Mon, 16 Jul 2007 14:39:46 -0400 Subject: [Tutor] CGI Calculator References: <469BA1CB.6020204@brunson.com> <469BB27C.3000402@brunson.com> Message-ID: Now another problem - the script is just printing the word 'Tokens' over and over again, it's supposed to work like this (JavaScript version made by me) - http://nazkyn.brinkster.net/1.8.html Thanks in advance for any help :) ----- Original Message ----- From: "Eric Brunson" To: "Darren Williams" Cc: Sent: Monday, July 16, 2007 2:01 PM Subject: Re: [Tutor] CGI Calculator > Darren Williams wrote: >> Ok, now i've modified my script but am getting another error, i've >> commented a few useless (hopefully) lines out - >> >> #!/usr/bin/env python >> >> import cgitb; cgitb.enable() >> import cgi >> >> > [snip] >> 17 while usedPockets > totalJunkies - labSpace * 17: >> >> 18 Tokens = Tokens + 1 >> >> 19 usedPockets = (usedPockets - totalJunkies + labSpace) >> * 17 >> >> usedPockets = '192000', totalJunkies = '200', labSpace = '0' >> >> TypeError: unsupported operand type(s) for -: 'str' and 'str' >> args = ("unsupported operand type(s) for -: 'str' and 'str'",) >> > > What does "dog" - "cat" mean? Similarly, what does "100" - "12" mean? > It's not the same in Python as 100 - 12, because those are numbers, "100" > and "12" are strings which happen to represent numbers. > > You need to coerce those strings into integers, maybe like this: > > usedPockets = int(form["usedPockets"].value) > > When you do that, you'll probably need to catch any exception that could > occur if the string can't be converted. > >> >> >> It's confused me - it says I can't subtract a string from a string but >> then gives the value's of the variables (that I randomly entered into the >> form) at the bottom - usedPockets = '192000', totalJunkies = '200', >> labSpace = '0' >> > > From brunson at brunson.com Mon Jul 16 20:48:24 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 16 Jul 2007 12:48:24 -0600 Subject: [Tutor] CGI Calculator In-Reply-To: References: <469BA1CB.6020204@brunson.com> <469BB27C.3000402@brunson.com> Message-ID: <469BBD78.1080608@brunson.com> Darren Williams wrote: > Now another problem - the script is just printing the word 'Tokens' > over and over again, it's supposed to work like this (JavaScript > version made by me) - http://nazkyn.brinkster.net/1.8.html > > Thanks in advance for any help :) It's doing exactly what you've told it to do: while usedPockets > totalJunkies - labSpace * 17: Tokens = Tokens + 1 usedPockets = (usedPockets - totalJunkies + labSpace) * 17 totalJunkies = totalJunkies + 1 print "Tokens" The print statement is inside the while loop and you've quoted the work "Tokens" so it's printing the string rather than the variable. How about grabbing a short tutorial on Python and reading through it to better understand the differences between Python and Javascript. If you're an experienced JS programmer it shouldn't take very long. This is probably closer is what I infer you're looking for: while usedPockets > totalJunkies - labSpace * 17: Tokens = Tokens + 1 usedPockets = (usedPockets - totalJunkies + labSpace) * 17 totalJunkies = totalJunkies + 1 print "Tokens: %s" % Tokens e. > > ----- Original Message ----- From: "Eric Brunson" > To: "Darren Williams" > Cc: > Sent: Monday, July 16, 2007 2:01 PM > Subject: Re: [Tutor] CGI Calculator > > >> Darren Williams wrote: >>> Ok, now i've modified my script but am getting another error, i've >>> commented a few useless (hopefully) lines out - >>> >>> #!/usr/bin/env python >>> >>> import cgitb; cgitb.enable() >>> import cgi >>> >>> >> [snip] >>> 17 while usedPockets > totalJunkies - labSpace * 17: >>> >>> 18 Tokens = Tokens + 1 >>> >>> 19 usedPockets = (usedPockets - totalJunkies + >>> labSpace) * 17 >>> >>> usedPockets = '192000', totalJunkies = '200', labSpace = '0' >>> >>> TypeError: unsupported operand type(s) for -: 'str' and 'str' >>> args = ("unsupported operand type(s) for -: 'str' and 'str'",) >>> >> >> What does "dog" - "cat" mean? Similarly, what does "100" - "12" >> mean? It's not the same in Python as 100 - 12, because those are >> numbers, "100" and "12" are strings which happen to represent numbers. >> >> You need to coerce those strings into integers, maybe like this: >> >> usedPockets = int(form["usedPockets"].value) >> >> When you do that, you'll probably need to catch any exception that >> could occur if the string can't be converted. >> >>> >>> >>> It's confused me - it says I can't subtract a string from a string >>> but then gives the value's of the variables (that I randomly entered >>> into the form) at the bottom - usedPockets = '192000', totalJunkies >>> = '200', labSpace = '0' >>> >> >> > From D3IBZ at hotmail.com Mon Jul 16 21:48:16 2007 From: D3IBZ at hotmail.com (Darren Williams) Date: Mon, 16 Jul 2007 15:48:16 -0400 Subject: [Tutor] CGI Calculator References: <469BA1CB.6020204@brunson.com> <469BB27C.3000402@brunson.com> <469BBD78.1080608@brunson.com> Message-ID: That's just printing Tokens: 1 Tokens: 2 ... Tokens: 6000 etc... Can you recommend any tutorials for me? ----- Original Message ----- From: "Eric Brunson" To: "Darren Williams" Cc: Sent: Monday, July 16, 2007 2:48 PM Subject: Re: [Tutor] CGI Calculator > Darren Williams wrote: >> Now another problem - the script is just printing the word 'Tokens' >> over and over again, it's supposed to work like this (JavaScript >> version made by me) - http://nazkyn.brinkster.net/1.8.html >> >> Thanks in advance for any help :) > > It's doing exactly what you've told it to do: > > while usedPockets > totalJunkies - labSpace * 17: > Tokens = Tokens + 1 > usedPockets = (usedPockets - totalJunkies + labSpace) * 17 > totalJunkies = totalJunkies + 1 > print "Tokens" > > The print statement is inside the while loop and you've quoted the work > "Tokens" so it's printing the string rather than the variable. > > How about grabbing a short tutorial on Python and reading through it to > better understand the differences between Python and Javascript. If > you're an experienced JS programmer it shouldn't take very long. > > This is probably closer is what I infer you're looking for: > > while usedPockets > totalJunkies - labSpace * 17: > Tokens = Tokens + 1 > usedPockets = (usedPockets - totalJunkies + labSpace) * 17 > totalJunkies = totalJunkies + 1 > print "Tokens: %s" % Tokens > > e. > >> >> ----- Original Message ----- From: "Eric Brunson" >> To: "Darren Williams" >> Cc: >> Sent: Monday, July 16, 2007 2:01 PM >> Subject: Re: [Tutor] CGI Calculator >> >> >>> Darren Williams wrote: >>>> Ok, now i've modified my script but am getting another error, i've >>>> commented a few useless (hopefully) lines out - >>>> >>>> #!/usr/bin/env python >>>> >>>> import cgitb; cgitb.enable() >>>> import cgi >>>> >>>> >>> [snip] >>>> 17 while usedPockets > totalJunkies - labSpace * 17: >>>> >>>> 18 Tokens = Tokens + 1 >>>> >>>> 19 usedPockets = (usedPockets - totalJunkies + >>>> labSpace) * 17 >>>> >>>> usedPockets = '192000', totalJunkies = '200', labSpace = '0' >>>> >>>> TypeError: unsupported operand type(s) for -: 'str' and 'str' >>>> args = ("unsupported operand type(s) for -: 'str' and 'str'",) >>>> >>> >>> What does "dog" - "cat" mean? Similarly, what does "100" - "12" >>> mean? It's not the same in Python as 100 - 12, because those are >>> numbers, "100" and "12" are strings which happen to represent numbers. >>> >>> You need to coerce those strings into integers, maybe like this: >>> >>> usedPockets = int(form["usedPockets"].value) >>> >>> When you do that, you'll probably need to catch any exception that >>> could occur if the string can't be converted. >>> >>>> >>>> >>>> It's confused me - it says I can't subtract a string from a string >>>> but then gives the value's of the variables (that I randomly entered >>>> into the form) at the bottom - usedPockets = '192000', totalJunkies >>>> = '200', labSpace = '0' >>>> >>> >>> >> > > From keridee at jayco.net Mon Jul 16 11:08:31 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 16 Jul 2007 04:08:31 -0500 Subject: [Tutor] curses Message-ID: <00ab01c7c788$e5295780$0ffce004@JSLAPTOP> curses does not run on my Windows XP computer. Is this supposed to be a Linux only module? Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\curses\__init__.py", line 15, in from _curses import * ImportError: No module named _curses JS From tinoloc at gmail.com Mon Jul 16 22:12:54 2007 From: tinoloc at gmail.com (Tino Dai) Date: Mon, 16 Jul 2007 16:12:54 -0400 Subject: [Tutor] curses In-Reply-To: <00ab01c7c788$e5295780$0ffce004@JSLAPTOP> References: <00ab01c7c788$e5295780$0ffce004@JSLAPTOP> Message-ID: On 7/16/07, Tiger12506 wrote: > > curses does not run on my Windows XP computer. > Is this supposed to be a Linux only module? > > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\curses\__init__.py", line 15, in > from _curses import * > ImportError: No module named _curses That and cygwin. -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070716/b29d2b61/attachment.htm From rabidpoobear at gmail.com Mon Jul 16 22:22:38 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 16 Jul 2007 15:22:38 -0500 Subject: [Tutor] curses In-Reply-To: References: <00ab01c7c788$e5295780$0ffce004@JSLAPTOP> Message-ID: <469BD38E.7010807@gmail.com> Tino Dai wrote: > > > On 7/16/07, *Tiger12506* > wrote: > > curses does not run on my Windows XP computer. > Is this supposed to be a Linux only module? > > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\curses\__init__.py", line 15, in > from _curses import * > ImportError: No module named _curses > > > That and cygwin. > > -Tino There's a Console module that you can use to do the same thing at a DOS prompt in windows, but that's not cross-platform either. -Luke From bhaaluu at gmail.com Mon Jul 16 22:54:58 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 16 Jul 2007 16:54:58 -0400 Subject: [Tutor] curses In-Reply-To: <00ab01c7c788$e5295780$0ffce004@JSLAPTOP> References: <00ab01c7c788$e5295780$0ffce004@JSLAPTOP> Message-ID: On 7/16/07, Tiger12506 wrote: > curses does not run on my Windows XP computer. > Is this supposed to be a Linux only module? > > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\curses\__init__.py", line 15, in > from _curses import * > ImportError: No module named _curses > > JS There IS a way to try Linux, Python, and curses WITHOUT installing anything to the hard-drive of your MSWindowsXP computer, and that is to download a Linux LiveCD ISO image, and make a bootable CD from that image. Your computer BIOS should be setup to boot from a CD. Put the LiveCD in the CD drive, and reboot. The LiveCD runs in RAM, so you need at LEAST 128MB RAM to run it (for good results). Since it runs in RAM, nothing touches the HD. When you are finished, simply Shutdown the computer, take out the CD, and reboot into MSWindowsXP. Warning: there are over 200 Linux LiveCDs to choose from! Not all of them are designed for developers, so they may or may not have Python installed by default. One easy-to-use general-purpose Linux LiveCD is called SimplyMEPIS. You can find a download mirror here: http://www.mepis.org/mirrors You should have a fast connection to download this ISO image. The SimplyMEPIS LiveCD is about 700MB in size! Python is already installed, as well as the curses module. This is a general-purpose desktop OS that runs the K Desktop Environment (KDE), and has all sorts of interpreters and compilers on it besides Python. It has a 75% 'Ubuntu' core with a 25% MEPIS wrapper that makes things work out of the box. A Linux LiveCD can be carried with you, and used on remote computers without having to install anything on the remote computer. So you can have Python with you, wherever you go. =) -- bhaaluu at gmail dot com From janos.juhasz at VELUX.com Mon Jul 16 23:24:37 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Mon, 16 Jul 2007 23:24:37 +0200 Subject: [Tutor] ADO problem In-Reply-To: Message-ID: Hi Tim, thanks your help. It is clear for me now. > From: Tim Golden > Subject: Re: [Tutor] ADO problem > J?nos Juh?sz wrote: > > while not rs.EOF: > > print rs.Fields[0].Value, rs.Fields[1].Value > > rs.MoveNext() > > > > It print the next result: > > IT (u'\xc1kos Szab\xf3',) > > IT (u'Szabolcs K\xe1m\xe1n',) > > ... > > > > So rs.Fields[1] is a tuple. > Well, here's the most obvious thing: > By the look of it: rs.Fields[1] is *not* a tuple. > It's an instance of some sort. rs.Fields[1].Value > *is* a tuple. So something like this: > rs.Fields[1].Value[0] > should work. I'm not quite clear why that second > field returns a tuple while the first one doesn't. Yes, It works. So, I have to use rs.Fields[1].Value[0] instead of rs.Fields[1][0].Value > To do this specific thing, you might find it easier > to use a module wrapper: > http://tgolden.sc.sabren.com/python/active_directory.html > where your query would become something like (untested): Your module works perfectly. You should know something about the recordsets :) > > import active_directory > for user in active_directory.search ( > objectClass="User", > name="*.ferbeau", > department="IT" > ): > print user.name, user.description, user.department > > Regards, Janos From rabidpoobear at gmail.com Mon Jul 16 23:33:49 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 16 Jul 2007 16:33:49 -0500 Subject: [Tutor] curses In-Reply-To: References: <00ab01c7c788$e5295780$0ffce004@JSLAPTOP> Message-ID: <469BE43D.5@gmail.com> Hey bhaaluu - I've enjoyed your posts to the list so far. They're very informative and well-written. -Luke bhaaluu wrote: > On 7/16/07, Tiger12506 wrote: > >> curses does not run on my Windows XP computer. >> Is this supposed to be a Linux only module? >> >> Traceback (most recent call last): >> File "", line 1, in >> File "C:\Python25\lib\curses\__init__.py", line 15, in >> from _curses import * >> ImportError: No module named _curses >> >> JS >> > > There IS a way to try Linux, Python, and curses WITHOUT > installing anything to the hard-drive of your MSWindowsXP > computer, and that is to download a Linux LiveCD ISO image, > and make a bootable CD from that image. Your computer > BIOS should be setup to boot from a CD. Put the LiveCD in > the CD drive, and reboot. The LiveCD runs in RAM, so you > need at LEAST 128MB RAM to run it (for good results). > Since it runs in RAM, nothing touches the HD. When you > are finished, simply Shutdown the computer, take out the CD, > and reboot into MSWindowsXP. > > Warning: there are over 200 Linux LiveCDs to choose from! > Not all of them are designed for developers, so they may > or may not have Python installed by default. One easy-to-use > general-purpose Linux LiveCD is called SimplyMEPIS. > You can find a download mirror here: > http://www.mepis.org/mirrors > You should have a fast connection to download this ISO image. > The SimplyMEPIS LiveCD is about 700MB in size! > > Python is already installed, as well as the curses module. > > This is a general-purpose desktop OS that runs the K Desktop > Environment (KDE), and has all sorts of interpreters and compilers > on it besides Python. It has a 75% 'Ubuntu' core with a 25% MEPIS > wrapper that makes things work out of the box. > > A Linux LiveCD can be carried with you, and used on remote > computers without having to install anything on the remote computer. > So you can have Python with you, wherever you go. =) > From kent37 at tds.net Mon Jul 16 23:39:14 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 Jul 2007 17:39:14 -0400 Subject: [Tutor] Here is newbie doc on how to implement generators In-Reply-To: <5e58f2e40707121739m6422fb0fib6ad685a9d1364b0@mail.gmail.com> References: <20070712232608.GA59300@cutter.rexx.com> <5e58f2e40707121739m6422fb0fib6ad685a9d1364b0@mail.gmail.com> Message-ID: <469BE582.5090107@tds.net> John Fouhy wrote: > def walkTree(tree): > # stack to hold nodes as we walk through > stack = [] > stack.append(tree) > > while stack: > value, children = stack.pop() > for child in reversed(children): # reverse children to get > the right order. > stack.append(child) FWIW this could be written as stack.extend(reversed(children)) Kent From kent37 at tds.net Mon Jul 16 23:45:42 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 Jul 2007 17:45:42 -0400 Subject: [Tutor] Here is newbie doc on how to implement generators In-Reply-To: <20070713184657.GA22487@cutter.rexx.com> References: <20070712232608.GA59300@cutter.rexx.com> <5e58f2e40707121739m6422fb0fib6ad685a9d1364b0@mail.gmail.com> <20070713184657.GA22487@cutter.rexx.com> Message-ID: <469BE706.5000109@tds.net> Dave Kuhlman wrote: > On Fri, Jul 13, 2007 at 12:39:40PM +1200, John Fouhy wrote: >> On 13/07/07, Dave Kuhlman wrote: >>> And, I have a question -- If you look at the example of the >>> iterative (non-recursive) generator (the Doubler class), you will >>> see that it walks a list, not a tree. That's because I was *not* >>> able to figure out how to implement a non-recursive tree walk >>> generator. >> You should just be able to use a stack -- push the children onto a >> stack, then pop them off and walk through them. >> >> Here's an example, using tuples and lists as a basic tree data type: >> >> ####### treetest.py ######### >> >> TREE = (0, [(1, [(2, [(3, []), >> (4, []), >> (5, [(6, []), >> (7, []), >> (8, []), >> (9, []), >> ]), >> (10, [(11, []), >> (12, []), >> ]), >> ]), >> (13, [(14, []), >> (15, []), >> (16, [])]), >> (17, []), >> (18, []), >> ]), >> (19, []), >> (20, []), >> ]) >> >> def walkTree(tree): >> # stack to hold nodes as we walk through >> stack = [] >> stack.append(tree) >> >> while stack: >> value, children = stack.pop() >> for child in reversed(children): # reverse children to get >> the right order. >> stack.append(child) >> yield value >> >> if __name__ == '__main__': >> for value in walkTree(TREE): >> print value >> >> ####### treetest.py ######### > > John - > > That is so cool. I can't believe that it is so simple and elegant. > I thought that a stack was involved in the solution, but I could > not figure out how to use it. Thanks. > > And, to extend this a bit more, here are two slightly modified > versions of your solution that implement classes whose > instances are iterators. > > > # > # Version #1 -- This version has a next() method, as required by > # the iterator protocol. > # > class Node(object): > def __init__(self, value='', children=None): > self.value = chr(value + 97) * 3 > if children is None: > children = [] > else: > self.children = children > def walk_tree(self): > # stack to hold nodes as we walk through > stack = [] > stack.append(self) > while stack: > node = stack.pop() > # reverse children to get the right order. > stack.extend(reversed(node.children)) > yield node > def __iter__(self): > self.iterator = self.walk_tree() > return self > def next(self): > return self.iterator.next() > > > # > # Version #2 -- This version does not have a next() method, but > # the iterators returned by __iter__() do have a next(). > # > class Node(object): > def __init__(self, value='', children=None): > self.value = chr(value + 97) * 3 > if children is None: > children = [] > else: > self.children = children > def walk_tree(self): > # stack to hold nodes as we walk through > stack = [] > stack.append(self) > while stack: > node = stack.pop() > # reverse children to get the right order. > stack.extend(reversed(node.children)) > yield node > def __iter__(self): > return self.walk_tree() I think Version 2 is preferable. Not only is it shorter, but it is safer. Version 1 has essentially a singleton iterator so any code that tries to iterate the same node more than once will fail. For example multi-threaded code, or perhaps during an iteration there could be a reason to start a new iteration. Kent From kent37 at tds.net Tue Jul 17 00:13:35 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 Jul 2007 18:13:35 -0400 Subject: [Tutor] Here is newbie doc on how to implement generators In-Reply-To: <20070712232608.GA59300@cutter.rexx.com> References: <20070712232608.GA59300@cutter.rexx.com> Message-ID: <469BED8F.1030904@tds.net> Dave Kuhlman wrote: > I find iterators and generators fascinating. So, in order to try > to understand them better myself, I've written up some notes. I'm > hoping that these notes might help someone new to the generators > and iterators in Python. You can find it here: > > http://www.rexx.com/~dkuhlman/python_comments.html > http://www.rexx.com/~dkuhlman/python_comments.html#iterators-and-generators > > I'll appreciate any comments and suggestions that might help me > improve it. In the Consumers section, the first time you mention the iterator protocol, you omit mention of __init__() - this is a required method of an iterator. In the section "The iterator protocol", the __iter__() bullet, "(2) return the value returned by a generator method" is not correct. An iterator must return self from __iter__(). An object that returns a (new) generator from __iter__() is an iterable, not an iterator. In some cases there is no need to write a separate generator method and call it in __iter__(); __iter__() itself can be written as a generator method using yield. This works if the generator method doesn't need any arguments. Your Doubler class will not behave correctly because of the re-initialization of the index in __iter__(). Calling __iter__() should not have any side effects. Here is an example of why this is a problem, using Doubler as you have written it: In [9]: d=Doubler(range(5)) In [10]: d.next() Out[10]: 0 In [11]: d.next() Out[11]: 2 In [12]: for i in d: print i ....: 0 2 4 6 8 Notice how the for loop resets the iterator (because it calls __iter__() to make sure it has an iterator). Compare with a correctly implemented iterator: In [13]: it = iter(range(5)) In [14]: it.next() Out[14]: 0 In [15]: it.next() Out[15]: 1 In [16]: for i in it: print i ....: 2 3 4 Double would actually be easier to implement with __iter__() as a generator method. I already commented on the pitfalls of making an object its own iterator. In the standard library, a file is its own iterator. That makes sense because it is a wrapper around a singleton state - the seek position of the file. I don't think it makes much sense in general to have an object be its own iterator unless the object is just an iterator. Another reference is the What's New doc for Python 2.2: http://www.python.org/doc/2.2.3/whatsnew/node4.html and the following page. Kent From keridee at jayco.net Mon Jul 16 13:11:50 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 16 Jul 2007 06:11:50 -0500 Subject: [Tutor] interpreter restarts References: <674d5ce60707130944h4bc161e6k6942b119a1d71566@mail.gmail.com><674d5ce60707131146g85e3d99sd9d6bb6435652709@mail.gmail.com> <674d5ce60707131147o3e2a78e1xb33fcfa4dea3dc30@mail.gmail.com> <46984873.3010404@gmail.com> Message-ID: <01f201c7c79a$d6395100$0ffce004@JSLAPTOP> > But there's an exception to that - if you right-click a file in Windoze > and 'edit' it, > IDLE won't open up its subprocess, and as such, it can't restart the > interpreter session because it's running in the same > process as IDLE, and to restart the interpreter would mean restarting > IDLE. > Boy, that 'edit with idle' thing sure does cause some problems, don't it? > :) > -Luke Thanks, Luke. I hadn't thought of that. Question: Why won't IDLE open up its subprocess? This is the command that is in the registry concerning the Edit with IDLE menu. "C:\Python25\pythonw.exe" "C:\Python25\Lib\idlelib\idle.pyw" -n -e "%1" This is the Target for the shortcut in the Start Menu (Note: the Target box was disabled!) Python 2.5.1 I thought that this was incredibly strange, so I opened this shortcut in a hex editor to see what was different about this shortcut. (Normally, they have a path in the target box) What I found surprised me. The title of the file in the hex editor said "python_icon.exe" I started laughing maniacally and checked the full path of the file from within the hex editor. C:\windows\installer\{31800004-6386-4999-a519-518f2d78d8f0}\python_icon.exe IDLE is started in two *very* different ways. So my next question was: Can you pass arguments to this python_icon.exe? Simple navigations to that directory and a confirmation... Yuck. You can't even execute it from explorer. A low-level ZwTerminateProcess function from ntdll is called ... Let me try something... Woah... {31800004-6386-4999-a519-518f2d78d8f0} appears in the registry in alot of places. The Uninstall key for Add/Remove Programs, some weird data thing... Okay, this is beyond me. I don't know the registry or understand CLSIDs very well. Someone who knows Windows inside and out has done a number with the python installer, or at least the msi installer does this all automatically. Interesting. I wonder just how python_icon.exe starts IDLE. If I could figure that out, I could emulate it with the Edit w/Idle menu item and get IDLE to start a subprocess! But how.... any ideas? JS From keridee at jayco.net Mon Jul 16 13:35:04 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 16 Jul 2007 06:35:04 -0500 Subject: [Tutor] curses References: <00ab01c7c788$e5295780$0ffce004@JSLAPTOP> Message-ID: <021d01c7c79d$5e5c7920$0ffce004@JSLAPTOP> > There IS a way to try Linux, Python, and curses WITHOUT > installing anything to the hard-drive of your MSWindowsXP > computer, and that is to download a Linux LiveCD ISO image, > and make a bootable CD from that image. Your computer > BIOS should be setup to boot from a CD. *That* is the problem. I have *NEVER* been able to get a computer to boot from a CD. Yes, the BIOS settings are there, the CDs all seem valid (they all have the appropriate MBRs etc.) and yet *none* of the computers I have ever come in contact with will boot from a CD. You can imagine the hell I have to work through trying to repair damaged XP installations. (The Windows OS installer fits on SIX floppy disks, and if you choose an install option that you didn't mean to, you can't go back. You have to restart and run through all six disks AGAIN). > Put the LiveCD in > the CD drive, and reboot. The LiveCD runs in RAM, so you > need at LEAST 128MB RAM to run it (for good results). > Since it runs in RAM, nothing touches the HD. When you > are finished, simply Shutdown the computer, take out the CD, > and reboot into MSWindowsXP. RAM isn't a problem. Nothing touches the HD unless I want it to... ;-) It would be great to be able to boot from a CD, it seems that the the computers that fall into my lap all need to be tweaked from a bootdisk before they will boot Windows. > Warning: there are over 200 Linux LiveCDs to choose from! > Not all of them are designed for developers, so they may > or may not have Python installed by default. One easy-to-use > general-purpose Linux LiveCD is called SimplyMEPIS. > You can find a download mirror here: > http://www.mepis.org/mirrors > You should have a fast connection to download this ISO image. > The SimplyMEPIS LiveCD is about 700MB in size! The size of a CD. Aah. To stuff your media as tightly as possible. That worries me. I like very clean, very efficient things. ;-) > Python is already installed, as well as the curses module. > > This is a general-purpose desktop OS that runs the K Desktop > Environment (KDE), and has all sorts of interpreters and compilers > on it besides Python. It has a 75% 'Ubuntu' core with a 25% MEPIS > wrapper that makes things work out of the box. > > A Linux LiveCD can be carried with you, and used on remote > computers without having to install anything on the remote computer. > So you can have Python with you, wherever you go. =) I tried to install linux on one of my old desktop machines. The boot install floppy that I used put junk characters on the screen, and certainly didn't bring up the install menu ;-) Debian looked the most promising at the time for easy install and casual trans to linux. Thanks for the advice, though. JS PS > Hey bhaaluu - I've enjoyed your posts to the list so far. They're very > informative and well-written. > -Luke I agree completely!!! From kent37 at tds.net Tue Jul 17 01:52:36 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 Jul 2007 19:52:36 -0400 Subject: [Tutor] Searching for word in text file In-Reply-To: <468972B6.1000001@vladoportos.sk> References: <468972B6.1000001@vladoportos.sk> Message-ID: <469C04C4.8070009@tds.net> Vladimir Strycek wrote: > Hi all, > > i need script which open two text files and take first word from the > first file, runn throught first fords of second file and give me result > if its there or not... > > what i have so far is: > > import re, string > > # Nacitanie suborov na porovnanie > subor1 = open("snow.txt", "r") > subor2 = open("anakin.txt", "r") > > def prehladaj(najdi): > for riadok1 in subor2.readlines(): > z = riadok1.rsplit(" ") > if najdi in z[2]: > return z[3] > > def porovnaj(): > for riadok in subor1.readlines(): > x = riadok.rsplit(" ") #rozdelime do array dany riadok kde v 2 > bude nazov a verzia v 3 > print x[2] + " " + x[3] > print prehladaj(x[2]) > > > > #vytvorenie tabulky > print " Server: snow Server: anakin" > print "--------------------------------------------------------------------" > print " Name Version Version" > porovnaj() > > subor1.close() > subor2.close() > > > > the snow.txt looks like: > > B3693AA C.03.86.00 HP GlancePlus/UX for s800 11i > B3901BA B.11.11.14 HP C/ANSI C Developer's Bundle for HP-UX (S800) > B3913DB C.03.65 HP aC++ Compiler (S800) > B4967AA C.03.86.00 HP MeasureWare Server Agent for s800 11i > B5458DA C.01.18.04 HP-UX Runtime Environment for Java* > B5725AA B.3.5.89 HP-UX Installation Utilities (Ignite-UX) > > etc... > > anakint.txt is the same but different versions of programs.... im not > sure why tmi script dont work ( only for first one ) > > > What i basicaly need is to look up if version of programs match on bouth > text files diff in linux wont work for it cause there are not the same > programs on the same lines... > > Any idea why mi script is not working or any suggestion for different > aproach ? You don't say how it is failing, but one problem is that the subor2.readlines() in prehladaj() will only work the first time. I'm pretty sure that if you want to read the lines from the file again you will have to close and re-open the file. If the files are long this approach will be slow. Possibly a better way to do this is to build a dict from the data in anakin.txt though this assums that field 2 in anakin.txt is unique and that you want to do exact match searching which is not what your program does. The keys can be field 2 (that you search on) and the values field 3. For example, subor2 = open("anakin.txt", "r") d = {} # you can think of a better name, I'm sure for riadok1 in subor2.readlines(): z = riadok1.rsplit(" ") d[z[2]] = z[3] Then the matching is if najdi in d: return d[najdi] with no looping over subor2 needed. Kent From keridee at jayco.net Mon Jul 16 14:54:31 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 16 Jul 2007 07:54:31 -0500 Subject: [Tutor] reading random line from a file References: <76A18CD7-378E-4A9A-9DB4-67AD379D368D@gmail.com><46999D5E.5020509@gmail.com><3E202D96-8B0C-4E39-BFA1-5E000A524B3A@gmail.com> <4699C60E.2070107@gmail.com> Message-ID: <018101c7c7a8$781ae490$18fde004@JSLAPTOP> Perhaps ~this~ is what you are worried about performance-wise? Image Name Mem Usage ----------------------------- python.exe 11,096 K That's not too bad considering ~this~ explorer.exe 14,356 K svchost.exe 24,000 K And I worry about the mp3 player I wrote in C using 2,520 K I keep thinking I could cut that down if I mess with the compiler settings ;-) I wouldn't worry about it too much. Reading the whole file in at once is a performance issue when you are dealing with millions and millions of lines of text. An example is DNA sequences. Or databases. JS > max baseman wrote: >> cool thanks >> >> oh for performance eventualy i would like the file to contain many quotes > Using readlines isn't exactly going to cause a performance bottleneck. > I used the following code > #make the file.py > f = file("temp.txt","w") > x = 100000 > while x > 0: > f.write("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n") > x -= 1 > f.close() > #------- > this creates a file with a whole lot of lines of 'a's. > 100,000 lines, to be exact, and 4,200,000 bytes. > > In other words, this is a fair approximation for if you had, say, 25,000 > quotes (since your quotes are likely to be, on average, longer than the > amount of 'a's I used.) > I think you'll agree that that's quite a few quotes. > > Now how long does it take to use readlines() on this file? > > #test performance.py > import timeit > string = "f = file('temp.txt','r');f.readlines();f.close()" > temp = timeit.Timer(stmt=string) > print "1000 iterations took: " + str(temp.timeit(1000)) > #----- > what this code does is opens, reads all the text of the file, and closes > the file. > We call timeit with 1000 as the argument, so it repeats this process > 1000 times. > > The output of this program on my machine is: > 1000 iterations took: 51.0771701431 > > In other words, if you have 25,000 quotes, you could read all of them > into memory in 51.07717/1000 (approximately) > or 0.05107 seconds. And I'm skeptical that you would even have that > many quotes. > So, like i said before, I doubt this will cause any significant > performance problem in pretty much any normal situation. > > Also, by the way - please reply to me on-list so that others get the > benefit of our conversations. > -Luke From rabidpoobear at gmail.com Tue Jul 17 02:00:53 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 16 Jul 2007 19:00:53 -0500 Subject: [Tutor] interpreter restarts In-Reply-To: <01f201c7c79a$d6395100$0ffce004@JSLAPTOP> References: <674d5ce60707130944h4bc161e6k6942b119a1d71566@mail.gmail.com><674d5ce60707131146g85e3d99sd9d6bb6435652709@mail.gmail.com> <674d5ce60707131147o3e2a78e1xb33fcfa4dea3dc30@mail.gmail.com> <46984873.3010404@gmail.com> <01f201c7c79a$d6395100$0ffce004@JSLAPTOP> Message-ID: <469C06B5.7060608@gmail.com> Tiger12506 wrote: >> But there's an exception to that - if you right-click a file in Windoze >> and 'edit' it, >> IDLE won't open up its subprocess, and as such, it can't restart the >> interpreter session because it's running in the same >> process as IDLE, and to restart the interpreter would mean restarting >> IDLE. >> Boy, that 'edit with idle' thing sure does cause some problems, don't it? >> :) >> -Luke >> > > Thanks, Luke. I hadn't thought of that. Question: Why won't IDLE open up its > subprocess? > > This is the command that is in the registry concerning the Edit with IDLE > menu. > "C:\Python25\pythonw.exe" "C:\Python25\Lib\idlelib\idle.pyw" -n -e "%1" > > This is the Target for the shortcut in the Start Menu (Note: the Target box > was disabled!) > Python 2.5.1 > > I thought that this was incredibly strange, so I opened this shortcut in a > hex editor to see what was different about this shortcut. (Normally, they > have a path in the target box) > > What I found surprised me. The title of the file in the hex editor said > "python_icon.exe" > I started laughing maniacally and checked the full path of the file from > within the hex editor. > C:\windows\installer\{31800004-6386-4999-a519-518f2d78d8f0}\python_icon.exe > > IDLE is started in two *very* different ways. So my next question was: Can > you pass arguments to this python_icon.exe? Simple navigations to that > directory and a confirmation... Yuck. You can't even execute it from > explorer. A low-level ZwTerminateProcess function from ntdll is called ... > Let me try something... > > Woah... {31800004-6386-4999-a519-518f2d78d8f0} appears in the registry in > alot of places. The Uninstall key for Add/Remove Programs, some weird data > thing... Okay, this is beyond me. I don't know the registry or understand > CLSIDs very well. Someone who knows Windows inside and out has done a number > with the python installer, or at least the msi installer does this all > automatically. Interesting. I wonder just how python_icon.exe starts IDLE. > If I could figure that out, I could emulate it with the Edit w/Idle menu > item and get IDLE to start a subprocess! But how.... any ideas? > It sounds like python_icon.exe is a fake executable that just contains the icon for python programs... hence the name. You probably stumbled across the path to the icon to use, instead of the path that is used when running the 'Edit with IDLE' thing. Try this: open an Explorer window, via Start Button -> Run -> explorer {ENTER} or your favorite method. Use the My Computer shortcut if you want, either way. Now hit "Alt, t, o" to browse to the Tools -> Folder Options menu setting. Go to the File Types tab, and scroll down till you find "PY" click the Advanced button. You should now see a dialog box with Edit with IDLE listed under actions. Click Edit when "Edit with IDLE" is selected. in the "Application used to perform action:" field you should see something like this: "C:\Python24\pythonw.exe" "C:\Python24\Lib\idlelib\idle.pyw" -n -e "%1" Basically, this is the same as saying: python idle.py except it's more verbose because python may not be on your path (and pythonw is used instead of python so there's no dos box) As you will notice, there are some parameters there at the end. the -n is the one you're interested in . -n means no subprocess. Just remove that, and you will have a subprocess on the 'Edit with IDLE' feature. There is some caveat here - it doesn't work correctly on some systems, I'm told. I've never had problems changing this, but I don't recommend it to people randomly just in case it were to cause problems for them. Then I'd feel bad. But since you asked, I thought I'd give you all the info you need. HTH, -Luke P.S. nice detective skillz ;) From slaramen at gmail.com Tue Jul 17 02:57:06 2007 From: slaramen at gmail.com (Sebastian Lara) Date: Mon, 16 Jul 2007 20:57:06 -0400 Subject: [Tutor] Serve a file using http Message-ID: Hello all, I'm using a SimpleXMLRPCServer to update a file remotely from a simple xml-rpc python client. After that, I need to serve this file but I don't know if I can do this with SimpleXMLRPCServer or if I need another server. Thanks in advance -- Sebasti?n Lara Menares Ingenier?a Civil Electr?nica Universidad de Concepci?n From dos.fool at gmail.com Tue Jul 17 03:27:25 2007 From: dos.fool at gmail.com (max baseman) Date: Mon, 16 Jul 2007 19:27:25 -0600 Subject: [Tutor] curses Message-ID: <629446A1-721A-4A7A-AF35-4226520D7A2B@gmail.com> hello all sorry to bother I'm working on my first curses program ive been wanting to learn curses for a while now and now that a have a lop top with fedora core running in run level 3 ware im trying to program all the tools i'll use but curses will be my only gui ALAN has been helping me with this program import curses from time import sleep scr=curses.initscr() population=0 seconds=0 try: scr.nodelay(1) scr.leaveok(0) max_y, max_x = scr.getmaxyx() while 1: sleep(1) second=seconds=+1 population=population+2.5 scr.addstr(0,0,"seconds",seconds) scr.addch,max_y/2, max_x/2, str(population)[0] scr.refresh() finally: curses.endwin() depending on ware i run this i get different results on may mac OSX 10.4 i only get a wired second thing in the top left corner that looks like this secooes and when i run this on fedora core 6 i get the seconds word in top left but no number and i get a single digit in the midle that changes i think the single digit is part of population but not all i cant find out what is wrong any help would be great :) From sarliz73 at yahoo.com Tue Jul 17 03:50:04 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Mon, 16 Jul 2007 18:50:04 -0700 (PDT) Subject: [Tutor] interpreter restarts Message-ID: <843928.81222.qm@web35107.mail.mud.yahoo.com> Luke, Jacob, et. al... Dumb question (may be slightly off course from what you two were discussing), but are you both describing how to get the IDLE to run along with the editor? I may just be getting too many things confused. I've tried to run IDLE, but that's not working. I have the same function through opening it separately from the Start menu but then it doesn't work as IDLE should work with the editor (or so I've been told that happens). I can type the word Python in my editor and it comes up, but then the editor is gone. I've gone so long with just SSH, but at this point it's worth it if I find a way that makes sense. As someone mentioned from this list, at least it'll be code that is easier to read for a newbie like myself. (Hope that didn't confuse or cause unnecessary headaches...) Sara ----- Original Message ---- From: Luke Paireepinart To: Tiger12506 Cc: tutor at python.org Sent: Monday, July 16, 2007 7:00:53 PM Subject: Re: [Tutor] interpreter restarts Tiger12506 wrote: >> But there's an exception to that - if you right-click a file in Windoze >> and 'edit' it, >> IDLE won't open up its subprocess, and as such, it can't restart the >> interpreter session because it's running in the same >> process as IDLE, and to restart the interpreter would mean restarting >> IDLE. >> Boy, that 'edit with idle' thing sure does cause some problems, don't it? >> :) >> -Luke >> > > Thanks, Luke. I hadn't thought of that. Question: Why won't IDLE open up its > subprocess? > > This is the command that is in the registry concerning the Edit with IDLE > menu. > "C:\Python25\pythonw.exe" "C:\Python25\Lib\idlelib\idle.pyw" -n -e "%1" > > This is the Target for the shortcut in the Start Menu (Note: the Target box > was disabled!) > Python 2.5.1 > > I thought that this was incredibly strange, so I opened this shortcut in a > hex editor to see what was different about this shortcut. (Normally, they > have a path in the target box) > > What I found surprised me. The title of the file in the hex editor said > "python_icon.exe" > I started laughing maniacally and checked the full path of the file from > within the hex editor. > C:\windows\installer\{31800004-6386-4999-a519-518f2d78d8f0}\python_icon.exe > > IDLE is started in two *very* different ways. So my next question was: Can > you pass arguments to this python_icon.exe? Simple navigations to that > directory and a confirmation... Yuck. You can't even execute it from > explorer. A low-level ZwTerminateProcess function from ntdll is called ... > Let me try something... > > Woah... {31800004-6386-4999-a519-518f2d78d8f0} appears in the registry in > alot of places. The Uninstall key for Add/Remove Programs, some weird data > thing... Okay, this is beyond me. I don't know the registry or understand > CLSIDs very well. Someone who knows Windows inside and out has done a number > with the python installer, or at least the msi installer does this all > automatically. Interesting. I wonder just how python_icon.exe starts IDLE. > If I could figure that out, I could emulate it with the Edit w/Idle menu > item and get IDLE to start a subprocess! But how.... any ideas? > It sounds like python_icon.exe is a fake executable that just contains the icon for python programs... hence the name. You probably stumbled across the path to the icon to use, instead of the path that is used when running the 'Edit with IDLE' thing. Try this: open an Explorer window, via Start Button -> Run -> explorer {ENTER} or your favorite method. Use the My Computer shortcut if you want, either way. Now hit "Alt, t, o" to browse to the Tools -> Folder Options menu setting. Go to the File Types tab, and scroll down till you find "PY" click the Advanced button. You should now see a dialog box with Edit with IDLE listed under actions. Click Edit when "Edit with IDLE" is selected. in the "Application used to perform action:" field you should see something like this: "C:\Python24\pythonw.exe" "C:\Python24\Lib\idlelib\idle.pyw" -n -e "%1" Basically, this is the same as saying: python idle.py except it's more verbose because python may not be on your path (and pythonw is used instead of python so there's no dos box) As you will notice, there are some parameters there at the end. the -n is the one you're interested in . -n means no subprocess. Just remove that, and you will have a subprocess on the 'Edit with IDLE' feature. There is some caveat here - it doesn't work correctly on some systems, I'm told. I've never had problems changing this, but I don't recommend it to people randomly just in case it were to cause problems for them. Then I'd feel bad. But since you asked, I thought I'd give you all the info you need. HTH, -Luke P.S. nice detective skillz ;) _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ____________________________________________________________________________________ Be a better Globetrotter. Get better travel answers from someone who knows. Yahoo! Answers - Check it out. http://answers.yahoo.com/dir/?link=list&sid=396545469 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070716/1bb1b994/attachment-0001.htm From brunson at brunson.com Tue Jul 17 04:28:20 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 16 Jul 2007 20:28:20 -0600 Subject: [Tutor] CGI Calculator In-Reply-To: References: <469BA1CB.6020204@brunson.com> <469BB27C.3000402@brunson.com> <469BBD78.1080608@brunson.com> Message-ID: <469C2944.1060206@brunson.com> Here's a start by Guido: http://docs.python.org/tut/tut.html And here's a bunch more: http://www.python.org/doc/Intros.html I'm not sure of your level of expertise, so I can't recommend any of them in particular. Darren Williams wrote: > That's just printing Tokens: 1 Tokens: 2 ... Tokens: 6000 etc... > > Can you recommend any tutorials for me? > > ----- Original Message ----- > From: "Eric Brunson" > To: "Darren Williams" > Cc: > Sent: Monday, July 16, 2007 2:48 PM > Subject: Re: [Tutor] CGI Calculator > > > >> Darren Williams wrote: >> >>> Now another problem - the script is just printing the word 'Tokens' >>> over and over again, it's supposed to work like this (JavaScript >>> version made by me) - http://nazkyn.brinkster.net/1.8.html >>> >>> Thanks in advance for any help :) >>> >> It's doing exactly what you've told it to do: >> >> while usedPockets > totalJunkies - labSpace * 17: >> Tokens = Tokens + 1 >> usedPockets = (usedPockets - totalJunkies + labSpace) * 17 >> totalJunkies = totalJunkies + 1 >> print "Tokens" >> >> The print statement is inside the while loop and you've quoted the work >> "Tokens" so it's printing the string rather than the variable. >> >> How about grabbing a short tutorial on Python and reading through it to >> better understand the differences between Python and Javascript. If >> you're an experienced JS programmer it shouldn't take very long. >> >> This is probably closer is what I infer you're looking for: >> >> while usedPockets > totalJunkies - labSpace * 17: >> Tokens = Tokens + 1 >> usedPockets = (usedPockets - totalJunkies + labSpace) * 17 >> totalJunkies = totalJunkies + 1 >> print "Tokens: %s" % Tokens >> >> e. >> >> >>> ----- Original Message ----- From: "Eric Brunson" >>> To: "Darren Williams" >>> Cc: >>> Sent: Monday, July 16, 2007 2:01 PM >>> Subject: Re: [Tutor] CGI Calculator >>> >>> >>> >>>> Darren Williams wrote: >>>> >>>>> Ok, now i've modified my script but am getting another error, i've >>>>> commented a few useless (hopefully) lines out - >>>>> >>>>> #!/usr/bin/env python >>>>> >>>>> import cgitb; cgitb.enable() >>>>> import cgi >>>>> >>>>> >>>>> >>>> [snip] >>>> >>>>> 17 while usedPockets > totalJunkies - labSpace * 17: >>>>> >>>>> 18 Tokens = Tokens + 1 >>>>> >>>>> 19 usedPockets = (usedPockets - totalJunkies + >>>>> labSpace) * 17 >>>>> >>>>> usedPockets = '192000', totalJunkies = '200', labSpace = '0' >>>>> >>>>> TypeError: unsupported operand type(s) for -: 'str' and 'str' >>>>> args = ("unsupported operand type(s) for -: 'str' and 'str'",) >>>>> >>>>> >>>> What does "dog" - "cat" mean? Similarly, what does "100" - "12" >>>> mean? It's not the same in Python as 100 - 12, because those are >>>> numbers, "100" and "12" are strings which happen to represent numbers. >>>> >>>> You need to coerce those strings into integers, maybe like this: >>>> >>>> usedPockets = int(form["usedPockets"].value) >>>> >>>> When you do that, you'll probably need to catch any exception that >>>> could occur if the string can't be converted. >>>> >>>> >>>>> It's confused me - it says I can't subtract a string from a string >>>>> but then gives the value's of the variables (that I randomly entered >>>>> into the form) at the bottom - usedPockets = '192000', totalJunkies >>>>> = '200', labSpace = '0' >>>>> >>>>> >>>> >> From keridee at jayco.net Mon Jul 16 17:47:49 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 16 Jul 2007 10:47:49 -0500 Subject: [Tutor] tutor References: <674d5ce60707132332u57819d11kffccfb358311e7de@mail.gmail.com> <674d5ce60707132338t3b6d208bu15be93f457c413e6@mail.gmail.com> Message-ID: <022f01c7c7c0$ae0c5300$18fde004@JSLAPTOP> > please think about your first programming class, and then think about how > long it took the prof to teach the concept of array. > > yes, it's about a week, if he is really good. [gentle rant] Yes, and I find that most idiots in math classes NEVER gain the concept of multiplying fractions (longer than a week - 2 years for my peers). Very simple. Multiply the top numbers together. Multiply the bottom numbers together. But can they understand? No. They "learn" by mimicking, like a monkey. They don't think. They don't understand. And they can't follow rules or *syntax*, that *documentation* provides. And the worst part: They don't try. All they can do is produce the same result - give the answer that someone else provides. That is the world today. [/gentle rant] If the "prof" is good, it will take ten minutes to explain the concept of an array. Having said that, it is usually not the professor nor the language that is the problem: it's the student. The student *must* be willing to learn. The student *must* be willing to study material. If someone references tutorials, then the student *must* be willing to read and work through those tutorials. These list members are not providing links for no reason. They have provided many tutorials for beginner programmers. They have provided many links for people who have never seen what a programming language is before in their life. *If* you can say that you have honestly read, worked, and asked questions about those tutorials, and you still don't have the fundamentals, then perhaps programming is not for you. The problem is - you have to work ALL THE WAY THROUGH THEM. You cannot expect to write files, for example, if you've read the first chapter that tells you how to use print "Hello World". And you would not know how to add to a formatting string unless you read the next part of the tutorial for example. I apologize for my harshness. But the statement about my first programming class, and arrays, and a week... @!#$% I am not lucky enough to be able to pay for a programming class. And yet using the same tutorials that those on the list have quoted I learned python well enough to do what you are attempting in a few days. Granted, I couldn't write GUI apps using Tkinter, but I TRIED. And I listened to the advice of Alan, Kent, Danny, and the others when they said I should read this or that tutorial. And no. I didn't have ANY previous programming experience. If it really takes professors a week to teach the concept of an array, then they should be sacked and replaced with one of the excellent tutorials these list members have mentioned. JS PS - if you had read those tutorials through, you would understand that this f.write("\"%s\"" % title) --which someone on the list gave to you-- provided the answer to this: ############### organge = 5 f.write( "there are orange "florida" oranges on the counter") ############## which should be ################ orange = 5 f.write("there are %s \"florida\" oranges on the counter" % orange) ############### From keridee at jayco.net Mon Jul 16 17:48:34 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 16 Jul 2007 10:48:34 -0500 Subject: [Tutor] reading random line from a file Message-ID: <023601c7c7c0$c87c0e10$18fde004@JSLAPTOP> If you truly wish to kill yourself trying to make it as efficient memory as possible, then you can follow this example. (This is more like what I would write in C). The getrandomline function picks a random byte between the beginning and the end of the file, then backs up until the beginning of the line and uses readline to return the whole line. I tested it :-) ############################################# from os import stat from random import randint def getrandomline(f, length): pos = randint(0,length) f.seek(pos) while f.read(1)!='\n': try: f.seek(-2,1) except IOError: # This is to catch seeking before the beginning of the file f.seek(0) return f.readline() f = file("quotes.txt","rb") sizeoffile = stat("quotes.txt")[6] while (1): print getrandomline(f, sizeoffile), f.close() ################################### This holds at 3,688 K mem usage, whereas with the same file (100,000 lines), using readlines gives me 47,724 K. Big difference. Maybe not important to you, but I'm strange. Hope this helps. JS From keridee at jayco.net Mon Jul 16 18:15:55 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 16 Jul 2007 11:15:55 -0500 Subject: [Tutor] interpreter restarts References: <674d5ce60707130944h4bc161e6k6942b119a1d71566@mail.gmail.com><674d5ce60707131146g85e3d99sd9d6bb6435652709@mail.gmail.com> <674d5ce60707131147o3e2a78e1xb33fcfa4dea3dc30@mail.gmail.com> <46984873.3010404@gmail.com> <01f201c7c79a$d6395100$0ffce004@JSLAPTOP> <469C06B5.7060608@gmail.com> Message-ID: <02a301c7c7c4$9a293de0$18fde004@JSLAPTOP> Hmmm. You should read closer ;-) > It sounds like python_icon.exe is a fake executable that just contains the > icon for python programs... > hence the name. Perhaps. If that's the case though, someone needs to talk to the guys who design the setup file for python. It is an inefficient waste of space to store icons in a dead executable. An .ico file is better. That is for what they are designed. I believe that it is not a dead executable, because those writers have more sense than that. Also the odd location of the executable suggests it has another purpose. And it has to have a purpose, otherwise IDLE never would get started. > You probably stumbled across the path to the icon to use, instead of the > path that is used when running the 'Edit with IDLE' thing. As my message said, I already have that. I was trying to find the path that the icon in the start menu uses to start IDLE, so that I could compare them. > Try this: > open an Explorer window, via Start Button -> Run -> explorer {ENTER} > or your favorite method. Use the My Computer shortcut if you want, either > way. > Now hit "Alt, t, o" to browse to the Tools -> Folder Options menu setting. > Go to the File Types tab, and scroll down till you find "PY" > click the Advanced button. > You should now see a dialog box with Edit with IDLE listed under actions. > Click Edit when "Edit with IDLE" is selected. > in the "Application used to perform action:" field you should see > something like this: > > "C:\Python24\pythonw.exe" "C:\Python24\Lib\idlelib\idle.pyw" -n -e "%1" And you can also get to Folder Options by opening Control Panel. You can also get there by typing in Folder Options in any open folder. Quoting my own message: >> This is the command that is in the registry concerning the Edit with IDLE >> menu. >> "C:\Python25\pythonw.exe" "C:\Python25\Lib\idlelib\idle.pyw" -n -e "%1" Yes~ I know about Folder Options. ~smirk~ I also know where in the Windows Registry that Folder Options stores those file extensions. > As you will notice, there are some parameters there at the end. > the -n is the one you're interested in . > -n means no subprocess. Yes. Yes. That is what I'm interested in. Sigh. I know Windows very well for my background. The command line parameters for pythonw.exe ~ not so much. JS From keridee at jayco.net Mon Jul 16 18:33:27 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 16 Jul 2007 11:33:27 -0500 Subject: [Tutor] IDLE Usage - was Interpreter Restarts References: <843928.81222.qm@web35107.mail.mud.yahoo.com> Message-ID: <031101c7c7c7$0d1ea540$18fde004@JSLAPTOP> > Luke, Jacob, et. al... > > Dumb question (may be slightly off course from what you two were > discussing), but are you both describing how to get the IDLE to run along > with the editor? I may just be getting too many things confused. I've > tried to run IDLE, but that's not working. I have the same function > through opening it separately from the Start menu but then it doesn't work > as IDLE should work with the editor (or so I've been told that happens). > I can type the word Python in my editor and it comes up, but then the > editor is gone. I've gone so long with just SSH, but at this point it's > worth it if I find a way that makes sense. As someone mentioned from this > list, at least it'll be code that is easier to read for a newbie like > myself. > > (Hope that didn't confuse or cause unnecessary headaches...) > > Sara Not quite what we were discussing, but I think you may have given just enough clues that i can be of some help. Just for reference ~ which editor are you using? IDLE is both an editor and a python shell or interpreter. It is not the same thing as typing python.exe wherever you might be typing it. Typing Python into an editor should put the word "Python" into your currently open file. I don't believe that this is what you mean. Perhaps you are confusing what exactly is an editor? You use Windows you've mentioned before. So here's what you can do. Start -> Programs -> Python 2.5 -> Python (commandline) This is the python interpreter. As you might already know. And then this. Start -> Programs -> Python 2.5 -> IDLE (Python GUI) This is IDLE. As you probably know. Two windows should come up when you click IDLE. One is an editor. The other is the python shell, or interpreter. You can open .py files in IDLE by right clicking and selecting "Edit with IDLE". At any time that you wish to run a program that is open in the editor half of IDLE, hit F5 and the Python shell half of IDLE comes to the top and runs the program. If doing all that doesn't do what I expect it to do, or you have something else in mind, reply back. If it does, then great! Oh. And tell me which editor you are using which magically opens a python interpreter when you type Python into it. ;-) JS From sarliz73 at yahoo.com Tue Jul 17 06:26:52 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Mon, 16 Jul 2007 21:26:52 -0700 (PDT) Subject: [Tutor] IDLE Usage - was Interpreter Restarts Message-ID: <114046.30409.qm@web35107.mail.mud.yahoo.com> First off, yes, I was referring to (I guess you could say) a non-python editor. I use an SSH editor set up by my school. If I type python at the prompt in SSH, I get the Python shell. My problem is, I can't open a GUI no matter what I subscribe to or purchase. I have Python 2.3 and yes, I can access the commandline, but that does not work the way it's been described to work. If this still doesn't make any sense, just ignore me... Sara >>Not quite what we were discussing, but I think you may have given just enough clues that i can be of some help. Just for reference ~ which editor are you using? IDLE is both an editor and a python shell or interpreter. It is not the same thing as typing python.exe wherever you might be typing it. Typing Python into an editor should put the word "Python" into your currently open file. I don't believe that this is what you mean. Perhaps you are confusing what exactly is an editor? You use Windows you've mentioned before. So here's what you can do. Start -> Programs -> Python 2.5 -> Python (commandline) This is the python interpreter. As you might already know. And then this. Start -> Programs -> Python 2.5 -> IDLE (Python GUI) This is IDLE. As you probably know. Two windows should come up when you click IDLE. One is an editor. The other is the python shell, or interpreter. You can open .py files in IDLE by right clicking and selecting "Edit with IDLE". At any time that you wish to run a program that is open in the editor half of IDLE, hit F5 and the Python shell half of IDLE comes to the top and runs the program. If doing all that doesn't do what I expect it to do, or you have something else in mind, reply back. If it does, then great! Oh. And tell me which editor you are using which magically opens a python interpreter when you type Python into it. ;-) JS _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ____________________________________________________________________________________ It's here! Your new message! Get new email alerts with the free Yahoo! Toolbar. http://tools.search.yahoo.com/toolbar/features/mail/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070716/11eb5671/attachment.html From rabidpoobear at gmail.com Tue Jul 17 07:20:09 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 17 Jul 2007 00:20:09 -0500 Subject: [Tutor] interpreter restarts In-Reply-To: <02a301c7c7c4$9a293de0$18fde004@JSLAPTOP> References: <674d5ce60707130944h4bc161e6k6942b119a1d71566@mail.gmail.com><674d5ce60707131146g85e3d99sd9d6bb6435652709@mail.gmail.com> <674d5ce60707131147o3e2a78e1xb33fcfa4dea3dc30@mail.gmail.com> <46984873.3010404@gmail.com> <01f201c7c79a$d6395100$0ffce004@JSLAPTOP> <469C06B5.7060608@gmail.com> <02a301c7c7c4$9a293de0$18fde004@JSLAPTOP> Message-ID: <469C5189.6010005@gmail.com> Tiger12506 wrote: > Hmmm. You should read closer ;-) > Heh. You're right, I didn't read your whole message. I just skimmed it :P > >> It sounds like python_icon.exe is a fake executable that just contains the >> icon for python programs... >> hence the name. >> > > Perhaps. If that's the case though, someone needs to talk to the guys who > design the setup file for python. It is an inefficient waste of space to > store icons in a dead executable. An .ico file is better. That is for what > they are designed. I believe that it is not a dead executable, because those > writers have more sense than that. Also the odd location of the executable > suggests it has another purpose. And it has to have a purpose, otherwise > IDLE never would get started. > If you really desire to know, you should ask the folks over at comp.lang.python. They're more likely to know what's going on there. Or maybe some Windows python list. > >> You probably stumbled across the path to the icon to use, instead of the >> path that is used when running the 'Edit with IDLE' thing. >> > > As my message said, I already have that. I was trying to find the path that > the icon in the start menu uses to start IDLE, so that I could compare them. > Ah, okay. > > And you can also get to Folder Options by opening Control Panel. > You can also get there by typing in Folder Options in any open folder. > Didn't know about the Folder Options thing. Neat-o. > Quoting my own message: > > >>> This is the command that is in the registry concerning the Edit with IDLE >>> menu. >>> "C:\Python25\pythonw.exe" "C:\Python25\Lib\idlelib\idle.pyw" -n -e "%1" >>> > > Yes~ I know about Folder Options. ~smirk~ I also know where in the Windows > Registry that Folder Options stores those file extensions. > I didn't realize that was what you were doing <_<. > >> As you will notice, there are some parameters there at the end. >> the -n is the one you're interested in . >> -n means no subprocess. >> > > Yes. Yes. That is what I'm interested in. > Sigh. I know Windows very well for my background. The command line > parameters for pythonw.exe ~ not so much. > Oh well. Sorry for restating you. :) It was a situation where I thought I knew what you needed without reading the full e-mail. I'll be more considerate in the future. -Luke From rabidpoobear at gmail.com Tue Jul 17 07:24:11 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 17 Jul 2007 00:24:11 -0500 Subject: [Tutor] IDLE Usage - was Interpreter Restarts In-Reply-To: <114046.30409.qm@web35107.mail.mud.yahoo.com> References: <114046.30409.qm@web35107.mail.mud.yahoo.com> Message-ID: <469C527B.7020103@gmail.com> Sara Johnson wrote: > First off, yes, I was referring to (I guess you could say) a > non-python editor. I use an SSH editor set up by my school. If I > type python at the prompt in SSH, I get the Python shell. My problem > is, I can't open a GUI no matter what I subscribe to or purchase. I > have Python 2.3 and yes, I can access the commandline, but that does > not work the way it's been described to work. > > If this still doesn't make any sense, just ignore me... I'm not sure what your problem is. Does the SSH program provide a file transfer utility? could you write your code on your local computer then just transfer the final code to the server? A lot of Python programmers use Vi for writing their code. do you have access to that through SSH? I'm not quite sure what you mean by "SSH editor." -Luke From rikard.bosnjakovic at gmail.com Tue Jul 17 08:30:42 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Tue, 17 Jul 2007 08:30:42 +0200 Subject: [Tutor] 200 dollar questions! In-Reply-To: <674d5ce60706301517n154d6f52n77c99be0f6df9a5d@mail.gmail.com> References: <100452.41767.qm@web86103.mail.ird.yahoo.com> <674d5ce60706301517n154d6f52n77c99be0f6df9a5d@mail.gmail.com> Message-ID: On 01/07/07, elis aeris wrote: [...] > GainFocus(handle) > > Keyboard_event ( "hello python!") > Mouse_event (x,y, left, 2) > > the (x,y) = should be relative to the active window and independent of the > window's position. > 2 as in clicking twice. This sounds the rentacoder-job I got some weeks ago. Are you perhaps by chance the same buyer? -- - Rikard - http://bos.hack.org/cv/ From kent37 at tds.net Tue Jul 17 12:54:19 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Jul 2007 06:54:19 -0400 Subject: [Tutor] interpreter restarts In-Reply-To: <469C5189.6010005@gmail.com> References: <674d5ce60707130944h4bc161e6k6942b119a1d71566@mail.gmail.com><674d5ce60707131146g85e3d99sd9d6bb6435652709@mail.gmail.com> <674d5ce60707131147o3e2a78e1xb33fcfa4dea3dc30@mail.gmail.com> <46984873.3010404@gmail.com> <01f201c7c79a$d6395100$0ffce004@JSLAPTOP> <469C06B5.7060608@gmail.com> <02a301c7c7c4$9a293de0$18fde004@JSLAPTOP> <469C5189.6010005@gmail.com> Message-ID: <469C9FDB.5020802@tds.net> Luke Paireepinart wrote: > Tiger12506 wrote: >>> As you will notice, there are some parameters there at the end. >>> the -n is the one you're interested in . >>> -n means no subprocess. >>> >> Yes. Yes. That is what I'm interested in. >> Sigh. I know Windows very well for my background. The command line >> parameters for pythonw.exe ~ not so much. There is a man page for python showing the command line parameters. Unfortunately AFAIK it is not available on Windows. You can read it here: http://linuxcommand.org/man_pages/python1.html -n is an IDLE option, not a Python option. To see all available IDLE command line options, type "C:\Python25\python.exe" "C:\Python25\Lib\idlelib\idle.pyw" -h Kent From kent37 at tds.net Tue Jul 17 13:17:32 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Jul 2007 07:17:32 -0400 Subject: [Tutor] Question about lambda and new.instancemethod In-Reply-To: References: Message-ID: <469CA54C.2030209@tds.net> Tino Dai wrote: > Hi Everybody, > > I have been working on a parser for myself. I want to create > methods on the fly with the information that I get from a file. Here is > my question: > > class configure: > <.....stuff deleted......> > def parseGlobal(self,projectName,section,project): > for element in section.childNodes: > if not element.nodeName == "#text": > self.glblFunc ["get" + > project.getAttribute("name").encode("ascii").capitalize() + > element.nodeName.encode("ascii").capitalize()] = \ > lambda self : element.firstChild.data.encode ("ascii") > > <...and later on...> > > def addMethod(instName,funcDict): > for k,v in funcDict.iteritems(): > instName.__dict__[k]=new.instancemethod(v,instName,'configure') > > The instance name and funcDict (which is the populated self.glblFunc) > get sent up to addMethod. This is supposed to create a new method within > the instance of my class. Instead, I get a AttributeError exception > thrown. What is the AttributeError and when do you get it? I see a couple of possible problems. First, closures don't work the way you want them to in your lambda. Each lambda will be bound to the same value of element - the last value of element. Here is a simple example showing the problem: In [1]: funcs = [] In [2]: for i in range(3): funcs.append(lambda: i) In [3]: for f in funcs: ...: print f() 2 2 2 A simple workaround is to bind the changing variable as a default argument to the lambda: In [4]: funcs = [] In [5]: for i in range(3): funcs.append(lambda i=i: i) In [6]: for f in funcs: print f() 0 1 2 Another fix is to create a factory function that returns the lambda as its result. Second problem is that the third argument to new.instancemethod() should be the class object, not the name of the class. You might find this helpful: http://groups.google.com/group/comp.lang.python/browse_thread/thread/cc04b8e480d4be62/ > So, I check the code using inspect.getsource, and for all of the > new methods that I create, I get > > > ' + element.nodeName.encode("ascii").capitalize()] = > lambda self : sys.stdout.write(element.firstChild.data.encode > ("ascii"))\n\n' > > instead of > > lambda self : sys.stdout.write(element.firstChild.data.encode("ascii") Seems like getsource() is just a little confused, but it is showing you the correct source. If you created the lambda on a line by itself it might give a better result. Kent From kent37 at tds.net Tue Jul 17 13:57:41 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Jul 2007 07:57:41 -0400 Subject: [Tutor] Good writeup on Python assignment semantics Message-ID: <469CAEB5.1090901@tds.net> A recent comp.lang.python thread has a good explanation of Python's assignment semantics: http://groups.google.com/group/comp.lang.python/browse_thread/thread/56e7d62bf66a435c/ Kent From bhaaluu at gmail.com Tue Jul 17 14:16:18 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 17 Jul 2007 08:16:18 -0400 Subject: [Tutor] IDLE Usage - was Interpreter Restarts In-Reply-To: <469C527B.7020103@gmail.com> References: <114046.30409.qm@web35107.mail.mud.yahoo.com> <469C527B.7020103@gmail.com> Message-ID: Greetings, I use an editor called 'vim' on GNU/Linux. I invoke vim on the command-line by typing: vi (vi is a link to /usr/bin/vim) In my home directory I have a vim config file named .vimrc (that is: dot_vimrc [the dot makes it hidden]). The .vimrc file has some things in it that do some nice stuff for editing Python files; such as syntax highlighting, line numbers, indenting, and also runs Python when I press the F2 function key. I run vim in an X ternminal called Konsole. I can also run it from the command-line in any tty. Okay, here it is. Just copy/paste this into an editor, and save it as: .vimrc -------------8<------Cut Here-------->8--------------- " .vimrc " " Created by Jeff Elkner 23 January 2006 " Last modified 2 February 2006 " " Turn on syntax highlighting and autoindenting syntax enable filetype indent on " set autoindent width to 4 spaces (see " http://www.vim.org/tips/tip.php?tip_id=83) set nu set et set sw=4 set smarttab " Bind key to running the python interpreter on the currently active " file. (curtesy of Steve Howell from email dated 1 Feb 2006). map :w\|!python % -------------8<------Cut Here-------->8--------------- To use it, just type: vi myCode.py (If you don't have a link named vi that points to /usr/bin/vim, you'll have to type vim or /usr/bin/vim to get it going... since I don't have any idea what you're working at, I can't say.) Once you're in vim, looking at your code, press F2 to run it. I understand that Emacs also does Python! =) But I won't go there... I don't do Emacs. -- bhaaluu at gmail dot com On 7/17/07, Luke Paireepinart wrote: > A lot of Python programmers > use Vi for writing their code. do you have access to that through SSH? > I'm not quite sure what you mean by "SSH editor." > -Luke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Tue Jul 17 16:05:02 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 17 Jul 2007 07:05:02 -0700 Subject: [Tutor] Good writeup on Python assignment semantics In-Reply-To: <469CAEB5.1090901@tds.net> References: <469CAEB5.1090901@tds.net> Message-ID: <20070717140517.680731E400F@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070717/8dc20bd3/attachment.htm From kent37 at tds.net Tue Jul 17 16:38:56 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Jul 2007 10:38:56 -0400 Subject: [Tutor] Good writeup on Python assignment semantics In-Reply-To: <20070717140520.GSRV26408.inaamta12.mail.tds.net@sccrmhc13.comcast.net> References: <469CAEB5.1090901@tds.net> <20070717140520.GSRV26408.inaamta12.mail.tds.net@sccrmhc13.comcast.net> Message-ID: <469CD480.6020402@tds.net> Dick Moores wrote: > At 04:57 AM 7/17/2007, you wrote: >> A recent comp.lang.python thread has a good explanation of Python's >> assignment semantics: >> http://groups.google.com/group/comp.lang.python/browse_thread/thread/56e7d62bf66a435c/ > > > Kent, > > Yes, interesting. But could you explain what you mean by "assignment > semantics"? Semantics: < > http://dictionary.reference.com/search?q=semantics> > I have trouble relating semantics to programming. Semantics: The study or science of meaning in language. In other words, what does it mean to say a = b in Python? Syntax is like spelling and grammar rules - if you understand syntax, you can write a program that will compile and run. But without understanding what the various programming constructs actually mean, you will have trouble writing a program that does something useful. I think to write correct programs in any language, you must have a correct mental model of what the program is doing, where by 'correct' I mean a model that is consistent with the actual behaviour of the program. Programmers coming from a background in C and C++ have a mental model of variables as containers for values. This model works in those languages, where variables correspond to memory locations and assignment copies a value from one location to another. It doesn't work in Python, where variables are names for values and assignment creates another name for the same value without copying. To write correct Python programs you have to have a different model for what variables are and how they behave. We regularly see questions on this list from people who are confused by assignment because they are using a faulty model. So "what does it mean?" might be interpreted as "what is a useful model of this operation that allows me to understand and predict its behaviour?", and "assignment semantics" is a shortcut for saying "a useful model of assignment that allows me to understand and predict its behaviour." Kent From rdm at rcblue.com Tue Jul 17 16:54:04 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 17 Jul 2007 07:54:04 -0700 Subject: [Tutor] Good writeup on Python assignment semantics In-Reply-To: <469CD480.6020402@tds.net> References: <469CAEB5.1090901@tds.net> <20070717140520.GSRV26408.inaamta12.mail.tds.net@sccrmhc13.comcast.net> <469CD480.6020402@tds.net> Message-ID: <20070717145418.D5AF81E400F@bag.python.org> At 07:38 AM 7/17/2007, Kent Johnson wrote: >Dick Moores wrote: >>At 04:57 AM 7/17/2007, you wrote: >>>A recent comp.lang.python thread has a good explanation of Python's >>>assignment semantics: >>>http://groups.google.com/group/comp.lang.python/browse_thread/thread/56e7d62bf66a435c/ >>> >> >>Kent, >>Yes, interesting. But could you explain what you mean by >>"assignment semantics"? Semantics: < >>http://dictionary.reference.com/search?q=semantics> >>I have trouble relating semantics to programming. > >Semantics: The study or science of meaning in language. > >In other words, what does it mean to say > a = b >in Python? > >Syntax is like spelling and grammar rules - if you understand >syntax, you can write a program that will compile and run. But >without understanding what the various programming constructs >actually mean, you will have trouble writing a program that does >something useful. > >I think to write correct programs in any language, you must have a >correct mental model of what the program is doing, where by >'correct' I mean a model that is consistent with the actual >behaviour of the program. > >Programmers coming from a background in C and C++ have a mental >model of variables as containers for values. This model works in >those languages, where variables correspond to memory locations and >assignment copies a value from one location to another. It doesn't >work in Python, where variables are names for values and assignment >creates another name for the same value without copying. To write >correct Python programs you have to have a different model for what >variables are and how they behave. We regularly see questions on >this list from people who are confused by assignment because they >are using a faulty model. > >So "what does it mean?" might be interpreted as "what is a useful >model of this operation that allows me to understand and predict its >behaviour?", and "assignment semantics" is a shortcut for saying "a >useful model of assignment that allows me to understand and predict >its behaviour." > >Kent Thanks very much for your trouble, Kent. A big help. Dick From brunson at brunson.com Tue Jul 17 17:14:30 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 17 Jul 2007 09:14:30 -0600 Subject: [Tutor] interpreter restarts In-Reply-To: <843928.81222.qm@web35107.mail.mud.yahoo.com> References: <843928.81222.qm@web35107.mail.mud.yahoo.com> Message-ID: <469CDCD6.5040406@brunson.com> Sara, Stick with ssh, IDE's are a crutch. ;-) But that's just my opinion, others may differ. However, if you were running an X server on your local machine, you could use SSH to allow you to run GUI programs from your remote server. There are a couple of free X servers for Windoze, but running Linux on your local machine would give you the greatest success. If you are interested in pursuing this, google up and install an X server, then post back. Sincerely, e. Sara Johnson wrote: > Luke, Jacob, et. al... > > Dumb question (may be slightly off course from what you two were > discussing), but are you both describing how to get the IDLE to run > along with the editor? I may just be getting too many things > confused. I've tried to run IDLE, but that's not working. I have the > same function through opening it separately from the Start menu but > then it doesn't work as IDLE should work with the editor (or so I've > been told that happens). I can type the word Python in my editor and > it comes up, but then the editor is gone. I've gone so long with just > SSH, but at this point it's worth it if I find a way that makes > sense. As someone mentioned from this list, at least it'll be code > that is easier to read for a newbie like myself. > > (Hope that didn't confuse or cause unnecessary headaches...) > > Sara > > ----- Original Message ---- > From: Luke Paireepinart > To: Tiger12506 > Cc: tutor at python.org > Sent: Monday, July 16, 2007 7:00:53 PM > Subject: Re: [Tutor] interpreter restarts > > Tiger12506 wrote: > >> But there's an exception to that - if you right-click a file in Windoze > >> and 'edit' it, > >> IDLE won't open up its subprocess, and as such, it can't restart the > >> interpreter session because it's running in the same > >> process as IDLE, and to restart the interpreter would mean restarting > >> IDLE. > >> Boy, that 'edit with idle' thing sure does cause some problems, > don't it? > >> :) > >> -Luke > >> > > > > Thanks, Luke. I hadn't thought of that. Question: Why won't IDLE > open up its > > subprocess? > > > > This is the command that is in the registry concerning the Edit with > IDLE > > menu. > > "C:\Python25\pythonw.exe" "C:\Python25\Lib\idlelib\idle.pyw" -n -e "%1" > > > > This is the Target for the shortcut in the Start Menu (Note: the > Target box > > was disabled!) > > Python 2.5.1 > > > > I thought that this was incredibly strange, so I opened this > shortcut in a > > hex editor to see what was different about this shortcut. (Normally, > they > > have a path in the target box) > > > > What I found surprised me. The title of the file in the hex editor said > > "python_icon.exe" > > I started laughing maniacally and checked the full path of the file > from > > within the hex editor. > > > C:\windows\installer\{31800004-6386-4999-a519-518f2d78d8f0}\python_icon.exe > > > > IDLE is started in two *very* different ways. So my next question > was: Can > > you pass arguments to this python_icon.exe? Simple navigations to that > > directory and a confirmation... Yuck. You can't even execute it from > > explorer. A low-level ZwTerminateProcess function from ntdll is > called ... > > Let me try something... > > > > Woah... {31800004-6386-4999-a519-518f2d78d8f0} appears in the > registry in > > alot of places. The Uninstall key for Add/Remove Programs, some > weird data > > thing... Okay, this is beyond me. I don't know the registry or > understand > > CLSIDs very well. Someone who knows Windows inside and out has done > a number > > with the python installer, or at least the msi installer does this all > > automatically. Interesting. I wonder just how python_icon.exe starts > IDLE. > > If I could figure that out, I could emulate it with the Edit w/Idle > menu > > item and get IDLE to start a subprocess! But how.... any ideas? > > > It sounds like python_icon.exe is a fake executable that just contains > the icon for python programs... > hence the name. > You probably stumbled across the path to the icon to use, instead of the > path that is used when running the 'Edit with IDLE' thing. > Try this: > open an Explorer window, via Start Button -> Run -> explorer {ENTER} > or your favorite method. Use the My Computer shortcut if you want, > either way. > Now hit "Alt, t, o" to browse to the Tools -> Folder Options menu setting. > Go to the File Types tab, and scroll down till you find "PY" > click the Advanced button. > You should now see a dialog box with Edit with IDLE listed under actions. > Click Edit when "Edit with IDLE" is selected. > in the "Application used to perform action:" field you should see > something like this: > > "C:\Python24\pythonw.exe" "C:\Python24\Lib\idlelib\idle.pyw" -n -e "%1" > > Basically, this is the same as saying: > python idle.py > except it's more verbose because python may not be on your path (and > pythonw is used instead of python so there's no dos box) > As you will notice, there are some parameters there at the end. > the -n is the one you're interested in . > -n means no subprocess. > Just remove that, and you will have a subprocess on the 'Edit with IDLE' > feature. > There is some caveat here - it doesn't work correctly on some systems, > I'm told. > I've never had problems changing this, but I don't recommend it to > people randomly just in case it were to cause problems for them. > Then I'd feel bad. > But since you asked, I thought I'd give you all the info you need. > HTH, > -Luke > P.S. nice detective skillz ;) > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------------------------------------------------ > Get the Yahoo! toolbar and be alerted to new email > wherever > you're surfing. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From jim at well.com Tue Jul 17 17:35:07 2007 From: jim at well.com (jim stockford) Date: Tue, 17 Jul 2007 08:35:07 -0700 Subject: [Tutor] Good writeup on Python assignment semantics In-Reply-To: <469CD480.6020402@tds.net> References: <469CAEB5.1090901@tds.net> <20070717140520.GSRV26408.inaamta12.mail.tds.net@sccrmhc13.comcast.net> <469CD480.6020402@tds.net> Message-ID: as I understand things... there's a writeup somewhere that uses the term "bind" instead of "assign" for the operation a = b for example, in Python a = 1 the value 1 now has a name of a associated with it. b = a the value 1 now has two names, a and b, associated with it the value 1 exists as an object independent of the storage for the names a or b, which are bound to the integer object 1 in C a = 1; creates an integer-sized area in RAM, names it a, and puts the value 1 in that area. b = a; copies the value in the area named a to a new, integer-sized area named b in either language (pseudocode below): a = 1 print a a b = 1 print b 1 a = 2 print a 2 print b 1 I'm curious to know the practical value of knowing the difference: where can one get tripped up in this case? On Jul 17, 2007, at 7:38 AM, Kent Johnson wrote: > Dick Moores wrote: >> At 04:57 AM 7/17/2007, you wrote: >>> A recent comp.lang.python thread has a good explanation of Python's >>> assignment semantics: >>> http://groups.google.com/group/comp.lang.python/browse_thread/ >>> thread/56e7d62bf66a435c/ >> >> >> Kent, >> >> Yes, interesting. But could you explain what you mean by "assignment >> semantics"? Semantics: < >> http://dictionary.reference.com/search?q=semantics> >> I have trouble relating semantics to programming. > > Semantics: The study or science of meaning in language. > > In other words, what does it mean to say > a = b > in Python? > > Syntax is like spelling and grammar rules - if you understand syntax, > you can write a program that will compile and run. But without > understanding what the various programming constructs actually mean, > you > will have trouble writing a program that does something useful. > > I think to write correct programs in any language, you must have a > correct mental model of what the program is doing, where by 'correct' I > mean a model that is consistent with the actual behaviour of the > program. > > Programmers coming from a background in C and C++ have a mental model > of > variables as containers for values. This model works in those > languages, > where variables correspond to memory locations and assignment copies a > value from one location to another. It doesn't work in Python, where > variables are names for values and assignment creates another name for > the same value without copying. To write correct Python programs you > have to have a different model for what variables are and how they > behave. We regularly see questions on this list from people who are > confused by assignment because they are using a faulty model. > > So "what does it mean?" might be interpreted as "what is a useful model > of this operation that allows me to understand and predict its > behaviour?", and "assignment semantics" is a shortcut for saying "a > useful model of assignment that allows me to understand and predict its > behaviour." > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Jul 17 17:58:12 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Jul 2007 11:58:12 -0400 Subject: [Tutor] Good writeup on Python assignment semantics In-Reply-To: References: <469CAEB5.1090901@tds.net> <20070717140520.GSRV26408.inaamta12.mail.tds.net@sccrmhc13.comcast.net> <469CD480.6020402@tds.net> Message-ID: <469CE714.4070603@tds.net> jim stockford wrote: > > as I understand things... > > there's a writeup somewhere that uses the term "bind" instead > of "assign" for the operation > a = b Yes, that is how I prefer to talk about it - the effect of an assignment statement is to bind a name to a value. > > for example, in Python > a = 1 > the value 1 now has a name of a associated with it. > > in C > a = 1; > creates an integer-sized area in RAM, names it a, and puts > the value 1 in that area. > I'm curious to know the practical value of knowing the > difference: where can one get tripped up in this case? The problems come with mutable values. For example, a = [] b = a b.append(1) What is the current value of a? If your model of variables is storage containers, and your model of assignment is copying, you will expect that a and b are different lists and a==[]. But in Python, a and b are names for the same value, so a==b==[1]. This can occur in more subtle ways also. For example, parameter passing has the same semantics as assignment - it binds a name in the local scope to the passed-in value. If you pass a list as a value and modify the list, the caller will see the modification. This may or may not be what you want; if you model parameter passing as copying values you will be surprised by this behaviour. If you take this behaviour to mean that values are passed "by reference", then you may be surprised when an assignment to the parameter name in a function *doesn't* affect the value at the caller. In other words, given def f(x, y): x = 3 y.append(1) a = 5 b = [] f(a, b) What are the current values of a and b? Without a correct model of parameter passing you will not answer correctly. Kent From jim at well.com Tue Jul 17 18:00:31 2007 From: jim at well.com (jim stockford) Date: Tue, 17 Jul 2007 09:00:31 -0700 Subject: [Tutor] interpreter restarts In-Reply-To: <469CDCD6.5040406@brunson.com> References: <843928.81222.qm@web35107.mail.mud.yahoo.com> <469CDCD6.5040406@brunson.com> Message-ID: $ who am i unohoo $ which python /usr/bin/python $ python Python 2.3.4 (#1, Mar 20 2006, 00:23:47) [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print 1 1 >>> help() help> quit >>> $ $ vi doit.py $ ls doit.py $ python doit.py $ On Jul 17, 2007, at 8:14 AM, Eric Brunson wrote: > > Sara, > > Stick with ssh, IDE's are a crutch. ;-) > > But that's just my opinion, others may differ. > > However, if you were running an X server on your local machine, you > could use SSH to allow you to run GUI programs from your remote server. > There are a couple of free X servers for Windoze, but running Linux on > your local machine would give you the greatest success. If you are > interested in pursuing this, google up and install an X server, then > post back. > > Sincerely, > e. > > Sara Johnson wrote: >> Luke, Jacob, et. al... >> >> Dumb question (may be slightly off course from what you two were >> discussing), but are you both describing how to get the IDLE to run >> along with the editor? I may just be getting too many things >> confused. I've tried to run IDLE, but that's not working. I have the >> same function through opening it separately from the Start menu but >> then it doesn't work as IDLE should work with the editor (or so I've >> been told that happens). I can type the word Python in my editor and >> it comes up, but then the editor is gone. I've gone so long with just >> SSH, but at this point it's worth it if I find a way that makes >> sense. As someone mentioned from this list, at least it'll be code >> that is easier to read for a newbie like myself. >> >> (Hope that didn't confuse or cause unnecessary headaches...) >> >> Sara >> >> ----- Original Message ---- >> From: Luke Paireepinart >> To: Tiger12506 >> Cc: tutor at python.org >> Sent: Monday, July 16, 2007 7:00:53 PM >> Subject: Re: [Tutor] interpreter restarts >> >> Tiger12506 wrote: >>>> But there's an exception to that - if you right-click a file in >>>> Windoze >>>> and 'edit' it, >>>> IDLE won't open up its subprocess, and as such, it can't restart the >>>> interpreter session because it's running in the same >>>> process as IDLE, and to restart the interpreter would mean >>>> restarting >>>> IDLE. >>>> Boy, that 'edit with idle' thing sure does cause some problems, >> don't it? >>>> :) >>>> -Luke >>>> >>> >>> Thanks, Luke. I hadn't thought of that. Question: Why won't IDLE >> open up its >>> subprocess? >>> >>> This is the command that is in the registry concerning the Edit with >> IDLE >>> menu. >>> "C:\Python25\pythonw.exe" "C:\Python25\Lib\idlelib\idle.pyw" -n -e >>> "%1" >>> >>> This is the Target for the shortcut in the Start Menu (Note: the >> Target box >>> was disabled!) >>> Python 2.5.1 >>> >>> I thought that this was incredibly strange, so I opened this >> shortcut in a >>> hex editor to see what was different about this shortcut. (Normally, >> they >>> have a path in the target box) >>> >>> What I found surprised me. The title of the file in the hex editor >>> said >>> "python_icon.exe" >>> I started laughing maniacally and checked the full path of the file >> from >>> within the hex editor. >>> >> C:\windows\installer\{31800004-6386-4999-a519 >> -518f2d78d8f0}\python_icon.exe >>> >>> IDLE is started in two *very* different ways. So my next question >> was: Can >>> you pass arguments to this python_icon.exe? Simple navigations to >>> that >>> directory and a confirmation... Yuck. You can't even execute it from >>> explorer. A low-level ZwTerminateProcess function from ntdll is >> called ... >>> Let me try something... >>> >>> Woah... {31800004-6386-4999-a519-518f2d78d8f0} appears in the >> registry in >>> alot of places. The Uninstall key for Add/Remove Programs, some >> weird data >>> thing... Okay, this is beyond me. I don't know the registry or >> understand >>> CLSIDs very well. Someone who knows Windows inside and out has done >> a number >>> with the python installer, or at least the msi installer does this >>> all >>> automatically. Interesting. I wonder just how python_icon.exe starts >> IDLE. >>> If I could figure that out, I could emulate it with the Edit w/Idle >> menu >>> item and get IDLE to start a subprocess! But how.... any ideas? >>> >> It sounds like python_icon.exe is a fake executable that just contains >> the icon for python programs... >> hence the name. >> You probably stumbled across the path to the icon to use, instead of >> the >> path that is used when running the 'Edit with IDLE' thing. >> Try this: >> open an Explorer window, via Start Button -> Run -> explorer {ENTER} >> or your favorite method. Use the My Computer shortcut if you want, >> either way. >> Now hit "Alt, t, o" to browse to the Tools -> Folder Options menu >> setting. >> Go to the File Types tab, and scroll down till you find "PY" >> click the Advanced button. >> You should now see a dialog box with Edit with IDLE listed under >> actions. >> Click Edit when "Edit with IDLE" is selected. >> in the "Application used to perform action:" field you should see >> something like this: >> >> "C:\Python24\pythonw.exe" "C:\Python24\Lib\idlelib\idle.pyw" -n -e >> "%1" >> >> Basically, this is the same as saying: >> python idle.py >> except it's more verbose because python may not be on your path (and >> pythonw is used instead of python so there's no dos box) >> As you will notice, there are some parameters there at the end. >> the -n is the one you're interested in . >> -n means no subprocess. >> Just remove that, and you will have a subprocess on the 'Edit with >> IDLE' >> feature. >> There is some caveat here - it doesn't work correctly on some systems, >> I'm told. >> I've never had problems changing this, but I don't recommend it to >> people randomly just in case it were to cause problems for them. >> Then I'd feel bad. >> But since you asked, I thought I'd give you all the info you need. >> HTH, >> -Luke >> P.S. nice detective skillz ;) >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> ---------------------------------------------------------------------- >> -- >> Get the Yahoo! toolbar and be alerted to new email >> > toolbar/features/mail/index.php>wherever >> you're surfing. >> ---------------------------------------------------------------------- >> -- >> >> _______________________________________________ >> 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 > From keridee at jayco.net Tue Jul 17 19:18:31 2007 From: keridee at jayco.net (Tiger12506) Date: Tue, 17 Jul 2007 12:18:31 -0500 Subject: [Tutor] reading random line from a file References: <023601c7c7c0$c87c0e10$18fde004@JSLAPTOP> <3D8D64A9-0449-407D-A972-E43A1DF40D97@gmail.com> Message-ID: <002f01c7c896$83926ed0$c7fde004@JSLAPTOP> > wow thats pretty cool :) it's a bit above my level but it's interesting > :) thanks I'm deeply flattered! Thank you. >> ############################################# >> from os import stat os.stat returns a tuple whose 7th member is the size of the file. (python docs) >> from random import randint randint(a,b) returns a random integer between a and b, inclusive >> def getrandomline(f, length): >> pos = randint(0,length) Picks a random position between the beginning and the end of the file. >> f.seek(pos) Seek to that position in the file - i.e. the next character read will be at that position in the file. >> while f.read(1)!='\n': This sets up the loop. Read a character, if it is a newline then break the loop >> try: >> f.seek(-2,1) However, if it's not a newline character, that means we are in the middle of a line, so we move the file position two characters back from where we just were. Two characters because f.read(1) moves the position forward one. One step forward, two steps back means read character right before. Continuing this loop means that eventually we will back up until we meet a newline character, that is, the beginning of the line where our randomly chosen character belongs. >> except IOError: f.seek(0) This is a special case where randint chose a character in the first line. Thinking about it a bit, we realize that backing up will never find a newline, and loop will never break. OOPS! I just realized a mistake I made. There should be a break afterwards. except IOError: f.seek(0) break See! Anyway. When you seek before the beginning of a file, an IOError is raised. I caught it here and set the file position properly. (The beginning of the first line in this special case) >> return f.readline() Since the file position is set at the beginning of a random line, the readline function will read that line and return it. >> f = file("quotes.txt","rb") >> sizeoffile = stat("quotes.txt")[6] As I said above, the 7th member of the stat tuple gives the file size so that I can use it in randint >> while (1): >> print getrandomline(f, sizeoffile), Obviously you won't use this - it was just to maintain the program while I checked it's memory usage. >> f.close() >> ################################### See! Not a bit above your level. ;-) HTH, JS From keridee at jayco.net Tue Jul 17 19:33:54 2007 From: keridee at jayco.net (Tiger12506) Date: Tue, 17 Jul 2007 12:33:54 -0500 Subject: [Tutor] IDLE Usage - was Interpreter Restarts References: <114046.30409.qm@web35107.mail.mud.yahoo.com><469C527B.7020103@gmail.com> Message-ID: <00ad01c7c898$a744b2f0$c7fde004@JSLAPTOP> Yeah. But she's running Windows. Perhaps vim is scary to some Windows users. (I thought it was scary and annoying. Are all those ~ characters really in the file or not? I kept second guessing the editor.) --Sara, could you give an example of how it doesn't work? Just what happens? Just what doesn't happen? You say you have Python 2.3 installed... > Greetings, > > I use an editor called 'vim' on GNU/Linux. > I invoke vim on the command-line by typing: vi > (vi is a link to /usr/bin/vim) > In my home directory I have a vim config file > named .vimrc (that is: dot_vimrc [the dot makes it hidden]). > The .vimrc file has some things in it that do some nice stuff > for editing Python files; such as syntax highlighting, line numbers, > indenting, and also runs Python when I press the F2 function key. > I run vim in an X ternminal called Konsole. I can also run it > from the command-line in any tty. > > Okay, here it is. Just copy/paste this into an editor, and save it as: > .vimrc > > -------------8<------Cut Here-------->8--------------- > " .vimrc > " > " Created by Jeff Elkner 23 January 2006 > " Last modified 2 February 2006 > " > " Turn on syntax highlighting and autoindenting > syntax enable > filetype indent on > " set autoindent width to 4 spaces (see > " http://www.vim.org/tips/tip.php?tip_id=83) > set nu > set et > set sw=4 > set smarttab > " Bind key to running the python interpreter on the currently active > " file. (curtesy of Steve Howell from email dated 1 Feb 2006). > map :w\|!python % > -------------8<------Cut Here-------->8--------------- > > To use it, just type: vi myCode.py > (If you don't have a link named vi that points to /usr/bin/vim, > you'll have to type vim or /usr/bin/vim to get it going... > since I don't have any idea what you're working at, I can't say.) > > Once you're in vim, looking at your code, press F2 to run it. > > I understand that Emacs also does Python! =) > But I won't go there... I don't do Emacs. > -- > bhaaluu at gmail dot com > > On 7/17/07, Luke Paireepinart wrote: >> A lot of Python programmers >> use Vi for writing their code. do you have access to that through SSH? >> I'm not quite sure what you mean by "SSH editor." >> -Luke >> _______________________________________________ >> 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 > From sarliz73 at yahoo.com Tue Jul 17 19:03:02 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Tue, 17 Jul 2007 10:03:02 -0700 (PDT) Subject: [Tutor] IDLE Usage - was Interpreter Restarts Message-ID: <639779.46736.qm@web35101.mail.mud.yahoo.com> Everyone who has commented... I have XWin32....It hasn't worked. I've talked to some people in the IT departments and they've given me things to check (boxes to check or uncheck) and that doesn't seem to make a difference. When I picked up these projects I was given a lot of stuff and left to figure it out. I was also left with the impression that I should have the GUI working. If a lot of Python programmers use SSH, then I guess there is no problem. But when you're a newbie who really doesn't understand what they're doing, anything that might make the process a tad more straight-forward is worth it. For example, I worked on this basic Unix editor 'Pico' before I learned I could switch to Vi and have my code color-coordinated so that I knew where my comments were and I could see if I accidentally commented something out that needs to be there. So maybe it's not too important that I use the Python shell with my school's editor program open (as I was advised to do). Some of you have already seen my confusion from the different questions I've asked about my code (or rather, the code I've been editing). So I thought most of the Python programmers preferred to use IDLE and that maybe it would simplify things just a tad for me. I'm about 2000 miles away from where I should be with these projects. Thanks, Sara ----- Original Message ---- From: Luke Paireepinart To: Sara Johnson Cc: tutor at python.org Sent: Tuesday, July 17, 2007 12:24:11 AM Subject: Re: [Tutor] IDLE Usage - was Interpreter Restarts Sara Johnson wrote: > First off, yes, I was referring to (I guess you could say) a > non-python editor. I use an SSH editor set up by my school. If I > type python at the prompt in SSH, I get the Python shell. My problem > is, I can't open a GUI no matter what I subscribe to or purchase. I > have Python 2.3 and yes, I can access the commandline, but that does > not work the way it's been described to work. > > If this still doesn't make any sense, just ignore me... I'm not sure what your problem is. Does the SSH program provide a file transfer utility? could you write your code on your local computer then just transfer the final code to the server? A lot of Python programmers use Vi for writing their code. do you have access to that through SSH? I'm not quite sure what you mean by "SSH editor." -Luke _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ____________________________________________________________________________________ Need a vacation? Get great deals to amazing places on Yahoo! Travel. http://travel.yahoo.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070717/bb955936/attachment.htm From sarliz73 at yahoo.com Tue Jul 17 19:09:28 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Tue, 17 Jul 2007 10:09:28 -0700 (PDT) Subject: [Tutor] IDLE Usage - was Interpreter Restarts Message-ID: <448583.64093.qm@web35108.mail.mud.yahoo.com> I initially thought Vim was sort of the same as Vi, just a few small differences or upgrades. Or have I got that confused? Sara ----- Original Message ---- From: Tiger12506 To: tutor at python.org Sent: Tuesday, July 17, 2007 12:33:54 PM Subject: Re: [Tutor] IDLE Usage - was Interpreter Restarts Yeah. But she's running Windows. Perhaps vim is scary to some Windows users. (I thought it was scary and annoying. Are all those ~ characters really in the file or not? I kept second guessing the editor.) --Sara, could you give an example of how it doesn't work? Just what happens? Just what doesn't happen? You say you have Python 2.3 installed... > Greetings, > > I use an editor called 'vim' on GNU/Linux. > I invoke vim on the command-line by typing: vi > (vi is a link to /usr/bin/vim) > In my home directory I have a vim config file > named .vimrc (that is: dot_vimrc [the dot makes it hidden]). > The .vimrc file has some things in it that do some nice stuff > for editing Python files; such as syntax highlighting, line numbers, > indenting, and also runs Python when I press the F2 function key. > I run vim in an X ternminal called Konsole. I can also run it > from the command-line in any tty. > > Okay, here it is. Just copy/paste this into an editor, and save it as: > .vimrc > > -------------8<------Cut Here-------->8--------------- > " .vimrc > " > " Created by Jeff Elkner 23 January 2006 > " Last modified 2 February 2006 > " > " Turn on syntax highlighting and autoindenting > syntax enable > filetype indent on > " set autoindent width to 4 spaces (see > " http://www.vim.org/tips/tip.php?tip_id=83) > set nu > set et > set sw=4 > set smarttab > " Bind key to running the python interpreter on the currently active > " file. (curtesy of Steve Howell from email dated 1 Feb 2006). > map :w\|!python % > -------------8<------Cut Here-------->8--------------- > > To use it, just type: vi myCode.py > (If you don't have a link named vi that points to /usr/bin/vim, > you'll have to type vim or /usr/bin/vim to get it going... > since I don't have any idea what you're working at, I can't say.) > > Once you're in vim, looking at your code, press F2 to run it. > > I understand that Emacs also does Python! =) > But I won't go there... I don't do Emacs. > -- > bhaaluu at gmail dot com > > On 7/17/07, Luke Paireepinart wrote: >> A lot of Python programmers >> use Vi for writing their code. do you have access to that through SSH? >> I'm not quite sure what you mean by "SSH editor." >> -Luke >> _______________________________________________ >> 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 > _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ____________________________________________________________________________________ Boardwalk for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's economy) at Yahoo! Games. http://get.games.yahoo.com/proddesc?gamekey=monopolyherenow -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070717/1df7b95a/attachment.htm From sarliz73 at yahoo.com Tue Jul 17 19:20:01 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Tue, 17 Jul 2007 10:20:01 -0700 (PDT) Subject: [Tutor] IDLE Usage - was Interpreter Restarts Message-ID: <716926.48897.qm@web35115.mail.mud.yahoo.com> Sorry all... SSH editor means "Unix" ____________________________________________________________________________________ Shape Yahoo! in your own image. Join our Network Research Panel today! http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070717/b06320bb/attachment.html From jim at well.com Tue Jul 17 19:30:12 2007 From: jim at well.com (jim stockford) Date: Tue, 17 Jul 2007 10:30:12 -0700 Subject: [Tutor] IDLE Usage - was Interpreter Restarts In-Reply-To: <114046.30409.qm@web35107.mail.mud.yahoo.com> References: <114046.30409.qm@web35107.mail.mud.yahoo.com> Message-ID: <87fe7719922f51b3b7af28711d9b6be9@well.com> you want a very brief set of vi(m) commands-- a get-you-started tutorial that's nearly painless? I'll send if "yes". jim On Jul 16, 2007, at 9:26 PM, Sara Johnson wrote: > First off, yes, I was referring to (I guess you could say) a > non-python editor.? I use an SSH editor set up by my school.? If I > type python at the prompt in SSH, I get the Python shell. ?My problem > is, I can't open a GUI no matter what I subscribe to or purchase.? I > have Python 2.3 and yes, I can access the commandline, but that does > not work the?way it's been described to work. > ? > If this still doesn't make any sense, just ignore me... > ? > Sara > > > >>Not quite what we were discussing, but I think you may have given > just > enough clues that i can be of some help. Just for reference ~ which > editor > are you using? > > IDLE is both an editor and a python shell or interpreter. It is not > the same > thing as typing python.exe wherever you might be typing it. > > Typing Python into an editor should put the word "Python" into your > currently open file. I don't believe that this is what you mean. > Perhaps you > are confusing what exactly is an editor? > > You use Windows you've mentioned before. So here's what you can do. > Start -> > Programs -> Python 2.5 -> Python (commandline) > > This is the python interpreter. As you might already know. > > And then this. > Start -> Programs -> Python 2.5 -> IDLE (Python GUI) > > This is IDLE. As you probably know. > > Two windows should come up when you click IDLE. One is an editor. The > other > is the python shell, or interpreter. You can open .py files in IDLE by > right > clicking and selecting "Edit with IDLE". At any time that you wish to > run a > program that is open in the editor half of IDLE, hit F5 and the Python > shell > half of IDLE comes to the top and runs the program. > > If doing all that doesn't do what I expect it to do, or you have > something > else in mind, reply back. If it does, then great! > > Oh. And tell me which editor you are using which magically opens a > python > interpreter when you type Python into it. ;-) > > JS > > _______________________________________________ > Tutor maillist??-??Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > Moody friends. Drama queens. Your life? Nope! - their life, your story. > Play Sims Stories at Yahoo! > Games._______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From humbolt at comcast.net Tue Jul 17 19:31:30 2007 From: humbolt at comcast.net (Robert H. Haener IV) Date: Tue, 17 Jul 2007 13:31:30 -0400 Subject: [Tutor] IDLE Usage - was Interpreter Restarts In-Reply-To: <448583.64093.qm@web35108.mail.mud.yahoo.com> References: <448583.64093.qm@web35108.mail.mud.yahoo.com> Message-ID: <469CFCF2.7040909@comcast.net> Sara Johnson wrote: > I initially thought Vim was sort of the same as Vi, just a few small > differences or upgrades. Or have I got that confused? > > Sara Vim is Vi Improved. I only know enough about its workings to be functional, but as I recall there is practically no difference between vi and vim when in comes to basic editing tasks. -Robert From zmachinez at gmail.com Tue Jul 17 19:45:41 2007 From: zmachinez at gmail.com (z machinez) Date: Tue, 17 Jul 2007 13:45:41 -0400 Subject: [Tutor] Basic DB question In-Reply-To: <469B98BC.5090708@kostyrka.org> References: <469B98BC.5090708@kostyrka.org> Message-ID: Thank you. I am mainly interested in finding ways to connect to aKDB+ (KX Systems). That is the relational database that we are using. And I would like to open a connection to it. I understand from the vendor that they do not have a good ODBC driver. So if anyone has experience connecting to them, I would appreciate any advice. Thank you. On 7/16/07, Andreas Kostyrka wrote: > > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > DBAPI is an interface standard describing what you can expect in a > database access module, like psycopg. > > Andreas > > z machinez wrote: > > Hi All, > > > > I am just starting out with Python and was hoping someone could point me > > in the direction of reading materials for working with RDBMS? In > > particular, I am working with two various relational databases. One of > > which stores real-time data for trading. In Python I am planning on > > building various time series models to collate historical tick data and > > real-time data. As I am very new to Python, I was hoping someone could > > recommend some docs/books. > > > > I have read up on the DBAPI, but do not think this is what I need. I > > might be wrong though. > > > > Thanks in advance for the help. > > > > Z. > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.2 (GNU/Linux) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iD8DBQFGm5i8HJdudm4KnO0RAgxtAKDLosrBW+t1pRHdo9EBH+V8TreSwQCg6A9a > oNXWmoAk25u7GxiiVeO4YdU= > =D7JY > -----END PGP SIGNATURE----- > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070717/90f07079/attachment.htm From jim at well.com Tue Jul 17 19:51:53 2007 From: jim at well.com (jim stockford) Date: Tue, 17 Jul 2007 10:51:53 -0700 Subject: [Tutor] IDLE Usage - was Interpreter Restarts In-Reply-To: <448583.64093.qm@web35108.mail.mud.yahoo.com> References: <448583.64093.qm@web35108.mail.mud.yahoo.com> Message-ID: <3cc1c4aa2451d46576c2bcea80ad021e@well.com> change "small" to "large" and you're right. Vim is Vi improved. Any tutorial or reference on Vi ought to work for Vim. On Jul 17, 2007, at 10:09 AM, Sara Johnson wrote: > I initially thought Vim was sort of the same as Vi, just a few small > differences or upgrades.? Or have I got that confused? > ? > Sara > > ----- Original Message ---- > From: Tiger12506 > To: tutor at python.org > Sent: Tuesday, July 17, 2007 12:33:54 PM > Subject: Re: [Tutor] IDLE Usage - was Interpreter Restarts > > Yeah. But she's running Windows. > Perhaps vim is scary to some Windows users. > (I thought it was scary and annoying. Are all those ~ characters > really in > the file or not? > I kept second guessing the editor.) > > --Sara, could you give an example of how it doesn't work? > ??Just what happens? Just what doesn't happen? > > You say you have Python 2.3 installed... > > > > Greetings, > > > > I use an editor called 'vim' on GNU/Linux. > > I invoke vim on the command-line by typing: vi > > (vi is a link to /usr/bin/vim) > > In my home directory I have a vim config file > > named .vimrc (that is: dot_vimrc [the dot makes it hidden]). > > The .vimrc file has some things in it that do some nice stuff > > for editing Python files; such as syntax highlighting, line numbers, > > indenting, and also runs Python when I press the F2 function key. > > I run vim in an X ternminal called Konsole. I can also run it > > from the command-line in any tty. > > > > Okay, here it is. Just copy/paste this into an editor, and save it > as: > > .vimrc > > > > -------------8<------Cut Here-------->8--------------- > > " .vimrc > > " > > " Created by Jeff Elkner 23 January 2006 > > " Last modified 2 February 2006 > > " > > " Turn on syntax highlighting and autoindenting > > syntax enable > > filetype indent on > > " set autoindent width to 4 spaces (see > > " http://www.vim.org/tips/tip.php?tip_id=83) > > set nu > > set et > > set sw=4 > > set smarttab > > " Bind key to running the python interpreter on the currently > active > > " file.??(curtesy of Steve Howell from email dated 1 Feb 2006). > > map :w\|!python % > > -------------8<------Cut Here-------->8--------------- > > > > To use it, just type: vi myCode.py > > (If you don't have a link named vi that points to /usr/bin/vim, > > you'll have to type vim or /usr/bin/vim to get it going... > > since I don't have any idea what you're working at, I can't say.) > > > > Once you're in vim, looking at your code, press F2 to run it. > > > > I understand that Emacs also does Python! =) > > But I won't go there... I don't do Emacs. > > -- > > bhaaluu at gmail dot com > > > > On 7/17/07, Luke Paireepinart wrote: > >> A lot of Python programmers > >> use Vi for writing their code.??do you have access to that through > SSH? > >> I'm not quite sure what you mean by "SSH editor." > >> -Luke > >> _______________________________________________ > >> 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 > > > > _______________________________________________ > Tutor maillist??-??Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > Got a little couch potato? > Check out fun summer activities for > kids._______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From humbolt at comcast.net Tue Jul 17 19:49:25 2007 From: humbolt at comcast.net (Robert H. Haener IV) Date: Tue, 17 Jul 2007 13:49:25 -0400 Subject: [Tutor] IDLE Usage - was Interpreter Restarts In-Reply-To: <639779.46736.qm@web35101.mail.mud.yahoo.com> References: <639779.46736.qm@web35101.mail.mud.yahoo.com> Message-ID: <469D0125.3030502@comcast.net> Sara Johnson wrote: > Everyone who has commented... > > I have XWin32....It hasn't worked. I've talked to some people in the IT > departments and they've given me things to check (boxes to check or > uncheck) and that doesn't seem to make a difference. > > When I picked up these projects I was given a lot of stuff and left to > figure it out. I was also left with the impression that I should have > the GUI working. If a lot of Python programmers use SSH, then I guess > there is no problem. But when you're a newbie who really doesn't > understand what they're doing, anything that might make the process a > tad more straight-forward is worth it. For example, I worked on this > basic Unix editor 'Pico' before I learned I could switch to Vi and have > my code color-coordinated so that I knew where my comments were and I > could see if I accidentally commented something out that needs to be > there. So maybe it's not too important that I use the Python shell with > my school's editor program open (as I was advised to do). Some of you > have already seen my confusion from the different questions I've asked > about my code (or rather, the code I've been editing). So I thought > most of the Python programmers preferred to use IDLE and that maybe it > would simplify things just a tad for me. I'm about 2000 miles away from > where I should be with these projects. > > Thanks, > Sara It sounds like the SSH server you're connecting to isn't set to allow X Forwarding; either that, or your SSH client isn't set to use X Forwarding. Here is a page which describes how to use the SSH server's GUI programs from your computer via X Forwarding, bear in mind that it's written with regard to a college's server and therefore will include a few specific instructions that don't apply to you: http://ugweb.cs.ualberta.ca/howtos/XForwarding/index.html If you name the SSH client (which I believe you've been calling an "SSH editor") you're using, I might be able to give you step by step instructions for setting your client to use X Forwarding. If the SSH server doesn't allow X Forwarding, I recommend using a program called 'screen'. Basically, 'screen' allows you to use a shell a bit like the tabbed browsing in Firefox (or Opera, IE7, etc.) by creating a framework wherein you can create new virtual shells and switch between them using keyboard shortcuts. What is more, you can label the virtual shells and even copy/paste text between them. I can give you plenty of information about using 'screen' if you want it, what I'm getting around to is that if I was in your situation I would have the python interpreter running in one virtual shell whilst running vim in another virtual shell. -Robert From queprime at gmail.com Tue Jul 17 17:09:45 2007 From: queprime at gmail.com (Que Prime) Date: Tue, 17 Jul 2007 08:09:45 -0700 Subject: [Tutor] File parse Message-ID: <17285ccf0707170809p48799327k1e33937f536a0c3a@mail.gmail.com> I'm trying to parse a file and extract 'src=172.16.148.27 dst=10.52.10.10' out of each line that contains 10.52.10.10, but get lost with writing the information and am not sure if I should .re at all. import re infile = open("in.txt","r") outfile = open("out.txt", "w") for line in infile: re.match('src=*10.52.10.10') outfile.write(re.compile) ofile.close() wfile.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070717/429a259e/attachment.html From kent37 at tds.net Tue Jul 17 20:00:16 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Jul 2007 14:00:16 -0400 Subject: [Tutor] Good writeup on Python assignment semantics In-Reply-To: <469CD480.6020402@tds.net> References: <469CAEB5.1090901@tds.net> <20070717140520.GSRV26408.inaamta12.mail.tds.net@sccrmhc13.comcast.net> <469CD480.6020402@tds.net> Message-ID: <469D03B0.7010605@tds.net> Kent Johnson wrote: > I think to write correct programs in any language, you must have a > correct mental model of what the program is doing, where by 'correct' I > mean a model that is consistent with the actual behaviour of the program. Here is a sketch of what the different parts of a model for Python might be: http://wiki.python.org/moin/ConceptualRoadmap Kent From sarliz73 at yahoo.com Tue Jul 17 20:01:59 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Tue, 17 Jul 2007 11:01:59 -0700 (PDT) Subject: [Tutor] IDLE Usage - was Interpreter Restarts Message-ID: <440190.65323.qm@web35111.mail.mud.yahoo.com> Sure, sounds good. Should I assume that 'any' Unix version allows Vim? Thanks, Sara ----- Original Message ---- From: jim stockford To: Sara Johnson Cc: tutor at python.org Sent: Tuesday, July 17, 2007 12:30:12 PM Subject: Re: [Tutor] IDLE Usage - was Interpreter Restarts you want a very brief set of vi(m) commands-- a get-you-started tutorial that's nearly painless? I'll send if "yes". jim On Jul 16, 2007, at 9:26 PM, Sara Johnson wrote: > First off, yes, I was referring to (I guess you could say) a > non-python editor. I use an SSH editor set up by my school. If I > type python at the prompt in SSH, I get the Python shell. My problem > is, I can't open a GUI no matter what I subscribe to or purchase. I > have Python 2.3 and yes, I can access the commandline, but that does > not work the way it's been described to work. > > If this still doesn't make any sense, just ignore me... > > Sara > > > >>Not quite what we were discussing, but I think you may have given > just > enough clues that i can be of some help. Just for reference ~ which > editor > are you using? > > IDLE is both an editor and a python shell or interpreter. It is not > the same > thing as typing python.exe wherever you might be typing it. > > Typing Python into an editor should put the word "Python" into your > currently open file. I don't believe that this is what you mean. > Perhaps you > are confusing what exactly is an editor? > > You use Windows you've mentioned before. So here's what you can do. > Start -> > Programs -> Python 2.5 -> Python (commandline) > > This is the python interpreter. As you might already know. > > And then this. > Start -> Programs -> Python 2.5 -> IDLE (Python GUI) > > This is IDLE. As you probably know. > > Two windows should come up when you click IDLE. One is an editor. The > other > is the python shell, or interpreter. You can open .py files in IDLE by > right > clicking and selecting "Edit with IDLE". At any time that you wish to > run a > program that is open in the editor half of IDLE, hit F5 and the Python > shell > half of IDLE comes to the top and runs the program. > > If doing all that doesn't do what I expect it to do, or you have > something > else in mind, reply back. If it does, then great! > > Oh. And tell me which editor you are using which magically opens a > python > interpreter when you type Python into it. ;-) > > JS > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > Moody friends. Drama queens. Your life? Nope! - their life, your story. > Play Sims Stories at Yahoo! > Games._______________________________________________ > 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 ____________________________________________________________________________________ 8:00? 8:25? 8:40? Find a flick in no time with the Yahoo! Search movie showtime shortcut. http://tools.search.yahoo.com/shortcuts/#news -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070717/5904253f/attachment.htm From humbolt at comcast.net Tue Jul 17 20:09:14 2007 From: humbolt at comcast.net (Robert H. Haener IV) Date: Tue, 17 Jul 2007 14:09:14 -0400 Subject: [Tutor] IDLE Usage - was Interpreter Restarts In-Reply-To: <440190.65323.qm@web35111.mail.mud.yahoo.com> References: <440190.65323.qm@web35111.mail.mud.yahoo.com> Message-ID: <469D05CA.9060000@comcast.net> Sara Johnson wrote: > Sure, sounds good. Should I assume that 'any' Unix version allows Vim? > > Thanks, > Sara Vim is extremely ubiquitous, you can check to see if it's installed by entering 'which vim' at the shell. -Robert From sarliz73 at yahoo.com Tue Jul 17 20:22:57 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Tue, 17 Jul 2007 11:22:57 -0700 (PDT) Subject: [Tutor] IDLE Usage - was Interpreter Restarts Message-ID: <203180.79521.qm@web35104.mail.mud.yahoo.com> ----- Original Message ---- From: Robert H. Haener IV humbolt at comcast.net If you name the SSH client (which I believe you've been calling an "SSH editor") you're using, I might be able to give you step by step instructions for setting your client to use X Forwarding. If the SSH server doesn't allow X Forwarding, I recommend using a program called 'screen'. Basically, 'screen' allows you to use a shell a bit like the tabbed browsing in Firefox (or Opera, IE7, etc.) by creating a framework wherein you can create new virtual shells and switch between them using keyboard shortcuts. What is more, you can label the virtual shells and even copy/paste text between them. I can give you plenty of information about using 'screen' if you want it, what I'm getting around to is that if I was in your situation I would have the python interpreter running in one virtual shell whilst running vim in another virtual shell. ================================ That's pretty much what I was attempting. I was advised to mark the "Tunneling" box (TunnelingX11 Connections), and it's checked. I don't see the X Forwarding option, however. Under that same tab I checked for anything else system-wise that would pertain and I don't see anything. Again, I have XWin32 installed, but I probably need to renew it or somehow get it to work as you've described. Anything else I should check? >>For example, I worked on this basic Unix editor 'Pico' before I learned I could switch to Vi and >>have Sorry...I meant to say "Putty" not Pico... Not important, just clarifying. Thanks, Sara ____________________________________________________________________________________ Get the Yahoo! toolbar and be alerted to new email wherever you're surfing. http://new.toolbar.yahoo.com/toolbar/features/mail/index.php -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070717/6ab4b577/attachment.html From humbolt at comcast.net Tue Jul 17 20:49:19 2007 From: humbolt at comcast.net (Robert H. Haener IV) Date: Tue, 17 Jul 2007 14:49:19 -0400 Subject: [Tutor] IDLE Usage - was Interpreter Restarts In-Reply-To: <203180.79521.qm@web35104.mail.mud.yahoo.com> References: <203180.79521.qm@web35104.mail.mud.yahoo.com> Message-ID: <469D0F2F.4020403@comcast.net> Sara Johnson wrote: > That's pretty much what I was attempting. I was advised to mark the > "Tunneling" box (TunnelingX11 Connections), and it's checked. I don't > see the X Forwarding option, however. Under that same tab I checked for > anything else system-wise that would pertain and I don't see anything. > Again, I have XWin32 installed, but I probably need to renew it or > somehow get it to work as you've described. Anything else I should check? > >>>For example, I worked on this basic Unix editor 'Pico' before I > learned I could switch to Vi and >>have > Sorry...I meant to say "Putty" not Pico... Not important, just clarifying. > > Thanks, > Sara I have never attempted to use X Forwarding in Windows, but here is a guide that seems to tell you all you need to know: http://www.math.umn.edu/systems_guide/putty_xwin32.html >From what I can gather, you should contact whomever is in charge of the SSH server if you can't get GUI programs working after following that guide. Also, just so we don't end up massively confusing each other: PuTTy is your "SSH client." The server to which you are connecting is the "SSH server." Pico and Vim are examples of "text editors," which are sometimes called "UNIX editors" by Windows folks. -Robert From keridee at jayco.net Tue Jul 17 23:14:48 2007 From: keridee at jayco.net (Tiger12506) Date: Tue, 17 Jul 2007 16:14:48 -0500 Subject: [Tutor] File parse References: <17285ccf0707170809p48799327k1e33937f536a0c3a@mail.gmail.com> Message-ID: <02e501c7c8b7$873c8810$c7fde004@JSLAPTOP> > I'm trying to parse a file and extract 'src=172.16.148.27 dst=10.52.10.10' > out of each line that contains 10.52.10.10, but get lost with writing the > information and am not sure if I should .re at all. Could you send a few lines of "in.txt"? I can help better. > import re > > infile = open("in.txt","r") > outfile = open("out.txt", "w") > > for line in infile: > re.match('src=*10.52.10.10') This will not help you whatsoever. You will have to check the return of re.match. Also, I suspect that your re pattern could use some tweaking. Those lines from your file? From carroll at tjc.com Tue Jul 17 23:51:34 2007 From: carroll at tjc.com (Terry Carroll) Date: Tue, 17 Jul 2007 14:51:34 -0700 (PDT) Subject: [Tutor] IDLE Usage - was Interpreter Restarts In-Reply-To: <440190.65323.qm@web35111.mail.mud.yahoo.com> Message-ID: Sara -- I'd also recommend that you find and install a Windows version of whatever editor (whether vi, vim or something else like emacs) you're going to be using on the Unix box. Play with it locally on your own machine for a while and get comfortable with it, and then start using the copy on the unix system. That will let you take baby steps, and gain a little confidence. From keridee at jayco.net Wed Jul 18 03:39:33 2007 From: keridee at jayco.net (Tiger12506) Date: Tue, 17 Jul 2007 20:39:33 -0500 Subject: [Tutor] File parse References: <17285ccf0707170809p48799327k1e33937f536a0c3a@mail.gmail.com> <02e501c7c8b7$873c8810$c7fde004@JSLAPTOP> <17285ccf0707171450o703a569dj36e84583ad404010@mail.gmail.com> Message-ID: <002201c7c8dc$81fd9b30$93fce004@JSLAPTOP> > Here you go. > > I've been working on something like this, but it's mixing the 2. Thanks > for > helping me. Okay. But you still haven't given me a few lines of your input file. The "in.txt" that you are using in your code. > import re > > infile = open("in.txt","r") > outfile = open("out.txt", "w") > > patt = 'src=\*10.52.10.10' > > m = re.match(line, patt) > > > for line in infile: > if z in line: > outfile.write(z) > > > ofile.close() > wfile.close() Mmmm. This isn't making sense. This is better syntactically. But I will need your data file in order to fix the actual regular expression ####################### import re infile = open("in.txt","r") outfile = open("out.txt","w") patt = re.compile('src=\*10.52.10.10') # I am absolutely sure this is not the re exp you want for line in infile: m = patt.match(line) if m: outfile.write(m.group()[0]) ofile.close() wfile.close() ####################### Give me data. I'll fix your re. ;-) JS From bhaaluu at gmail.com Wed Jul 18 02:52:21 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 17 Jul 2007 20:52:21 -0400 Subject: [Tutor] IDLE Usage - was Interpreter Restarts In-Reply-To: References: <440190.65323.qm@web35111.mail.mud.yahoo.com> Message-ID: On 7/17/07, Terry Carroll wrote: > Sara -- > > I'd also recommend that you find and install a Windows version of whatever > editor (whether vi, vim or something else like emacs) you're going to be > using on the Unix box. Play with it locally on your own machine for a > while and get comfortable with it, and then start using the copy on the > unix system. That will let you take baby steps, and gain a little > confidence. This is an excellent idea! =) There are tutorials for vi, emacs, etc. available on MS-Windows platforms. -- bhaaluu at gmail dot com From keridee at jayco.net Wed Jul 18 07:30:36 2007 From: keridee at jayco.net (Tiger12506) Date: Wed, 18 Jul 2007 00:30:36 -0500 Subject: [Tutor] File parse References: <17285ccf0707170809p48799327k1e33937f536a0c3a@mail.gmail.com> <02e501c7c8b7$873c8810$c7fde004@JSLAPTOP> <17285ccf0707171450o703a569dj36e84583ad404010@mail.gmail.com> <002201c7c8dc$81fd9b30$93fce004@JSLAPTOP> <17285ccf0707172030q22aff38ai4f24f872fcc2eac0@mail.gmail.com> Message-ID: <003d01c7c8fc$c9400bc0$affde004@JSLAPTOP> >I sent a sample of the file "testin.txt" in the last email. Here are the > lines themsevles: Oh! Sorry. I didn't look in the attachments - I expected the lines in the email. My mistake. Try this ~~ :-P ############################## import re infile = open("testin.txt","r") outfile = open("out.txt","w") patt = re.compile(r".*src=([\d\.]*) dst=([\d\.]*).*") for line in infile: m = patt.match(line) if m: outfile.write("src=%s dst=%s\n"%m.groups()) infile.close() outfile.close() ############################# Seeing the input file makes me wonder if regular expressions is over kill in this instance. JS From kent37 at tds.net Wed Jul 18 12:09:14 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Jul 2007 06:09:14 -0400 Subject: [Tutor] Serve a file using http In-Reply-To: References: Message-ID: <469DE6CA.6020201@tds.net> Sebastian Lara wrote: > Hello all, > > I'm using a SimpleXMLRPCServer to update a file remotely from a simple > xml-rpc python client. After that, I need to serve this file but I > don't know if I can do this with SimpleXMLRPCServer or if I need > another server. If you want to serve the file over HTTP so it is visible in a browser you will need another server. If your needs are simple then SimpleHTTPServer, in the standard library, may work for you. If you need more functionality then you should look at the other HTTP servers available for Python such as CherryPy and Karrigell. Kent From kent37 at tds.net Wed Jul 18 12:19:38 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Jul 2007 06:19:38 -0400 Subject: [Tutor] reading random line from a file In-Reply-To: <023601c7c7c0$c87c0e10$18fde004@JSLAPTOP> References: <023601c7c7c0$c87c0e10$18fde004@JSLAPTOP> Message-ID: <469DE93A.1000003@tds.net> Tiger12506 wrote: > If you truly wish to kill yourself trying to make it as efficient memory as > possible, then you can follow this example. (This is more like what I would > write in C). > The getrandomline function picks a random byte between the beginning and the > end of the file, then backs up until the beginning of the line and uses > readline to return the whole line. It probably doesn't matter, but this will pick longer lines more often than short ones. > I tested it :-) Hmm. What happens if you run it on a file with only one line? (see below) > > > ############################################# > from os import stat > from random import randint > > def getrandomline(f, length): > pos = randint(0,length) > f.seek(pos) > while f.read(1)!='\n': > try: > f.seek(-2,1) > except IOError: # This is to catch seeking before the > beginning of the file > f.seek(0) I think you need a break here to avoid an infinite loop. Kent > return f.readline() > > f = file("quotes.txt","rb") > sizeoffile = stat("quotes.txt")[6] > > while (1): > print getrandomline(f, sizeoffile), > > f.close() > ################################### From kent37 at tds.net Wed Jul 18 12:45:23 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Jul 2007 06:45:23 -0400 Subject: [Tutor] Basic DB question In-Reply-To: References: <469B98BC.5090708@kostyrka.org> Message-ID: <469DEF43.1040805@tds.net> z machinez wrote: > Thank you. I am mainly interested in finding ways to connect to aKDB+ > (KX Systems). That is the relational database that we are using. And I > would like to open a connection to it. I understand from the vendor that > they do not have a good ODBC driver. Googling 'python kdb kx' finds http://kx.com/a/k/connect/python/pyk-0.9/ There is a C interface to kdb so you might be able to use the ctypes module to access it from Python though that is probably not a beginner project and not something I can help with. Kent From kent37 at tds.net Wed Jul 18 12:59:14 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Jul 2007 06:59:14 -0400 Subject: [Tutor] How do you install EGG files In-Reply-To: References: Message-ID: <469DF282.1040001@tds.net> Terry Carroll wrote: > On Wed, 11 Jul 2007, shawn bright wrote: > >> Hey there all, >> i got the news that storm was released as open source. Storm is a db orm for >> python. >> i have a downloaded package and i would like to play with it, but it does >> not come with any install instructions. >> i found the package here https://storm.canonical.com/FrontPage >> there is a makefile in the top level folder, so should i use gcc and try to >> 'make' 'make install' or is that not necessarily the way to go here? The makefile is just a front-end to the tests. I think you can just copy the storm directory (the one containing __init__.py, not the top-level storm-0.9 dir) to your site-packages directory. > I see it comes in an EGG format, which is just a ZIP file. What will (I > think) work is to open the EGG file with your favorite unzipper and unzip > into your site-packages directory (making sure to use the directory names > from the EGG file). egg files are zip files packaged for use with easy_install: http://peak.telecommunity.com/DevCenter/EasyInstall In many cases easy_install gives one-step installation of Python packages, including downloading from the CheeseShop. In the case of storm it didn't work for me (using the --dry-run option though). YMMV. Kent From org.python.tutor at pooryorick.com Wed Jul 18 15:04:05 2007 From: org.python.tutor at pooryorick.com (=?utf-8?Q?Poor=20Yorick?=) Date: Wed, 18 Jul 2007 13:04:05 +0000 Subject: [Tutor] reading random line from a file Message-ID: <20070718130405.17036.qmail@station198.com> > -------Original Message------- > From: Kent Johnson > Subject: Re: [Tutor] reading random line from a file > Sent: 2007-07-18 10:19 > [SNIP] > > It probably doesn't matter, but this will pick longer lines more often > than short ones. > This method only keeps one line in memory, only reads through the file once, and does not favor lines based on any characteristic of the line. It's probably fast enough to not even bother keeping an index around: #!/bin/env python import os import random text = 'shaks12.txt' if not os.path.exists(text): os.system('wget http://www.gutenberg.org/dirs/etext94/shaks12.txt') f = file(text, 'rb') def randline(f): for i,j in enumerate(f): if random.randint(0,i) == i: line = j return line print randline(f) --- Yorick From nephish at gmail.com Wed Jul 18 15:21:28 2007 From: nephish at gmail.com (shawn bright) Date: Wed, 18 Jul 2007 08:21:28 -0500 Subject: [Tutor] How do you install EGG files In-Reply-To: <469DF282.1040001@tds.net> References: <469DF282.1040001@tds.net> Message-ID: <384c93600707180621y43860ba8nb66ada3d0da496c4@mail.gmail.com> Hey thanks for this, yes, i used the easy_install method and it did work on the python 2.4, the python 2.5 failed. shawn On 7/18/07, Kent Johnson wrote: > > Terry Carroll wrote: > > On Wed, 11 Jul 2007, shawn bright wrote: > > > >> Hey there all, > >> i got the news that storm was released as open source. Storm is a db > orm for > >> python. > >> i have a downloaded package and i would like to play with it, but it > does > >> not come with any install instructions. > >> i found the package here https://storm.canonical.com/FrontPage > >> there is a makefile in the top level folder, so should i use gcc and > try to > >> 'make' 'make install' or is that not necessarily the way to go here? > > The makefile is just a front-end to the tests. I think you can just copy > the storm directory (the one containing __init__.py, not the top-level > storm-0.9 dir) to your site-packages directory. > > > I see it comes in an EGG format, which is just a ZIP file. What will > (I > > think) work is to open the EGG file with your favorite unzipper and > unzip > > into your site-packages directory (making sure to use the directory > names > > from the EGG file). > > egg files are zip files packaged for use with easy_install: > http://peak.telecommunity.com/DevCenter/EasyInstall > > In many cases easy_install gives one-step installation of Python > packages, including downloading from the CheeseShop. In the case of > storm it didn't work for me (using the --dry-run option though). YMMV. > > 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/20070718/0213be97/attachment.htm From Junaid.Khan2 at waridtel.com Wed Jul 18 15:56:12 2007 From: Junaid.Khan2 at waridtel.com (Junaid.Khan/Finance/Lahore) Date: Wed, 18 Jul 2007 18:56:12 +0500 Subject: [Tutor] Question from a newbie Message-ID: <18196F17933FFE4B848F682B04D611A4017CDE94@LHR-MAIL.WT.WI.Pri> Hi I am totally new to Python. I downloaded it and I really like it as its very simple but I came across a small problem. My question is: How can I save something in Python. I tried to save it but it don't save it. Even I tried to add *.py as extension in the end of file name but still it doesn't works. I coded a simple program but don't know how to save it now in the PythonWin Editor. Let me tell you that I have installed the windows xp version of Python. Muhammad Junaid Khan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070718/4be5a7cb/attachment.html From rabidpoobear at gmail.com Wed Jul 18 16:40:36 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Jul 2007 09:40:36 -0500 Subject: [Tutor] Question from a newbie In-Reply-To: <18196F17933FFE4B848F682B04D611A4017CDE94@LHR-MAIL.WT.WI.Pri> References: <18196F17933FFE4B848F682B04D611A4017CDE94@LHR-MAIL.WT.WI.Pri> Message-ID: <469E2664.1090101@gmail.com> Junaid.Khan/Finance/Lahore wrote: > > Hi > > I am totally new to Python. I downloaded it and I really like it as > its very simple but I came across a small problem. My question is: > > How can I save something in Python. I tried to save it but it don?t > save it. Even I tried to add *.py as extension in the end of file name > but still it doesn?t works. I coded a simple program but don?t know > how to save it now in the PythonWin Editor. Let me tell you that I > have installed the windows xp version of Python. > How do you know it's not saving? The way you save in PythonWin should be similar to saving in another program, but I haven't used it in a few years so I may have forgotten something. Thanks for giving us your IDE and OS. -Luke > > **Muhammad Junaid Khan** > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From D3IBZ at hotmail.com Wed Jul 18 17:02:10 2007 From: D3IBZ at hotmail.com (Darren Williams) Date: Wed, 18 Jul 2007 11:02:10 -0400 Subject: [Tutor] Question from a newbie References: <18196F17933FFE4B848F682B04D611A4017CDE94@LHR-MAIL.WT.WI.Pri> <469E2664.1090101@gmail.com> Message-ID: I have exactly the same problem using PythonWin. I know it's not saving because in the location where I am saving my program to, nothing appears, I can even search my whole computer for the file but nothing... I just use Komodo Edit for writing and saving the final versions and PythonWin for testing lines of code up until then. ----- Original Message ----- From: "Luke Paireepinart" To: "Junaid.Khan/Finance/Lahore" Cc: Sent: Wednesday, July 18, 2007 10:40 AM Subject: Re: [Tutor] Question from a newbie Junaid.Khan/Finance/Lahore wrote: > > Hi > > I am totally new to Python. I downloaded it and I really like it as > its very simple but I came across a small problem. My question is: > > How can I save something in Python. I tried to save it but it don?t > save it. Even I tried to add *.py as extension in the end of file name > but still it doesn?t works. I coded a simple program but don?t know > how to save it now in the PythonWin Editor. Let me tell you that I > have installed the windows xp version of Python. > How do you know it's not saving? The way you save in PythonWin should be similar to saving in another program, but I haven't used it in a few years so I may have forgotten something. Thanks for giving us your IDE and OS. -Luke > > **Muhammad Junaid Khan** > > ------------------------------------------------------------------------ > > _______________________________________________ > 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 From D3IBZ at hotmail.com Wed Jul 18 17:46:09 2007 From: D3IBZ at hotmail.com (Darren Williams) Date: Wed, 18 Jul 2007 11:46:09 -0400 Subject: [Tutor] while Loop Message-ID: Hi all, I'm writing a calculator for an online game that I used to play but don't seem to be able to break out of the while loop, the program will just go over and over the loop, crashing the program and I don't know if Python is just really slow at this type of thing or i'm doing it completely wrong in Python (the equivalent code in JavaScript works fine). Python code - def main(): usedPocketsOne = 192000 junkiesOne = 500 labSpaceOne = 0 resultOne = 0 while usedPocketsOne > (junkiesOne - labSpaceOne) * 17: resultOne = resultOne + 1 usedPocketsOne = (UsedPocketsOne - junkiesOne + labSpaceOne) * 17 junkiesOne = junkiesOne + 1 main() And the JavaScript equivalent (incase there are any stalwarts beside Alan here) - function main() { var usedPocketsOne = 192000 var junkiesOne = 500 var labSpaceOne = 0 var resultOne = 0 while (usedPocketsOne > junkiesOne - labSpaceOne * 17) { resultOne = resultOne + 1 usedPocketsOne = usedPocketsOne - junkiesOne + labSpaceOne * 17 junkiesOne = junkiesOne + 1 } } Thanks in advance for any help :) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070718/9cdbe4cf/attachment.htm From kent37 at tds.net Wed Jul 18 17:55:21 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Jul 2007 11:55:21 -0400 Subject: [Tutor] while Loop In-Reply-To: References: Message-ID: <469E37E9.5020400@tds.net> Darren Williams wrote: > Hi all, > > I'm writing a calculator for an online game that I used to play but > don't seem to be able to break out of the while loop, the program will > just go over and over the loop, crashing the program and I don't know if > Python is just really slow at this type of thing or i'm doing it > completely wrong in Python (the equivalent code in JavaScript works fine). > > Python code - > > def main(): > usedPocketsOne = 192000 > junkiesOne = 500 > labSpaceOne = 0 > > resultOne = 0 > while usedPocketsOne > (junkiesOne - labSpaceOne) * 17: > resultOne = resultOne + 1 > usedPocketsOne = (UsedPocketsOne - junkiesOne + labSpaceOne) * 17 Maybe this should be usedPocketsOne = UsedPocketsOne - junkiesOne + labSpaceOne * 17 which is what you have in the JS. Kent > junkiesOne = junkiesOne + 1 > > main() > > And the JavaScript equivalent (incase there are any stalwarts beside > Alan here) - > > function main() { > var usedPocketsOne = 192000 > var junkiesOne = 500 > var labSpaceOne = 0 > > var resultOne = 0 > while (usedPocketsOne > junkiesOne - labSpaceOne * 17) { > resultOne = resultOne + 1 > usedPocketsOne = usedPocketsOne - junkiesOne + labSpaceOne * 17 > junkiesOne = junkiesOne + 1 > } > } > > Thanks in advance for any help :) > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From rabidpoobear at gmail.com Wed Jul 18 17:57:33 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Jul 2007 10:57:33 -0500 Subject: [Tutor] while Loop In-Reply-To: References: Message-ID: <469E386D.8040002@gmail.com> Darren Williams wrote: > Hi all, > > I'm writing a calculator for an online game that I used to play but > don't seem to be able to break out of the while loop, the program will > just go over and over the loop, crashing the program and I don't know > if Python is just really slow at this type of thing or i'm doing it > completely wrong in Python (the equivalent code in JavaScript works fine). I don't think you're doing it completely wrong, just partially :) And I doubt that, if it's quick in Javascript, it will be any slower in Python, since Javascript is interpreted as well, but by the browser while it's simultaneously downloading the content of the webpage and rendering it to the screen. Also, I'm pretty sure the code here is not equivalent to the Javascript code you included (specific remarks below.) > > Python code - > > def main(): > usedPocketsOne = 192000 > junkiesOne = 500 > labSpaceOne = 0 > > resultOne = 0 > while usedPocketsOne > (junkiesOne - labSpaceOne) * 17: I don't know much about Javascript, but doesn't it have order of operations? For example, usedPocketsOne > junkiesOne - labSpaceOne * 17 is generally assumed to be x = labSpaceOne * 17 y = junkiesOne - x usedPocketsOne > y Whereas your Python equivalent, with the parenthesis, usedPocketsOne > (junkiesOne - labSpaceOne) * 17 changes the order of operations (forces the subtraction before the multiplication) and hence changes the resulting value. That is, unless Javascript evaluates left-to-right with no operator heirarchy (which I would be saddened to learn, if it's true.) > resultOne = resultOne + 1 > usedPocketsOne = (UsedPocketsOne - junkiesOne + labSpaceOne) * 17 This shouldn't even run - you should get a syntax error because UsedPocketsOne is not defined anywhere else in the program (that you've shown us.) Perhaps you're running it in IDLE with no subprocess and some value for UsedPocketsOne is hanging around (from previous edits of the program, or interpreter session, or something else) and mucking up the works? -Luke From D3IBZ at hotmail.com Wed Jul 18 18:16:27 2007 From: D3IBZ at hotmail.com (Darren Williams) Date: Wed, 18 Jul 2007 12:16:27 -0400 Subject: [Tutor] while Loop References: <469E386D.8040002@gmail.com> Message-ID: Luke and Kent, you're right, I didn't think JavaScript calculated multiplaction and division before addition and subtraction but seems it does :) I dunno what you mean about usedPocketsOne not being defined, didn't I define it with usedPocketsOne = 192000? ----- Original Message ----- From: "Luke Paireepinart" To: "Darren Williams" Cc: Sent: Wednesday, July 18, 2007 11:57 AM Subject: Re: [Tutor] while Loop > Darren Williams wrote: >> Hi all, >> I'm writing a calculator for an online game that I used to play but >> don't seem to be able to break out of the while loop, the program will >> just go over and over the loop, crashing the program and I don't know if >> Python is just really slow at this type of thing or i'm doing it >> completely wrong in Python (the equivalent code in JavaScript works >> fine). > I don't think you're doing it completely wrong, just partially :) > And I doubt that, if it's quick in Javascript, it will be any slower in > Python, since Javascript is interpreted as well, but by the browser while > it's simultaneously downloading the content of the webpage and rendering > it to the screen. > Also, I'm pretty sure the code here is not equivalent to the Javascript > code you included (specific remarks below.) >> Python code - >> def main(): >> usedPocketsOne = 192000 >> junkiesOne = 500 >> labSpaceOne = 0 >> resultOne = 0 >> while usedPocketsOne > (junkiesOne - labSpaceOne) * 17: > I don't know much about Javascript, but doesn't it have order of > operations? > For example, > usedPocketsOne > junkiesOne - labSpaceOne * 17 > is generally assumed to be > x = labSpaceOne * 17 > y = junkiesOne - x > usedPocketsOne > y > > > Whereas your Python equivalent, with the parenthesis, > usedPocketsOne > (junkiesOne - labSpaceOne) * 17 > > changes the order of operations (forces the subtraction before the > multiplication) > and hence changes the resulting value. That is, unless Javascript > evaluates left-to-right with no operator heirarchy (which I would be > saddened to learn, if it's true.) >> resultOne = resultOne + 1 >> usedPocketsOne = (UsedPocketsOne - junkiesOne + labSpaceOne) * 17 > This shouldn't even run - you should get a syntax error because > UsedPocketsOne is not defined anywhere else in the program (that you've > shown us.) > Perhaps you're running it in IDLE with no subprocess and some value for > UsedPocketsOne is hanging around (from previous edits of the program, or > interpreter session, or something else) and mucking up the works? > -Luke > > > From picioslug at gmail.com Wed Jul 18 18:27:53 2007 From: picioslug at gmail.com (Picio) Date: Wed, 18 Jul 2007 18:27:53 +0200 Subject: [Tutor] python to serve xml or json or.... Message-ID: <825bef0c0707180927g1c2b16d0yfb274188836bb087@mail.gmail.com> Hello, I' ve a bunch of things to ask about using Python as a server side language in a web application: I have a mysql db and I've alredy developed a python app that query the db and shot-out an xml file (made by the nice elementtree module like some people here on the list suggested). This file is then chewed-up by a javascript file who's responsible to generate a graph (see http://www.JSViz.org). Now I need to put it on line so that a user from web browser can query the db and see the graph. Next step could be to use ajax but for now something like a "PHP style" in python would be enough. I saw some PSP (python server pages) solution around but since I'm more or less a newbie I can't understand if I have to go to webware or spyce or a full fledged django. I like to start simple and make things more perfect but If there is a full featured solution to my case I will apply It. Can You Help? Any advice would be appreciated! -- http://picio.gotdns.com ...Il mio blog su NSLU2 From picioslug at gmail.com Wed Jul 18 18:39:28 2007 From: picioslug at gmail.com (Picio) Date: Wed, 18 Jul 2007 18:39:28 +0200 Subject: [Tutor] python and Java developers, same team Message-ID: <825bef0c0707180939t518d9019i6a667fd12e6e0e0a@mail.gmail.com> Hello, a friend of mine want me to join a team on a project. They use Java (the IDE is java studio creator), and the deployment server is Tomcat. Anyway I have all my apps in python and I'd like to continue my development using it instead of learning java. Is it possible to translate my apps from python to Java in a way they can integrate them in Tomcat? Is it jython? I have just some simple apps and scripts. (Or Is it better that I start to learn Java leaving a part my beloved python? I hope you answer NO ;) ) -- http://picio.gotdns.com ...Il mio blog su NSLU2 From kent37 at tds.net Wed Jul 18 19:26:48 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Jul 2007 13:26:48 -0400 Subject: [Tutor] python and Java developers, same team In-Reply-To: <825bef0c0707180939t518d9019i6a667fd12e6e0e0a@mail.gmail.com> References: <825bef0c0707180939t518d9019i6a667fd12e6e0e0a@mail.gmail.com> Message-ID: <469E4D58.2090001@tds.net> Picio wrote: > Hello, a friend of mine want me to join a team on a project. They use > Java (the IDE is java studio creator), and the deployment server is > Tomcat. Anyway I have all my apps in python and I'd like to continue > my development using it instead of learning java. > Is it possible to translate my apps from python to Java in a way they > can integrate them in Tomcat? Is it jython? I have just some simple > apps and scripts. Jython is a good bet, depending on what the scripts do. You can write servlets in Jython and embed them in Tomcat. > (Or Is it better that I start to learn Java leaving a part my beloved > python? I hope you answer NO ;) ) You will probably have to learn some Java. Or run the other way :-) Kent From kent37 at tds.net Wed Jul 18 19:36:59 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Jul 2007 13:36:59 -0400 Subject: [Tutor] python to serve xml or json or.... In-Reply-To: <825bef0c0707180927g1c2b16d0yfb274188836bb087@mail.gmail.com> References: <825bef0c0707180927g1c2b16d0yfb274188836bb087@mail.gmail.com> Message-ID: <469E4FBB.6030200@tds.net> Picio wrote: > Hello, I' ve a bunch of things to ask about using Python as a server > side language in a web application: > I have a mysql db and I've alredy developed a python app that query > the db and shot-out an xml file (made by the nice elementtree module > like some people here on the list suggested). This file is then > chewed-up by a javascript file who's responsible to generate a graph > (see http://www.JSViz.org). > Now I need to put it on line so that a user from web browser can query > the db and see the graph. Next step could be to use ajax but for now > something like a "PHP style" in python would be enough. I saw some PSP > (python server pages) solution around but since I'm more or less a > newbie I can't understand if I have to go to webware or spyce or a > full fledged django. > I like to start simple and make things more perfect but If there is a > full featured solution to my case I will apply It. This is hard to answer because there are many possibilities spanning a broad spectrum, and which is best depends on both requirements and personal taste. Django, TurboGears and Pylons are popular and include or support template languages and AJAX. Many more options listed here: http://wiki.python.org/moin/WebFrameworks Kent From rabidpoobear at gmail.com Wed Jul 18 21:08:46 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Jul 2007 14:08:46 -0500 Subject: [Tutor] while Loop In-Reply-To: References: <469E386D.8040002@gmail.com> Message-ID: <469E653E.8080402@gmail.com> Darren Williams wrote: > Luke and Kent, you're right, I didn't think JavaScript calculated > multiplaction and division before addition and subtraction but seems > it does :) > > I dunno what you mean about usedPocketsOne not being defined, didn't I > define it with usedPocketsOne = 192000? no, I said UsedPocketsOne was not defined. Note the different starting letter. Python is case senstitive, meaning usedPocketsOne is not the same as UsedPocketsOne. So yes, you defined usedPocketsOne with the assignment to 192000, but you did not define UsedPocketsOne. Note what happens when I test your code: >>> def main(): usedPocketsOne = 192000 junkiesOne = 500 labSpaceOne = 0 resultOne = 0 while usedPocketsOne > (junkiesOne - labSpaceOne) * 17: resultOne = resultOne + 1 usedPocketsOne = (UsedPocketsOne - junkiesOne + labSpaceOne) * 17 >>> main() Traceback (most recent call last): File "", line 1, in -toplevel- main() File "", line 10, in main usedPocketsOne = (UsedPocketsOne - junkiesOne + labSpaceOne) * 17 NameError: global name 'UsedPocketsOne' is not defined You should get a similar error, unless you've somehow defined UsedPocketsOne somewhere else. HTH, -Luke Correction of previous e-mail: This raises a NameError, not a SyntaxError, as I said before. sorry about that. From D3IBZ at hotmail.com Wed Jul 18 21:33:11 2007 From: D3IBZ at hotmail.com (Darren Williams) Date: Wed, 18 Jul 2007 15:33:11 -0400 Subject: [Tutor] while Loop References: <469E386D.8040002@gmail.com> <469E653E.8080402@gmail.com> Message-ID: Oops, didn't notice the uppercase U, thanks Luke. ----- Original Message ----- From: "Luke Paireepinart" To: "Darren Williams" Cc: Sent: Wednesday, July 18, 2007 3:08 PM Subject: Re: [Tutor] while Loop > Darren Williams wrote: >> Luke and Kent, you're right, I didn't think JavaScript calculated >> multiplaction and division before addition and subtraction but seems >> it does :) >> >> I dunno what you mean about usedPocketsOne not being defined, didn't I >> define it with usedPocketsOne = 192000? > no, I said UsedPocketsOne was not defined. Note the different starting > letter. > Python is case senstitive, meaning usedPocketsOne is not the same as > UsedPocketsOne. > So yes, you defined usedPocketsOne with the assignment to 192000, but > you did not define UsedPocketsOne. > > Note what happens when I test your code: > >>> def main(): > > usedPocketsOne = 192000 > junkiesOne = 500 > labSpaceOne = 0 > > resultOne = 0 > while usedPocketsOne > (junkiesOne - labSpaceOne) * 17: > resultOne = resultOne + 1 > usedPocketsOne = (UsedPocketsOne - junkiesOne + labSpaceOne) * 17 > > > >>> main() > > Traceback (most recent call last): > File "", line 1, in -toplevel- > main() > File "", line 10, in main > usedPocketsOne = (UsedPocketsOne - junkiesOne + labSpaceOne) * 17 > NameError: global name 'UsedPocketsOne' is not defined > > You should get a similar error, unless you've somehow defined > UsedPocketsOne somewhere else. > HTH, > -Luke > > Correction of previous e-mail: This raises a NameError, not a > SyntaxError, as I said before. sorry about that. > > > From keridee at jayco.net Wed Jul 18 22:41:23 2007 From: keridee at jayco.net (Tiger12506) Date: Wed, 18 Jul 2007 15:41:23 -0500 Subject: [Tutor] reading random line from a file References: <20070718130405.17036.qmail@station198.com> Message-ID: <006301c7c97c$04c3ffb0$4bfce004@JSLAPTOP> Yuck. Talk about a one shot function! Of course it only reads through the file once! You only call the function once. Put a second print randline(f) at the bottom of your script and see what happens :-) JS > This method only keeps one line in memory, only reads through the file > once, and does not favor lines based on any characteristic of the line. > It's probably fast enough to not even bother keeping an index around: > > #!/bin/env python > > import os > import random > > text = 'shaks12.txt' > if not os.path.exists(text): > os.system('wget http://www.gutenberg.org/dirs/etext94/shaks12.txt') > > f = file(text, 'rb') > > def randline(f): > for i,j in enumerate(f): > if random.randint(0,i) == i: > line = j > return line > > print randline(f) From flaper87 at gmail.com Wed Jul 18 21:49:49 2007 From: flaper87 at gmail.com (Flaper87) Date: Wed, 18 Jul 2007 15:49:49 -0400 Subject: [Tutor] pybluez + link quality Message-ID: Hi everybody: I would like to know how can i get the link wuality of a device (cellphone), with the pybluez module. (if there is another way to do it without the pybluez, i'm interested too) Thanks -- Flavio Percoco Premoli, A.K.A. [Flaper87] http://www.flaper87.com Usuario Linux registrado #436538 Geek by nature, Linux by choice, Debian of course. Key Fingerprint: CFC0 C67D FF73 463B 7E55 CF43 25D1 E75B E2DB 15C7 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070718/746f7dea/attachment.html From rabidpoobear at gmail.com Wed Jul 18 22:33:30 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Jul 2007 15:33:30 -0500 Subject: [Tutor] pybluez + link quality In-Reply-To: References: Message-ID: <469E791A.1080508@gmail.com> Flaper87 wrote: > Hi everybody: > > I would like to know how can i get the link wuality of a device > (cellphone), with the pybluez module. (if there is another way to do > it without the pybluez, i'm interested too) PyBluez is not cross-platform for all aspects of the bluetooth protocol, so you might want to check to see if what you're trying to do is cross-platform. -Luke From flaper87 at gmail.com Wed Jul 18 22:41:35 2007 From: flaper87 at gmail.com (Flaper87) Date: Wed, 18 Jul 2007 16:41:35 -0400 Subject: [Tutor] pybluez + link quality In-Reply-To: <469E791A.1080508@gmail.com> References: <469E791A.1080508@gmail.com> Message-ID: No, what i'm doing is just for linux.... 2007/7/18, Luke Paireepinart : > > Flaper87 wrote: > > Hi everybody: > > > > I would like to know how can i get the link wuality of a device > > (cellphone), with the pybluez module. (if there is another way to do > > it without the pybluez, i'm interested too) > PyBluez is not cross-platform for all aspects of the bluetooth protocol, > so you might want to check to see if what you're trying to do is > cross-platform. > -Luke > -- Flavio Percoco Premoli, A.K.A. [Flaper87] http://www.flaper87.com Usuario Linux registrado #436538 Geek by nature, Linux by choice, Debian of course. Key Fingerprint: CFC0 C67D FF73 463B 7E55 CF43 25D1 E75B E2DB 15C7 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070718/109e78cd/attachment.html From justin.cardinal at exbsolutions.com Wed Jul 18 22:50:10 2007 From: justin.cardinal at exbsolutions.com (Justin Cardinal) Date: Wed, 18 Jul 2007 15:50:10 -0500 Subject: [Tutor] Working with bash (subversion) Message-ID: <00b001c7c97d$3c2940e0$9d01a8c0@exbspider> I'm trying to write a program that will list all subversion repository directories, then issue a command using each directory as an argument, then parse those results. So far, I'm able to get a list of the directories...and that's it! Here's what I've got so far: ========================================= #!/usr/bin/env python import commands as c lsout = c.getoutput('ls -d /home/svn/repository/*/').split('\n') results = file("results.txt", "w") for row in lsout: results.write(c.getoutput('svnadmin lslocks ' + eval(row))) ========================================= lsout is a list of repository directories, like I wanted. (['/home/svn/repository/projecta/', '/home/svn/repository/projectb/', '/home/svn/repository/projectc/'] The next 3 lines are probably totally wrong. I want to perform the following bash command for each directory... ================================== svnadmin lslocks /home/svn/repository/projecta ================================== ...and then parse the results. I just don't know where/how to store the results from each svnadmin command. When I run the program in its current form, I get the following error: =========================================== Traceback (most recent call last): File "checklocks.py", line 8, in ? results.write(c.getoutput('svnadmin lslocks ' + eval(row))) File "", line 1 /home/svn/repository/projecta/ ^ SyntaxError: invalid syntax =========================================== Any advice would be much appreciated. Thanks! -Justin Cardinal -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070718/5f306657/attachment.htm From rabidpoobear at gmail.com Wed Jul 18 23:12:52 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Jul 2007 16:12:52 -0500 Subject: [Tutor] Working with bash (subversion) In-Reply-To: <00b001c7c97d$3c2940e0$9d01a8c0@exbspider> References: <00b001c7c97d$3c2940e0$9d01a8c0@exbspider> Message-ID: <469E8254.1030409@gmail.com> Justin Cardinal wrote: > I'm trying to write a program that will list all subversion repository > directories, then issue a command using each directory as an argument, > then parse those results. So far, I'm able to get a list of the > directories...and that's it! > Here's what I've got so far: > ========================================= > #!/usr/bin/env python > > import commands as c > > lsout = c.getoutput('ls -d /home/svn/repository/*/').split('\n') > results = file("results.txt", "w") > for row in lsout: > results.write(c.getoutput('svnadmin lslocks ' + eval(row))) > ========================================= > lsout is a list of repository directories, like I wanted. > (['/home/svn/repository/projecta/', '/home/svn/repository/projectb/', > '/home/svn/repository/projectc/'] > The next 3 lines are probably totally wrong. I want to perform the > following bash command for each directory... > ================================== > svnadmin lslocks /home/svn/repository/projecta > ================================== > ...and then parse the results. I just don't know where/how to store > the results from each svnadmin command. When I run the program in its > current form, I get the following error: > =========================================== > Traceback (most recent call last): > File "checklocks.py", line 8, in ? > results.write(c.getoutput('svnadmin lslocks ' + eval(row))) > File "", line 1 > /home/svn/repository/projecta/ > ^ > SyntaxError: invalid syntax > =========================================== > > Any advice would be much appreciated. Thanks! eval evaluates the string as a python command. Because there are no Python commands that start with a forward slash, Python's pointing to this as a syntax error. Because row is a string already (and note that 'column' would be a more apt term for this, as a 1-dimensional list is more similar to a single row than a single column) you can just do simple string concatenation (or you can use string substitution but in this case it's not necessary and would just make your code less readable.) Here's a basic example: >>> 'hello ' + 'world!' 'hello world!' Does that tell you everything you need to know? (recall that whether 'world!' is referenced using a variable name or used directly, the effect will be the same. I.E. a = 'ba' a + 'nana' has the same end result as 'ba' + 'nana' with the exception being that the variable 'a' is not defined or is not bound to a new value after this statement.) HTH, -Luke From rabidpoobear at gmail.com Wed Jul 18 23:16:58 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Jul 2007 16:16:58 -0500 Subject: [Tutor] Working with bash (subversion) In-Reply-To: <00b001c7c97d$3c2940e0$9d01a8c0@exbspider> References: <00b001c7c97d$3c2940e0$9d01a8c0@exbspider> Message-ID: <469E834A.6000100@gmail.com> Justin Cardinal wrote: > I'm trying to write a program that will list all subversion repository > directories, then issue a command using each directory as an argument, > then parse those results. So far, I'm able to get a list of the > directories...and that's it! > Here's what I've got so far: > ========================================= > #!/usr/bin/env python > > import commands as c As a side note, why is this 'commands' module part of the standard library? it just appears to wrap os.popen in a very bare way and it is not platform-independent. It seems pretty useless, as far as I can tell. -Luke From andreas at kostyrka.org Wed Jul 18 23:49:16 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 18 Jul 2007 23:49:16 +0200 Subject: [Tutor] Working with bash (subversion) In-Reply-To: <469E834A.6000100@gmail.com> References: <00b001c7c97d$3c2940e0$9d01a8c0@exbspider> <469E834A.6000100@gmail.com> Message-ID: <469E8ADC.6070809@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 mkarg is quite useful, from time to time. Andreas Luke Paireepinart wrote: > Justin Cardinal wrote: >> I'm trying to write a program that will list all subversion repository >> directories, then issue a command using each directory as an argument, >> then parse those results. So far, I'm able to get a list of the >> directories...and that's it! >> Here's what I've got so far: >> ========================================= >> #!/usr/bin/env python >> >> import commands as c > As a side note, why is this 'commands' module part of the standard library? > it just appears to wrap os.popen in a very bare way and it is not > platform-independent. > It seems pretty useless, as far as I can tell. > -Luke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGnorcHJdudm4KnO0RAilrAKCDCM5eOvtqgVJ0ViouGpuEqOjDOACgxg88 4sCL39aNoFiZqRR4e1zUEJk= =Q4ZW -----END PGP SIGNATURE----- From keridee at jayco.net Thu Jul 19 01:11:14 2007 From: keridee at jayco.net (Tiger12506) Date: Wed, 18 Jul 2007 18:11:14 -0500 Subject: [Tutor] reading random line from a file References: <20070718211541.25724.qmail@station198.com> Message-ID: <000a01c7c991$083ffa80$4bfce004@JSLAPTOP> > import os > import random > > text = 'shaks12.txt' > if not os.path.exists(text): > os.system('wget http://www.gutenberg.org/dirs/etext94/shaks12.txt') > > def randline(f): > for i,j in enumerate(file(f, 'rb')): Alright. But put randline in a loop and you open a lot of file handles. Thank goodness python has GB. Seperate variable, open file at start, close file at end. So the file is read every time you call randline. At least as far as the line chosen. Whereas my version only reads at absolute most twice the same line. And it will run faster. Searching through the file lines to find the one who's index matches i is time-consuming. Yes, my version will favor longer lines, but I don't think that seriously strict randomization is necessary? IMHO, memory and speed are more important here. (You must forgive me a little, I've been studying C and assembly) I'm just proud of my function ;-) JS From keridee at jayco.net Thu Jul 19 01:20:46 2007 From: keridee at jayco.net (Tiger12506) Date: Wed, 18 Jul 2007 18:20:46 -0500 Subject: [Tutor] Working with bash (subversion) References: <00b001c7c97d$3c2940e0$9d01a8c0@exbspider> Message-ID: <004501c7c992$48c09fa0$4bfce004@JSLAPTOP> > results.write(c.getoutput('svnadmin lslocks ' + eval(row))) Mmm... I want to add that the eval function tries to execute whatever is in the argument passed as python expressions. >>> eval('1+2') 3 >>> row = 4 >>> 1+row 5 >>> eval('1+row') 5 >>> JS From hunter92383 at gmail.com Thu Jul 19 00:21:27 2007 From: hunter92383 at gmail.com (elis aeris) Date: Thu, 19 Jul 2007 06:21:27 +0800 Subject: [Tutor] Python Image library Message-ID: <674d5ce60707181521h60722bfetfa299ef811bfc2d0@mail.gmail.com> import time import ImageGrab # Part of PIL from ctypes import * # Load up the Win32 APIs we need to use. 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 # Sleep for 2 seconds - click the window you want to grab. #time.sleep(2) # 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)) # Save the screenshot as a BMP. time.sleep(2) image.save("c:\python_codes\screenshot.bmp") # Get the pixel 10 pixels along the top of the foreground window - this # will be a piece of the window border. # print time.time() start = time.time() pixels = image.getdata() for x in xrange(0, 500): for y in xrange(0, 500): rgb = pixels[500 * x + y] # print pixels[500 * 2 + 400] print ( time.time() - start ) # PIL returns colours as RGB values packed into a triple: #print "RGB(%d, %d, %d)" % (rgb[0], rgb[1], rgb[2]) # This prints RGB(0, 74, 216) on my XP machine getdata() returns a flattened list, [n] but i am not sure how to access it. when I want to get rgb from a window of 100,200, get data starts from 0 (0~99, 0~199) the point of x,y = 2, 1 do I put in pixel[100] ? it's actually not the case @_@ what should I put in ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070719/e959c227/attachment.htm From justin.cardinal at exbsolutions.com Thu Jul 19 00:22:06 2007 From: justin.cardinal at exbsolutions.com (Justin Cardinal) Date: Wed, 18 Jul 2007 17:22:06 -0500 Subject: [Tutor] Working with bash (subversion) In-Reply-To: <469E8254.1030409@gmail.com> References: <00b001c7c97d$3c2940e0$9d01a8c0@exbspider> <469E8254.1030409@gmail.com> Message-ID: <00b501c7c98a$1fadc460$9d01a8c0@exbspider> That fixed it, thanks! Now I just need to do some studying on working with lists (or whatever this output is...) so I can filter out the results I don't want. Here's an updated version of the program: ================================================================ #!/usr/bin/env python import commands as c lsout = c.getoutput('ls -d /home/svn/repository/*/').split('\n') results = [] for row in lsout: temp = c.getoutput('svnadmin lslocks ' + row).split('\n') if temp != ['']: results.append(temp) print results ================================================================ ...and the output: ================================================================ ['Path: /test/trunk/data.bin', 'UUID Token: opaquelocktoken:9ee85aae-c9dc-4388-8958-87b708e628a3', 'Owner: jcardinal', 'Created: 2007-07-17 14:36:18 -0500 (Tue, 17 Jul 2007)', 'Expires: ', 'Comment (1 line):', '', ''] ================================================================ Thanks very much to all who replied, it's amazing how quick help arrives! -Justin > Here's what I've got so far: > ========================================= > #!/usr/bin/env python > > import commands as c > > lsout = c.getoutput('ls -d /home/svn/repository/*/').split('\n') > results = file("results.txt", "w") > for row in lsout: > results.write(c.getoutput('svnadmin lslocks ' + eval(row))) > =========================================== > Traceback (most recent call last): > File "checklocks.py", line 8, in ? > results.write(c.getoutput('svnadmin lslocks ' + eval(row))) > File "", line 1 > /home/svn/repository/projecta/ > ^ > SyntaxError: invalid syntax > =========================================== > > Any advice would be much appreciated. Thanks! eval evaluates the string as a python command. Because there are no Python commands that start with a forward slash, Python's pointing to this as a syntax error. Because row is a string already (and note that 'column' would be a more apt term for this, as a 1-dimensional list is more similar to a single row than a single column) you can just do simple string concatenation (or you can use string substitution but in this case it's not necessary and would just make your code less readable.) Here's a basic example: >>> 'hello ' + 'world!' 'hello world!' Does that tell you everything you need to know? (recall that whether 'world!' is referenced using a variable name or used directly, the effect will be the same. I.E. a = 'ba' a + 'nana' has the same end result as 'ba' + 'nana' with the exception being that the variable 'a' is not defined or is not bound to a new value after this statement.) HTH, -Luke From rabidpoobear at gmail.com Thu Jul 19 00:26:50 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Jul 2007 17:26:50 -0500 Subject: [Tutor] Working with bash (subversion) In-Reply-To: <004501c7c992$48c09fa0$4bfce004@JSLAPTOP> References: <00b001c7c97d$3c2940e0$9d01a8c0@exbspider> <004501c7c992$48c09fa0$4bfce004@JSLAPTOP> Message-ID: <469E93AA.90109@gmail.com> Tiger12506 wrote: >> results.write(c.getoutput('svnadmin lslocks ' + eval(row))) >> > > Mmm... I want to add that the eval function tries to execute whatever is in > the argument passed as python expressions. > Did I not say that already? ;) I guess my term 'command' was the problem, eh? -Luke From rabidpoobear at gmail.com Thu Jul 19 00:34:24 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Jul 2007 17:34:24 -0500 Subject: [Tutor] Working with bash (subversion) In-Reply-To: <00b501c7c98a$1fadc460$9d01a8c0@exbspider> References: <00b001c7c97d$3c2940e0$9d01a8c0@exbspider> <469E8254.1030409@gmail.com> <00b501c7c98a$1fadc460$9d01a8c0@exbspider> Message-ID: <469E9570.7040509@gmail.com> Justin Cardinal wrote: > That fixed it, thanks! Now I just need to do some studying on working with > lists (or whatever this output is...) so I can filter out the results I > don't want. Here's an updated version of the program: > ================================================================ > #!/usr/bin/env python > > import commands as c > > lsout = c.getoutput('ls -d /home/svn/repository/*/').split('\n') > results = [] > for row in lsout: > temp = c.getoutput('svnadmin lslocks ' + row).split('\n') > if temp != ['']: > results.append(temp) > temp is a list, so results is going to end up being a list of lists. is that the desired behavior? > print results > ================================================================ > ...and the output: > ================================================================ > ['Path: /test/trunk/data.bin', 'UUID Token: > opaquelocktoken:9ee85aae-c9dc-4388-8958-87b708e628a3', 'Owner: jcardinal', > 'Created: 2007-07-17 14:36:18 -0500 (Tue, 17 Jul 2007)', 'Expires: ', > 'Comment (1 line):', '', ''] > ================================================================ > > Thanks very much to all who replied, it's amazing how quick help arrives! > Well, I for one would rather answer your questions than study for a Differential Equations test :) > -Justin -Luke From keridee at jayco.net Thu Jul 19 01:38:45 2007 From: keridee at jayco.net (Tiger12506) Date: Wed, 18 Jul 2007 18:38:45 -0500 Subject: [Tutor] Python Image library References: <674d5ce60707181521h60722bfetfa299ef811bfc2d0@mail.gmail.com> Message-ID: <008801c7c994$cbfd0cd0$4bfce004@JSLAPTOP> You know the height and the width of the image, no? So you know that every 'width' number of pixels will start a new row. So if you wanted say the fifth row down, second pixel, how would you find it? The 1st line: 'width' number of pixels The 2nd line: 'width' number of pixels The 3rd line: 'width number of pixels The 4th line: 'width' number of pixels The 5th line: 2 pixels in from the left Add those up ~ width+width+width+width+2 Or 4*width+2 That number is the index to use to get the pixel at coords (2,5) so pixel = getdata() pixel[4*width+2] For this example. Work out a more general solution for yourself please. JS > getdata() returns a flattened list, [n] > > > but i am not sure how to access it. > > when I want to get rgb from a window of 100,200, > > get data starts from 0 (0~99, 0~199) > > the point of x,y = 2, 1 > > do I put in > > pixel[100] ? > > > it's actually not the case @_@ > > what should I put in ? From hunter92383 at gmail.com Thu Jul 19 00:41:44 2007 From: hunter92383 at gmail.com (elis aeris) Date: Thu, 19 Jul 2007 06:41:44 +0800 Subject: [Tutor] Python Image library In-Reply-To: <008801c7c994$cbfd0cd0$4bfce004@JSLAPTOP> References: <674d5ce60707181521h60722bfetfa299ef811bfc2d0@mail.gmail.com> <008801c7c994$cbfd0cd0$4bfce004@JSLAPTOP> Message-ID: <674d5ce60707181541h688cee24x40991a6293f3b903@mail.gmail.com> ahh~ it goes horizontally first why didn't I think of that? thank you ~ On 7/19/07, Tiger12506 wrote: > > You know the height and the width of the image, no? > > So you know that every 'width' number of pixels will start a new row. > So if you wanted say the fifth row down, second pixel, how would you find > it? > > The 1st line: 'width' number of pixels > The 2nd line: 'width' number of pixels > The 3rd line: 'width number of pixels > The 4th line: 'width' number of pixels > The 5th line: 2 pixels in from the left > > Add those up ~ width+width+width+width+2 > Or 4*width+2 > > That number is the index to use to get the pixel at coords (2,5) > so > > pixel = getdata() > pixel[4*width+2] > > For this example. > Work out a more general solution for yourself please. > > JS > > > getdata() returns a flattened list, [n] > > > > > > but i am not sure how to access it. > > > > when I want to get rgb from a window of 100,200, > > > > get data starts from 0 (0~99, 0~199) > > > > the point of x,y = 2, 1 > > > > do I put in > > > > pixel[100] ? > > > > > > it's actually not the case @_@ > > > > what should I put in ? > > _______________________________________________ > 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/20070719/8876a5d1/attachment.html From rabidpoobear at gmail.com Thu Jul 19 00:48:31 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 18 Jul 2007 17:48:31 -0500 Subject: [Tutor] Python Image library In-Reply-To: <008801c7c994$cbfd0cd0$4bfce004@JSLAPTOP> References: <674d5ce60707181521h60722bfetfa299ef811bfc2d0@mail.gmail.com> <008801c7c994$cbfd0cd0$4bfce004@JSLAPTOP> Message-ID: <469E98BF.4080607@gmail.com> Tiger12506 wrote: > You know the height and the width of the image, no? > > So you know that every 'width' number of pixels will start a new row. > So if you wanted say the fifth row down, second pixel, how would you find > it? > > The 1st line: 'width' number of pixels > The 2nd line: 'width' number of pixels > The 3rd line: 'width number of pixels > The 4th line: 'width' number of pixels > The 5th line: 2 pixels in from the left > > Add those up ~ width+width+width+width+2 > Or 4*width+2 > if you start counting at the 0th row and 0th column, this will give you the 4th row and 2nd column. if you're counting from the 1st row and 1st column, this will give you the 5th row and 3rd column. > That number is the index to use to get the pixel at coords (2,5) > So this is actually (3,5) or, to count from 0, (2,4). But yeah, the general idea is there. If my math is wrong I'm sure you won't hesitate to correct me ;) -Luke From hunter92383 at gmail.com Thu Jul 19 00:56:26 2007 From: hunter92383 at gmail.com (elis aeris) Date: Thu, 19 Jul 2007 06:56:26 +0800 Subject: [Tutor] Python Image library In-Reply-To: <469E98BF.4080607@gmail.com> References: <674d5ce60707181521h60722bfetfa299ef811bfc2d0@mail.gmail.com> <008801c7c994$cbfd0cd0$4bfce004@JSLAPTOP> <469E98BF.4080607@gmail.com> Message-ID: <674d5ce60707181556ld3fbbd7r68ab21794a84996a@mail.gmail.com> that's illustrative. On 7/19/07, Luke Paireepinart wrote: > > Tiger12506 wrote: > > You know the height and the width of the image, no? > > > > So you know that every 'width' number of pixels will start a new row. > > So if you wanted say the fifth row down, second pixel, how would you > find > > it? > > > > The 1st line: 'width' number of pixels > > The 2nd line: 'width' number of pixels > > The 3rd line: 'width number of pixels > > The 4th line: 'width' number of pixels > > The 5th line: 2 pixels in from the left > > > > Add those up ~ width+width+width+width+2 > > Or 4*width+2 > > > if you start counting at the 0th row and 0th column, this will give you > the 4th row and 2nd column. > if you're counting from the 1st row and 1st column, this will give you > the 5th row and 3rd column. > > That number is the index to use to get the pixel at coords (2,5) > > > So this is actually (3,5) or, to count from 0, (2,4). > But yeah, the general idea is there. > If my math is wrong I'm sure you won't hesitate to correct me ;) > -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/20070719/286050dc/attachment.htm From keridee at jayco.net Thu Jul 19 02:43:48 2007 From: keridee at jayco.net (Tiger12506) Date: Wed, 18 Jul 2007 19:43:48 -0500 Subject: [Tutor] Python Image library References: <674d5ce60707181521h60722bfetfa299ef811bfc2d0@mail.gmail.com> <008801c7c994$cbfd0cd0$4bfce004@JSLAPTOP> <469E98BF.4080607@gmail.com> Message-ID: <001d01c7c99d$e283b7c0$0756e104@JSLAPTOP> > if you start counting at the 0th row and 0th column, this will give you > the 4th row and 2nd column. > if you're counting from the 1st row and 1st column, this will give you > the 5th row and 3rd column. >> That number is the index to use to get the pixel at coords (2,5) >> > So this is actually (3,5) or, to count from 0, (2,4). > But yeah, the general idea is there. > If my math is wrong I'm sure you won't hesitate to correct me ;) > -Luke No. You're right, of course. :-) I wasn't thinking. JS From hunter92383 at gmail.com Thu Jul 19 02:51:20 2007 From: hunter92383 at gmail.com (elis aeris) Date: Thu, 19 Jul 2007 08:51:20 +0800 Subject: [Tutor] odd Message-ID: <674d5ce60707181751i3158961ej5ea8026fad873845@mail.gmail.com> I ran this for x in range(5,10): print x and OP was 5 6 7 8 9 why is that? shouldn't it print t 6 7 8 9 10? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070719/dafb44ce/attachment.htm From wescpy at gmail.com Thu Jul 19 03:00:51 2007 From: wescpy at gmail.com (wesley chun) Date: Wed, 18 Jul 2007 18:00:51 -0700 Subject: [Tutor] odd In-Reply-To: <674d5ce60707181751i3158961ej5ea8026fad873845@mail.gmail.com> References: <674d5ce60707181751i3158961ej5ea8026fad873845@mail.gmail.com> Message-ID: <78b3a9580707181800j570f9fb1ne34e425c7881e547@mail.gmail.com> > for x in range(5,10): > print x > > and OP was > > 5 > 6 > 7 > 8 > 9 > > why is that? shouldn't it print > > t > 6 > 7 > 8 > 9 > 10? no. the (well, one) syntax for range() is (start, stop) where it counts starting from 'start' up to but not including 'stop'. if you're familiar with C/C++ (or PHP or Java), it's similar to the counting loop, "for (int i=5; i < 10; i++)", which counts 5, 6, 7, 8, 9. hope this helps! -- 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 david at graniteweb.com Thu Jul 19 03:01:36 2007 From: david at graniteweb.com (David Rock) Date: Wed, 18 Jul 2007 20:01:36 -0500 Subject: [Tutor] odd In-Reply-To: <674d5ce60707181751i3158961ej5ea8026fad873845@mail.gmail.com> References: <674d5ce60707181751i3158961ej5ea8026fad873845@mail.gmail.com> Message-ID: <20070719010136.GB6783@wdfs.graniteweb.com> * elis aeris [2007-07-19 08:51]: > I ran this > > > for x in range(5,10): > print x > > and OP was > > 5 > 6 > 7 > 8 > 9 > > why is that? shouldn't it print > > 5 > 6 > 7 > 8 > 9 > 10? That is the expected behaviour, per the documentation: http://docs.python.org/lib/built-in-funcs.html#l2h-58 -- David Rock david at graniteweb.com From witham.ian at gmail.com Thu Jul 19 03:06:12 2007 From: witham.ian at gmail.com (Ian Witham) Date: Thu, 19 Jul 2007 13:06:12 +1200 Subject: [Tutor] odd In-Reply-To: <674d5ce60707181751i3158961ej5ea8026fad873845@mail.gmail.com> References: <674d5ce60707181751i3158961ej5ea8026fad873845@mail.gmail.com> Message-ID: from Guido's tutorial: The given end point is never part of the generated list; range(10) generates a list of 10 values, the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the `step') On 7/19/07, elis aeris wrote: > > I ran this > > > for x in range(5,10): > print x > > > > > and OP was > > 5 > 6 > 7 > 8 > 9 > > > > why is that? shouldn't it print > > > t > 6 > 7 > 8 > 9 > 10? > > _______________________________________________ > 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/20070719/77652350/attachment.html From hunter92383 at gmail.com Thu Jul 19 03:14:42 2007 From: hunter92383 at gmail.com (elis aeris) Date: Thu, 19 Jul 2007 09:14:42 +0800 Subject: [Tutor] if and things Message-ID: <674d5ce60707181814s2140a5ads3e6f9f31e72886e9@mail.gmail.com> # pixel[] is a list of tuples: (r,g,b) # pixel[1030*(y-a) + x][0] = r # pixel[1030*(y-a) + x][1] = g # pixel[1030*(y-a) + x][2] = b for a in range(0, 10): if pixel[1030*(y-a) + x][1] > pixel[1030*(y-a) + x][0] and pixel[1030*(y-a) + x][1] > pixel[1030*(y-a) + x][2]: box = box + 1 print box i have never used double conditions before, is this correct? I want box++ when the g is both bigger than r and b. import time import ImageGrab # Part of PIL from ctypes import * # Load up the Win32 APIs we need to use. 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 # Sleep for 2 seconds - click the window you want to grab. #time.sleep(2) # 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)) # Save the screenshot as a BMP. time.sleep(2) image.save("c:\python_codes\screenshot.bmp") # Get the pixel 10 pixels along the top of the foreground window - this # will be a piece of the window border. # print time.time() start = time.time() pixels = image.getdata() for x in xrange(0, 500): for y in xrange(0, 500): rgb = pixels[500 * x + y] print pixels[1][0] print ( time.time() - start ) # PIL returns colours as RGB values packed into a triple: #print "RGB(%d, %d, %d)" % (rgb[0], rgb[1], rgb[2]) # This prints RGB(0, 74, 216) on my XP machine -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070719/2e63153c/attachment-0001.htm From witham.ian at gmail.com Thu Jul 19 03:37:43 2007 From: witham.ian at gmail.com (Ian Witham) Date: Thu, 19 Jul 2007 13:37:43 +1200 Subject: [Tutor] if and things In-Reply-To: <674d5ce60707181814s2140a5ads3e6f9f31e72886e9@mail.gmail.com> References: <674d5ce60707181814s2140a5ads3e6f9f31e72886e9@mail.gmail.com> Message-ID: try this: for a in range(10): r, g, b = pixel[1030*(y-a) + x] if g > r and g > b: box += 1 This is an example of "unpacking" a tuple into separate variables, r, g and b. On 7/19/07, elis aeris wrote: > > # pixel[] is a list of tuples: (r,g,b) > # pixel[1030*(y-a) + x][0] = r > # pixel[1030*(y-a) + x][1] = g > # pixel[1030*(y-a) + x][2] = b > > for a in range(0, 10): > if pixel[1030*(y-a) + x][1] > pixel[1030*(y-a) + x][0] and > pixel[1030*(y-a) + x][1] > pixel[1030*(y-a) + x][2]: > box = box + 1 > > print box > > > i have never used double conditions before, is this correct? > > I want box++ when the g is both bigger than r and b. > > > > > > > > > > > > > > > > > > import time > > import ImageGrab # Part of PIL > from ctypes import * > > # Load up the Win32 APIs we need to use. > 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 > > # Sleep for 2 seconds - click the window you want to grab. > #time.sleep(2) > > > > # 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)) > > # Save the screenshot as a BMP. > time.sleep(2) > > > image.save("c:\python_codes\screenshot.bmp") > > # Get the pixel 10 pixels along the top of the foreground window - this > # will be a piece of the window border. > > # print time.time() > > start = time.time() > > pixels = image.getdata() > for x in xrange(0, 500): > for y in xrange(0, 500): > rgb = pixels[500 * x + y] > > print pixels[1][0] > > print ( time.time() - start ) > > # PIL returns colours as RGB values packed into a triple: > #print "RGB(%d, %d, %d)" % (rgb[0], rgb[1], rgb[2]) # This prints RGB(0, > 74, 216) on my XP machine > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070719/67409aba/attachment.html From hunter92383 at gmail.com Thu Jul 19 03:38:11 2007 From: hunter92383 at gmail.com (elis aeris) Date: Thu, 19 Jul 2007 09:38:11 +0800 Subject: [Tutor] if and things Message-ID: <674d5ce60707181838o7d1d9714x157b8fcbca4187ab@mail.gmail.com> full code below. # pixel[] is a list of tuples: (r,g,b) # pixel[1030*(y-a) + x][0] = r # pixel[1030*(y-a) + x][1] = g # pixel[1030*(y-a) + x][2] = b for a in range(0, 10): if pixel[1030*(y-a) + x][1] > pixel[1030*(y-a) + x][0] and pixel[1030*(y-a) + x][1] > pixel[1030*(y-a) + x][2]: box = box + 1 print box i have never used double conditions before, is this correct? I want box++ when the g is both bigger than r and b. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070719/07b6d93a/attachment.htm From hunter92383 at gmail.com Thu Jul 19 03:39:02 2007 From: hunter92383 at gmail.com (elis aeris) Date: Thu, 19 Jul 2007 09:39:02 +0800 Subject: [Tutor] if and things In-Reply-To: References: <674d5ce60707181814s2140a5ads3e6f9f31e72886e9@mail.gmail.com> Message-ID: <674d5ce60707181839h6ccbbd2bm89c724b4a9d687c0@mail.gmail.com> man that looks totally pythonic. On 7/19/07, Ian Witham wrote: > > try this: > > for a in range(10): > r, g, b = pixel[1030*(y-a) + x] > if g > r and g > b: > box += 1 > > This is an example of "unpacking" a tuple into separate variables, r, g > and b. > > On 7/19/07, elis aeris wrote: > > > > # pixel[] is a list of tuples: (r,g,b) > > # pixel[1030*(y-a) + x][0] = r > > # pixel[1030*(y-a) + x][1] = g > > # pixel[1030*(y-a) + x][2] = b > > > > for a in range(0, 10): > > if pixel[1030*(y-a) + x][1] > pixel[1030*(y-a) + x][0] and > > pixel[1030*(y-a) + x][1] > pixel[1030*(y-a) + x][2]: > > box = box + 1 > > > > print box > > > > > > i have never used double conditions before, is this correct? > > > > I want box++ when the g is both bigger than r and b. > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > import time > > > > import ImageGrab # Part of PIL > > from ctypes import * > > > > # Load up the Win32 APIs we need to use. > > 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 > > > > # Sleep for 2 seconds - click the window you want to grab. > > #time.sleep(2) > > > > > > > > # 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)) > > > > # Save the screenshot as a BMP. > > time.sleep(2) > > > > > > image.save("c:\python_codes\screenshot.bmp") > > > > # Get the pixel 10 pixels along the top of the foreground window - this > > # will be a piece of the window border. > > > > # print time.time() > > > > start = time.time() > > > > pixels = image.getdata() > > for x in xrange(0, 500): > > for y in xrange(0, 500): > > rgb = pixels[500 * x + y] > > > > print pixels[1][0] > > > > print ( time.time() - start ) > > > > # PIL returns colours as RGB values packed into a triple: > > #print "RGB(%d, %d, %d)" % (rgb[0], rgb[1], rgb[2]) # This prints > > RGB(0, 74, 216) on my XP machine > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070719/1e412d39/attachment.html From keridee at jayco.net Thu Jul 19 04:42:40 2007 From: keridee at jayco.net (Tiger12506) Date: Wed, 18 Jul 2007 21:42:40 -0500 Subject: [Tutor] if and things References: <674d5ce60707181814s2140a5ads3e6f9f31e72886e9@mail.gmail.com> <674d5ce60707181839h6ccbbd2bm89c724b4a9d687c0@mail.gmail.com> Message-ID: <007c01c7c9ae$84fffd50$0756e104@JSLAPTOP> > man that looks totally pythonic. What you had is correct though. Good job. JS From keridee at jayco.net Thu Jul 19 04:53:27 2007 From: keridee at jayco.net (Tiger12506) Date: Wed, 18 Jul 2007 21:53:27 -0500 Subject: [Tutor] if and things References: <674d5ce60707181814s2140a5ads3e6f9f31e72886e9@mail.gmail.com> Message-ID: <00b001c7c9b0$05652410$0756e104@JSLAPTOP> It's nice to see you haven't given up. A few suggestions to make you code a little more creative. > import time > > import ImageGrab # Part of PIL > from ctypes import * > > # Load up the Win32 APIs we need to use. > 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 > > # Sleep for 2 seconds - click the window you want to grab. > #time.sleep(2) > > > > # 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)) > > # Save the screenshot as a BMP. > time.sleep(2) > > > image.save("c:\python_codes\screenshot.bmp") > > # Get the pixel 10 pixels along the top of the foreground window - this > # will be a piece of the window border. > > # print time.time() > > start = time.time() > > pixels = image.getdata() > for x in xrange(0, 500): > for y in xrange(0, 500): > rgb = pixels[500 * x + y] You will be planning to do something else with this right? As it is, you are looping 250,000 times and resetting the variable rgb each time, losing the previous value. I imagine that you have other plans. > print pixels[1][0] > > print ( time.time() - start ) Oh. I bet this is all supposed to be indented. Nevermind about the above loop. > # PIL returns colours as RGB values packed into a triple: > #print "RGB(%d, %d, %d)" % (rgb[0], rgb[1], rgb[2]) # This prints RGB(0, > 74, 216) on my XP machine Here is what I really meant to look at - yes this commented line print "RGB(%d, %d, %d)" % (rgb[0], rgb[1], rgb[2]) Since the percent formatter is followed by a tuple (which is what you are making by putting rgb[0], rgb[1], rgb[2] into parentheses) and rgb is already a tuple, you can write this much more simply as: print "RGB(%d, %d, %d)" % rgb JS From hunter92383 at gmail.com Thu Jul 19 04:27:01 2007 From: hunter92383 at gmail.com (elis aeris) Date: Thu, 19 Jul 2007 10:27:01 +0800 Subject: [Tutor] if and things In-Reply-To: <00b001c7c9b0$05652410$0756e104@JSLAPTOP> References: <674d5ce60707181814s2140a5ads3e6f9f31e72886e9@mail.gmail.com> <00b001c7c9b0$05652410$0756e104@JSLAPTOP> Message-ID: <674d5ce60707181927u640bf792u946c41e0ab7c17ec@mail.gmail.com> given up? man i have a project to go live :) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070719/c6573192/attachment.html From gslindstrom at gmail.com Thu Jul 19 04:26:05 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Wed, 18 Jul 2007 21:26:05 -0500 Subject: [Tutor] Creating Packages Message-ID: Hello- I have written a class to help folks like me manipulate data segments (the kind one deals with when reading/writing data files). The classes and tests are written -- at least enough to get things going -- what I need help with is creating a package out of this and then creating routines to install them. Can one of you help me out either with some tutoring or pointing me to some literature? I would like to use the cheese shop. Thanks for your help, --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070718/341b883c/attachment-0001.htm From com.gmail.kyleaschmitt at pooryorick.com Wed Jul 18 23:15:41 2007 From: com.gmail.kyleaschmitt at pooryorick.com (=?utf-8?Q?Nathan=20Coulter?=) Date: Wed, 18 Jul 2007 21:15:41 +0000 Subject: [Tutor] reading random line from a file Message-ID: <20070718211541.25724.qmail@station198.com> > -------Original Message------- > From: Tiger12506 > Yuck. Talk about a one shot function! Of course it only reads through the > file once! You only call the function once. Put a second print randline(f) > at the bottom of your script and see what happens :-) > > JS > *sigh* #!/bin/env python import os import random text = 'shaks12.txt' if not os.path.exists(text): os.system('wget http://www.gutenberg.org/dirs/etext94/shaks12.txt') def randline(f): for i,j in enumerate(file(f, 'rb')): if random.randint(0,i) == i: line = j return line print randline(text) print randline(text) print randline(text) -- Yorick From kent37 at tds.net Thu Jul 19 05:20:41 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Jul 2007 23:20:41 -0400 Subject: [Tutor] Creating Packages In-Reply-To: References: Message-ID: <469ED889.2060504@tds.net> Greg Lindstrom wrote: > Hello- > > I have written a class to help folks like me manipulate data segments > (the kind one deals with when reading/writing data files). The classes > and tests are written -- at least enough to get things going -- what I > need help with is creating a package out of this and then creating > routines to install them. Can one of you help me out either with some > tutoring or pointing me to some literature? I would like to use the > cheese shop. Here is a starting point for the CheeseShop: http://wiki.python.org/moin/CheeseShopTutorial For info on packaging see http://docs.python.org/dist/dist.html Kent From sarliz73 at gmail.com Thu Jul 19 06:17:28 2007 From: sarliz73 at gmail.com (sarliz73) Date: Wed, 18 Jul 2007 23:17:28 -0500 Subject: [Tutor] IDLE Usage - was Interpreter Restarts References: Message-ID: <008b01c7c9bb$b889e2a0$ba1a6144@SaraOffice> Unfortunately, it's the Olympic style leaps now, the baby steps later. But I definitely agree with the process. I do have some information to plow through for now. Thanks to all! Sara > > I'd also recommend that you find and install a Windows version of whatever > editor (whether vi, vim or something else like emacs) you're going to be > using on the Unix box. Play with it locally on your own machine for a > while and get comfortable with it, and then start using the copy on the > unix system. That will let you take baby steps, and gain a little > confidence. > > From a_n_lal at yahoo.com Thu Jul 19 15:14:59 2007 From: a_n_lal at yahoo.com (Aditya Lal) Date: Thu, 19 Jul 2007 06:14:59 -0700 (PDT) Subject: [Tutor] reading random line from a file In-Reply-To: <20070718211541.25724.qmail@station198.com> Message-ID: <135885.45650.qm@web90405.mail.mud.yahoo.com> An alternative approach (I found the Yorick's code to be too slow for large # of calls) : We can use file size to pick a random point in the file. We can read and ignore text till next new line. This will avoid outputting partial lines. Return the next line (which I guess is still random :)). Indicative code - import os,random def getrandomline(filename) : offset = random.randint(0,os.stat(filename)[6]) fd = file(filename,'rb') fd.seek(offset) fd.readline() # Read and ignore return fd.readline() getrandomline("shaks12.txt") Caveat: The above code will never choose 1st line and will return '' for last line. Other than the boundary conditions it will work well (even for large files). Interestingly : On modifying this code to take in file object rather than filename, the performance improved by ~50%. On wrapping it in a class, it further improved by ~25%. On executing the get random line 100,000 times on large file (size 2707519 with 9427 lines), the class version finished < 5 seconds. Platform : 2GHz Intel Core 2 Duo macBook (2GB RAM) running Mac OSX (10.4.10). Output using python 2.5.1 (stackless) Approach using enum approach : 9.55798196793 : for [100] iterations Approach using filename : 11.552863121 : for [100000] iterations Approach using file descriptor : 5.97015094757 : for [100000] iterations Approach using class : 4.46039891243 : for [100000] iterations Output using python 2.3.5 (default python on OSX) Approach using enum approach : 12.2886080742 : for [100] iterations Approach using filename : 12.5682640076 : for [100000] iterations Approach using file descriptor : 6.55952501297 : for [100000] iterations Approach using class : 5.35413718224 : for [100000] iterations I am attaching test program FYI. -- Aditya --- Nathan Coulter wrote: > > -------Original Message------- > > From: Tiger12506 > > > Yuck. Talk about a one shot function! Of course > it only reads through the > > file once! You only call the function once. Put a > second print randline(f) > > at the bottom of your script and see what happens > :-) > > > > JS > > > > *sigh* > > #!/bin/env python > > import os > import random > > text = 'shaks12.txt' > if not os.path.exists(text): > os.system('wget > http://www.gutenberg.org/dirs/etext94/shaks12.txt') > > def randline(f): > for i,j in enumerate(file(f, 'rb')): > if random.randint(0,i) == i: > line = j > return line > > print randline(text) > print randline(text) > print randline(text) > > -- > Yorick > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ____________________________________________________________________________________ Sucker-punch spam with award-winning protection. Try the free Yahoo! Mail Beta. http://advision.webevents.yahoo.com/mailbeta/features_spam.html -------------- next part -------------- A non-text attachment was scrubbed... Name: randline.py Type: text/script Size: 2039 bytes Desc: 941365746-randline.py Url : http://mail.python.org/pipermail/tutor/attachments/20070719/cf073b56/attachment.bin From a_n_lal at yahoo.com Thu Jul 19 16:33:45 2007 From: a_n_lal at yahoo.com (Aditya Lal) Date: Thu, 19 Jul 2007 07:33:45 -0700 (PDT) Subject: [Tutor] reading random line from a file In-Reply-To: <135885.45650.qm@web90405.mail.mud.yahoo.com> Message-ID: <16011.50991.qm@web90401.mail.mud.yahoo.com> Sorry, I did not see the other thread in which this approach has already been covered. The point Kent has raised about going into infinite loop with file having single line is very true. Following is the corrected version (for completeness sake) - import os,random def getrandfromMem(filename) : fd = file(filename,'rb') l = fd.readlines() pos = random.randint(0,len(l)) fd.close() return (pos,l[pos]) def getrandomline2(filename) : filesize = os.stat(filename)[6] if filesize < 4096 : # Seek may not be very useful return getrandfromMem(filename) fd = file(filename,'rb') for _ in range(10) : # Try 10 times pos = random.randint(0,filesize) fd.seek(pos) fd.readline() # Read and ignore line = fd.readline() if line != '' : break if line != '' : return (pos,line) else : getrandfromMem(filename) getrandomline2("shaks12.txt") Caveat : It will still skip 1st line during random selection if its size exceed 4096 chars !! --- Aditya Lal wrote: > An alternative approach (I found the Yorick's code > to > be too slow for large # of calls) : > > We can use file size to pick a random point in the > file. We can read and ignore text till next new > line. > This will avoid outputting partial lines. Return the > next line (which I guess is still random :)). > > Indicative code - > > import os,random > > def getrandomline(filename) : > offset = random.randint(0,os.stat(filename)[6]) > fd = file(filename,'rb') > fd.seek(offset) > fd.readline() # Read and ignore > return fd.readline() > > getrandomline("shaks12.txt") > > Caveat: The above code will never choose 1st line > and > will return '' for last line. Other than the > boundary > conditions it will work well (even for large files). > > > Interestingly : > > On modifying this code to take in file object rather > than filename, the performance improved by ~50%. On > wrapping it in a class, it further improved by ~25%. > > On executing the get random line 100,000 times on > large file (size 2707519 with 9427 lines), the class > version finished < 5 seconds. > > Platform : 2GHz Intel Core 2 Duo macBook (2GB RAM) > running Mac OSX (10.4.10). > > Output using python 2.5.1 (stackless) > > Approach using enum approach : 9.55798196793 : for > [100] iterations > Approach using filename : 11.552863121 : for > [100000] > iterations > Approach using file descriptor : 5.97015094757 : for > [100000] iterations > Approach using class : 4.46039891243 : for [100000] > iterations > > Output using python 2.3.5 (default python on OSX) > > Approach using enum approach : 12.2886080742 : for > [100] iterations > Approach using filename : 12.5682640076 : for > [100000] > iterations > Approach using file descriptor : 6.55952501297 : for > [100000] iterations > Approach using class : 5.35413718224 : for [100000] > iterations > > I am attaching test program FYI. > > -- > Aditya > > --- Nathan Coulter > wrote: > > > > -------Original Message------- > > > From: Tiger12506 > > > > > Yuck. Talk about a one shot function! Of course > > it only reads through the > > > file once! You only call the function once. Put > a > > second print randline(f) > > > at the bottom of your script and see what > happens > > :-) > > > > > > JS > > > > > > > *sigh* > > > > #!/bin/env python > > > > import os > > import random > > > > text = 'shaks12.txt' > > if not os.path.exists(text): > > os.system('wget > > > http://www.gutenberg.org/dirs/etext94/shaks12.txt') > > > > def randline(f): > > for i,j in enumerate(file(f, 'rb')): > > if random.randint(0,i) == i: > > line = j > > return line > > > > print randline(text) > > print randline(text) > > print randline(text) > > > > -- > > Yorick > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > ____________________________________________________________________________________ > Sucker-punch spam with award-winning protection. > Try the free Yahoo! Mail Beta. > http://advision.webevents.yahoo.com/mailbeta/features_spam.html> import os > import random > > class randomline : > > def __init__(self, filename="largefile.txt") : > self.filesize = os.stat(filename)[6] > self.fd = file(filename, 'rb') > > def getline(self) : > offset = random.randint(0,self.filesize) > self.fd.seek(offset) > self.fd.readline() > line = self.fd.readline() > return (offset,line) > > def close(self) : > self.fd.close() > > # Uses file name > def getrandomline(filename) : > offset = random.randint(0,os.stat(filename)[6]) > fd = file(filename, 'rb') > fd.seek(offset) > ret = (offset,fd.readline()) > fd.close() > return ret > > # Uses file descriptor > def getrandline(fd) : > offset = random.randint(0,os.fstat(fd.fileno())[6]) > fd.seek(offset) > line = fd.readline() > return (offset,fd.readline()) > > # Uses enumeration > def randline(fd): > for i,j in enumerate(fd) : > if random.randint(0,i) == i: > line = j > fd.seek(0) > return line > > > if __name__ == '__main__' : > > # Substitute your file name > filename = "largefile.txt" > > # Class > rd = randomline(filename) > print rd.getline() > rd.close() > > # file name > print getrandomline(filename) > > # file descriptor > fd = file(filename,'rb') > print getrandline(fd) > fd.close() > > # Using enum approach > fd = file(filename,'rb') > print randline(fd) > fd.close() > > from timeit import Timer > t_class = Timer('rd.getline()', 'from __main__ > import randomline ; rd = > randomline("'+filename+'")') > t_filename = Timer('getrandomline("'+filename+'")', > 'from __main__ import getrandomline') > t_fd = Timer('getrandline(fd)', 'from __main__ > import getrandline ; fd = file("'+filename+'")') > t_enum = Timer('randline(fd)', 'from __main__ > import randline ; fd = file("'+filename+'")') > > print 'Approach using enum approach : %s : for [%d] > iterations' % (str(t_enum.timeit(100)),100) > print 'Approach using filename : %s : for [%d] > iterations' % > (str(t_filename.timeit(100000)),100000) > print 'Approach using file descriptor : %s : for > [%d] iterations' % (str(t_fd.timeit(100000)),100000) > print 'Approach using class : %s : for [%d] > iterations' % (str(t_class.timeit(100000)),100000) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ____________________________________________________________________________________ Sick sense of humor? Visit Yahoo! TV's Comedy with an Edge to see what's on, when. http://tv.yahoo.com/collections/222 From jim at well.com Thu Jul 19 16:58:46 2007 From: jim at well.com (jim stockford) Date: Thu, 19 Jul 2007 07:58:46 -0700 Subject: [Tutor] IDLE Usage - was Interpreter Restarts In-Reply-To: <440190.65323.qm@web35111.mail.mud.yahoo.com> References: <440190.65323.qm@web35111.mail.mud.yahoo.com> Message-ID: <73dc3bfcd70e77e8f0c288195ebd2e74@well.com> here's a link to the very brief vi get-started web page: http://www.sf-lug.com/How2vi.html On Jul 17, 2007, at 11:01 AM, Sara Johnson wrote: > Sure, sounds good.? Should I assume that?'any' Unix version allows Vim? > ? > Thanks, > Sara > > ----- Original Message ---- > From: jim stockford > To: Sara Johnson > Cc: tutor at python.org > Sent: Tuesday, July 17, 2007 12:30:12 PM > Subject: Re: [Tutor] IDLE Usage - was Interpreter Restarts > > you want a very brief set of vi(m) commands-- > a get-you-started tutorial that's nearly painless? > I'll send if "yes". > jim > > On Jul 16, 2007, at 9:26 PM, Sara Johnson wrote: > > > First off, yes, I was referring to (I guess you could say) a > > non-python editor.? I use an SSH editor set up by my school.? If I > > type python at the prompt in SSH, I get the Python shell. ?My problem > > is, I can't open a GUI no matter what I subscribe to or purchase.? I > > have Python 2.3 and yes, I can access the commandline, but that does > > not work the?way it's been described to work. > > ? > > If this still doesn't make any sense, just ignore me... > > ? > > Sara > > > > > > >>Not quite what we were discussing, but I think you may have given > > just > > enough clues that i can be of some help. Just for reference ~ which > > editor > > are you using? > > > > IDLE is both an editor and a python shell or interpreter. It is not > > the same > > thing as typing python.exe wherever you might be typing it. > > > > Typing Python into an editor should put the word "Python" into your > > currently open file. I don't believe that this is what you mean. > > Perhaps you > > are confusing what exactly is an editor? > > > > You use Windows you've mentioned before. So here's what you can do. > > Start -> > > Programs -> Python 2.5 -> Python (commandline) > > > > This is the python interpreter. As you might already know. > > > > And then this. > > Start -> Programs -> Python 2.5 -> IDLE (Python GUI) > > > > This is IDLE. As you probably know. > > > > Two windows should come up when you click IDLE. One is an editor. The > > other > > is the python shell, or interpreter. You can open .py files in IDLE > by > > right > > clicking and selecting "Edit with IDLE". At any time that you wish to > > run a > > program that is open in the editor half of IDLE, hit F5 and the > Python > > shell > > half of IDLE comes to the top and runs the program. > > > > If doing all that doesn't do what I expect it to do, or you have > > something > > else in mind, reply back. If it does, then great! > > > > Oh. And tell me which editor you are using which magically opens a > > python > > interpreter when you type Python into it. ;-) > > > > JS > > > > _______________________________________________ > > Tutor maillist??-??Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > Moody friends. Drama queens. Your life? Nope! - their life, your > story. > > Play Sims Stories at Yahoo! > > Games._______________________________________________ > > 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 > > > No need to miss a message. Get email on-the-go > with Yahoo! Mail for Mobile. Get > started._______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From bhaaluu at gmail.com Thu Jul 19 17:40:02 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 19 Jul 2007 11:40:02 -0400 Subject: [Tutor] reading random line from a file In-Reply-To: <16011.50991.qm@web90401.mail.mud.yahoo.com> References: <135885.45650.qm@web90405.mail.mud.yahoo.com> <16011.50991.qm@web90401.mail.mud.yahoo.com> Message-ID: Greetings, Thanks for including the complete source code! It really helps to have something that works to look at. I modified an earlier version of this to run on my computer (GNU/Linux; Python 2.4.3). The os.module() stuff is new for me, so I played around with it... here's my modified file just in case another beginner is interested: #!/usr/bin/env python """ 2007-07-19 Modified snippet from Tutor mailing list. Example of checking to see if a file exists, using 'os.path()' Examples of using 'os.system()' with wget and mv commmands. Lookup: enumerate(), random.randint() This is obviously NOT cross-platform. Works on GNU/Linux. b h a a l u u at g m a i l dot c o m """ import os import random def randline(): text = 'list_classifiers' if not os.path.exists(text): os.system('wget http://cheeseshop.python.org/pypi?%3Aaction=list_classifiers ') os.system('mv pypi\?\:action\=list_classifiers list_classifiers') f = file(text, 'rb') for i,j in enumerate(f): if random.randint(0,i) == i: line = j f.close() return line while True: print "\n", randline() answer = raw_input("Another line? [y/n]: ") if answer == 'n': break Happy Programming! -- bhaaluu at gmail dot com From tinoloc at gmail.com Thu Jul 19 20:40:58 2007 From: tinoloc at gmail.com (Tino Dai) Date: Thu, 19 Jul 2007 14:40:58 -0400 Subject: [Tutor] File parse In-Reply-To: <003d01c7c8fc$c9400bc0$affde004@JSLAPTOP> References: <17285ccf0707170809p48799327k1e33937f536a0c3a@mail.gmail.com> <02e501c7c8b7$873c8810$c7fde004@JSLAPTOP> <17285ccf0707171450o703a569dj36e84583ad404010@mail.gmail.com> <002201c7c8dc$81fd9b30$93fce004@JSLAPTOP> <17285ccf0707172030q22aff38ai4f24f872fcc2eac0@mail.gmail.com> <003d01c7c8fc$c9400bc0$affde004@JSLAPTOP> Message-ID: On 7/18/07, Tiger12506 wrote: > > >I sent a sample of the file "testin.txt" in the last email. Here are the > > lines themsevles: > > Oh! Sorry. I didn't look in the attachments - I expected the lines in the > email. My mistake. > Try this ~~ :-P > > > ############################## > import re > > infile = open("testin.txt","r") > outfile = open("out.txt","w") > > patt = re.compile(r".*src=([\d\.]*) dst=([\d\.]*).*") > > for line in infile: > m = patt.match(line) > if m: > outfile.write("src=%s dst=%s\n"%m.groups()) > > infile.close() > outfile.close() > ############################# > > Seeing the input file makes me wonder if regular expressions is over kill > in > this instance. > > JS Hi there, If you are looking for one ip address, and only one ip address, you might want to consider: for line in input_file: if "10.52.10.10" in line: outfile.writeline(line) outfile.close() Is that what you want? -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070719/d716113e/attachment-0001.html From nephish at gmail.com Thu Jul 19 20:53:21 2007 From: nephish at gmail.com (shawn bright) Date: Thu, 19 Jul 2007 13:53:21 -0500 Subject: [Tutor] about importing a module Message-ID: <384c93600707191153m32b42ff1k216a356f7b540210@mail.gmail.com> hello there, if i have a module that is in the same directory as the file that imports it, but that module has the same name as a module in my python path, which one gets imported ? i ask because i want to do some work on the module, but dont want to mess with my stable one in site-packages. so i want to import it from the local directory only. thanks shawn -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070719/6a1557d7/attachment.html From tinoloc at gmail.com Thu Jul 19 21:03:34 2007 From: tinoloc at gmail.com (Tino Dai) Date: Thu, 19 Jul 2007 15:03:34 -0400 Subject: [Tutor] Style question with classes and modules Message-ID: Hi there Everybody, I have style question with importing of modules and classes. Presently, I have several files importing several modules. #apacheModule import dbBase import dbCommon import miscBase My question is there any advantage to me wrapping them in a single file (wrapper), and the importing a single file into that file (barring namespace collisons). Example shown below: In aggreateBase: import dbBase import dbCommon import miscBase In apacheModule: import aggreateBase # instead of #import dbBase #import dbCommon #import miscBase or perhaps even In aggreateBase: from dbBase import dbBase from dbCommon import dbCommon from miscBase import miscBase The two advantages that I can see are, I don't need to type as much, and there would be a speed up in the execution of code. Is there a reason why I shouldn't? Thanks in advance, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070719/a4ba5127/attachment.htm From rabidpoobear at gmail.com Thu Jul 19 21:05:20 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 19 Jul 2007 14:05:20 -0500 Subject: [Tutor] reading random line from a file In-Reply-To: References: <135885.45650.qm@web90405.mail.mud.yahoo.com> <16011.50991.qm@web90401.mail.mud.yahoo.com> Message-ID: <469FB5F0.3090907@gmail.com> bhaaluu wrote: > Greetings, > Thanks for including the complete source code! > It really helps to have something that works to look at. > I modified an earlier version of this to run on my > computer (GNU/Linux; Python 2.4.3). > I think the best strategy for this problem would be to build an index of the offset of the start of each line, and then randomly select from this list. that makes each line equally probable, and you can set up your class so that the index is only built on the first call to the function. -Luke From kent37 at tds.net Thu Jul 19 21:06:47 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Jul 2007 15:06:47 -0400 Subject: [Tutor] about importing a module In-Reply-To: <384c93600707191153m32b42ff1k216a356f7b540210@mail.gmail.com> References: <384c93600707191153m32b42ff1k216a356f7b540210@mail.gmail.com> Message-ID: <469FB647.9090907@tds.net> shawn bright wrote: > hello there, > > if i have a module that is in the same directory as the file that > imports it, > but that module has the same name as a module in my python path, which one > gets imported ? The local one. sys.path has the list of directories that are searched for imports, in the order they are searched. The local directory is first. You can look at the __file__ attribute of a module to see where it comes from, e.g. import mymodule print mymodule.__file__ Kent > > i ask because i want to do some work on the module, but dont want to > mess with my stable > one in site-packages. > so i want to import it from the local directory only. > > thanks > > shawn > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From rabidpoobear at gmail.com Thu Jul 19 21:15:17 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 19 Jul 2007 14:15:17 -0500 Subject: [Tutor] Style question with classes and modules In-Reply-To: References: Message-ID: <469FB845.2010503@gmail.com> Tino Dai wrote: > Hi there Everybody, > > I have style question with importing of modules and classes. > Presently, I have several files importing several modules. > > #apacheModule > import dbBase > import dbCommon > import miscBase > > My question is there any advantage to me wrapping them in a single > file (wrapper), and the importing a single file > into that file (barring namespace collisons). Example shown below: > > In aggreateBase: > import dbBase > import dbCommon > import miscBase > > In apacheModule: > import aggreateBase This statement binds the variable name aggreateBase (do you mean aggregate?) to the module aggreateBase.py which has imports inside of it. So every time you want to use one of the modules you import via aggreateBase, you'd have to type: aggreateBase.dbBase.function_name() you can get around this by typing from aggreateBase import * > # instead of > #import dbBase > #import dbCommon > #import miscBase > > or perhaps even > In aggreateBase: > from dbBase import dbBase > from dbCommon import dbCommon > from miscBase import miscBase This doesn't work. try it out. >>> from sys import sys Traceback (most recent call last): File "", line 1, in -toplevel- from sys import sys ImportError: cannot import name sys > > The two advantages that I can see are, I don't need to type as much, > and there would be a speed up in the execution of code. > Is there a reason why I shouldn't? You need to type more or the same amount, not less. There wouldn't be a speed up in code execution. Why would there be? The reason why you shouldn't is because it hides the external modules you're using in that particular module's implementation. Secondly, you'd have to create a new aggreateBase for each new set of imports that you'd want to use, otherwise certain modules would be importing things they didn't actually need. It's much easier and clearer to put the imports of the modules that you're using in the module that you're using them. For what purpose would you do this? -Luke From kent37 at tds.net Thu Jul 19 21:27:49 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Jul 2007 15:27:49 -0400 Subject: [Tutor] Style question with classes and modules In-Reply-To: References: Message-ID: <469FBB35.4030600@tds.net> Tino Dai wrote: > Hi there Everybody, > > I have style question with importing of modules and classes. > Presently, I have several files importing several modules. > > #apacheModule > import dbBase > import dbCommon > import miscBase > > My question is there any advantage to me wrapping them in a single file > (wrapper), and the importing a single file > into that file (barring namespace collisons). Example shown below: > > In aggreateBase: > import dbBase > import dbCommon > import miscBase > > In apacheModule: > import aggreateBase > # instead of > #import dbBase > #import dbCommon > #import miscBase Then you will have to refer to aggreateBase.dbBase.somethingInDbBase which is a bit awkward. BTW I think you mean aggregateBase? > or perhaps even > In aggreateBase: > from dbBase import dbBase > from dbCommon import dbCommon > from miscBase import miscBase This is pretty commonly done in a package __init__.py to promote names to package scope. So you might have /mypackage/ __init__.py stuff.py class foo... nonsense.py class bar... If __init__.py is empty then in a client you have to write e.g. from mypackage.stuff import foo If __init__.py contains from stuff import * from nonsense import * then a client can say from mypackage import foo If your modules are related and belong together in a package then this can be handy. I wouldn't use it to group unrelated modules though. Using from xx import * does obscure the true location of an object. > The two advantages that I can see are, I don't need to type as much, and > there would be a speed up in the execution of code. Why do you expect a speedup? > Is there a reason why I shouldn't? If they belong together, put them in a package and use __init__.py. if they don't belong together you are just obscuring the design for very little savings. Kent From tinoloc at gmail.com Thu Jul 19 21:48:04 2007 From: tinoloc at gmail.com (Tino Dai) Date: Thu, 19 Jul 2007 15:48:04 -0400 Subject: [Tutor] Style question with classes and modules In-Reply-To: <469FBB35.4030600@tds.net> References: <469FBB35.4030600@tds.net> Message-ID: On 7/19/07, Kent Johnson wrote: > > > The two advantages that I can see are, I don't need to type as much, and > > there would be a speed up in the execution of code. > > Why do you expect a speedup? In the Python Reference by David Beazley on p. 40, he substituted import math with from math import sqrt and he switched out d = d + math.sqrt(i) with sqrt(i). He said that that change made the program run twice as fast. So therefore I was under the impression that "from somemodule import someclass" would always be faster than import somemodule. > Is there a reason why I shouldn't? > > If they belong together, put them in a package and use __init__.py. if > they don't belong together you are just obscuring the design for very > little savings. Ok, so I will keep the code as is. Thank you Luke and Kent! -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070719/e7b7a008/attachment.htm From tinoloc at gmail.com Thu Jul 19 21:49:50 2007 From: tinoloc at gmail.com (Tino Dai) Date: Thu, 19 Jul 2007 15:49:50 -0400 Subject: [Tutor] Style question with classes and modules In-Reply-To: <469FB845.2010503@gmail.com> References: <469FB845.2010503@gmail.com> Message-ID: > > > For what purpose would you do this? For one thing: sheer laziness ;). But seriously, I though that if I abstracted all of those classes, it would be easier to maintain in the future. That is the real reason behind my wanting refactor that piece of code. -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070719/0556457a/attachment.html From brunson at brunson.com Thu Jul 19 21:57:56 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 19 Jul 2007 13:57:56 -0600 Subject: [Tutor] Style question with classes and modules In-Reply-To: References: <469FBB35.4030600@tds.net> Message-ID: <469FC244.4030602@brunson.com> Tino Dai wrote: > On 7/19/07, *Kent Johnson* > > wrote: > > > The two advantages that I can see are, I don't need to type as > much, and > > there would be a speed up in the execution of code. > > Why do you expect a speedup? > > > In the Python Reference by David Beazley on p. 40, he substituted > import math > with from math import sqrt and he switched out d = d + math.sqrt(i) with > sqrt(i). He said that that change made the program run twice as fast. > So therefore > I was under the impression that "from somemodule import someclass" > would always be > faster than import somemodule. The reason it's faster is because to get the actual function for math.sqrt() after importing math, you have to do a dictionary lookup in the "math" namespace. I don't think it should run twice as fast. I would only worry about it if you had some situation where you were using the same name over and over: import math for i in range( 0, 1000000000 ): x = math.sqrt(i) That's 1000000000 dictionary lookups. Importing just the sqrt name would avoid those lookups, so would: import math f = math.sqrt for i in range( 0, 1000000000 ): x = f(i) Does that make sense? > > > Is there a reason why I shouldn't? > > If they belong together, put them in a package and use __init__.py. if > they don't belong together you are just obscuring the design for very > little savings. > > > Ok, so I will keep the code as is. Thank you Luke and Kent! > > -Tino > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From tinoloc at gmail.com Thu Jul 19 22:06:42 2007 From: tinoloc at gmail.com (Tino Dai) Date: Thu, 19 Jul 2007 16:06:42 -0400 Subject: [Tutor] Style question with classes and modules In-Reply-To: <469FC244.4030602@brunson.com> References: <469FBB35.4030600@tds.net> <469FC244.4030602@brunson.com> Message-ID: On 7/19/07, Eric Brunson wrote: > > Tino Dai wrote: > > On 7/19/07, *Kent Johnson* > > > wrote: > > > > > The two advantages that I can see are, I don't need to type as > > much, and > > > there would be a speed up in the execution of code. > > > > Why do you expect a speedup? > > > > > > In the Python Reference by David Beazley on p. 40, he substituted > > import math > > with from math import sqrt and he switched out d = d + math.sqrt(i) with > > sqrt(i). He said that that change made the program run twice as fast. > > So therefore > > I was under the impression that "from somemodule import someclass" > > would always be > > faster than import somemodule. > > The reason it's faster is because to get the actual function for > math.sqrt() after importing math, you have to do a dictionary lookup in > the "math" namespace. I don't think it should run twice as fast. I > would only worry about it if you had some situation where you were using > the same name over and over: > > import math > for i in range( 0, 1000000000 ): > x = math.sqrt(i) > > That's 1000000000 dictionary lookups. Importing just the sqrt name > would avoid those lookups, so would: > > import math > f = math.sqrt > for i in range( 0, 1000000000 ): > x = f(i) > > Does that make sense? I guess there is no silver bullet. Thanks for that! It makes total sense now that you mention it. -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070719/454ce78c/attachment.html From kent37 at tds.net Thu Jul 19 22:27:54 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Jul 2007 16:27:54 -0400 Subject: [Tutor] Style question with classes and modules In-Reply-To: References: <469FBB35.4030600@tds.net> Message-ID: <469FC94A.9050204@tds.net> Tino Dai wrote: > Why do you expect a speedup? > > > In the Python Reference by David Beazley on p. 40, he substituted > import math > with from math import sqrt and he switched out d = d + math.sqrt(i) with > sqrt(i). He said that that change made the program run twice as fast. > So therefore > I was under the impression that "from somemodule import someclass" would > always be > faster than import somemodule. Attribute access is somewhat expensive so if you can pull it out of a critical loop you get a speedup. import foo foo.bar() and from foo import bar bar() will not have an appreciable difference in speed. OTOH import foo for i in range(10000): foo.bar() may be slower than from foo import bar for i in range(10000): bar() because the attribute access is essentially being hoisted outside the loop so it only happens once. You can also get a speedup by putting a loop into a function so critical variables are found in the local namespace instead of the module namespace. Attribute lookup seems to have gotten better since Beazley wrote; here is a test program that uses three ways to access math.sqrt - module attribute, global name, local name. Note that in the third version, all three names (sqrt, d, i) are local: ########################### import math from time import time start = time() d = 0.0 for i in xrange(1000000): d = d + math.sqrt(i) duration = time() - start print duration * 1000. sqrt = math.sqrt start = time() d = 0.0 for i in xrange(1000000): d = d + sqrt(i) duration = time() - start print duration * 1000. def compute(): sqrt = math.sqrt d = 0.0 for i in xrange(1000000): d = d + sqrt(i) start = time() compute() duration = time() - start print duration * 1000. ################################ Sample output: 745.465993881 561.167001724 369.343996048 Another way to measure this is with the timeit module: kent $ python -m timeit -s "import math" "math.sqrt(1)" 1000000 loops, best of 3: 0.361 usec per loop kent $ python -m timeit -s "from math import sqrt" "sqrt(1)" 1000000 loops, best of 3: 0.293 usec per loop timeit runs both the setup code and the code under test inside a function so all the names are local in this case. Kent From carroll at tjc.com Thu Jul 19 22:44:57 2007 From: carroll at tjc.com (Terry Carroll) Date: Thu, 19 Jul 2007 13:44:57 -0700 (PDT) Subject: [Tutor] Style question with classes and modules In-Reply-To: <469FC94A.9050204@tds.net> Message-ID: On Thu, 19 Jul 2007, Kent Johnson wrote: > Attribute lookup seems to have gotten better since Beazley wrote; here > is a test program that uses three ways to access math.sqrt - module > attribute, global name, local name. Note that in the third version, all > three names (sqrt, d, i) are local: . . . > Sample output: > 745.465993881 > 561.167001724 > 369.343996048 I'm surprised the difference between the second and third versions is so dramatic. I get a result consistent with that (although you obviously have a much faster CPU than I!). Why is that so much faster? A smaller namespace to look through? Or the search being short-cut by finding in in the local space and therefore not needing to search the global? Something else? From keridee at jayco.net Thu Jul 19 23:53:54 2007 From: keridee at jayco.net (Tiger12506) Date: Thu, 19 Jul 2007 16:53:54 -0500 Subject: [Tutor] reading random line from a file References: <135885.45650.qm@web90405.mail.mud.yahoo.com> <16011.50991.qm@web90401.mail.mud.yahoo.com> <469FB5F0.3090907@gmail.com> Message-ID: <001a01c7ca4f$6ff8ec40$81fde004@JSLAPTOP> > I think the best strategy for this problem would be to build an index of > the offset of the start of each line, and then randomly select from this > list. > that makes each line equally probable, and you can set up your class so > that the index is only built on the first call to the function. > -Luke Oh fudge! I knew there was a "best-way-to-do-it". Now I'm upset cuz i didn't think of it first. ;-) JS From keridee at jayco.net Fri Jul 20 00:05:47 2007 From: keridee at jayco.net (Tiger12506) Date: Thu, 19 Jul 2007 17:05:47 -0500 Subject: [Tutor] about importing a module References: <384c93600707191153m32b42ff1k216a356f7b540210@mail.gmail.com> Message-ID: <006401c7ca51$157b6ac0$81fde004@JSLAPTOP> I'm pretty sure that the one in the current directory gets imported first. However, it is much simpler to just change the name of the module in the current directory. JS > hello there, > > if i have a module that is in the same directory as the file that imports > it, > but that module has the same name as a module in my python path, which one > gets imported ? > > i ask because i want to do some work on the module, but dont want to mess > with my stable > one in site-packages. > so i want to import it from the local directory only. > > thanks > > shawn From keridee at jayco.net Fri Jul 20 00:26:49 2007 From: keridee at jayco.net (Tiger12506) Date: Thu, 19 Jul 2007 17:26:49 -0500 Subject: [Tutor] about importing a module References: <384c93600707191153m32b42ff1k216a356f7b540210@mail.gmail.com> <006401c7ca51$157b6ac0$81fde004@JSLAPTOP> Message-ID: <006e01c7ca53$edcd2790$81fde004@JSLAPTOP> If the module has been imported before your code is run, it will be the library module (very important if working in IDLE which importants many modules, for example). But if it has not been imported before, the module in the current directory is imported first. You can check if a module has been imported previously by checking if in sys.modules. JS From kent37 at tds.net Thu Jul 19 23:51:33 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Jul 2007 17:51:33 -0400 Subject: [Tutor] Style question with classes and modules In-Reply-To: References: Message-ID: <469FDCE5.4050705@tds.net> Terry Carroll wrote: > On Thu, 19 Jul 2007, Kent Johnson wrote: > >> Attribute lookup seems to have gotten better since Beazley wrote; here >> is a test program that uses three ways to access math.sqrt - module >> attribute, global name, local name. Note that in the third version, all >> three names (sqrt, d, i) are local: > . . . >> Sample output: >> 745.465993881 >> 561.167001724 >> 369.343996048 > > I'm surprised the difference between the second and third versions is so > dramatic. I get a result consistent with that (although you obviously > have a much faster CPU than I!). > > Why is that so much faster? A smaller namespace to look through? Or the > search being short-cut by finding in in the local space and therefore not > needing to search the global? Something else? Two reasons, IIUC: - the search is short-cut by finding the name in the local space. - I'm pretty sure that local names are allocated in an *array* on the call stack, not in a dict, so access to local names is very fast - just a fixed offset into an array, no hashing and other overhead of dictionary lookup. This is such a common optimization that Raymond Hettinger (the king of speed :-) wrote a decorator to do it automatically: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 Kent From carroll at tjc.com Fri Jul 20 00:08:21 2007 From: carroll at tjc.com (Terry Carroll) Date: Thu, 19 Jul 2007 15:08:21 -0700 (PDT) Subject: [Tutor] Style question with classes and modules In-Reply-To: <469FDCE5.4050705@tds.net> Message-ID: On Thu, 19 Jul 2007, Kent Johnson wrote: > This is such a common optimization that Raymond Hettinger (the king of > speed :-) wrote a decorator to do it automatically: Some day I'm going to have to figure out decorators. From hunter92383 at gmail.com Fri Jul 20 00:14:50 2007 From: hunter92383 at gmail.com (elis aeris) Date: Fri, 20 Jul 2007 06:14:50 +0800 Subject: [Tutor] python: how do I create a list of definitions? Message-ID: <674d5ce60707191514h14e8f008j4a378d9b4b77d5eb@mail.gmail.com> like, I am doing string substitution: if x = 2243: string = string + "e" if x = 2234: string = string + "p" and so forth. how do I create this: list = [ (2342,p) (4234,e) and so forth, ] so I can use it like this: for a in range(10): If x = list[a][0]: string = string + list[a][1] ? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070720/45630e4e/attachment.html From brunson at brunson.com Fri Jul 20 00:22:17 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 19 Jul 2007 16:22:17 -0600 Subject: [Tutor] python: how do I create a list of definitions? In-Reply-To: <674d5ce60707191514h14e8f008j4a378d9b4b77d5eb@mail.gmail.com> References: <674d5ce60707191514h14e8f008j4a378d9b4b77d5eb@mail.gmail.com> Message-ID: <469FE419.1000806@brunson.com> elis aeris wrote: > like, I am doing string substitution: > > > if x = 2243: > string = string + "e" > if x = 2234: > string = string + "p" If I'm following correctly... How about using a dict: list = { 1: 'a', 2: 'b', 3: 'c', 2342: 'p', 4234: 'e' } if x in list: string += list[x] But I'm not sure what that outer loop is good for in your final example, so I may not understand what you're asking. > > and so forth. > > > how do I create this: > > > list = [ > (2342,p) > (4234,e) > and so forth, > > > ] > > > > so I can use it like this: > > for a in range(10): > If x = list[a][0]: > string = string + list[a][1] > > > ? > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From hunter92383 at gmail.com Fri Jul 20 00:24:37 2007 From: hunter92383 at gmail.com (elis aeris) Date: Fri, 20 Jul 2007 06:24:37 +0800 Subject: [Tutor] python: how do I create a list of definitions? In-Reply-To: <469FE419.1000806@brunson.com> References: <674d5ce60707191514h14e8f008j4a378d9b4b77d5eb@mail.gmail.com> <469FE419.1000806@brunson.com> Message-ID: <674d5ce60707191524p4d98b7c2y221ad2103e2b7d13@mail.gmail.com> oh, just to have some numerals translated into the later. array[n][0] = "this" array[n][1] = "= to this" On 7/20/07, Eric Brunson wrote: > > elis aeris wrote: > > like, I am doing string substitution: > > > > > > if x = 2243: > > string = string + "e" > > if x = 2234: > > string = string + "p" > > If I'm following correctly... > > How about using a dict: > > list = { 1: 'a', 2: 'b', 3: 'c', 2342: 'p', 4234: 'e' } > > if x in list: > string += list[x] > > But I'm not sure what that outer loop is good for in your final example, > so I may not understand what you're asking. > > > > > and so forth. > > > > > > how do I create this: > > > > > > list = [ > > (2342,p) > > (4234,e) > > and so forth, > > > > > > ] > > > > > > > > so I can use it like this: > > > > for a in range(10): > > If x = list[a][0]: > > string = string + list[a][1] > > > > > > ? > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > 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/20070720/94b2b92d/attachment.html From hunter92383 at gmail.com Fri Jul 20 00:24:47 2007 From: hunter92383 at gmail.com (elis aeris) Date: Fri, 20 Jul 2007 06:24:47 +0800 Subject: [Tutor] python: how do I create a list of definitions? In-Reply-To: <469FE419.1000806@brunson.com> References: <674d5ce60707191514h14e8f008j4a378d9b4b77d5eb@mail.gmail.com> <469FE419.1000806@brunson.com> Message-ID: <674d5ce60707191524v6406ebb4w2d69532a4fd6f2fe@mail.gmail.com> I don't understand dict On 7/20/07, Eric Brunson wrote: > > elis aeris wrote: > > like, I am doing string substitution: > > > > > > if x = 2243: > > string = string + "e" > > if x = 2234: > > string = string + "p" > > If I'm following correctly... > > How about using a dict: > > list = { 1: 'a', 2: 'b', 3: 'c', 2342: 'p', 4234: 'e' } > > if x in list: > string += list[x] > > But I'm not sure what that outer loop is good for in your final example, > so I may not understand what you're asking. > > > > > and so forth. > > > > > > how do I create this: > > > > > > list = [ > > (2342,p) > > (4234,e) > > and so forth, > > > > > > ] > > > > > > > > so I can use it like this: > > > > for a in range(10): > > If x = list[a][0]: > > string = string + list[a][1] > > > > > > ? > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > 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/20070720/8054f016/attachment.htm From kent37 at tds.net Fri Jul 20 00:25:13 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Jul 2007 18:25:13 -0400 Subject: [Tutor] Style question with classes and modules In-Reply-To: References: Message-ID: <469FE4C9.5040803@tds.net> Terry Carroll wrote: > On Thu, 19 Jul 2007, Kent Johnson wrote: > >> This is such a common optimization that Raymond Hettinger (the king of >> speed :-) wrote a decorator to do it automatically: > > Some day I'm going to have to figure out decorators. Well, that particular decorator is hairy, but in general they are not that hard. If you understand the idea of a function that takes a function as an argument and returns another function then you can understand decorators. OK, it also helps if you can understand a function whose return value is a function that takes a function as its argument and returns a function :-) Here is my gentle introduction: http://personalpages.tds.net/~kent37/kk/00001.html Kent From doug at foruminfosystems.com Thu Jul 19 23:42:22 2007 From: doug at foruminfosystems.com (Doug Glenn) Date: Thu, 19 Jul 2007 17:42:22 -0400 Subject: [Tutor] Generators Message-ID: Greetings all, Please forgive my instrusion with some simple questions. I don't have any formal training in programming so I have to get some guidance to some terminology from time to time. What is a generator and what is its purpose? I am planning on building a DVD catalog utility for Linux in Python, or at least that is my ultimate goal in starting out. The only one I have found is buggy and does not work on my system. So the only other alternative is to write one myself. Because I plan on releasing it with the source when I get done I would prefer to have it as polished as I can make it :) I look dumb enough on my own thank you! So I may have a quite few questions as I move along regarding databases and connectivity along with a possible way to mount a CDROM or any other media as needed either authenticated or unauthenticated depending on the system settings in the fstable. Obviously if user is not in there then I will have to sudo to root to mount the drive in order to read it. Then we have sorting. It doesn;t make sense to toss this into a database willy nilly if I don't so some sorting on it beforehand by type. I am open to suggestions. So thank you all in advance for your time and your patience! Warm regards, -- Doug Glenn FORUM Information Systems, LLC http://foruminfosystems.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070719/daea07ed/attachment.html From kent37 at tds.net Fri Jul 20 00:31:23 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Jul 2007 18:31:23 -0400 Subject: [Tutor] Generators In-Reply-To: References: Message-ID: <469FE63B.5010503@tds.net> Doug Glenn wrote: > Greetings all, > > Please forgive my instrusion with some simple questions. I don't have > any formal training in programming so I have to get some guidance to > some terminology from time to time. What is a generator and what is its > purpose? If you are that new to programming you probably don't need to understand generators. Why do you ask? Here is a short introduction: http://personalpages.tds.net/~kent37/kk/00004.html Kent From carroll at tjc.com Fri Jul 20 00:32:26 2007 From: carroll at tjc.com (Terry Carroll) Date: Thu, 19 Jul 2007 15:32:26 -0700 (PDT) Subject: [Tutor] Decorators (was: Style question with classes and modules In-Reply-To: <469FE4C9.5040803@tds.net> Message-ID: On Thu, 19 Jul 2007, Kent Johnson wrote: > Here is my gentle introduction: > http://personalpages.tds.net/~kent37/kk/00001.html Thanks. I see the concept, but I think the part that makes it so hard for me to really get is nicely summarized in your tutorial: Good beginner examples of real-world decorators are hard to come by. Decorators tend to be either very simple, in which case they don't add much to the examples above, or significantly more complex and difficult to understand. From keridee at jayco.net Fri Jul 20 02:35:48 2007 From: keridee at jayco.net (Tiger12506) Date: Thu, 19 Jul 2007 19:35:48 -0500 Subject: [Tutor] python: how do I create a list of definitions? References: <674d5ce60707191514h14e8f008j4a378d9b4b77d5eb@mail.gmail.com><469FE419.1000806@brunson.com> <674d5ce60707191524v6406ebb4w2d69532a4fd6f2fe@mail.gmail.com> Message-ID: <005a01c7ca65$f7f6e910$81fde004@JSLAPTOP> > I don't understand dict Think of dict as a dictionary. Literally. You have a word, you look up it's definition in the dictionary. A dictionary is made up of key, value pairs. So for your example: a_dict = {2243 : 'e', 2234 : 'p', 2235 : 'lol', 'how' : 'under'} if x in a_dict: string = string + a_dict[x] JS From brunson at brunson.com Fri Jul 20 01:47:57 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 19 Jul 2007 17:47:57 -0600 Subject: [Tutor] python: how do I create a list of definitions? In-Reply-To: <005a01c7ca65$f7f6e910$81fde004@JSLAPTOP> References: <674d5ce60707191514h14e8f008j4a378d9b4b77d5eb@mail.gmail.com><469FE419.1000806@brunson.com> <674d5ce60707191524v6406ebb4w2d69532a4fd6f2fe@mail.gmail.com> <005a01c7ca65$f7f6e910$81fde004@JSLAPTOP> Message-ID: <469FF82D.2000408@brunson.com> Tiger12506 wrote: >> I don't understand dict >> > > Think of dict as a dictionary. Literally. You have a word, you look up it's > definition in the dictionary. A dictionary is made up of key, value pairs. > So for your example: > > a_dict = {2243 : 'e', > 2234 : 'p', > 2235 : 'lol', > 'how' : 'under'} > > if x in a_dict: > string = string + a_dict[x] > > > How can one get through any tutorial on Python and not come across dicts? In more standard computer parlance a python dictionary is an associative array. From rabidpoobear at gmail.com Fri Jul 20 04:04:42 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 19 Jul 2007 21:04:42 -0500 Subject: [Tutor] python: how do I create a list of definitions? In-Reply-To: <674d5ce60707191514h14e8f008j4a378d9b4b77d5eb@mail.gmail.com> References: <674d5ce60707191514h14e8f008j4a378d9b4b77d5eb@mail.gmail.com> Message-ID: <46A0183A.3090305@gmail.com> elis aeris wrote: > like, I am doing string substitution: > > > if x = 2243: this will always evaluate to true. x is being assigned the value of 2243. 2243 is being returned by the assignment. You can observe this in the following situation: >>> y = x = 2243 >>> y 2243 As you can see, (x = 2243) assigns the variable name to the integer 2243, then assigns y to this integer object as well. so in essence you're saying if 2243: which is the same as saying 'if ' and anything nonzero, which is True. so basically the following line > string = string + "e" is always being executed. > if x = 2234: > string = string + "p" same with this one. > > how do I create this: > list = [ > (2342,p) > (4234,e) > and so forth, > ] > > so I can use it like this: > > for a in range(10): > If x = list[a][0]: If is invalid. Python is case sensitive. 'if' and 'If' are not the same. Also, you're using an assignment instead of a comparison again. > string = string + list[a][1] > > > ? You could probably solve this easily with a dictionary. -Luke From brunson at brunson.com Fri Jul 20 04:14:11 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 19 Jul 2007 20:14:11 -0600 Subject: [Tutor] python: how do I create a list of definitions? In-Reply-To: <46A0183A.3090305@gmail.com> References: <674d5ce60707191514h14e8f008j4a378d9b4b77d5eb@mail.gmail.com> <46A0183A.3090305@gmail.com> Message-ID: <46A01A73.4040601@brunson.com> Luke Paireepinart wrote: > elis aeris wrote: > >> like, I am doing string substitution: >> >> >> if x = 2243: >> > this will always evaluate to true. > Good eye, I missed that completely... However, that will actually throw an exception. >>> if x = 1: File "", line 1 if x = 1: ^ SyntaxError: invalid syntax Guido did it that way just to avoid programming errors like that. Python ain't C (thankfully). > x is being assigned the value of 2243. 2243 is being returned by the > assignment. > You can observe this in the following situation: > >>> y = x = 2243 > >>> y > 2243 > > As you can see, (x = 2243) assigns the variable name to the integer > 2243, then assigns y to this integer object as well. > so in essence you're saying > if 2243: > which is the same as saying 'if ' and anything nonzero, which is True. > so basically the following line > >> string = string + "e" >> > is always being executed. > >> if x = 2234: >> string = string + "p" >> > same with this one. > >> how do I create this: >> list = [ >> (2342,p) >> (4234,e) >> and so forth, >> ] >> >> so I can use it like this: >> >> for a in range(10): >> If x = list[a][0]: >> > If is invalid. Python is case sensitive. 'if' and 'If' are not the same. > Also, you're using an assignment instead of a comparison again. > >> string = string + list[a][1] >> >> >> ? >> > You could probably solve this easily with a dictionary. > -Luke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Fri Jul 20 04:20:17 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Jul 2007 22:20:17 -0400 Subject: [Tutor] python: how do I create a list of definitions? In-Reply-To: <46A0183A.3090305@gmail.com> References: <674d5ce60707191514h14e8f008j4a378d9b4b77d5eb@mail.gmail.com> <46A0183A.3090305@gmail.com> Message-ID: <46A01BE1.8030002@tds.net> Luke Paireepinart wrote: >> if x = 2243: > this will always evaluate to true. No, it is a syntax error. > x is being assigned the value of 2243. 2243 is being returned by the > assignment. No, assignment is a statement, not an expression; that's why it is a syntax error. > You can observe this in the following situation: > >>> y = x = 2243 > >>> y > 2243 I think this is a special case of assignment. Try y = (x = 2243) and you will see that (x = 2243) is not an expression. Kent From rabidpoobear at gmail.com Fri Jul 20 04:26:04 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 19 Jul 2007 21:26:04 -0500 Subject: [Tutor] python: how do I create a list of definitions? In-Reply-To: <46A01BE1.8030002@tds.net> References: <674d5ce60707191514h14e8f008j4a378d9b4b77d5eb@mail.gmail.com> <46A0183A.3090305@gmail.com> <46A01BE1.8030002@tds.net> Message-ID: <46A01D3C.5090502@gmail.com> > >> You can observe this in the following situation: >> >>> y = x = 2243 >> >>> y >> 2243 >> > > I think this is a special case of assignment. Try > y = (x = 2243) > and you will see that (x = 2243) is not an expression. > Oh. Thanks for pointing that out. I wondered why I couldn't "print x = 2243" but I could chain together assignments. > Kent From nephish at gmail.com Fri Jul 20 05:06:04 2007 From: nephish at gmail.com (shawn bright) Date: Thu, 19 Jul 2007 22:06:04 -0500 Subject: [Tutor] about importing a module In-Reply-To: <006e01c7ca53$edcd2790$81fde004@JSLAPTOP> References: <384c93600707191153m32b42ff1k216a356f7b540210@mail.gmail.com> <006401c7ca51$157b6ac0$81fde004@JSLAPTOP> <006e01c7ca53$edcd2790$81fde004@JSLAPTOP> Message-ID: <384c93600707192006o6c68d4dfmfa36d684317c0b49@mail.gmail.com> change the name of the module, simple. thanks shawn On 7/19/07, Tiger12506 wrote: > > If the module has been imported before your code is run, it will be the > library module (very important if working in IDLE which importants many > modules, for example). But if it has not been imported before, the module > in > the current directory is imported first. You can check if a module has > been > imported previously by checking if in sys.modules. > > JS > > _______________________________________________ > 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/20070719/62426ab7/attachment.html From hunter92383 at gmail.com Fri Jul 20 08:36:15 2007 From: hunter92383 at gmail.com (elis aeris) Date: Fri, 20 Jul 2007 14:36:15 +0800 Subject: [Tutor] odd bug Message-ID: <674d5ce60707192336u64767bbbnc5e96d5b8e7c678d@mail.gmail.com> I ran the code attached at the end of the email, it' supposed to out put a string of characters, yet I got only this ####### 2.4.3.3.8.5. definition check: 3 ####### now, it's proper output, however, this part got run only once, when it's supposed to run multiple times to produce more portions like the one above, i don't know why this part got run only once: when that happens if box_v == 0: zero_count = zero_count + 1 if zero_count == 2: zero_count = 0 if one_char_box in loc_window_loc_definition: print one_char_box box_string = box_string + str(loc_window_loc_definition [one_char_box]) print "definition check:" print box_string ###################### for b in range(1,50,1): ## Next point to check x = radar_loc_window_xx + b y = radar_loc_window_yy ## omit 0 when there are 2 zeros, and check def when that happens if box_v == 0: zero_count = zero_count + 1 if zero_count == 2: zero_count = 0 if one_char_box in loc_window_loc_definition: print one_char_box box_string = box_string + str(loc_window_loc_definition[one_char_box]) print "definition check:" print box_string else: one_char_box = one_char_box + str(box_v) + "." box_v = 0 for a in range(0,10,1): r, g, b = pixels[1030*(y-a) + x] if g > r and g > b: box_v = box_v + 1 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070720/176bb26d/attachment.html From dcreno9000 at yahoo.com Fri Jul 20 08:04:38 2007 From: dcreno9000 at yahoo.com (Deby Campbell) Date: Thu, 19 Jul 2007 23:04:38 -0700 (PDT) Subject: [Tutor] scrips Message-ID: <518104.72088.qm@web35204.mail.mud.yahoo.com> Hi , I?ve been using the IDLE python but when I try to make scrips with a word editor, but when I try to use them in the commend prompt it says there is no such file or directory except when I use the first one I made. So I thought I would just use the one that worked but for some reason it still brings up the answer for the old one. If you know how to fix this I would be very grateful. thanks ____________________________________________________________________________________ Be a better Heartthrob. Get better relationship answers from someone who knows. Yahoo! Answers - Check it out. http://answers.yahoo.com/dir/?link=list&sid=396545433 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070719/53964a62/attachment.html From a_n_lal at yahoo.com Fri Jul 20 07:50:31 2007 From: a_n_lal at yahoo.com (Aditya Lal) Date: Thu, 19 Jul 2007 22:50:31 -0700 (PDT) Subject: [Tutor] reading random line from a file In-Reply-To: <469FB5F0.3090907@gmail.com> Message-ID: <769390.54156.qm@web90409.mail.mud.yahoo.com> A bug: The function random.randint(a,b) include both ends i.e. b is also included. Thus for file with single line a=0,b=1 my algo will give an IndexError. Significance of number 4096 : file is stored in blocks of size 2K/4K/8K (depending upon the machine). file seek for an offset goes block by block rather than byte by byte. Hence for file size < 4096 (assuming you have 4K block size), you will anyway end up scanning it entirely so as well load it up in memory. Luke suggestion for Index: I think its an implicit need to give equal probability to each line. Taking an example - suppose we are trying to find "quote of the day" from a dictionary of quotations which may contain 100s of thousands of quotes. We would like to see a new one each time on invocation rather than favour the longest one. So, creating an index is the right solution. But I just want to add that since index creation is quite a laborious task (in terms of CPU/time) one should do it only once (or till file is changed). Thus it should be kept on disk and ensure that index is re-created in case file changes. I would like suggestions on index creation. --- Luke Paireepinart wrote: > bhaaluu wrote: > > Greetings, > > Thanks for including the complete source code! > > It really helps to have something that works to > look at. > > I modified an earlier version of this to run on my > > computer (GNU/Linux; Python 2.4.3). > > > I think the best strategy for this problem would be > to build an index of > the offset of the start of each line, and then > randomly select from this > list. > that makes each line equally probable, and you can > set up your class so > that the index is only built on the first call to > the function. > -Luke > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ____________________________________________________________________________________ Choose the right car based on your needs. Check out Yahoo! Autos new Car Finder tool. http://autos.yahoo.com/carfinder/ From christopher.henk at gm.com Fri Jul 20 15:37:53 2007 From: christopher.henk at gm.com (christopher.henk at gm.com) Date: Fri, 20 Jul 2007 09:37:53 -0400 Subject: [Tutor] odd bug In-Reply-To: <674d5ce60707192336u64767bbbnc5e96d5b8e7c678d@mail.gmail.com> Message-ID: try adding: print "current block:", one_char_box print "zeros: ", zero_count to the lines just below your if statement that you think is called only once. This way you know how many times its called and you might be able to find the error. Chris Henk Allison Transmission phone: 317.242.2569 fax: 317.242.3469 e-mail: christopher.henk at gm.com "elis aeris" Sent by: tutor-bounces at python.org 07/20/2007 02:36 AM To "Luke Paireepinart" cc python tutor Subject [Tutor] odd bug I ran the code attached at the end of the email, it' supposed to out put a string of characters, yet I got only this ####### 2.4.3.3.8.5. definition check: 3 ####### now, it's proper output, however, this part got run only once, when it's supposed to run multiple times to produce more portions like the one above, i don't know why this part got run only once: when that happens if box_v == 0: zero_count = zero_count + 1 if zero_count == 2: zero_count = 0 if one_char_box in loc_window_loc_definition: print one_char_box box_string = box_string + str(loc_window_loc_definition [one_char_box]) print "definition check:" print box_string ###################### for b in range(1,50,1): ## Next point to check x = radar_loc_window_xx + b y = radar_loc_window_yy ## omit 0 when there are 2 zeros, and check def when that happens if box_v == 0: zero_count = zero_count + 1 if zero_count == 2: zero_count = 0 if one_char_box in loc_window_loc_definition: print one_char_box box_string = box_string + str(loc_window_loc_definition [one_char_box]) print "definition check:" print box_string else: one_char_box = one_char_box + str(box_v) + "." box_v = 0 for a in range(0,10,1): r, g, b = pixels[1030*(y-a) + x] if g > r and g > b: box_v = box_v + 1 _______________________________________________ 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/20070720/c1f820ba/attachment.htm From dkuhlman at rexx.com Fri Jul 20 17:46:10 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 20 Jul 2007 08:46:10 -0700 Subject: [Tutor] scrips In-Reply-To: <518104.72088.qm@web35204.mail.mud.yahoo.com> References: <518104.72088.qm@web35204.mail.mud.yahoo.com> Message-ID: <20070720154610.GA39137@cutter.rexx.com> On Thu, Jul 19, 2007 at 11:04:38PM -0700, Deby Campbell wrote: > > > Hi , I?ve been using the IDLE python but when I try to make > scrips with a word editor, but when I try to use them in the commend prompt it > says there is no such file or directory except when I use the first one I made. > So I thought I would just use the one that worked but for some reason it still > brings up the answer for the old one. > Here are a few comments and questions that may help you work through your problem: 1. You mention using a "word editor". You should be using a (plain) text editor. Do *not* use a word processor. You can find a list of text editors suggested for editing Python scripts here: http://wiki.python.org/moin/PythonEditors 2. At the command line, when you type "dir" (without quotes), what do you see? Is your script listed? If not, you will need to find your script. 3. If your script is not in the current directory, either (1) change to the directory containing the script with the "cd" command or (2) use the full path to the script, as in: python c:\some\path\to\myscript.py Hope this helps. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From nephish at gmail.com Fri Jul 20 17:52:29 2007 From: nephish at gmail.com (shawn bright) Date: Fri, 20 Jul 2007 10:52:29 -0500 Subject: [Tutor] question about datetime object Message-ID: <384c93600707200852q72327f8bp1af8ae6f0645901e@mail.gmail.com> Hello there, if i have a python datetime object, what is the easiest way to make it into epoch seconds ? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070720/4b435dc8/attachment.html From kent37 at tds.net Fri Jul 20 18:00:58 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 Jul 2007 12:00:58 -0400 Subject: [Tutor] question about datetime object In-Reply-To: <384c93600707200852q72327f8bp1af8ae6f0645901e@mail.gmail.com> References: <384c93600707200852q72327f8bp1af8ae6f0645901e@mail.gmail.com> Message-ID: <46A0DC3A.8030900@tds.net> shawn bright wrote: > Hello there, > > if i have a python datetime object, what is the easiest way to make it > into epoch seconds ? impIn [1]: import datetime In [2]: now = datetime.datetime.now() In [4]: now.timetuple() Out[4]: (2007, 7, 20, 11, 56, 58, 4, 201, -1) In [5]: import calendar In [6]: calendar.timegm(now.timetuple()) Out[6]: 1184932618 Kent From nephish at gmail.com Fri Jul 20 18:08:00 2007 From: nephish at gmail.com (shawn bright) Date: Fri, 20 Jul 2007 11:08:00 -0500 Subject: [Tutor] another question ( unrelated ) Message-ID: <384c93600707200908i1ca53093y7457fa310203ea43@mail.gmail.com> If i have a thread, of type threading.Thread that i initiate with an __init__ in the def run(self): while 1: do some stuff is there a way i can stop this thread and restart this thread from within itself ? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070720/bd369766/attachment.htm From rabidpoobear at gmail.com Fri Jul 20 18:18:50 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 20 Jul 2007 11:18:50 -0500 Subject: [Tutor] another question ( unrelated ) In-Reply-To: <384c93600707200908i1ca53093y7457fa310203ea43@mail.gmail.com> References: <384c93600707200908i1ca53093y7457fa310203ea43@mail.gmail.com> Message-ID: <46A0E06A.40706@gmail.com> shawn bright wrote: > If i have a thread, of type threading.Thread > that i initiate with an __init__ > in the > def run(self): > while 1: > do some stuff > > > is there a way i can stop this thread and restart this thread from > within itself ? Speaking from a purely theoretical standpoint (in other words I don't know the answer to your question) a thread can be thought of as a separate execution path. If it's going along and executing stuff, and it reaches a point where it needs to terminate itself, that means it is no longer executing, therefore it can't possibly restart itself. Metaphor: If a wizard can cast Revive to bring people back to life, but he's dead, he can't revive himself because he can't cast spells anymore. However, I think you could have it just do a sleep of some sort so that the CPU is delegated (relegated?) to the other threads mostly, until the sleep is up. Or, if you didn't want a constant amount of time to be given up to the other threads, you'd have to communicate to the halted thread when it should resume. Those are my thoughts on this, but as I said, I'm not sure and I could be wrong. Why do you need to do this? -Luke From kent37 at tds.net Fri Jul 20 18:21:40 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 Jul 2007 12:21:40 -0400 Subject: [Tutor] another question ( unrelated ) In-Reply-To: <384c93600707200908i1ca53093y7457fa310203ea43@mail.gmail.com> References: <384c93600707200908i1ca53093y7457fa310203ea43@mail.gmail.com> Message-ID: <46A0E114.70402@tds.net> shawn bright wrote: > If i have a thread, of type threading.Thread > that i initiate with an __init__ > in the > def run(self): > while 1: > do some stuff > > > is there a way i can stop this thread and restart this thread from > within itself ? No. A thread stops by exiting the run method, then it is done. And how would a stopped thread restart itself? What you can do, is write your run() method to do whatever you want; in particular it could sense some condition and re-initialize itself. If you are using a Thread subclass and overriding run() (as opposed to passing the run method to the constructor) you can use the subclass to hold any state you need and you can write/call any other methods you need. Kent From nephish at gmail.com Fri Jul 20 18:32:12 2007 From: nephish at gmail.com (shawn bright) Date: Fri, 20 Jul 2007 11:32:12 -0500 Subject: [Tutor] another question ( unrelated ) In-Reply-To: <46A0E114.70402@tds.net> References: <384c93600707200908i1ca53093y7457fa310203ea43@mail.gmail.com> <46A0E114.70402@tds.net> Message-ID: <384c93600707200932l6bea15c4y32d02f8de8339566@mail.gmail.com> ok, how would i have it re-initialize itself ? yes, i want to do this on a failure condition. something wrapped in a try - except its long and complicated dealing with talking to a dataserver over ip and passing byte streams back and forth. i just need to do this for testing to see where something is failing and how soon i could re-connect to the data server. whew ! thanks shawn On 7/20/07, Kent Johnson wrote: > > shawn bright wrote: > > If i have a thread, of type threading.Thread > > that i initiate with an __init__ > > in the > > def run(self): > > while 1: > > do some stuff > > > > > > is there a way i can stop this thread and restart this thread from > > within itself ? > > No. A thread stops by exiting the run method, then it is done. And how > would a stopped thread restart itself? > > What you can do, is write your run() method to do whatever you want; in > particular it could sense some condition and re-initialize itself. > > If you are using a Thread subclass and overriding run() (as opposed to > passing the run method to the constructor) you can use the subclass to > hold any state you need and you can write/call any other methods you need. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070720/1b81f42c/attachment.html From kent37 at tds.net Fri Jul 20 19:08:21 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 Jul 2007 13:08:21 -0400 Subject: [Tutor] another question ( unrelated ) In-Reply-To: <384c93600707200932l6bea15c4y32d02f8de8339566@mail.gmail.com> References: <384c93600707200908i1ca53093y7457fa310203ea43@mail.gmail.com> <46A0E114.70402@tds.net> <384c93600707200932l6bea15c4y32d02f8de8339566@mail.gmail.com> Message-ID: <46A0EC05.8030500@tds.net> shawn bright wrote: > ok, how would i have it re-initialize itself ? > > yes, i want to do this on a failure condition. > something wrapped in a try - except Nothing magic, it's just code. Something like this: def run(self): while 1: # (re)initialization code goes here while 1: try: # do some real work here, repeatedly except: # oops. any error recovery goes here break # break out of the inner loop to repeat the init code # and restart the inner loop Kent From bgailer at alum.rpi.edu Fri Jul 20 21:03:42 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 20 Jul 2007 12:03:42 -0700 Subject: [Tutor] another question ( unrelated ) In-Reply-To: <384c93600707200908i1ca53093y7457fa310203ea43@mail.gmail.com> References: <384c93600707200908i1ca53093y7457fa310203ea43@mail.gmail.com> Message-ID: <46A1070E.2030509@alum.rpi.edu> shawn bright wrote: > If i have a thread, of type threading.Thread > that i initiate with an __init__ > in the > def run(self): > while 1: > do some stuff > > > is there a way i can stop this thread and restart this thread from > within itself ? A thread may suspend itself using one of the lock or event objects in the Threading module. It does take an external activity to end the suspension. Let's step back and ask what you want to accomplish by stopping and restarting. Perhaps there is another way to do it. -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From dcreno9000 at yahoo.com Fri Jul 20 22:14:25 2007 From: dcreno9000 at yahoo.com (Deby Campbell) Date: Fri, 20 Jul 2007 13:14:25 -0700 (PDT) Subject: [Tutor] scrips again Message-ID: <942829.55886.qm@web35211.mail.mud.yahoo.com> Hi , I've been using the IDLE python but when I try to make scrips with a word editor, but when I try to use them in the commend prompt it says there is no such file or directory except when I use the first one I made. So I thought I would just use the one that worked but for some reason it still brings up the answer for the old one. ps. I have been saving them as .py , and ive been using notepad. If you know how to fix this I would be very grateful. thanks ____________________________________________________________________________________ Park yourself in front of a world of choices in alternative vehicles. Visit the Yahoo! Auto Green Center. http://autos.yahoo.com/green_center/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070720/4125b296/attachment.htm From rabidpoobear at gmail.com Fri Jul 20 22:20:24 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 20 Jul 2007 15:20:24 -0500 Subject: [Tutor] scrips again In-Reply-To: <942829.55886.qm@web35211.mail.mud.yahoo.com> References: <942829.55886.qm@web35211.mail.mud.yahoo.com> Message-ID: <46A11908.4060304@gmail.com> Deby Campbell wrote: > > Hi , I've been using the IDLE python but when I try to make scrips with a > > word editor, but when I try to use them in the commend prompt it says > there > is no such file or directory except when I use the first one I made. So I > thought I would just use the one that worked but for some reason it still > brings up the answer for the old one. > ps. I have been saving them as .py , and ive been using notepad. > > > > If you know how to fix this I would be very grateful. > I am unclear on what your question is, therefore I cannot give you direction on fixing this. Try to answer some of these questions and I'll see if I can figure out what's wrong. What do you mean by the 'first one you made' works but the 'second one' doesn't? which is the first and which is the second? are you creating both of them in the same way? By 'command prompt' do you mean 'IDLE interactive interpreter' or do you mean the DOS prompt? 'the one that worked' is 'the first one', right? how can the first one bring up the answer for the old one? If you go to the directory where you saved the new file, is its icon a snake or a text document? -Luke From mc_anjo at tamu.edu Fri Jul 20 23:30:21 2007 From: mc_anjo at tamu.edu (Chris Smith) Date: Fri, 20 Jul 2007 16:30:21 -0500 Subject: [Tutor] Running program from Python Message-ID: Howdy, I am working on some research. I'm trying to optimize the performance of an antenna. For the simulation of the antenna it would be easiest to use an antenna software package that I have in my lab. I know that Matlab can call the antenna software through a command called system. Matlab also uses system to pass a VB script file to the antenna software that tells the software what to do. However, I don't have access to Matlab in my lab. I use Python for a lot of program prototyping, and was looking through a Python reference book to see if there was something in there I could use. I ran across two functions that I thought might work. They are in the os module and are the different exec functions and also the spawnv function. The python program would run something like this: 1) optimization program comes up with initial variables to try 2) a VB script is generated 3) antenna program called and given the VB script 4) antenna program evaluates the antenna 5) results are sent back to optimization program 6) optimization program evaluates results and generates new variables 7) process from 2 on is repeated Would either of these two functions be what I need? Thanks for your help. Chris S. From mc_anjo at tamu.edu Fri Jul 20 23:31:15 2007 From: mc_anjo at tamu.edu (Chris Smith) Date: Fri, 20 Jul 2007 16:31:15 -0500 Subject: [Tutor] Running another program from Python Message-ID: Howdy, I am working on some research. I'm trying to optimize the performance of an antenna. For the simulation of the antenna it would be easiest to use an antenna software package that I have in my lab. I know that Matlab can call the antenna software through a command called system. Matlab also uses system to pass a VB script file to the antenna software that tells the software what to do. However, I don't have access to Matlab in my lab. I use Python for a lot of program prototyping, and was looking through a Python reference book to see if there was something in there I could use. I ran across two functions that I thought might work. They are in the os module and are the different exec functions and also the spawnv function. The python program would run something like this: 1) optimization program comes up with initial variables to try 2) a VB script is generated 3) antenna program called and given the VB script 4) antenna program evaluates the antenna 5) results are sent back to optimization program 6) optimization program evaluates results and generates new variables 7) process from 2 on is repeated Would either of these two functions be what I need? Thanks for your help. Chris S. From tinoloc at gmail.com Fri Jul 20 23:36:38 2007 From: tinoloc at gmail.com (Tino Dai) Date: Fri, 20 Jul 2007 17:36:38 -0400 Subject: [Tutor] Running program from Python In-Reply-To: References: Message-ID: On 7/20/07, Chris Smith wrote: > > Howdy, > > I am working on some research. I'm trying to optimize the performance of > an antenna. For the simulation of the antenna it would be easiest to use > an antenna software package that I have in my lab. I know that Matlab > can call the antenna software through a command called system. Matlab > also uses system to pass a VB script file to the antenna software that > tells the software what to do. However, I don't have access to Matlab in > my lab. > > I use Python for a lot of program prototyping, and was looking through a > Python reference book to see if there was something in there I could > use. I ran across two functions that I thought might work. They are in > the os module and are the different exec functions and also the spawnv > function. > > The python program would run something like this: > 1) optimization program comes up with initial variables to try > 2) a VB script is generated > 3) antenna program called and given the VB script > 4) antenna program evaluates the antenna > 5) results are sent back to optimization program > 6) optimization program evaluates results and generates new variables > 7) process from 2 on is repeated > > Would either of these two functions be what I need? > > Thanks for your help. > > Chris S. =You might also want to try: http://docs.python.org/lib/ipc.html to see if that is what you need -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070720/59af4824/attachment.html From carroll at tjc.com Sat Jul 21 03:46:13 2007 From: carroll at tjc.com (Terry Carroll) Date: Fri, 20 Jul 2007 18:46:13 -0700 (PDT) Subject: [Tutor] How to determine if every character in one string is in another string? Message-ID: Is there a straightforward way to find out if all characters in one string are present in a second string? Basically, I have a string s, and I want to print it out only if every character in it is printable (because I accidentally brought my PC loudly to its knees printing a few thousand BEL characters when trying to debug something). A workable test for me is whether every character in the string to be printed is in string.printable. Right now I'm doing: def printable(s): import string return [x for x in s if x not in string.printable] == [] But that just seems lame. From clsdaniel at gmail.com Sat Jul 21 04:08:18 2007 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Fri, 20 Jul 2007 19:08:18 -0700 Subject: [Tutor] Running another program from Python In-Reply-To: References: Message-ID: <4fae7dfa0707201908j32de51e3o3464a2b1cfc67d8d@mail.gmail.com> There is also os.system which should work in a similar way as Matlab system. You pass a string with the command and arguments. The downside of system is that it opens an entire shell and environment for the program being run, you only have the return value from the application. Other options can be popen if you want to feed to process with some information or get some information from it (if everything is done through standard input and output), but in your case you are better of with exec or system. Exec functions will replace your current process with the application you want to run, this may not be what you want. Spawn will create a subprocess, you can wait for it to finish or let it run free knowing its process id to check it latter, it is roughly similar to fork. Good luck! Regards, Carlos Daniel Ruvalcaba On 7/20/07, Chris Smith wrote: > Howdy, > > I am working on some research. I'm trying to optimize the performance of > an antenna. For the simulation of the antenna it would be easiest to use > an antenna software package that I have in my lab. I know that Matlab > can call the antenna software through a command called system. Matlab > also uses system to pass a VB script file to the antenna software that > tells the software what to do. However, I don't have access to Matlab in > my lab. > > I use Python for a lot of program prototyping, and was looking through a > Python reference book to see if there was something in there I could > use. I ran across two functions that I thought might work. They are in > the os module and are the different exec functions and also the spawnv > function. > > The python program would run something like this: > 1) optimization program comes up with initial variables to try > 2) a VB script is generated > 3) antenna program called and given the VB script > 4) antenna program evaluates the antenna > 5) results are sent back to optimization program > 6) optimization program evaluates results and generates new variables > 7) process from 2 on is repeated > > Would either of these two functions be what I need? > > Thanks for your help. > > Chris S. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rabidpoobear at gmail.com Sat Jul 21 04:21:17 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 20 Jul 2007 21:21:17 -0500 Subject: [Tutor] How to determine if every character in one string is in another string? In-Reply-To: References: Message-ID: <46A16D9D.1010207@gmail.com> Terry Carroll wrote: > Is there a straightforward way to find out if all characters in one string > are present in a second string? > > Basically, I have a string s, and I want to print it out only if every > character in it is printable (because I accidentally brought my PC loudly > to its knees printing a few thousand BEL characters when trying to debug > something). A workable test for me is whether every character in the > string to be printed is in string.printable. > > Right now I'm doing: > > def printable(s): > import string > return [x for x in s if x not in string.printable] == [] > Well, my first thought was (assuming s is your string:) def printable(s): import string return s.strip(string.printable) == "" > But that just seems lame. > This seems kinda like an abuse of strip, but it should work (since your condition was that all characters must be printable; a different condition may not be satisfied by the strip because it only removes characters from the ends.) Let me know if this works :) -Luke From dkuhlman at rexx.com Sat Jul 21 05:03:42 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 20 Jul 2007 20:03:42 -0700 Subject: [Tutor] How to determine if every character in one string is in another string? In-Reply-To: References: Message-ID: <20070721030342.GB69676@cutter.rexx.com> On Fri, Jul 20, 2007 at 06:46:13PM -0700, Terry Carroll wrote: > Is there a straightforward way to find out if all characters in one string > are present in a second string? > > Basically, I have a string s, and I want to print it out only if every > character in it is printable (because I accidentally brought my PC loudly > to its knees printing a few thousand BEL characters when trying to debug > something). A workable test for me is whether every character in the > string to be printed is in string.printable. > > Right now I'm doing: > > def printable(s): > import string > return [x for x in s if x not in string.printable] == [] > Try thinking about a regular expression. Something along the lines of: pattern = r'[^%s]' % string.printable re_pattern = re.compile(pattern) match_obj = re_pattern.search(s) if match_obj: o o o Notice the carrot (^) just inside the square bracket. That reverses the pattern to all not in string.printable. You will have to work with this. I have not tested it. For more on regular expressions, see: http://docs.python.org/lib/re-syntax.html http://docs.python.org/lib/node46.html Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From tpc247 at gmail.com Sat Jul 21 05:33:37 2007 From: tpc247 at gmail.com (tpc247 at gmail.com) Date: Fri, 20 Jul 2007 20:33:37 -0700 Subject: [Tutor] don't repeat yourself; question about code optimization Message-ID: dear fellow Python enthusiasts: in the last year I have been experimenting with Python, and I set out to create a function that, given a number of items and a maximum number of items per row, would generate a table of rows of items. However, there is one part where I believe I violate the prime directive of coding, which is not to repeat yourself: class Table_Creator(object): def __init__(self, given_num_of_items, max_num_of_items_per_row): self.total_num_of_items = range(given_num_of_items) self.max_num_of_items_per_row = max_num_of_items_per_row def create_grid(self): table = [] row = [] count = 0 while self.total_num_of_items: row.append(self.total_num_of_items.pop(0)) count += 1 if (not self.total_num_of_items) or (count == self.max_num_of_items_per_row): table.append(tuple(row)) row = [] count = 0 return table as you can see, I repeat the expressions "row = []" and "count = 0", and I would like to know if there is something I can do to avoid repetition in this case. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070720/0cc35666/attachment.htm From bgailer at alum.rpi.edu Sat Jul 21 05:48:22 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 20 Jul 2007 20:48:22 -0700 Subject: [Tutor] How to determine if every character in one string is in another string? In-Reply-To: <46A16D9D.1010207@gmail.com> References: <46A16D9D.1010207@gmail.com> Message-ID: <46A18206.7010209@alum.rpi.edu> Luke Paireepinart wrote: > Terry Carroll wrote: > >> Is there a straightforward way to find out if all characters in one string >> are present in a second string? >> >> Basically, I have a string s, and I want to print it out only if every >> character in it is printable (because I accidentally brought my PC loudly >> to its knees printing a few thousand BEL characters when trying to debug >> something). A workable test for me is whether every character in the >> string to be printed is in string.printable. >> >> Right now I'm doing: >> >> def printable(s): >> import string >> return [x for x in s if x not in string.printable] == [] >> >> If you are only concerned about the first 32 ascii characters (non-printable) then this might be more efficient (since it compares each character to ' ' and stops at the first non-printable): import itertools testString = 'aso;dkfj hado;fg ja;lsfj asl;fj jf asdl; fj\g' candidate = [x for x in itertools.takewhile(lambda x : x >= ' ', s)] if len(candidate) == len(testString): print testString -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From bgailer at alum.rpi.edu Sat Jul 21 05:53:24 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 20 Jul 2007 20:53:24 -0700 Subject: [Tutor] don't repeat yourself; question about code optimization In-Reply-To: References: Message-ID: <46A18334.1040506@alum.rpi.edu> tpc247 at gmail.com wrote: > dear fellow Python enthusiasts: > > in the last year I have been experimenting with Python, and I set out > to create a function that, given a number of items and a maximum > number of items per row, would generate a table of rows of items. > However, there is one part where I believe I violate the prime > directive of coding, which is not to repeat yourself: > > class Table_Creator(object): > def __init__(self, given_num_of_items, max_num_of_items_per_row): > self.total_num_of_items = range(given_num_of_items) > self.max_num_of_items_per_row = max_num_of_items_per_row > > def create_grid(self): > table = [] > row = [] > count = 0 > while self.total_num_of_items: > row.append(self.total_num_of_items.pop(0)) > count += 1 > if (not self.total_num_of_items) or (count == > self.max_num_of_items_per_row): > table.append(tuple(row)) > row = [] > count = 0 > return table > > as you can see, I repeat the expressions "row = []" and "count = 0", > and I would like to know if there is something I can do to avoid > repetition in this case. First fix the indentation of the line starting with "if". -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From doug at foruminfosystems.com Sat Jul 21 03:28:51 2007 From: doug at foruminfosystems.com (Doug Glenn) Date: Fri, 20 Jul 2007 21:28:51 -0400 Subject: [Tutor] Python program design Message-ID: I have a question on program design. The program will be a catalog of portable media (DVD, CD, flash drive, floppy, etc). I am currently in the preliminary stages of design and I currently would like to get input on what the best method would be for initially gathering the data and what format it should take. I plan on using the os.walk function to iterate a scan through the media. This returns a set of three variables in a list that will change each iteration until the scan completes. I don't know anything at all about database design or the most efficient method of gathering the data and then inputing it into the database. In order to optimize this part of the design I wanted to get some input from the masters. It is better to get it right the first time then go back and fix it later. Since os.walk will generate a unique set of data each interation through the directory structure I must append the data from each pass into a 'master' array or list. In order to identify the media later I will have to get the disk label and the disk ID as the primary identifiers for the compiled data. Each iteration of the directories on the media I will create a list like this : root = current directory being scanned - contains single directory dirs = subdirectories under the current root - contains names of all directories files = filenames - contains all the files in the current working directory. I need to generate the following additional information on each file during each interation. size = size of file type = file extension My initial test example is something like this: import os from os.path import join, getsize for root, dirs, files in os.walk(device): # device name from config file Then I would need to get the file size (but this is giving me an error at the moment) for name in files: s = sum(getsize(join(root, name) print s (syntax error here. I have not figured it out yet. There are spaces in the path/filename combo) (code to parse the file extension here) Back to the data though, should I create something like these while reading the media and prior to inserting it into the database? [disk label, disk id [root[dir[file,size,type, permissions]]]] in a dictionary or tuple? or use a list? or flat in a dictionary, tuple or list like [disk label, disk id, root,dir,filename,size,type,permissions] When it has completed the scan I want to insert it into the database with the following fields disk label, disk id, root directory, path, filename, file size, file type, original file permissions, and comment field. (Does anyone thing I should have any other fields? Suggestions welcome) Thank you in advance. If this is off topic, please reply off the list and let me know. -- Doug Glenn FORUM Information Systems, LLC http://foruminfosystems.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070720/9e984c30/attachment.html From bgailer at alum.rpi.edu Sat Jul 21 06:00:24 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 20 Jul 2007 21:00:24 -0700 Subject: [Tutor] don't repeat yourself; question about code optimization In-Reply-To: References: Message-ID: <46A184D8.7040908@alum.rpi.edu> tpc247 at gmail.com wrote: > dear fellow Python enthusiasts: > > in the last year I have been experimenting with Python, and I set out > to create a function that, given a number of items and a maximum > number of items per row, would generate a table of rows of items. > However, there is one part where I believe I violate the prime > directive of coding, which is not to repeat yourself: > > class Table_Creator(object): > def __init__(self, given_num_of_items, max_num_of_items_per_row): > self.total_num_of_items = range(given_num_of_items) > self.max_num_of_items_per_row = max_num_of_items_per_row > > def create_grid(self): > table = [] > row = [] > count = 0 > while self.total_num_of_items: > row.append(self.total_num_of_items.pop(0)) > count += 1 > if (not self.total_num_of_items) or (count == > self.max_num_of_items_per_row): > table.append(tuple(row)) > row = [] > count = 0 > return table > > as you can see, I repeat the expressions "row = []" and "count = 0", > and I would like to know if there is something I can do to avoid > repetition in this case. Take advantage of slicing: def create_grid(self): table = [] for i in range(0, len(self.total_num_of_items), self.max_num_of_items_per_row): table.append(tuple(self.total_num_of_items[i : i + self.max_num_of_items_per_row])) return table -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From kent37 at tds.net Sat Jul 21 06:04:58 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 21 Jul 2007 00:04:58 -0400 Subject: [Tutor] How to determine if every character in one string is in another string? In-Reply-To: References: Message-ID: <46A185EA.4030008@tds.net> Terry Carroll wrote: > Is there a straightforward way to find out if all characters in one string > are present in a second string? > > Basically, I have a string s, and I want to print it out only if every > character in it is printable (because I accidentally brought my PC loudly > to its knees printing a few thousand BEL characters when trying to debug > something). A workable test for me is whether every character in the > string to be printed is in string.printable. > > Right now I'm doing: > > def printable(s): > import string > return [x for x in s if x not in string.printable] == [] My first thought is to use sets (not tested): _printable = set(string.printable) def printable(s): return set(s).issubset(printable) Using string.translate() might be very fast. Something like all_chars = ''.join(chr(i) for i in range(255)) def printable(s): return not s.translate(all_chars, string.printable) Kent From malaclypse2 at gmail.com Sat Jul 21 06:05:13 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Sat, 21 Jul 2007 00:05:13 -0400 Subject: [Tutor] How to determine if every character in one string is in another string? In-Reply-To: References: Message-ID: <16651e80707202105v5b50640bifd9e2fa31e18b05f@mail.gmail.com> On 7/20/07, Terry Carroll wrote: > Is there a straightforward way to find out if all characters in one string > are present in a second string? I like this one: all(char in string.printable for char in testString) >>> testString = "qwerty\buiop" >>> all(char in string.printable for char in testString) False -- Jerry From bgailer at alum.rpi.edu Sat Jul 21 06:09:49 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 20 Jul 2007 21:09:49 -0700 Subject: [Tutor] don't repeat yourself; question about code optimization In-Reply-To: References: Message-ID: <46A1870D.2030000@alum.rpi.edu> tpc247 at gmail.com wrote: > dear fellow Python enthusiasts: > > in the last year I have been experimenting with Python, and I set out > to create a function that, given a number of items and a maximum > number of items per row, would generate a table of rows of items. > However, there is one part where I believe I violate the prime > directive of coding, which is not to repeat yourself: > > class Table_Creator(object): > def __init__(self, given_num_of_items, max_num_of_items_per_row): > self.total_num_of_items = range(given_num_of_items) > self.max_num_of_items_per_row = max_num_of_items_per_row > > def create_grid(self): > table = [] > row = [] > count = 0 > while self.total_num_of_items: > row.append(self.total_num_of_items.pop(0)) > count += 1 > if (not self.total_num_of_items) or (count == > self.max_num_of_items_per_row): > table.append(tuple(row)) > row = [] > count = 0 > return table > > as you can see, I repeat the expressions "row = []" and "count = 0", > and I would like to know if there is something I can do to avoid > repetition in this case. OK - to address your original question: def create_grid(self): table = [] while self.total_num_of_items: row = [] count = 0 while count < self.max_num_of_items_per_row and self.total_num_of_items: row.append(self.total_num_of_items.pop(0)) count += 1 table.append(tuple(row)) return table -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From kent37 at tds.net Sat Jul 21 06:09:54 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 21 Jul 2007 00:09:54 -0400 Subject: [Tutor] Running program from Python In-Reply-To: References: Message-ID: <46A18712.3070907@tds.net> Tino Dai wrote: > =You might also want to try: > http://docs.python.org/lib/ipc.html to see if that is what you need Specifically the subprocess module which is the most modern way to start an external program. Kent From beanan2 at hotmail.com Sat Jul 21 14:26:44 2007 From: beanan2 at hotmail.com (Beanan O Loughlin) Date: Sat, 21 Jul 2007 12:26:44 +0000 Subject: [Tutor] correlation matrix Message-ID: hi all, I am new to python, and indeed to programming, but i have a question regarding correlation matrices. If i have a column vector x=[1;2;3;4;5] and its transpose row vector xt=[1,2,3,4,5] is there a simple way in python to create a 5x5 correlation matrix, obviously symmetric and having 1's on the diagonal? Thank you very much in advance, B. _________________________________________________________________ Get the ultimate real-time chat experience - Windows Live Messenger! http://get.live.com/en-ie/messenger/overview From dos.fool at gmail.com Sat Jul 21 17:13:47 2007 From: dos.fool at gmail.com (max baseman) Date: Sat, 21 Jul 2007 09:13:47 -0600 Subject: [Tutor] web browser Message-ID: has anyone ever written a web browser with python and Tkinter? if so is there any documentation on it? if not does anyone know if their which tutorials i should read if i wanted to write one for my apple? i don't know vary much Tkinter so i was going to start there then i thought i would be using the urllib and urllib2 modules which i know a little about know i don't know how i would display the html i can get the html of any site with urllib but how to show it in Tkinter? if anyone knows of tutorials for any of those, or has any ideas thank you From kent37 at tds.net Sat Jul 21 19:32:39 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 21 Jul 2007 13:32:39 -0400 Subject: [Tutor] web browser In-Reply-To: References: Message-ID: <46A24337.5080807@tds.net> max baseman wrote: > has anyone ever written a web browser with python and Tkinter? if so > is there any documentation on it? if not does anyone know if their > which tutorials i should read if i wanted to write one for my apple? > > i don't know vary much Tkinter so i was going to start there > then i thought i would be using the urllib and urllib2 modules which > i know a little about > know i don't know how i would display the html i can get the html of > any site with urllib but how to show it in Tkinter? There was a project to develop a Python web browser, called Grail, but it is long dead. wxPython has support for displaying HTML, that might be a better place to start than Tkinter. I don't know what your goal is, if it is just to learn and play then go for it, but if you are a beginning programmer and seriously thinking about creating a full-featured web browser...well, you should probably take on something smaller first. Kent From carroll at tjc.com Sat Jul 21 20:13:58 2007 From: carroll at tjc.com (Terry Carroll) Date: Sat, 21 Jul 2007 11:13:58 -0700 (PDT) Subject: [Tutor] correlation matrix In-Reply-To: Message-ID: On Sat, 21 Jul 2007, Beanan O Loughlin wrote: > I am new to python, and indeed to programming, but i have a question > regarding correlation matrices. Beanan, I never did get this kind of math, but have you looked at Numerical Python (NumPy), http://numpy.scipy.org/numpydoc/numpy.html ? Every time I've heard a question about matrices, it seems the answer ends up in there somewhere. From noufal at airtelbroadband.in Sat Jul 21 20:54:52 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Sun, 22 Jul 2007 00:24:52 +0530 Subject: [Tutor] correlation matrix In-Reply-To: References: Message-ID: <46A2567C.6020102@airtelbroadband.in> Beanan O Loughlin wrote: > hi all, > > I am new to python, and indeed to programming, but i have a question > regarding correlation matrices. > > If i have a column vector > > x=[1;2;3;4;5] > > and its transpose row vector > > xt=[1,2,3,4,5] > > is there a simple way in python to create a 5x5 correlation matrix, > obviously symmetric and having 1's on the diagonal? My knowledge of matrix algebra and statistics is quite rusty but from a programming perspective, I'd understand this like so. You want a 5x5 table of values (correlations in this case) computed from all permutations of 2 variables selected from a set of 5 elements. so, you'd want something like cor(1,1) cor(1,2) cor(1,3) .... cor(2,1) cor(2,2) cor(2,3) ... . . . Correct? If so, I think this might be what you're looking for (I've put some comments to make it explanatory). >>> import Numeric >>> x=[1,2,3] >>> ret = [] >>> for i in x: ... ret1=[] ... for j in x: # Since we're correlating an array with itself. ... ret1.append((i,j,)) # You'd need to call the actual correlation function here rather than just say (i,j) ... ret.append(ret1) ... >>> Numeric.array(ret) array([[[1, 1], [1, 2], [1, 3]], [[2, 1], [2, 2], [2, 3]], [[3, 1], [3, 2], [3, 3]]]) >>> The "Numeric" module has fast implementations of matrices and other such constructs. I'm quite sure that this thing which I've written above can be improved on but I think it would do your work for you. -- ~noufal From carroll at tjc.com Sat Jul 21 21:57:26 2007 From: carroll at tjc.com (Terry Carroll) Date: Sat, 21 Jul 2007 12:57:26 -0700 (PDT) Subject: [Tutor] Python program design In-Reply-To: Message-ID: On Fri, 20 Jul 2007, Doug Glenn wrote: > I have a question on program design. The program will be a catalog of > portable media (DVD, CD, flash drive, floppy, etc). I am currently in the > preliminary stages of design and I currently would like to get input on what > the best method would be for initially gathering the data and what format it > should take. Doug, I'd be interested in talking more about this. As it happens, I'm in the process of doing the same thing. Mine's going to be centered around SQLite, and when I get the DB part done, using wxPython for the GUI. For myself, I'll use it for cataloging three kinds of data collections: audio (MP3, etc.); images (JPG, GIF, PNG, BMP, etc.); and videos (MPG, AVI, etc). I plan on having the DB be extensible with separate auxiliary tables describing attributes specific to the type of file the database pertains to. For example, for an MP3 database, it will store the length of the song, and perhaps certain ID3 data. For an image database, the image height and width. I'm just finishing up the design and am about to start writing some code. The design I have so far is the database schema and the API to the module. I'd be happy to share some of my design ideas with you if you like. Once I have even a version up and running, I'm thinking of putting it up somewhere under an open source license, in case someone else can use it, and to get the benefits of anyone else's contributions, if any. I currently use Elcom's Advanced Disk Catalog for my cataloging. I'm switching to a homegrown version for a few reasons. First, ADC does not do anything media-specific, such as I described above. Although there are some open-source databases that do, they're all specific to a particular type of file, i.e., either MP3 or image, but not either/both. Second, I plan on storing the files' checksums, to be able to check whether a file I have is already duplicated in the library, without having to mount the disks. Third, I think it would just be a fun project, and a way to start into both SQLite and wxPython (it's my first project using either). Caveat: I'm no longer a programmer, and have two baby girls who take most of my spare time, so I am proceeding very slowly on this. It's just a hobby. From sarliz73 at yahoo.com Sun Jul 22 00:03:31 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Sat, 21 Jul 2007 15:03:31 -0700 (PDT) Subject: [Tutor] IDLE connection - was IDLE Usage Message-ID: <530558.83106.qm@web35111.mail.mud.yahoo.com> I am setting up an Xming/XWindows (forwarding?) and I followed what was instructed. When I got ready to connect, it all looked okay, but then I got this message. 'Warning: Missing charsets in String to FontSet conversion' Anyone know? Thanks, Sara ----- Original Message ---- From: Robert H. Haener IV To: Sara Johnson Cc: Python Sent: Tuesday, July 17, 2007 1:49:19 PM Subject: Re: [Tutor] IDLE Usage - was Interpreter Restarts Sara Johnson wrote: > That's pretty much what I was attempting. I was advised to mark the > "Tunneling" box (TunnelingX11 Connections), and it's checked. I don't > see the X Forwarding option, however. Under that same tab I checked for > anything else system-wise that would pertain and I don't see anything. > Again, I have XWin32 installed, but I probably need to renew it or > somehow get it to work as you've described. Anything else I should check? > >>>For example, I worked on this basic Unix editor 'Pico' before I > learned I could switch to Vi and >>have > Sorry...I meant to say "Putty" not Pico... Not important, just clarifying. > > Thanks, > Sara I have never attempted to use X Forwarding in Windows, but here is a guide that seems to tell you all you need to know: http://www.math.umn.edu/systems_guide/putty_xwin32.html >>From what I can gather, you should contact whomever is in charge of the SSH server if you can't get GUI programs working after following that guide. Also, just so we don't end up massively confusing each other: PuTTy is your "SSH client." The server to which you are connecting is the "SSH server." Pico and Vim are examples of "text editors," which are sometimes called "UNIX editors" by Windows folks. -Robert _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ____________________________________________________________________________________ Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. http://mobile.yahoo.com/go?refer=1GNXIC -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070721/e9764bd6/attachment.html From alan.gauld at btinternet.com Sun Jul 22 00:22:45 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 21 Jul 2007 23:22:45 +0100 Subject: [Tutor] How to determine if every character in one string is in another string? References: Message-ID: "Terry Carroll" wrote > Basically, I have a string s, and I want to print it out only if > every > character in it is printable Here is my attempt... def isPrintable(s) import string return not filter(lambda c: c not in string.printable, s) But thats very similar to your LC version just slightly more readable - to me at least! Alan G. Just back from a weeks vacation :-) From alan.gauld at btinternet.com Sun Jul 22 00:29:17 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 21 Jul 2007 23:29:17 +0100 Subject: [Tutor] How to determine if every character in one string is inanother string? References: <16651e80707202105v5b50640bifd9e2fa31e18b05f@mail.gmail.com> Message-ID: "Jerry Hill" wrote > I like this one: > all(char in string.printable for char in testString) What is all? Is that a 2.5 thing (I'm still on 2.4 here) >>>> testString = "qwerty\buiop" >>>> all(char in string.printable for char in testString) > False > > -- > Jerry > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From humbolt at comcast.net Sun Jul 22 04:04:52 2007 From: humbolt at comcast.net (Robert H. Haener IV) Date: Sat, 21 Jul 2007 22:04:52 -0400 Subject: [Tutor] IDLE connection - was IDLE Usage In-Reply-To: <530558.83106.qm@web35111.mail.mud.yahoo.com> References: <530558.83106.qm@web35111.mail.mud.yahoo.com> Message-ID: <46A2BB44.5030602@comcast.net> Sara Johnson wrote: > I am setting up an Xming/XWindows (forwarding?) and I followed what was > instructed. When I got ready to connect, it all looked okay, but then I > got this message. > > 'Warning: Missing charsets in String to FontSet conversion' > > Anyone know? > > Thanks, > Sara Sounds like you're missing some fonts, but that's just a guess. I will look it up further later tonight/tomorrow morning, I'm in the midst of a Thin Man marathon. -Robert From sarliz73 at yahoo.com Sun Jul 22 04:27:15 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Sat, 21 Jul 2007 19:27:15 -0700 (PDT) Subject: [Tutor] IDLE connection - was IDLE Usage Message-ID: <914219.34513.qm@web35110.mail.mud.yahoo.com> Okay, carry on then. :-) Still haven't figured it out either and I've tried reloading it. ----- Original Message ---- From: Robert H. Haener IV To: Sara Johnson Cc: Python Sent: Saturday, July 21, 2007 9:04:52 PM Subject: Re: [Tutor] IDLE connection - was IDLE Usage Sara Johnson wrote: > I am setting up an Xming/XWindows (forwarding?) and I followed what was > instructed. When I got ready to connect, it all looked okay, but then I > got this message. > > 'Warning: Missing charsets in String to FontSet conversion' > > Anyone know? > > Thanks, > Sara Sounds like you're missing some fonts, but that's just a guess. I will look it up further later tonight/tomorrow morning, I'm in the midst of a Thin Man marathon. -Robert _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ____________________________________________________________________________________ Get the Yahoo! toolbar and be alerted to new email wherever you're surfing. http://new.toolbar.yahoo.com/toolbar/features/mail/index.php -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070721/edfc3348/attachment.htm From alan.gauld at btinternet.com Sun Jul 22 11:39:51 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 22 Jul 2007 10:39:51 +0100 Subject: [Tutor] IDLE Usage - was Interpreter Restarts References: <114046.30409.qm@web35107.mail.mud.yahoo.com> Message-ID: "Sara Johnson" wrote > I use an SSH editor set up by my school. If I type python at the > prompt in SSH, > I get the Python shell. My problem is, I can't open a GUI no matter > what > I subscribe to or purchase. OK, Personally I'd forget about a GUI, its not that big a win for Python IMHO. What I'd do instead is open two SSH sessions, in one of them I'd open a vim session (or emacs if you prefer) to edit my code. In the second window open a python interactive session for testing stuff. You can also use Unix job control to background this session if you need to test the scripts, or you can open a third SSH session with a Unix shell prompt. In practice that's how I do nearly all my serious Python programming on Windows - using 3 separate windows: vim, Pyhon and shell. Try ideas out in the Python session, copy those ideas into the editor and save the file and then run the code in the shell window. Repeat as needed. > I have Python 2.3 and yes, I can access the commandline, but that > does > not work the way it's been described to work. What is missing? It should work like any standard >>> prompt. However it will be the vanilla version without some of the nice extras that IDE shells often provide and depending on how your Python was built it may not offer GNU readline capability to recall previous commands etc. Finally, If you really want to run an X GUI I'd recommend getting cygwin. Its big but it includes a near complete Unix/ X environment for your PC (including the fonts) as well as an SSH client and provi8ded your SSH server allows X to run - and many don't for security reasons - then it should work. You will have to issue the xhosts incantations of course to tell the server to accept requests from your PC. Pesonally I think its more work than is worth it unless you will be doing a lot of work on that server over a long time.. My opinion for what its worth! :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sarliz73 at yahoo.com Sun Jul 22 17:58:53 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Sun, 22 Jul 2007 08:58:53 -0700 (PDT) Subject: [Tutor] IDLE Usage - was Interpreter Restarts Message-ID: <915645.45086.qm@web35113.mail.mud.yahoo.com> Alan, Actually, I think you just solved one of the main issues I've had. That is, trying to figure out how much it'll help to have the GUI session open with the SSH session (as was recommended when I set out to do these projects). I had it in my mind that having this up and working would mean that these projects would make more sense. I could have been using two SSH sessions all along, I suppose. Another concern was more towards the specific nature of these projects, once I have to concern myself with graphics on a few tasks. For all I know it may not matter either way, but I had to check. I've been talking to someone else off list about that. Anyways, thanks for help! Sara ----- Original Message ---- From: Alan Gauld To: tutor at python.org Sent: Sunday, July 22, 2007 4:39:51 AM Subject: Re: [Tutor] IDLE Usage - was Interpreter Restarts "Sara Johnson" wrote > I use an SSH editor set up by my school. If I type python at the > prompt in SSH, > I get the Python shell. My problem is, I can't open a GUI no matter > what > I subscribe to or purchase. OK, Personally I'd forget about a GUI, its not that big a win for Python IMHO. What I'd do instead is open two SSH sessions, in one of them I'd open a vim session (or emacs if you prefer) to edit my code. In the second window open a python interactive session for testing stuff. You can also use Unix job control to background this session if you need to test the scripts, or you can open a third SSH session with a Unix shell prompt. In practice that's how I do nearly all my serious Python programming on Windows - using 3 separate windows: vim, Pyhon and shell. Try ideas out in the Python session, copy those ideas into the editor and save the file and then run the code in the shell window. Repeat as needed. > I have Python 2.3 and yes, I can access the commandline, but that > does > not work the way it's been described to work. What is missing? It should work like any standard >>> prompt. However it will be the vanilla version without some of the nice extras that IDE shells often provide and depending on how your Python was built it may not offer GNU readline capability to recall previous commands etc. Finally, If you really want to run an X GUI I'd recommend getting cygwin. Its big but it includes a near complete Unix/ X environment for your PC (including the fonts) as well as an SSH client and provi8ded your SSH server allows X to run - and many don't for security reasons - then it should work. You will have to issue the xhosts incantations of course to tell the server to accept requests from your PC. Pesonally I think its more work than is worth it unless you will be doing a lot of work on that server over a long time.. My opinion for what its worth! :-) -- 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 ____________________________________________________________________________________Ready for the edge of your seat? Check out tonight's top picks on Yahoo! TV. http://tv.yahoo.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070722/5e78acea/attachment.htm From dkuhlman at rexx.com Sun Jul 22 19:57:53 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 22 Jul 2007 10:57:53 -0700 Subject: [Tutor] IDLE Usage - was Interpreter Restarts In-Reply-To: References: <114046.30409.qm@web35107.mail.mud.yahoo.com> Message-ID: <20070722175753.GA81338@cutter.rexx.com> On Sun, Jul 22, 2007 at 10:39:51AM +0100, Alan Gauld wrote: > > > OK, Personally I'd forget about a GUI, its not that big a win for > Python IMHO. > > What I'd do instead is open two SSH sessions, in one of them I'd open > a > vim session (or emacs if you prefer) to edit my code. In the second > window > open a python interactive session for testing stuff. You can also use > Unix > job control to background this session if you need to test the > scripts, or > you can open a third SSH session with a Unix shell prompt. In practice > that's how I do nearly all my serious Python programming on Windows > - using 3 separate windows: vim, Pyhon and shell. And, the screen program might give you a bit of convenience. If you find yourself opening multiple sessions to the same UNIX/Linux box, you might want to look into screen, which enables you to create and switch between multiple sessions. I'm a command-line kind of person and I use screen heavily, even on my local machine, where instead of opening multiple xterm (Eterm, konsole, whatever) windows, I use screen create multiple sessions in a single window. For more on screen, do "man screen" and look here: http://en.wikipedia.org/wiki/GNU_Screen Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From alan.gauld at btinternet.com Mon Jul 23 00:35:21 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 22 Jul 2007 23:35:21 +0100 Subject: [Tutor] IDLE Usage - was Interpreter Restarts References: <114046.30409.qm@web35107.mail.mud.yahoo.com> <20070722175753.GA81338@cutter.rexx.com> Message-ID: "Dave Kuhlman" wrote > If you find yourself opening multiple sessions to the same > UNIX/Linux box, you might want to look into screen, which enables > you to create and switch between multiple sessions. > For more on screen, do "man screen" and look here: > > http://en.wikipedia.org/wiki/GNU_Screen I've heard of screen but never used it. The biggest problem I can see with it is that you can only see one screen(sic) at a time or use split screens to see partial screens. Can you copy/paste between sessions? Does it run on a remote server within the SSH client? If so how does it determine screen/window sizes? And do you know if you can get it for cygwin - its not installed by default, at least not on my cygwin. Alan G From brunson at brunson.com Mon Jul 23 01:13:05 2007 From: brunson at brunson.com (Eric Brunson) Date: Sun, 22 Jul 2007 17:13:05 -0600 Subject: [Tutor] IDLE Usage - was Interpreter Restarts In-Reply-To: References: <114046.30409.qm@web35107.mail.mud.yahoo.com> <20070722175753.GA81338@cutter.rexx.com> Message-ID: <46A3E481.6010507@brunson.com> Alan Gauld wrote: > "Dave Kuhlman" wrote > > >> If you find yourself opening multiple sessions to the same >> UNIX/Linux box, you might want to look into screen, which enables >> you to create and switch between multiple sessions. >> > > >> For more on screen, do "man screen" and look here: >> >> http://en.wikipedia.org/wiki/GNU_Screen >> > > I've heard of screen but never used it. > The biggest problem I can see with it is that you can only see one > screen(sic) at a time or use split screens to see partial screens. > You can only see one screen at a time as far as I know. If you need split screens, use emacs. > Can you copy/paste between sessions? > Yes, either with your native ssh client cut and paste, or with screen's somewhat cumbersome cut and paste, which I personally never use. > Does it run on a remote server within the SSH client? If so how > Yes. > does it determine screen/window sizes? > SIGWINCH+GNU doublegood magic. Screen has its own terminfo/termcap entry, clients write using screens window controls, then the screen application translates those directive to whatever term you're using at the time. > And do you know if you can get it for cygwin - its not installed by > default, at least not on my cygwin. > It's in the repos. The best thing (in my book) about screen, which I've been using for about 17 years, is you can disconnect from a screen session and reconnect from another login. I regularly start a long running process at work, then go home and use "screen -RD" to remotely detach the screen session and reconnect it to my current login. Plus, you don't have to worry about a compilation/database import/whatever dying because your VPN/dialup/cable modem dropped, everything keeps running and you just reattach. My *only* complaint about screen is its default control key is Ctrl-a, which is "beginning of line" in emacs parlance. You have to get used to using "Ctrl-a A" to go to the start of the line, but in all, it's a minor inconvenience. > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Mon Jul 23 01:40:20 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Jul 2007 00:40:20 +0100 Subject: [Tutor] IDLE Usage - was Interpreter Restarts References: <114046.30409.qm@web35107.mail.mud.yahoo.com> <20070722175753.GA81338@cutter.rexx.com> <46A3E481.6010507@brunson.com> Message-ID: "Eric Brunson" wrote >>> http://en.wikipedia.org/wiki/GNU_Screen >>> > You can only see one screen at a time as far as I know. If you need > split screens, use emacs. The wiki page shows a split screen session and claims you can split any session or have multiple sessions in split windows. > My *only* complaint about screen is its default control key is > Ctrl-a, How bizarre, but I guess they need to avoid collisions with the clients control key Thanks for the info. Alan G. From malaclypse2 at gmail.com Mon Jul 23 02:48:19 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Sun, 22 Jul 2007 20:48:19 -0400 Subject: [Tutor] How to determine if every character in one string is inanother string? In-Reply-To: References: <16651e80707202105v5b50640bifd9e2fa31e18b05f@mail.gmail.com> Message-ID: <16651e80707221748m210086b1qe5cdcb8ea1d8d495@mail.gmail.com> On 7/21/07, Alan Gauld wrote: > > all(char in string.printable for char in testString) > > What is all? > Is that a 2.5 thing (I'm still on 2.4 here) Yes, it's a 2.5 thing. All returns true if all of the elements of an iterable are true. According to the docs, it is the equivalent of the following: def all(iterable): for element in iterable: if not element: return False return True Using 'all' with a generator expression has the virtue of only needing to look at the string until it finds a single element that is false, and then returning. Not only that, it's concise (a single line) and quite readable (at least to me). -- Jerry From humbolt at comcast.net Mon Jul 23 08:14:08 2007 From: humbolt at comcast.net (Robert H. Haener IV) Date: Mon, 23 Jul 2007 02:14:08 -0400 Subject: [Tutor] IDLE Usage - was Interpreter Restarts In-Reply-To: References: <114046.30409.qm@web35107.mail.mud.yahoo.com> <20070722175753.GA81338@cutter.rexx.com> Message-ID: <46A44730.1000407@comcast.net> Alan Gauld wrote: > I've heard of screen but never used it. > The biggest problem I can see with it is that you can only see one > screen(sic) at a time or use split screens to see partial screens. > > Can you copy/paste between sessions? > Does it run on a remote server within the SSH client? If so how > does it determine screen/window sizes? > > And do you know if you can get it for cygwin - its not installed by > default, at least not on my cygwin. > > Alan G This is the second message I've seen asking some questions about screen which I already answered on the 17th. I know this is more than a little OT, I'm just wondering if somehow you didn't get that message. -Robert From tpc247 at gmail.com Mon Jul 23 08:24:53 2007 From: tpc247 at gmail.com (tpc247 at gmail.com) Date: Sun, 22 Jul 2007 23:24:53 -0700 Subject: [Tutor] don't repeat yourself; question about code optimization In-Reply-To: <46A1870D.2030000@alum.rpi.edu> References: <46A1870D.2030000@alum.rpi.edu> Message-ID: On 7/20/07, Bob Gailer wrote: > > Take advantage of slicing: > def create_grid(self): > table = [] > for i in range(0, len(self.total_num_of_items), > self.max_num_of_items_per_row): > table.append(tuple(self.total_num_of_items[i : i + > self.max_num_of_items_per_row])) > return table > simply amazing. Thank you. OK - to address your original question: > > def create_grid(self): > table = [] > while self.total_num_of_items: > row = [] > count = 0 > while count < self.max_num_of_items_per_row and > self.total_num_of_items: > row.append(self.total_num_of_items.pop(0)) > count += 1 > table.append(tuple(row)) > return table At first I regarded you with quiet awe, but then the nitpick in me saw the two "while self.total_num_of_item" statements, and I was less pleased. However, I see this as a doable challenge you have given me, and I will attempt to optimize your revisions. Thanks again. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070722/faf0bd99/attachment.html From alan.gauld at btinternet.com Mon Jul 23 09:22:33 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Jul 2007 08:22:33 +0100 Subject: [Tutor] IDLE Usage - was Interpreter Restarts References: <114046.30409.qm@web35107.mail.mud.yahoo.com> <20070722175753.GA81338@cutter.rexx.com> <46A44730.1000407@comcast.net> Message-ID: "Robert H. Haener IV" wrote > This is the second message I've seen asking some questions > about screen which I already answered on the 17th. > I know this is more than a little OT, I'm just wondering if somehow > you didn't get that message. I was still on vacation on the 17th so wouldn't have seen it then. But I just checked the gmane archive and there is nothing from you on the 17th about screen. (Lots about vim and SSH etc but not about screen) Alan G. From alan.gauld at btinternet.com Mon Jul 23 10:15:53 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Jul 2007 09:15:53 +0100 Subject: [Tutor] don't repeat yourself; question about code optimization References: Message-ID: wrote > one part where I believe I violate the prime directive of coding, > which is > not to repeat yourself: The prime directive of coding is make it readable! The DRY principle is just that a principle. If repeating makes for more maintainable or readable code then repeat yourself. Getting too hung up on a catchy acronym is a dangerous thing IMHO. It can lead to too much effort going into satisfying the principle and not enough into thinking about the problem at hand and how the code will be maintained. Remember 80% of the cost of software is in maintenance not initial development. DRY is one way to improve maintainablility and that's its purpose - to avoid having to fix things in two places - but it is not a rule that must be slavishly followed at the expense of readability/maintainability. It's in the same category as Do not use GOTO, Do not use global variables, Functions should be less than 25 lines long These are all useful principles which usually improve code quality but there are exceptions in every case. Now in your example removing repetition will improve things slightly, but I am always concerned when I see terms like "prime directive of coding" being applied to something like DRY. PS The most serious problem with your code from my perpspective is that your variable names are way too long. That affects maintenance and readability more that the repetition (and in the case of email it causes line wrapping that makes it even worse!) The names are also not accurate of their function, for example "total_num_of_items" is not a number at all but a list of numbers... I'd therefore suggest a rewrite of your init method like: def __init__(self, num_of_items, max_per_row): self.numbers = range(num_of_items) self.max_per_row = max_per_row And the modified create method looks like: def create_grid(self): table = [] row = [] count = 0 while self.numbers: row.append(self.numbers.pop(0)) count += 1 if (not self.numbers) or (count == self.max_per_row): table.append(tuple(row)) row = [] count = 0 return table Which makes the indentation error more obvious... The use of a while loop here could be replaced by a Python for loop which eliminates your repetition and is more natural: def create_grid(self): table = [] row = [] for number in self.numbers: row.append(number) if len(row) == self.max_per_row: table.append(tuple(row)) row = [] if len(row) != 0 # not sure if you want partially completed rows or not table.append(tuple(row)) return table However, since you are in effect trying to create a list of lists I suggest a combination of list comprehension and slicing would be a better solution. def create_grid(self): start = 0 table = [] num_rows = len(self.numbers)/max_per_row # this should really be in init! for n in range(num_rows): row = [num for num in self.numbers[start:start+self.max_per_row]] table.append(row) start += self.max_per_row return table Which happens to meet the DRY principle. But we got there, not by trying to avoid DRY but by improving the algorithm and structure of the code. DRY was merely a side efffect. Finally the class is not a good class in an OOP sense since it is nearly a verb. It is better done as a simple function in my view, just pass in the parameters to the create method. Like this: def create_table(num_items, row_size): start = 0 table = [] num_rows = num_items/row_size for n in range(num_rows): row = [num for num in range(start,start+row_size)] table.append(tuple(row)) start += row_size return table Or better still build a table class that knows how to create itself, but also knows how to maniplulate itself too - doing whatever it is you intend doing to the table you just created! This reflects another programming "rule" - the law of demeter" - one of the fundamentals of OOP. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From tinoloc at gmail.com Mon Jul 23 14:54:56 2007 From: tinoloc at gmail.com (Tino Dai) Date: Mon, 23 Jul 2007 08:54:56 -0400 Subject: [Tutor] Restarting a module Message-ID: Hi Everybody, I have a question about restarting a part of the program after it dies. I have a driver program that instantiates a class and runs methods from that class. Occasionally, the method gets bad data and it bombs out. Instead of bombing out, I would like the program to grab new data and start the processing. I already have the try except block ready, but I'm unsure about how to restart the method itself. Is it just as easy as self.someMethod() or do I need to do something to the namespace to insure that I don't get leakage from the past running of the method. Driver Section: ap=apacheModule.apacheModule(configXML,putInDB="1") while 1: rVs=ap.perf() for anObj in self.objList: Class Section (apacheModule module): def perf(self): <..stuff deleted..> self.putMethod: # putMethod is a variable controlled by an XML file, assume this is always true return self.put(self.parse(lines)) else: return self.parse(lines) def put(self,rVs): <..stuff deleted> try: (totalAccess,totalTraffic)=(rVs[3][1],self.sizeConvert (rVs[3][3],rVs[3][4])) (userUsage,sysUsage,cuserUsage,csysUsage,cpuLoad)=(rVs[4][1],rVs[4][2],rVs[4][3],rVs[4][4],rVs[4][6]) (requestsSec,bandwidth,perRequest)=(rVs[5][0], self.sizeConvert(rVs[5][1],rVs[5][2]),self.sizeConvert(rVs[5][3],rVs[5][4])) (requestsProc,idle)=(rVs[6][0],rVs[6][1]) except Exception,e: datetime.datetime.now() sys.stdout.write(str(e) + "\n") sys.stdout.write(rVs) <..stuff deleted..> Thanks, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070723/4c20d03e/attachment.html From alan.gauld at btinternet.com Mon Jul 23 16:30:21 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Jul 2007 15:30:21 +0100 Subject: [Tutor] Restarting a module References: Message-ID: "Tino Dai" wrote Your code confused me on several counts but in general... > I have a question about restarting a part of the program after > it dies. > I have a driver program that instantiates a class and runs methods > from that > class. Occasionally, the method gets bad data and it bombs out. > Instead of > bombing out, I would like the program to grab new data and start the > processing. I already have the try except block ready, but I'm > unsure about > how to restart the method itself. Is it just as easy as > self.someMethod() or > do I need to do something to the namespace to insure that I don't > get > leakage from the past running of the method. You generally can just call the method, there should be no "leakage" because you are not reloading the module just accessing one of its attributes - the method. Restart from the calling function not from the method itself of course! Thus you need a try/except in the driver section of your code and you need to do a raise in the implementation section after writing to sys.stdout... > Driver Section: > ap=apacheModule.apacheModule(configXML,putInDB="1") > while 1: > rVs=ap.perf() > for anObj in self.objList: Not sure what the last line signifies but you need to wrap the call to perf() in a try/except (if its perf that is failing - its not totally clear where the crash occurs). > Class Section (apacheModule module): > > def perf(self): > <..stuff deleted..> > self.putMethod: This is nonsensical syntax wise I have no idea what you are trying to suggest. Is it a call to self.putMetthod()? Or is it a branch: if self.putMethod: I'm assuming an if statement given what follows... > # putMethod is a variable controlled by an XML file, > assume > this is always true > return self.put(self.parse(lines)) If its put() that fails you could put the try/except here instead of the driver section. The question is whether you have the information needed to repair the damage or move onto the next data item(aka datum)? > else: > return self.parse(lines) > > def put(self,rVs): > <..stuff deleted> > try: > > (totalAccess,totalTraffic)=(rVs[3][1],self.sizeConvert > (rVs[3][3],rVs[3][4])) > > (userUsage,sysUsage,cuserUsage,csysUsage,cpuLoad)=(rVs[4][1],rVs[4][2],rVs[4][3],rVs[4][4],rVs[4][6]) > (requestsSec,bandwidth,perRequest)=(rVs[5][0], > self.sizeConvert(rVs[5][1],rVs[5][2]),self.sizeConvert(rVs[5][3],rVs[5][4])) > (requestsProc,idle)=(rVs[6][0],rVs[6][1]) > except Exception,e: > datetime.datetime.now() > sys.stdout.write(str(e) + "\n") > sys.stdout.write(rVs) > <..stuff deleted..> You need to add a raise here to force the exception up to the next level of detection. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From shidan at gmail.com Mon Jul 23 17:00:47 2007 From: shidan at gmail.com (Shidan) Date: Mon, 23 Jul 2007 11:00:47 -0400 Subject: [Tutor] Regex Ordering Message-ID: <429b380e0707230800o7adc73e1uf8c38cdc23693477@mail.gmail.com> I'm looking for a Python module that provides methods for ordering regexes based on how general they are ( how much they match). Do I have to write it myself or does something exist already. ---- Shidan From jjhartley at gmail.com Mon Jul 23 17:51:11 2007 From: jjhartley at gmail.com (James Hartley) Date: Mon, 23 Jul 2007 08:51:11 -0700 Subject: [Tutor] Regex Ordering In-Reply-To: <429b380e0707230800o7adc73e1uf8c38cdc23693477@mail.gmail.com> References: <429b380e0707230800o7adc73e1uf8c38cdc23693477@mail.gmail.com> Message-ID: On 7/23/07, Shidan wrote: > I'm looking for a Python module that provides methods for ordering > regexes based on > how general they are ( how much they match). Do I have to write it Your question is relative. Classifying which regular expression is more general depends upon the other regular expressions used in comparison along with the specific input. As you change input & regular expressions, the ordering will change. Yes, you will need to write this yourself. From brunson at brunson.com Mon Jul 23 18:03:07 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 23 Jul 2007 10:03:07 -0600 Subject: [Tutor] IDLE Usage - was Interpreter Restarts In-Reply-To: References: <114046.30409.qm@web35107.mail.mud.yahoo.com> <20070722175753.GA81338@cutter.rexx.com> <46A3E481.6010507@brunson.com> Message-ID: <46A4D13B.1090701@brunson.com> Alan Gauld wrote: > "Eric Brunson" wrote > > >>>> http://en.wikipedia.org/wiki/GNU_Screen >>>> >>>> >> You can only see one screen at a time as far as I know. If you need >> split screens, use emacs. >> > > The wiki page shows a split screen session and claims you can > split any session or have multiple sessions in split windows. > Well, if you knew the answer, why'd you ask? You're right, I never new you could do that. > >> My *only* complaint about screen is its default control key is >> Ctrl-a, >> > > How bizarre, but I guess they need to avoid collisions with the > clients control key > > Thanks for the info. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From humbolt at comcast.net Mon Jul 23 18:09:56 2007 From: humbolt at comcast.net (Robert H. Haener IV) Date: Mon, 23 Jul 2007 12:09:56 -0400 Subject: [Tutor] IDLE Usage - was Interpreter Restarts In-Reply-To: References: <114046.30409.qm@web35107.mail.mud.yahoo.com> <20070722175753.GA81338@cutter.rexx.com> <46A44730.1000407@comcast.net> Message-ID: <46A4D2D4.6010406@comcast.net> Alan Gauld wrote: > I was still on vacation on the 17th so wouldn't have seen it then. > But I just checked the gmane archive and there is nothing from > you on the 17th about screen. (Lots about vim and SSH etc but > not about screen) > > Alan G. This is the last I'll add to this little derailment, thought I'd point out that I just found the message on gmane. In case you care to look, it was sent at 17:49:25 GMT on the 17th, the screen info was under the link to the X11 Forwarding guide. Lacking other evidence, I'll stop worrying about message delivery and simply assume that I shouldn't cover two subjects in one post. -Robert From bgailer at alum.rpi.edu Mon Jul 23 18:15:01 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 23 Jul 2007 09:15:01 -0700 Subject: [Tutor] don't repeat yourself; question about code optimization In-Reply-To: References: <46A1870D.2030000@alum.rpi.edu> Message-ID: <46A4D405.1060909@alum.rpi.edu> tpc247 at gmail.com wrote: > > > On 7/20/07, *Bob Gailer* > wrote: > > Take advantage of slicing: > def create_grid(self): > table = [] > for i in range(0, len( self.total_num_of_items), > self.max_num_of_items_per_row): > table.append(tuple(self.total_num_of_items[i : i + > self.max_num_of_items_per_row ])) > return table > > > simply amazing. Thank you. One of the many "shifts" one makes in adjusting to "new" language features. I made such a shift in 1974 when I switched from FORTRAN and PL/I to APL. > > OK - to address your original question: > > def create_grid(self): > table = [] > while self.total_num_of_items: > row = [] > count = 0 > while count < self.max_num_of_items_per_row and > self.total_num_of_items: > row.append(self.total_num_of_items.pop(0)) > count += 1 > table.append(tuple(row)) > return table > > > At first I regarded you with quiet awe We gurus bask in attention. > , but then the nitpick in me saw the two "while > self.total_num_of_item" statements, and I was less pleased. Oh all right, that costs us one more statement. Independently we can get rid of count: def create_grid(self): table = [] while True: row = [] while len(row) < self.max_num_of_items_per_row: row.append(self.total_num_of_items.pop(0)) if not self.total_num_of_items: return table table.append(tuple(row)) -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From brunson at brunson.com Mon Jul 23 18:16:14 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 23 Jul 2007 10:16:14 -0600 Subject: [Tutor] IDLE Usage - was Interpreter Restarts In-Reply-To: <46A4D13B.1090701@brunson.com> References: <114046.30409.qm@web35107.mail.mud.yahoo.com> <20070722175753.GA81338@cutter.rexx.com> <46A3E481.6010507@brunson.com> <46A4D13B.1090701@brunson.com> Message-ID: <46A4D44E.2000603@brunson.com> Eric Brunson wrote: > Alan Gauld wrote: > >> "Eric Brunson" wrote >> >> >> >>>>> http://en.wikipedia.org/wiki/GNU_Screen >>>>> >>>>> >>>>> >>> You can only see one screen at a time as far as I know. If you need >>> split screens, use emacs. >>> >>> >> The wiki page shows a split screen session and claims you can >> split any session or have multiple sessions in split windows. >> >> > > Well, if you knew the answer, why'd you ask? > There should have been a smiley after than comment. :-) > You're right, I never new you could do that. > It's kinda cool. I thought the most annoyingly keystroke confusing thing I'd ever do was when I was writing and debugging an IRC bot. I had a screen session with the bot running in one session for debug output, a multi-buffer emacs session in another editing the bot source and the module source, and a BitchX session with multiple screens for the python-help channel, the bot's control channel and the channel the bot was interacting on. Talk about brain stymie trying to get around in that. But now I can throw multiple screen regions on top of it all? That's awesome! > >> >> >>> My *only* complaint about screen is its default control key is >>> Ctrl-a, >>> >>> >> How bizarre, but I guess they need to avoid collisions with the >> clients control key >> >> Thanks for the info. >> >> Alan G. >> >> >> _______________________________________________ >> 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 > From tinoloc at gmail.com Mon Jul 23 18:20:36 2007 From: tinoloc at gmail.com (Tino Dai) Date: Mon, 23 Jul 2007 12:20:36 -0400 Subject: [Tutor] Restarting a module In-Reply-To: References: Message-ID: Sorry about that. I think that a simpler question would be: In my driver code: ap = apacheModule.apacheModule(configXML) while 1: try: rVs=ap.perf() for anObj in self.objList: getattr(anObj,"do")(rVs) time.sleep(1) except ArraryOutOfBoundsException: pass except Exception, e: sys.stdout.write(str(e) + "\n") sys.exit(1) And in my apacheModule class: try: (totalAccess,totalTraffic)=(rVs[3][1],self.sizeConvert (rVs[3][3],rVs[3][4])) (userUsage,sysUsage,cuserUsage,csysUsage,cpuLoad)=(rVs[4][1],rVs[4][2],rVs[4][3],rVs[4][4],rVs[4][6]) (requestsSec,bandwidth,perRequest)=(rVs[5][0], self.sizeConvert(rVs[5][1],rVs[5][2]),self.sizeConvert(rVs[5][3],rVs[5][4])) (requestsProc,idle)=(rVs[6][0],rVs[6][1]) except Exception,e: datetime.datetime.now() sys.stdout.write(str(e) + "\n") sys.stdout.write(rVs) If the apacheModule comes raises an ArrayOutOfBound exception (don't remember if that the real exception name), the exception will bubble up, and the apacheDriver try-except will catch it, right? Thanks, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070723/1d696191/attachment.html From bgailer at alum.rpi.edu Mon Jul 23 18:44:55 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 23 Jul 2007 09:44:55 -0700 Subject: [Tutor] don't repeat yourself; question about code optimization CORRECTION In-Reply-To: References: <46A1870D.2030000@alum.rpi.edu> Message-ID: <46A4DB07.6010300@alum.rpi.edu> A correction to the code at the end. The test of self.total_num_of_items should precede the pop(0) tpc247 at gmail.com wrote: > > > On 7/20/07, *Bob Gailer* > wrote: > > Take advantage of slicing: > def create_grid(self): > table = [] > for i in range(0, len( self.total_num_of_items), > self.max_num_of_items_per_row): > table.append(tuple(self.total_num_of_items[i : i + > self.max_num_of_items_per_row ])) > return table > > > simply amazing. Thank you. One of the many "shifts" one makes in adjusting to "new" language features. I made such a shift in 1974 when I switched from FORTRAN and PL/I to APL. > > OK - to address your original question: > > def create_grid(self): > table = [] > while self.total_num_of_items: > row = [] > count = 0 > while count < self.max_num_of_items_per_row and > self.total_num_of_items: > row.append(self.total_num_of_items.pop(0)) > count += 1 > table.append(tuple(row)) > return table > > > At first I regarded you with quiet awe We gurus bask in attention. > , but then the nitpick in me saw the two "while > self.total_num_of_item" statements, and I was less pleased. Oh all right, that costs us one more statement. Independently we can get rid of count: def create_grid(self): table = [] while True: row = [] while len(row) < self.max_num_of_items_per_row: if not self.total_num_of_items: return table row.append(self.total_num_of_items.pop(0)) table.append(tuple(row)) -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From bill at celestial.net Mon Jul 23 18:29:30 2007 From: bill at celestial.net (Bill Campbell) Date: Mon, 23 Jul 2007 09:29:30 -0700 Subject: [Tutor] Regex Ordering In-Reply-To: References: <429b380e0707230800o7adc73e1uf8c38cdc23693477@mail.gmail.com> Message-ID: <20070723162930.GA1563@ayn.mi.celestial.com> On Mon, Jul 23, 2007, James Hartley wrote: >On 7/23/07, Shidan wrote: >> I'm looking for a Python module that provides methods for ordering >> regexes based on >> how general they are ( how much they match). Do I have to write it > >Your question is relative. Classifying which regular expression is >more general depends upon the other regular expressions used in >comparison along with the specific input. As you change input & >regular expressions, the ordering will change. As a first cut, one might sort the regular expression strings in reverse order such that the longer strings are tested first. Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 Virtually everything is under federal control nowadays except the federal budget. -- Herman E. Talmadge, 1975 From philippe at niquille.com Mon Jul 23 19:09:47 2007 From: philippe at niquille.com (Philippe Niquille) Date: Mon, 23 Jul 2007 19:09:47 +0200 Subject: [Tutor] sorting objects in lists by 2 attr Message-ID: <1ba302070707231009i31d69167r75de978d8ea97bd6@mail.gmail.com> Hi I have a hard time sorting an object list. Perhaps this is kind of a noob question, but I would very much appreciate any help! Using django I get a QuerySet of Score objects which are sorted by the actual score, the actual score divided by the max. possible score (so sorting by two db fields). I then need to loop through that queryset and sum up all the score objects which belong to the same user into one Score objects. This works (see code below). The problem I now have, is that I lost the sorting order, as described above. How would I resort it with a python algortithm instead of SQL? scores = Score.objects.order_by('score', 'score2','owner') # filter by course, MC !! # loop through scores to regroup by user newscore = [] for s in scores: i = False # loop through new object container and check for existant user index, add scores if existant for ns in newscore: if s.owner == ns.owner: ns.score = int(ns.score) + int(s.score) ns.maxscore = int(ns.maxscore) + int(s.maxscore) i = True # otherwise append new user index object, work with it later, perhaps (if more user objects exist) if i == False: newscore.append(s) ----------------- I did fiddle around with .sort() but didn't get any useful results (and it would only sort by one object..). class CmpAttr: def __init__(self, attr): self.attr = attr def __call__(self, x, y): return cmp(getattr(x, self.attr), getattr(y, self.attr)) newscore.sort(CmpAttr("score")) ps. could it be, that this maillist is blocking some e-mail addresses? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070723/4fb21fb2/attachment.html From brunson at brunson.com Mon Jul 23 19:28:29 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 23 Jul 2007 11:28:29 -0600 Subject: [Tutor] sorting objects in lists by 2 attr In-Reply-To: <1ba302070707231009i31d69167r75de978d8ea97bd6@mail.gmail.com> References: <1ba302070707231009i31d69167r75de978d8ea97bd6@mail.gmail.com> Message-ID: <46A4E53D.3040308@brunson.com> Philippe Niquille wrote: > > Hi > > > I have a hard time sorting an object list. Perhaps this is kind of a > noob question, but I would very much appreciate any help! > > > Using django I get a QuerySet of Score objects which are sorted by the > actual score, the actual score divided by the max. possible score (so > sorting by two db fields). > > I then need to loop through that queryset and sum up all the score > objects which belong to the same user into one Score objects. This > works (see code below). > > > The problem I now have, is that I lost the sorting order, as described > above. How would I resort it with a python algortithm instead of SQL? > This is not the question you're asking, but my first though was, why not have SQL do the summing for you using sum() and group by? > > scores = Score.objects.order_by('score', 'score2','owner') # filter by > course, MC !! > > # loop through scores to regroup by user > > newscore = [] > > for s in scores: > > i = False > > # loop through new object container and check for existant user index, > add scores if existant > > for ns in newscore: > > if s.owner == ns.owner: > > ns.score = int(ns.score) + int(s.score) > > ns.maxscore = int(ns.maxscore) + int(s.maxscore) > > i = True > > # otherwise append new user index object, work with it later, perhaps > (if more user objects exist) > > if i == False: > > newscore.append(s) > > > ----------------- > > > I did fiddle around with .sort() but didn't get any useful results > (and it would only sort by one object..). > > > class CmpAttr: > > def __init__(self, attr): > > self.attr = attr > > def __call__(self, x, y): > > return cmp(getattr(x, self.attr), getattr(y, self.attr)) > > > newscore.sort(CmpAttr("score")) > > > > ps. could it be, that this maillist is blocking some e-mail addresses? > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Mon Jul 23 19:52:55 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Jul 2007 18:52:55 +0100 Subject: [Tutor] Restarting a module References: Message-ID: "Tino Dai" wrote > Sorry about that. I think that a simpler question would be: I'm not sure what the better question is, but I think I answered it :-) > In my driver code: > > ap = apacheModule.apacheModule(configXML) > while 1: > try: > rVs=ap.perf() > for anObj in self.objList: > getattr(anObj,"do")(rVs) > time.sleep(1) > except ArraryOutOfBoundsException: > pass > except Exception, e: > sys.stdout.write(str(e) + "\n") > sys.exit(1) > > > And in my apacheModule class: > > try: > > (totalAccess,totalTraffic)=(rVs[3][1],self.sizeConvert ... > except Exception,e: > datetime.datetime.now() > sys.stdout.write(str(e) + "\n") > sys.stdout.write(rVs) > > If the apacheModule raises an ArrayOutOfBound exception (don't > remember if that the real exception name), the exception will bubble > up, and > the apacheDriver try-except will catch it, right? No, if you catch it here, as you will if you catch all Exceptions, then it will stop right there unless you explicitly raise it. You bneed to add a raise statement after the stdout.write stuff. Alan G. From alan.gauld at btinternet.com Mon Jul 23 19:56:46 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Jul 2007 18:56:46 +0100 Subject: [Tutor] sorting objects in lists by 2 attr References: <1ba302070707231009i31d69167r75de978d8ea97bd6@mail.gmail.com> Message-ID: "Philippe Niquille" wrote > The problem I now have, is that I lost the sorting order, as > described > above. How would I resort it with a python algortithm instead of > SQL? Why not use SQL? Best to get the highest quality data into your program that you can, the earlier you clean it the better. Unless your database is squealing and you need to move load onto your app server then I'd leave the database to handle the data. In fact I might even make it a stored procedure if the database supports those... Alan G. From carroll at tjc.com Mon Jul 23 20:37:59 2007 From: carroll at tjc.com (Terry Carroll) Date: Mon, 23 Jul 2007 11:37:59 -0700 (PDT) Subject: [Tutor] How to determine if every character in one string is inanother string? In-Reply-To: <16651e80707221748m210086b1qe5cdcb8ea1d8d495@mail.gmail.com> Message-ID: On Sun, 22 Jul 2007, Jerry Hill wrote: > On 7/21/07, Alan Gauld wrote: > > > all(char in string.printable for char in testString) > > > > What is all? > > Is that a 2.5 thing (I'm still on 2.4 here) > > Yes, it's a 2.5 thing. That was my favorite, too. I didn't notice the new all method in 2.5. It certainly seems the most Pythonic approach. I really enjoyed seeing all the proposed alternatives, however. Thanks, everybody! From eric at ericwalstad.com Mon Jul 23 21:06:19 2007 From: eric at ericwalstad.com (Eric Walstad) Date: Mon, 23 Jul 2007 12:06:19 -0700 Subject: [Tutor] sorting objects in lists by 2 attr In-Reply-To: <1ba302070707231009i31d69167r75de978d8ea97bd6@mail.gmail.com> References: <1ba302070707231009i31d69167r75de978d8ea97bd6@mail.gmail.com> Message-ID: <46A4FC2B.9020009@ericwalstad.com> Philippe Niquille wrote: > Using django I get a QuerySet of Score objects which are sorted by the > actual score, the actual score divided by the max. possible score (so > sorting by two db fields). > > I then need to loop through that queryset and sum up all the score > objects which belong to the same user into one Score objects. This works > (see code below). I'm with Eric and Alan here; do as much in the DB as possible/practical first, then work with the results in Python. Django's ORM may be able to do your aggregating for you. If not and if your DB has something like PostgreSQL's Views (stored queries) then you can create a database view that filters/sorts/aggregates your data as needed. From there you can create a Django Model associated with the DB View, just like you normally create a Django Model on a DB table. The main difference is that objects returned by the QuerySet on the DB View will be read-only because the DB View is read-only. On the other hand you'll still be able to python-ize your aggregated db data using Django's ORM in a manner you are used to, something like: scores = ModelOnMyDBView.objects.order_by('max_score','owner') I hope that is helpful, Eric. From wescpy at gmail.com Mon Jul 23 22:46:25 2007 From: wescpy at gmail.com (wesley chun) Date: Mon, 23 Jul 2007 13:46:25 -0700 Subject: [Tutor] How to determine if every character in one string is inanother string? In-Reply-To: References: <16651e80707221748m210086b1qe5cdcb8ea1d8d495@mail.gmail.com> Message-ID: <78b3a9580707231346i387d497l16faf1e8ff5b7b2f@mail.gmail.com> > > > > all(char in string.printable for char in testString) > > That was my favorite, too. I didn't notice the new all method in 2.5. It > certainly seems the most Pythonic approach. all() has a sister built-in function, also introduced in 2.5, so i think that any(char not in string.printable for char in testString) will work too. however, believe it or not, i kinda like your original answer... it's not as lame as you think! :-) i tweaked it slightly (for performance reasons) to: from string import printable as prglobal def printable(s): prlocal = prglobal for x in s: if x not in prlocal: return False return True - i got rid of the list comp and the list comparisons... they're not necessary and slow things down - i moved the import outside the function... not sure why i did this. must be leftover from the days i used to think that the import would occur every time the function's called, but now i know that there's a difference between "importing" and "loading" of a module! - i also created a local reference to string.printable to speed up the lookup -- recall the name resolution order is: locals, globals, built-ins - i also also short-circuit the rest of the string if/when it finds the 1st non-printable. (no need to go on in a 10-million character string if char#2 is a non-printable right?) the solutions using LCs above are great when it comes to an expressive piece of code in a one-liner, but i feel there's a waste of time/memory. the use of GEs is better, but it still has to iterate over the entire string when i don't feel that it should be necessary as per my example. anyway, just my $0.02! not the shortest, but hopefully the fastest! cheers, -- 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 tinoloc at gmail.com Mon Jul 23 23:30:49 2007 From: tinoloc at gmail.com (Tino Dai) Date: Mon, 23 Jul 2007 17:30:49 -0400 Subject: [Tutor] Restarting a module In-Reply-To: References: Message-ID: On 7/23/07, Alan Gauld wrote: > > > "Tino Dai" wrote > > > Sorry about that. I think that a simpler question would be: > > I'm not sure what the better question is, but I think I > answered it :-) > > > In my driver code: > > > > ap = apacheModule.apacheModule(configXML) > > while 1: > > try: > > rVs=ap.perf() > > for anObj in self.objList: > > getattr(anObj,"do")(rVs) > > time.sleep(1) > > except ArraryOutOfBoundsException: > > pass > > except Exception, e: > > sys.stdout.write(str(e) + "\n") > > sys.exit(1) > > > > > > And in my apacheModule class: > > > > try: > > > > (totalAccess,totalTraffic)=(rVs[3][1],self.sizeConvert ... > > except Exception,e: > > datetime.datetime.now() > > sys.stdout.write(str(e) + "\n") > > sys.stdout.write(rVs) > > > > If the apacheModule raises an ArrayOutOfBound exception (don't > > remember if that the real exception name), the exception will bubble > > up, and > > the apacheDriver try-except will catch it, right? > > No, if you catch it here, as you will if you catch all Exceptions, > then > it will stop right there unless you explicitly raise it. You bneed to > add a > raise statement after the stdout.write stuff. > > Alan G. Thanks Alan, That makes a lot of sense. I will be see what I can do tomorrow with a revision of the code. Thanks again, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070723/75cf453f/attachment.htm From alan.gauld at btinternet.com Mon Jul 23 23:46:23 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Jul 2007 22:46:23 +0100 Subject: [Tutor] How to determine if every character in one string isinanother string? References: <16651e80707221748m210086b1qe5cdcb8ea1d8d495@mail.gmail.com> <78b3a9580707231346i387d497l16faf1e8ff5b7b2f@mail.gmail.com> Message-ID: "wesley chun" wrote > the solutions using LCs above are great when it comes to an > expressive > piece of code in a one-liner, but i feel there's a waste of > time/memory. the use of GEs is better, but it still has to iterate > over the entire string when i don't feel that it should be necessary One of my only peeves with LCs is that they always iterate to the end, I'd like an optional extra 'until' clause, like: lst = [n for n in veryBigSequence if someTest(n) until anotherTest(n)] This would act as usual until the final expression was true at which point it would stop iterating. If I could find the time/inclination I might even try throwing it in as a PEP sometime... I don't think it would break much old code because (a) its an optional extra at the end of the LC and (b) 'until' isn't used in Python so far... Alan G. From dkuhlman at rexx.com Tue Jul 24 00:01:16 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Mon, 23 Jul 2007 15:01:16 -0700 Subject: [Tutor] Here is newbie doc on how to implement generators In-Reply-To: <469BED8F.1030904@tds.net> References: <20070712232608.GA59300@cutter.rexx.com> <469BED8F.1030904@tds.net> Message-ID: <20070723220116.GA45940@cutter.rexx.com> On Mon, Jul 16, 2007 at 06:13:35PM -0400, Kent Johnson wrote: Kent - Rather than try to reply in detail to your suggestions, I've tried to ammend my document to reflect your comments. Thanks again for the help. Dave [good suggestions and corrections from Kent, snipped] -- Dave Kuhlman http://www.rexx.com/~dkuhlman From wescpy at gmail.com Tue Jul 24 00:32:50 2007 From: wescpy at gmail.com (wesley chun) Date: Mon, 23 Jul 2007 15:32:50 -0700 Subject: [Tutor] How to determine if every character in one string isinanother string? In-Reply-To: References: <16651e80707221748m210086b1qe5cdcb8ea1d8d495@mail.gmail.com> <78b3a9580707231346i387d497l16faf1e8ff5b7b2f@mail.gmail.com> Message-ID: <78b3a9580707231532s3ecdbd06i5cc9ec079b0f5c5f@mail.gmail.com> > One of my only peeves with LCs is that they always iterate to the end, > I'd like an optional extra 'until' clause, like: > > lst = [n for n in veryBigSequence if someTest(n) until anotherTest(n)] > > This would act as usual until the final expression was true at which > point it would stop iterating. > > If I could find the time/inclination I might even try throwing it in > as > a PEP sometime... i think that's a great idea. my head's telling me "break" but "until" sounds more appropriate. you should file both a regular and a 3000-PEP... at least the latter since it's the future. :-) -wesley From keridee at jayco.net Tue Jul 24 01:35:01 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 23 Jul 2007 18:35:01 -0500 Subject: [Tutor] about importing a module References: <384c93600707191153m32b42ff1k216a356f7b540210@mail.gmail.com> <006401c7ca51$157b6ac0$81fde004@JSLAPTOP> <006e01c7ca53$edcd2790$81fde004@JSLAPTOP> <46A02737.5080805@gmail.com> Message-ID: <004c01c7cd82$1b2ee850$d4fce004@JSLAPTOP> >> If the module has been imported before your code is run, it will be the >> library module (very important if working in IDLE which importants many >> modules, for example). > So... how does IDLE go about importanting a module? ;) It's not *how* IDLE imports the module, but that fact that IDLE imports the module before his script would be executed. For example: ### sys.py ### path = "Hello" ############ ### test.py ### import sys print sys.path ############ Save sys.py and test.py in the same directory. Run test.py from the command line. Then open test.py in IDLE and run it in IDLE. You should get two different results because IDLE imports sys as part of it's own code and python does not re-import modules. However, when you run test.py from the command line, sys has not been previously imported and our own sys.py is imported. Hope this explains my reasoning. JS From keridee at jayco.net Tue Jul 24 01:39:08 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 23 Jul 2007 18:39:08 -0500 Subject: [Tutor] another question ( unrelated ) References: <384c93600707200908i1ca53093y7457fa310203ea43@mail.gmail.com> Message-ID: <008a01c7cd82$ada87750$d4fce004@JSLAPTOP> Perhaps everyone is trying too hard. Instead of trying to re-initialize the thread on error, let the thread create a new seperate thread and destroy itself naturally. Maybe a shot in the dark? :-/ JS From keridee at jayco.net Tue Jul 24 01:54:44 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 23 Jul 2007 18:54:44 -0500 Subject: [Tutor] Generators References: Message-ID: <012d01c7cd84$db5d2400$d4fce004@JSLAPTOP> > Please forgive my instrusion with some simple questions. I don't have any > formal training in programming so I have to get some guidance to some > terminology from time to time. What is a generator and what is its > purpose? Think of a generator as a list whose contents haven't been finished yet. Essentially, it "generates" each successive element of the list on the fly. Here's a classic example of where a generator is required, as opposed to a list. def fibonacci(): a = 1 b = 1 yield a while 1: yield b a, b = b, a+b Because fibonacci numbers are an infinite sequence (you can never stop generating the numbers) it would be ridiculous to try to store all of them in a list. A generator is custom suited to problems like this. Oh, test this code this way -> >>> a = fibonacci() >>> a.next() 1 >>> a.next() 1 >>> a.next() 2 >>> for i in range(100): print a.next() 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025 20365011074 32951280099 53316291173 86267571272 139583862445 225851433717 365435296162 591286729879 956722026041 1548008755920 2504730781961 4052739537881 6557470319842 10610209857723 17167680177565 27777890035288 44945570212853 72723460248141 117669030460994 190392490709135 308061521170129 498454011879264 806515533049393 1304969544928657 2111485077978050 3416454622906707 5527939700884757 8944394323791464 14472334024676221 23416728348467685 37889062373143906 61305790721611591 99194853094755497 160500643816367088 259695496911122585 420196140727489673 679891637638612258 1100087778366101931 1779979416004714189 2880067194370816120 4660046610375530309 7540113804746346429 12200160415121876738 19740274219868223167 31940434634990099905 51680708854858323072 83621143489848422977 135301852344706746049 218922995834555169026 354224848179261915075 573147844013817084101 927372692193078999176 1500520536206896083277 >>> Which provides the expected results for a fibonacci sequence. JS From philippe at niquille.com Tue Jul 24 01:53:49 2007 From: philippe at niquille.com (Philippe Niquille) Date: Tue, 24 Jul 2007 01:53:49 +0200 Subject: [Tutor] sorting objects in lists by 2 attr Message-ID: <1ba302070707231653x3228fb35x24721d18be3a8179@mail.gmail.com> Tanks a mill! I don't know why I searched so far.. Anyway, I wrapped the django custom SQL call and built a nice dictionary out of the resulting rows (which is similar to querysets). See http://www.djangosnippets.org/snippets/207/ for details. Philippe Am 23.07.2007 um 19:28 schrieb Eric Brunson: Philippe Niquille wrote: Hi I have a hard time sorting an object list. Perhaps this is kind of a noob question, but I would very much appreciate any help! Using django I get a QuerySet of Score objects which are sorted by the actual score, the actual score divided by the max. possible score (so sorting by two db fields). I then need to loop through that queryset and sum up all the score objects which belong to the same user into one Score objects. This works (see code below). The problem I now have, is that I lost the sorting order, as described above. How would I resort it with a python algortithm instead of SQL? This is not the question you're asking, but my first though was, why not have SQL do the summing for you using sum() and group by? scores = Score.objects.order_by('score', 'score2','owner') # filter by course, MC !! # loop through scores to regroup by user newscore = [] for s in scores: i = False # loop through new object container and check for existant user index, add scores if existant for ns in newscore: if s.owner == ns.owner: ns.score = int(ns.score) + int(s.score) ns.maxscore = int(ns.maxscore) + int(s.maxscore) i = True # otherwise append new user index object, work with it later, perhaps (if more user objects exist) if i == False: newscore.append(s) ----------------- I did fiddle around with .sort() but didn't get any useful results (and it would only sort by one object..). class CmpAttr: def __init__(self, attr): self.attr = attr def __call__(self, x, y): return cmp(getattr(x, self.attr), getattr(y, self.attr)) newscore.sort(CmpAttr("score")) ps. could it be, that this maillist is blocking some e-mail addresses? ------------------------------------------------------------------------ _______________________________________________ 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/20070724/c515797f/attachment.html From keridee at jayco.net Tue Jul 24 03:24:51 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 23 Jul 2007 20:24:51 -0500 Subject: [Tutor] Generators References: <002901c7cd81$ae8e8700$5f01a8c0@dcsoftware.local> Message-ID: <029001c7cd91$72ac6080$d4fce004@JSLAPTOP> > I am new to Python but not new to programming languages. I have seen this > "while 1" a lot. In fact in other languages I would expect "while 1" to > be > the same as "while TRUE". I have used that in other languages, but in the > definition below I would expect the "yield b..." to continue on until a > "break". So the question is, how does this work without going into an > infinite loop without a break? > > Jeff while 1: and while TRUE: mean the same thing. The thing is - it is an infinite loop. >>> a = fibonacci() >>> a.next() 1 >>> No matter how many times you call a.next(), it will continue to return numbers. You are being fooled by the yield statement. Generators are special objects. The yield statement is ~~ difficult to translate into computer terms. My first impulse is to compare it to an interrupt, but you might not know what that is. The best way to explain it is to litter that example with print statements. Here: def fibonacci(): a = 1 print "a = 1" b = 1 print "b = 1" print "Before yield a" yield a print "After yield a" while 1: print "Before yield b" yield b print "After yield b" a, b = b, a+b print "After calculation" >>> a = fibonacci() >>> a.next() a = 1 b = 1 Before yield a 1 >>> a.next() After yield a Before yield b 1 >>> a.next() After yield b After calculation Before yield b 2 >>> a.next() After yield b After calculation Before yield b 3 >>> JS From keridee at jayco.net Tue Jul 24 03:26:32 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 23 Jul 2007 20:26:32 -0500 Subject: [Tutor] reading random line from a file References: <769390.54156.qm@web90409.mail.mud.yahoo.com> Message-ID: <029301c7cd91$ae728040$d4fce004@JSLAPTOP> > Significance of number 4096 : > file is stored in blocks of size 2K/4K/8K (depending > upon the machine). file seek for an offset goes block > by block rather than byte by byte. Hence for file size > < 4096 (assuming you have 4K block size), you will > anyway end up scanning it entirely so as well load it > up in memory. Mmmm... It depends on the file system. FAT/FAT32 will read as small a block as a sector size, i.e. 512 bytes. I think I read somewhere that NTFS is 4K. Ridiculous waste i think. Anyway... It's dangerous to think one way or the other about boundaries like that. The only way that 4096 can help you is if you only start reading on boundary lines, and disable buffering on the OS level. Otherwise, you will get double and triple buffering occurring. Perhaps python takes care of this, but it's doubtful. C doesn't by default, and since python programmers often aren't of the background to grok how the OS caches reads, it would be extra overhead for a special case of that most aren't aware. Mmmm... The OS will read all of those characters in anyway right? 4K. But if you ask for the data byte by byte, it will copy it to your pointer byte by byte from the cache instead of copying all of the memory. Anyway... all this is making my head hurt because I can't quite remember how it works. (When I last read information about this, I didn't understand it's significance to my programming.) > But I > just want to add that since index creation is quite a > laborious task (in terms of CPU/time) one should do it > only once (or till file is changed). Agreed, but it is still better to make the index once at program start, rather than search through each time a line is requested. > Thus it should be > kept on disk and ensure that index is re-created in > case file changes. That's a good idea. Especially for large files. > I would like suggestions on index > creation. Creating an index is easy. There are many ways. Here is one. file_index=[0] for line in fobj: file_index.append(len(line)+file_index[-1]) From brunson at brunson.com Tue Jul 24 02:52:19 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 23 Jul 2007 18:52:19 -0600 Subject: [Tutor] sorting objects in lists by 2 attr In-Reply-To: <1ba302070707231653x3228fb35x24721d18be3a8179@mail.gmail.com> References: <1ba302070707231653x3228fb35x24721d18be3a8179@mail.gmail.com> Message-ID: <46A54D43.1050300@brunson.com> SQL databases are cool. Make them do as much as they can for you. :-) Philippe Niquille wrote: > Tanks a mill! > > I don't know why I searched so far.. > > Anyway, I wrapped the django custom SQL call and built a nice > dictionary out of the resulting rows (which is similar to querysets). > See http://www.djangosnippets.org/snippets/207/ > for details. > > Philippe > > Am 23.07.2007 um 19:28 schrieb Eric Brunson: >> Philippe Niquille wrote: >>> >>> >>> Hi >>> >>> >>> >>> >>> I have a hard time sorting an object list. Perhaps this is kind of a >>> noob question, but I would very much appreciate any help! >>> >>> >>> >>> >>> Using django I get a QuerySet of Score objects which are sorted by >>> the actual score, the actual score divided by the max. possible >>> score (so sorting by two db fields). >>> >>> >>> I then need to loop through that queryset and sum up all the score >>> objects which belong to the same user into one Score objects. This >>> works (see code below). >>> >>> >>> >>> >>> The problem I now have, is that I lost the sorting order, as >>> described above. How would I resort it with a python algortithm >>> instead of SQL? >>> >>> >> >> >> This is not the question you're asking, but my first though was, why >> not have SQL do the summing for you using sum() and group by? >> >> >>> >>> >>> scores = Score.objects.order_by('score', 'score2','owner') # filter >>> by course, MC !! >>> >>> >>> # loop through scores to regroup by user >>> >>> >>> newscore = [] >>> >>> >>> for s in scores: >>> >>> >>> i = False >>> >>> >>> # loop through new object container and check for existant user >>> index, add scores if existant >>> >>> >>> for ns in newscore: >>> >>> >>> if s.owner == ns.owner: >>> >>> >>> ns.score = int(ns.score) + int(s.score) >>> >>> >>> ns.maxscore = int(ns.maxscore) + int(s.maxscore ) >>> >>> >>> i = True >>> >>> >>> # otherwise append new user index object, work with it later, >>> perhaps (if more user objects exist) >>> >>> >>> if i == False: >>> >>> >>> newscore.append(s) >>> >>> >>> >>> >>> ----------------- >>> >>> >>> >>> >>> I did fiddle around with .sort() but didn't get any useful results >>> (and it would only sort by one object..). >>> >>> >>> >>> >>> class CmpAttr: >>> >>> >>> def __init__(self, attr): >>> >>> >>> self.attr = attr >>> >>> >>> def __call__(self, x, y): >>> >>> >>> return cmp(getattr(x, self.attr), getattr(y, self.attr)) >>> >>> >>> >>> >>> newscore.sort(CmpAttr("score")) >>> >>> >>> >>> >>> >>> >>> ps. could it be, that this maillist is blocking some e-mail addresses? >>> >>> >>> ------------------------------------------------------------------------ >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> > > From keridee at jayco.net Tue Jul 24 03:54:41 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 23 Jul 2007 20:54:41 -0500 Subject: [Tutor] Python program design References: Message-ID: <031801c7cd95$9d63e7e0$d4fce004@JSLAPTOP> > Then I would need to get the file size (but this is giving me an error at > the moment) > for name in files: > s = sum(getsize(join(root, name) > print s (syntax error here. I have not figured it out yet. There > are spaces in the path/filename combo) > (code to parse the file extension here) The line should be s = getsize(join(root, name)) which will print the file size for each "name in files" > > Back to the data though, should I create something like these while > reading > the media and prior to inserting it into the database? > [disk label, disk id [root[dir[file,size,type, permissions]]]] in a > dictionary or tuple? or use a list? > > or flat in a dictionary, tuple or list like > [disk label, disk id, root,dir,filename,size,type,permissions] > > When it has completed the scan I want to insert it into the database with > the following fields > disk label, disk id, root directory, path, filename, file size, file type, > original file permissions, and comment field. (Does anyone thing I should > have any other fields? Suggestions welcome) > > Thank you in advance. If this is off topic, please reply off the list and > let me know. Don't take my word for it completely, but a few things to consider. Disc IDs are the most likely to be unique, so I would use those as the keys However, It is possible for two discs to have the same IDs, so for stability, I would suggest using a tuple as a key. I know it's possible even to have two different discs with the same ID and label, but it's not likely. {(discID, discLbl) : [information in list], ... } You may wish to build a dict inside your dict. {(discID, discLbl): {'dir': '...', 'filename': '...", etc. I don't know how you want to use it, but keeping the root directory is not very useful. If you ever want to transfer your files to another computer where the drive letters are different, or classic example ~ you build your dict from a usb device that you plug in in a different order later so that it's assigned a different drive letter. I would suggest using the drive ID and some sort of api to find the drive letter at runtime. HTH, JS From rabidpoobear at gmail.com Tue Jul 24 02:55:20 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 23 Jul 2007 19:55:20 -0500 Subject: [Tutor] about importing a module In-Reply-To: <004c01c7cd82$1b2ee850$d4fce004@JSLAPTOP> References: <384c93600707191153m32b42ff1k216a356f7b540210@mail.gmail.com> <006401c7ca51$157b6ac0$81fde004@JSLAPTOP> <006e01c7ca53$edcd2790$81fde004@JSLAPTOP> <46A02737.5080805@gmail.com> <004c01c7cd82$1b2ee850$d4fce004@JSLAPTOP> Message-ID: <46A54DF8.4040907@gmail.com> Tiger12506 wrote: >>> If the module has been imported before your code is run, it will be the >>> library module (very important if working in IDLE which importants many >>> modules, for example). >>> > > >> So... how does IDLE go about importanting a module? ;) >> > > It's not *how* IDLE imports the module, but that fact that IDLE imports the > module before his script would be executed. For example: > Actually I was just teasing you about saying 'IDLE, which _importants_ many modules' instead of 'imports.' -Luke From rabidpoobear at gmail.com Tue Jul 24 02:57:57 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 23 Jul 2007 19:57:57 -0500 Subject: [Tutor] Generators In-Reply-To: <029001c7cd91$72ac6080$d4fce004@JSLAPTOP> References: <002901c7cd81$ae8e8700$5f01a8c0@dcsoftware.local> <029001c7cd91$72ac6080$d4fce004@JSLAPTOP> Message-ID: <46A54E95.1040409@gmail.com> Tiger12506 wrote: >> I am new to Python but not new to programming languages. I have seen this >> "while 1" a lot. In fact in other languages I would expect "while 1" to >> be >> the same as "while TRUE". I have used that in other languages, but in the >> definition below I would expect the "yield b..." to continue on until a >> "break". So the question is, how does this work without going into an >> infinite loop without a break? >> >> Jeff >> > > while 1: and while TRUE: mean the same thing. > The thing is - it is an infinite loop. This should be while True: not while TRUE: unless you set TRUE = True beforehand, since Python is case-sensitive. -Luke From bgailer at alum.rpi.edu Tue Jul 24 03:21:08 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 23 Jul 2007 18:21:08 -0700 Subject: [Tutor] How to determine if every character in one string isinanother string? In-Reply-To: References: <16651e80707221748m210086b1qe5cdcb8ea1d8d495@mail.gmail.com> <78b3a9580707231346i387d497l16faf1e8ff5b7b2f@mail.gmail.com> Message-ID: <46A55404.5000808@alum.rpi.edu> Alan Gauld wrote: > "wesley chun" wrote > > >> the solutions using LCs above are great when it comes to an >> expressive >> piece of code in a one-liner, but i feel there's a waste of >> time/memory. the use of GEs is better, but it still has to iterate >> over the entire string when i don't feel that it should be necessary >> > > One of my only peeves with LCs is that they always iterate to the end, > I'd like an optional extra 'until' clause, like: > > lst = [n for n in veryBigSequence if someTest(n) until anotherTest(n)] > > This would act as usual until the final expression was true at which > point it would stop iterating. > How about: lst = [n for n in itertools.takewhile(anotherTest(), veryBigSequence] if someTest(n)] # reverse the logic of anotherTest > If I could find the time/inclination I might even try throwing it in > as > a PEP sometime... > > I don't think it would break much old code because (a) its an optional > extra at the end of the LC and (b) 'until' isn't used in Python so > far... > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From sebastien at solutions-linux.org Tue Jul 24 02:38:13 2007 From: sebastien at solutions-linux.org (Sebastien) Date: Mon, 23 Jul 2007 19:38:13 -0500 Subject: [Tutor] Integrate content of rss file in static web pages with python Message-ID: <90135c19ba1bb7e9978b62959022c0f8@localhost> Hi, I have this website (http://solutions-linux.org/) and I have a little news section on the right side. Presently the pages are just static html pages, but I would like to do a little rss file to put the news in it and then do a little script that puts them on the pages with the right markup. I never worked with rss, but I know basics of xml, so I don't think there is any problem there. The part that gets me wondering is how to glue the rss to the html files. I worked a little bit with PHP in the past and I'm now learning Python. I think the normal way of doing that would be to do a CGI script in whatever language I prefer (my server offers me all the popular ones: perl, python, php ...). It doesn't need a lot of speed, because the site just has a couple of pages. But how exactly am I supposed to do that? I would prefer using python do to that it's if a good choice. I read a couple of python examples with the CGI module on how to deal with forms, but only how to create a new page entirely with cgi and python, not how to change only a part on an already existing page. Thanks in advance! Seb From kent37 at tds.net Tue Jul 24 04:30:14 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 23 Jul 2007 22:30:14 -0400 Subject: [Tutor] How to determine if every character in one string is inanother string? In-Reply-To: <78b3a9580707231346i387d497l16faf1e8ff5b7b2f@mail.gmail.com> References: <16651e80707221748m210086b1qe5cdcb8ea1d8d495@mail.gmail.com> <78b3a9580707231346i387d497l16faf1e8ff5b7b2f@mail.gmail.com> Message-ID: <46A56436.8080308@tds.net> wesley chun wrote: > from string import printable as prglobal > def printable(s): > prlocal = prglobal > for x in s: > if x not in prlocal: > return False > return True > > the solutions using LCs above are great when it comes to an expressive > piece of code in a one-liner, but i feel there's a waste of > time/memory. the use of GEs is better, but it still has to iterate > over the entire string when i don't feel that it should be necessary > as per my example. anyway, just my $0.02! not the shortest, but > hopefully the fastest! any() and all() also short-circuit, and they move the iteration out of Python into the C runtime. My guess is the solutions with any() and all() and equivalent hoisting of string.printable will be faster than yours, but I don't want to take the time to check ATM...I would also try using set(string.printable) instead of string.printable... Anyone feel like spending some time with timeit? Otherwise we're just guessing anyway. Kent From dperlman at wisc.edu Tue Jul 24 07:07:30 2007 From: dperlman at wisc.edu (David Perlman) Date: Tue, 24 Jul 2007 00:07:30 -0500 Subject: [Tutor] Regex Ordering In-Reply-To: <20070723162930.GA1563@ayn.mi.celestial.com> References: <429b380e0707230800o7adc73e1uf8c38cdc23693477@mail.gmail.com> <20070723162930.GA1563@ayn.mi.celestial.com> Message-ID: <8C59DAF8-F8DC-4E23-9C5A-FA4CB5CB222C@wisc.edu> Then maybe you could write a regex that matches every regex that does not match itself. ha! sorry, couldn't resist. On Jul 23, 2007, at 11:29 AM, Bill Campbell wrote: > On Mon, Jul 23, 2007, James Hartley wrote: >> On 7/23/07, Shidan wrote: >>> I'm looking for a Python module that provides methods for ordering >>> regexes based on >>> how general they are ( how much they match). Do I have to write it >> >> Your question is relative. Classifying which regular expression is >> more general depends upon the other regular expressions used in >> comparison along with the specific input. As you change input & >> regular expressions, the ordering will change. > > As a first cut, one might sort the regular expression strings in > reverse order such that the longer strings are tested first. > > Bill > -- > INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC > URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way > FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) > 236-1676 > > Virtually everything is under federal control nowadays except the > federal budget. > -- Herman E. Talmadge, 1975 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- -dave---------------------------------------------------------------- All I ask is that the kind of unsolvable that it turns out to be has respectable precedents. -Jerry Fodor From alan.gauld at btinternet.com Tue Jul 24 08:30:24 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 24 Jul 2007 07:30:24 +0100 Subject: [Tutor] Integrate content of rss file in static web pages withpython References: <90135c19ba1bb7e9978b62959022c0f8@localhost> Message-ID: "Sebastien" wrote > I read a couple of python examples with the CGI module on how > to deal with forms, but only how to create a new page entirely > with cgi and python, not how to change only a part on an > already existing page. CGI always generates new pages. It has to because it is returning a new page to the browser. But you can fake it quite easily by using something like: imprt cgi print ''' ......... ''' if specialCondition() print '''

Optional HTML here as required''' else: print '''

Default content instead...''' print '''

And the rest of the page goes here.... ''' HTH, Alan G. From wescpy at gmail.com Tue Jul 24 10:34:34 2007 From: wescpy at gmail.com (wesley chun) Date: Tue, 24 Jul 2007 01:34:34 -0700 Subject: [Tutor] How to determine if every character in one string is inanother string? In-Reply-To: <46A56436.8080308@tds.net> References: <16651e80707221748m210086b1qe5cdcb8ea1d8d495@mail.gmail.com> <78b3a9580707231346i387d497l16faf1e8ff5b7b2f@mail.gmail.com> <46A56436.8080308@tds.net> Message-ID: <78b3a9580707240134y19f0b0fbtff7c6b9c3f5592c1@mail.gmail.com> > any() and all() also short-circuit, and they move the iteration out of > Python into the C runtime. My guess is the solutions with any() and > all() and equivalent hoisting of string.printable will be faster than > yours, but I don't want to take the time to check ATM...I would also try > using set(string.printable) instead of string.printable... if they do, yeah, that'll be faster since it'll run in C. you're probably also right about set since it doesn't have to "look into a string" to see whether it has a character or not. (this is the same as the advantages that a hash table has over an array.). > Anyone feel like spending some time with timeit? Otherwise we're just > guessing anyway. i don't have any time myself either (getting ready for OSCON talk), but i'm not sure what terry's OP was about... looking for a well-written piece of code, a faster-performing snippet, or both? i think he was just unsatissfied with his 1st attempt. -- 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 amitsaxena69 at gmail.com Tue Jul 24 12:51:28 2007 From: amitsaxena69 at gmail.com (Amit Saxena) Date: Tue, 24 Jul 2007 16:21:28 +0530 Subject: [Tutor] Pop Up Window Problem Message-ID: <82c58b390707240351v12d99e01l4fd6a4adc84a3884@mail.gmail.com> Hi, This is Amit Saxena here, I am working as a Senior QA Engineer with Ketera Technologies, Bangalore. I am trying to automate a Test Scenario using Python 2.5, in that particular scenario there is a Pop Up window which i am not able to handle, can you please help in that. For automation purposes, i am using PAMIE, ctypes and pywin32 libraries. Waiting for a reply. Thanks and Regards, Amit Saxena Senior QA Engineer Ketera Direct: +91 4199 5028 Mobile: +91 99001 18641 asaxena at ketera.com ? Visit us at http://www.ketera.com ? Watch the demo at http://www.ketera.com/resources/demos.html -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070724/c5de08e1/attachment.html From doug at foruminfosystems.com Tue Jul 24 13:24:52 2007 From: doug at foruminfosystems.com (Doug Glenn) Date: Tue, 24 Jul 2007 07:24:52 -0400 Subject: [Tutor] Python program design In-Reply-To: <031801c7cd95$9d63e7e0$d4fce004@JSLAPTOP> References: <031801c7cd95$9d63e7e0$d4fce004@JSLAPTOP> Message-ID: On 7/23/07, Tiger12506 wrote: > > The line should be > s = getsize(join(root, name)) > > which will print the file size for each "name in files" I got it a bit later. It didn't like me trying to apply it in a print statement but if I assigned it first and the printed it, no issue. > You may wish to build a dict inside your dict. > > {(discID, discLbl): {'dir': '...', > 'filename': '...", > etc. That was my thinking also. I just don't know enough about databases to know if I should shove the data raw into the DB or do some sorting first. > I don't know how you want to use it, but keeping the root directory is not > very useful. If you ever want to transfer your files to another computer > If I were cataloging hard drives I would tend to agree. But this is for removable media and backups so "anything goes", especially since I would like to GPL it later and noobs will be using it so I can't make assumptions on their behavior :) I may stick everything in a sub directory to help organize it, but using my CD creator program I just tend to drag and drop them as I see them. Thanks for the input! -- Doug Glenn FORUM Information Systems, LLC http://foruminfosystems.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070724/536489c0/attachment.html From kent37 at tds.net Tue Jul 24 13:37:45 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Jul 2007 07:37:45 -0400 Subject: [Tutor] Pop Up Window Problem In-Reply-To: <82c58b390707240351v12d99e01l4fd6a4adc84a3884@mail.gmail.com> References: <82c58b390707240351v12d99e01l4fd6a4adc84a3884@mail.gmail.com> Message-ID: <46A5E489.4010907@tds.net> Amit Saxena wrote: > I am trying to automate a Test Scenario using Python 2.5, in that > particular scenario there is a Pop Up window which i am not able to > handle, can you please help in that. > > For automation purposes, i am using PAMIE, ctypes and pywin32 libraries. More details might be helpful. What kind of window? What is the application? In what way are you not able to handle the window? What have you tried? Kent From kent37 at tds.net Tue Jul 24 13:48:54 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Jul 2007 07:48:54 -0400 Subject: [Tutor] sorting objects in lists by 2 attr In-Reply-To: <1ba302070707231653x3228fb35x24721d18be3a8179@mail.gmail.com> References: <1ba302070707231653x3228fb35x24721d18be3a8179@mail.gmail.com> Message-ID: <46A5E726.3090104@tds.net> Philippe Niquille wrote: > Tanks a mill! > > I don't know why I searched so far.. > > Anyway, I wrapped the django custom SQL call and built a nice dictionary > out of the resulting rows (which is similar to querysets). > See http://www.djangosnippets.org/snippets/207/ > for details. That code could be much simpler. You wrote, fdicts = [] for row in rows: i = 0 cur_row = {} for key in qkeys: cur_row[key] = row[i] i = i+1 fdicts.append(cur_row) So qkeys is a list of names for the values in each row. You can convert the list of names and row into a dict with cur_row = dict(zip(qkeys, row)) zip(qkeys, row) converts the two list into a list of key, value pairs which can be used directly to create the dict. This is simple enough to use in a list comprehension, so the outer loop can be written as fdicts = [ dict(zip(qkeys, row)) for row in rows ] To answer your original question, the best way to sort on multiple attributes is to make a key function that returns a tuple of the desired attributes and provide that to sort. In Python 2.5, the function operator.attrgetter() will create the key function for you, so you can write import operator newscore.sort(key=operator.attrgetter('score', 'owner')) or whatever the correct attributes are. In older Python attrgetter only takes a single argument so you have to create the key function yourself: def key_func(item): return (item.score, item.owner) newscore.sort(key=key_func) Kent From amitsaxena69 at gmail.com Tue Jul 24 13:50:07 2007 From: amitsaxena69 at gmail.com (Amit Saxena) Date: Tue, 24 Jul 2007 17:20:07 +0530 Subject: [Tutor] Pop Up Window Problem In-Reply-To: <46A5E489.4010907@tds.net> References: <82c58b390707240351v12d99e01l4fd6a4adc84a3884@mail.gmail.com> <46A5E489.4010907@tds.net> Message-ID: <82c58b390707240450t2b05bbf1t97ff1a738a240bce@mail.gmail.com> It is a Java Web Application, and its basically a JSP Page which gets dynamically populated through the Pick Helper Tag. This is the initial level script i had created, you can have a look at it: # To use Pamie you must first create a new script or text file that you can saveas mytest.py. # This will import the class files so you can use it's methods #from ctypes import windll, c_string #import elementtree.ElementTree as ET from cPAMIE import PAMIE #from cModalPopUp import handlePopup # create a new instance of the PAMIE object ie = PAMIE( ) # Navigates to the Application if ie.navigate("http://localhost.ketera.com:8080/kcm/HomePage/HomePage.do"): print "URL Clicked" ie.textBoxSet("username", "test at ketera.com" ) #control name, value ie.textBoxSet("password", "abc123" ) #control name, value # Now Submit the form. if ie.imageClick("loginButton" ): print "Image Clicked" else: print "Image not Present" if ie.navigate(" http://localhost.ketera.com:8080/kcm/ListCatalogProcess/ViewProcessListCreateProcess.do" ): print "URL Clicked" ie.listBoxSelect("buyer", "AU Office") ie.imageClick("search-page.gif") on clicking this image, i get that Pop Up window and now i m in a fix what to do next as the browser is not able to identify the window, I tried the cModal Popup library but no help Amit On 7/24/07, Kent Johnson wrote: > > Amit Saxena wrote: > > > I am trying to automate a Test Scenario using Python 2.5, in that > > particular scenario there is a Pop Up window which i am not able to > > handle, can you please help in that. > > > > For automation purposes, i am using PAMIE, ctypes and pywin32 libraries. > > More details might be helpful. What kind of window? What is the > application? In what way are you not able to handle the window? What > have you tried? > > Kent > -- Amit Saxena Senior QA Engineer Ketera Direct: +91 4199 5028 Mobile: +91 99001 18641 asaxena at ketera.com ? Visit us at http://www.ketera.com ? Watch the demo at http://www.ketera.com/resources/demos.html -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070724/f28b5d67/attachment.htm From kent37 at tds.net Tue Jul 24 13:52:35 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Jul 2007 07:52:35 -0400 Subject: [Tutor] Regex Ordering In-Reply-To: <429b380e0707230800o7adc73e1uf8c38cdc23693477@mail.gmail.com> References: <429b380e0707230800o7adc73e1uf8c38cdc23693477@mail.gmail.com> Message-ID: <46A5E803.1070604@tds.net> Shidan wrote: > I'm looking for a Python module that provides methods for ordering > regexes based on > how general they are ( how much they match). Do I have to write it > myself or does something exist already. What do you mean by "how much they match" ? If you mean, what is the entire set of strings that is matched by the regex, then you have a hard problem. If you mean, which one matches more of one specific string, or a specific set of strings, then you can easily test each regex and pick the one with the longest match(es). Kent From kent37 at tds.net Tue Jul 24 14:11:59 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Jul 2007 08:11:59 -0400 Subject: [Tutor] Generators In-Reply-To: <029001c7cd91$72ac6080$d4fce004@JSLAPTOP> References: <002901c7cd81$ae8e8700$5f01a8c0@dcsoftware.local> <029001c7cd91$72ac6080$d4fce004@JSLAPTOP> Message-ID: <46A5EC8F.1040605@tds.net> Tiger12506 wrote: >> I am new to Python but not new to programming languages. I have seen this >> "while 1" a lot. In fact in other languages I would expect "while 1" to >> be >> the same as "while TRUE". The predefined constants True and False were not added to Python until version 2.3. Before that it was common to write 'while 1'. In fact 'while 1' is more efficient, too. Compare: In [5]: dis.dis(compile('while 1: pass', '', 'exec')) 1 0 SETUP_LOOP 3 (to 6) >> 3 JUMP_ABSOLUTE 3 >> 6 LOAD_CONST 0 (None) 9 RETURN_VALUE In [6]: dis.dis(compile('while True: pass', '', 'exec')) 1 0 SETUP_LOOP 12 (to 15) >> 3 LOAD_NAME 0 (True) 6 JUMP_IF_FALSE 4 (to 13) 9 POP_TOP 10 JUMP_ABSOLUTE 3 >> 13 POP_TOP 14 POP_BLOCK >> 15 LOAD_CONST 0 (None) 18 RETURN_VALUE 'while 1' is optimized to just a jump - the compiler recognizes that the test is not needed and skips it. 'while True' requires looking up the value of the name 'True' and testing it. Old habits die hard, especially when they are more efficient and require less typing :-) Kent From Dean.Gardner at barco.com Tue Jul 24 14:37:43 2007 From: Dean.Gardner at barco.com (Gardner, Dean) Date: Tue, 24 Jul 2007 14:37:43 +0200 Subject: [Tutor] Text matching and replacing Message-ID: Hi I have implemented some functionality that now forces test records to be stored against the product they were run against. This is fine however it was apparent that we needed to bring the legacy records in line with new format. So I wrote a script that went through each test record and appended the "Product Run: " field at the end of each test record. This works however I thought I could try and be a bit clever, as in some cases previously people have logged the product that the was run against in a comments field, and take the product name out of the comment field and place it in the ProductRun field. However I have got myself slightly confused as the best way to proceed. Here is my script and below a sample test record and what the record i am ultimately aiming for. I have changed the product names to something generic. The regular expression actually works and finds all instances of a test being run against a product but I am confused as to how I can then further process the information I will also take code critique as well. import os import re debug = False def writeUpdatedRecordsToFile(path,updated_records): for x,j in updated_records.iteritems(): f = open(path+x,"w") j.pop() for record in j: f.write(record) def findTestDirectories(path): os.chdir(path) directory_listing = os.listdir(os.getcwd()) test_record_directories = [] for directory in directory_listing: if "TestRecords" in directory: test_record_directories.append(directory) return test_record_directories def findProductFromComments(records_from_record_file): ''' Attempt to find products run against in the comment field if we find one. Write it to the newly created product run field ''' searchText = re.compile(r'(|||)', re.IGNORECASE) for record in records_from_record_file: if searchText.findall(record) !=[]: print record.split("\n\n") def amendProductField(dir): fileList = os.listdir(dir) currPath = os.getcwd()+"\\"+dir+"\\" dict_of_amended_records = {} list_of_amended_records = [] for file in fileList: if "CVS" in file: pass else: f = open(currPath+"\\"+file) if debug: print "opening %s for reading" %file fileContents = f.read() fileContents = fileContents.split("\n\n") findProductFromComments(fileContents) for record in fileContents: record+="\nProductRun:\n\n" list_of_amended_records.append(record) dict_of_amended_records[file] = list_of_amended_records list_of_amended_records = [] #writeUpdatedRecordsToFile(currPath,dict_of_amended_records) test_dir = findTestDirectories("C:\\Sandbox") if debug: print "Opening %s for amending" %test_dir[0] #for directory in test_dir: #amendProductField(directory) amendProductField(test_dir[0]) Current Record: TestedDate: 2005-04-30 TestId: 001591 Branch: xxxx Version: 3351 SpecId: Specification-0000-0966 Cpu: Pentium 4 OperatingSystem: Windows 2000 CpuCount: Single Tester: someone Comment: Run on MinutesTaken: 5 PassOrFail: Pass Desired Record: TestedDate: 2005-04-30 TestId: 001591 Branch: xxxx Version: 3351 SpecId: Specification-0000-0966 Cpu: Pentium 4 OperatingSystem: Windows 2000 CpuCount: Single Tester: someone Comment: Run on MinutesTaken: 5 PassOrFail: Pass Product: Dean Gardner DISCLAIMER: Unless indicated otherwise, the information contained in this message is privileged and confidential, and is intended only for the use of the addressee(s) named above and others who have been specifically authorized to receive it. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this message and/or attachments is strictly prohibited. The company accepts no liability for any damage caused by any virus transmitted by this email. Furthermore, the company does not warrant a proper and complete transmission of this information, nor does it accept liability for any delays. If you have received this message in error, please contact the sender and delete the message. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070724/3dbb19c9/attachment.html From ms at cerenity.org Tue Jul 24 15:46:00 2007 From: ms at cerenity.org (Michael Sparks) Date: Tue, 24 Jul 2007 14:46:00 +0100 Subject: [Tutor] Generators In-Reply-To: <46A5EC8F.1040605@tds.net> References: <002901c7cd81$ae8e8700$5f01a8c0@dcsoftware.local> <029001c7cd91$72ac6080$d4fce004@JSLAPTOP> <46A5EC8F.1040605@tds.net> Message-ID: <200707241446.01181.ms@cerenity.org> On Tuesday 24 July 2007 13:11, Kent Johnson wrote: > 'while 1' is optimized to just a jump - the compiler recognizes that the > test is not needed and skips it. 'while True' requires looking up the > value of the name 'True' and testing it. This may seem counter intuitive, but the reason for this (for anyone puzzled) is because True is a name for the value representing boolean true, rather than a keyword for the value. If it were a keyword for the value, then like "1" it could not change in value. However since it isn't, it can. For example, True can become false as the following demonstrates, so you do have to do those steps of looking up the value of the name "True" and test it: Python 2.5 (r25:51908, Nov 27 2006, 19:14:46) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> True = 10 >>> while True: ... print True ... True = True -1 ... 10 9 8 7 6 5 4 3 2 1 >>> Rebinding True to anything else is a bad idea, but doable :-) If you change True to "True" you get the same behaviour - python detects an immutable object in the condition and optimises it: >>> dis.dis(compile('while "True": pass', '', 'exec')) 1 0 SETUP_LOOP 3 (to 6) >> 3 JUMP_ABSOLUTE 3 >> 6 LOAD_CONST 0 (None) 9 RETURN_VALUE Regards, Michael From keridee at jayco.net Tue Jul 24 20:34:54 2007 From: keridee at jayco.net (Tiger12506) Date: Tue, 24 Jul 2007 13:34:54 -0500 Subject: [Tutor] Python program design References: <031801c7cd95$9d63e7e0$d4fce004@JSLAPTOP> Message-ID: <001d01c7ce21$5b5c80a0$f3fce004@JSLAPTOP> >> The line should be >> s = getsize(join(root, name)) >> >> which will print the file size for each "name in files" > > > I got it a bit later. It didn't like me trying to apply it in a print > statement but if I assigned it first and the printed it, no issue. This should give you no problem ~ print getsize(join(root, name)) If it does, copy/paste the error message >> You may wish to build a dict inside your dict. >> >> {(discID, discLbl): {'dir': '...', >> 'filename': '...", >> etc. > > > That was my thinking also. I just don't know enough about databases to > know > if I should shove the data raw into the DB or do some sorting first. No matter what DB you use, whether a high performance DB like SQL or just using pickle to write the dict to a file as is, you will want to keep the structure of the dict similar to how you will use it in your program. At least I would. Perhaps some will say that you want the dict structured so that feeding it into a DB engine is almost seamless (which depending on what structures the DB is capable of storing, may be lists or dicts, etc.) You will have to decide which is easiest for you. >> I don't know how you want to use it, but keeping the root directory is >> not >> very useful. If you ever want to transfer your files to another computer >> > > If I were cataloging hard drives I would tend to agree. But this is for > removable media and backups so "anything goes", EXACTLY! Anything goes. It is *very* possible for the drive letter of removeable media to change between plug - ins. For example, I have to USB flash drives that i plug in. They are assigned the first drive letter available, in the order that they appear. The next time, I plug the second flash drive in *first*, it is assigned the first drive letter this time! Keeping the root directory in this situation would be useless! You would be trying to access the files on the wrong flash drive! IF you were going to use it for hard drives, I would keep track of the root directory, but for removeable media, *forget it* and use the drive ID, disc lbl because they are more stable! JS From keridee at jayco.net Tue Jul 24 21:18:46 2007 From: keridee at jayco.net (Tiger12506) Date: Tue, 24 Jul 2007 14:18:46 -0500 Subject: [Tutor] Text matching and replacing References: Message-ID: <015201c7ce27$78b87770$f3fce004@JSLAPTOP> def findTestDirectories(path): os.chdir(path) directory_listing = os.listdir(os.getcwd()) ------------------ Change this to directory_listing = os.listdir(path) Why look up the current directory when you have *just* set what it is? ---------------- test_record_directories = [] for directory in directory_listing: if "TestRecords" in directory: test_record_directories.append(directory) -------------------------- This whole block could be turned into a list comprehension test_record directories = [di for di in directory_listing if "TestRecords" in di] ------------------------- return test_record_directories def findProductFromComments(records_from_record_file): ''' Attempt to find products run against in the comment field if we find one. Write it to the newly created product run field ''' searchText = re.compile(r'(|||)', re.IGNORECASE) --------------------------------------- Woah! Regular expression could use work. Try: re.compile(r'', re.IGNORECASE) This will match product #s 1-9 If you want to match all product numbers to infinity put a * after \d -------------------------------------- for record in records_from_record_file: if searchText.findall(record) !=[]: ----------------------------------- if searchText.findall(record): is sufficient --------------------------------- print record.split("\n\n") def amendProductField(dir): fileList = os.listdir(dir) currPath = os.getcwd()+"\\"+dir+"\\" -------------------- This could be currPath = os.path.join(os.getcwd(), dir) ------------------ dict_of_amended_records = {} list_of_amended_records = [] for file in fileList: if "CVS" in file: pass else: f = open(currPath+"\\"+file) --------------------------- And again ~ f = open(os.path.join(currPath,file)) -------------------------- if debug: print "opening %s for reading" %file fileContents = f.read() fileContents = fileContents.split("\n\n") findProductFromComments(fileContents) for record in fileContents: record+="\nProductRun:\n\n" list_of_amended_records.append(record) dict_of_amended_records[file] = list_of_amended_records list_of_amended_records = [] #writeUpdatedRecordsToFile(currPath,dict_of_amended_records) test_dir = findTestDirectories("C:\\Sandbox") if debug: print "Opening %s for amending" %test_dir[0] #for directory in test_dir: #amendProductField(directory) amendProductField(test_dir[0]) Current Record: TestedDate: 2005-04-30 TestId: 001591 Branch: xxxx Version: 3351 SpecId: Specification-0000-0966 Cpu: Pentium 4 OperatingSystem: Windows 2000 CpuCount: Single Tester: someone Comment: Run on MinutesTaken: 5 PassOrFail: Pass Desired Record: TestedDate: 2005-04-30 TestId: 001591 Branch: xxxx Version: 3351 SpecId: Specification-0000-0966 Cpu: Pentium 4 OperatingSystem: Windows 2000 CpuCount: Single Tester: someone Comment: Run on MinutesTaken: 5 PassOrFail: Pass Product: Dean Gardner DISCLAIMER: Unless indicated otherwise, the information contained in this message is privileged and confidential, and is intended only for the use of the addressee(s) named above and others who have been specifically authorized to receive it. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this message and/or attachments is strictly prohibited. The company accepts no liability for any damage caused by any virus transmitted by this email. Furthermore, the company does not warrant a proper and complete transmission of this information, nor does it accept liability for any delays. If you have received this message in error, please contact the sender and delete the message. Thank you. -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From titleistfour at gmail.com Tue Jul 24 22:10:20 2007 From: titleistfour at gmail.com (jay) Date: Tue, 24 Jul 2007 15:10:20 -0500 Subject: [Tutor] Logging module Message-ID: <7c25bb490707241310g3c888f44x20c02c4bde688d0b@mail.gmail.com> Hello, I'm trying to setup simple Syslog logging in python using the logging module. I would like to use a config file, but so far haven't been able to get the correct configuration. Actually, I don't get any warnings or errors, program runs fine, but nothing is logged anywhere. I have my syslog LOCAL6 setup to go to /var/log/scripts.log, and that worked fine during testing of the syslog module. But logging gives me more flexibility, I'd rather use that. Anyone with some experience using this module? The documentation, at least to me, is a bit confusing, and I haven't found a good example on the web yet. ---main.py--- #!/usr/bin/env python import logging, logging.config logging.config.fileConfig('logging.conf') log = logging.getLogger() log.info('here we go, testing logger') --- end main.py --- --- logging.conf --- [formatters] keys: detailed,simple [handlers] keys: console,syslog [loggers] keys: root [formatter_simple] format: %(name)s:%(levelname)s: %(message)s [formatter_detailed] format: %(name)s:%(levelname)s %(module)s:%(lineno)d: %(message)s [handler_console] class: StreamHandler args: [] formatter: simple [handler_syslog] class: handlers.SysLogHandler args: [('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_LOCAL6 ] formatter: detailed [logger_root] level: INFO handlers: syslog ---- end logging.conf --- Thanks for any help! jay -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070724/1a14eccb/attachment.htm From beanan.o.loughlin at gmail.com Wed Jul 25 00:40:19 2007 From: beanan.o.loughlin at gmail.com (Beanan O Loughlin) Date: Tue, 24 Jul 2007 23:40:19 +0100 Subject: [Tutor] location of points in a covariance matrix Message-ID: Hi all, I'm a meteorology postgrad working with python for the first time. I have found the location minimum in a large covariance matrix. this value corresponds to the covariance of two points on a latitude, longitude grid. I need to find a method to locate these two points on the lat,lon grid. this is the code i have used, where 'se' is a 3-D array of data >>> nt,nlat,nlon = shape(se) >>>nt,nlat,nlon # 3-D array of data taken 1464 times, over 41 latitudes and 58 longitudes (1464, 41, 58) >>> >>> >>>m=reshape(se,(nt,nlat*nlon)) # reshape to (time,latitude longitude data point) where 2378 = 41*58 >>> >>>shape(m) (1464,2378) >>> >>> >>>covmat=cov(m) # calculate covariance matrix >>> >>>shape(covmat) (2378,2378) >>>def min(R): U = triu(R) #just use one half of the diagonal matrix n = U.shape[0] U.flat[::n+1] = 1000000000.0 #give the diagonal elements a large value so they wont be selected k = argmin(U.flat) #find the min value of the flattened array i, j = divmod(k,n) #calculate the index of the minimum data return i, j, R[i,j] >>> >>> min(covmat) (7, 1914, -2.3016361721151051) so the minimum is found at (7,1914) in the covariance matrix and has a value of -2.3 This min point corresponds to the covariance between two 'lat,lon' data points in my (41,58) sample grid. Is there a way i can move back from my (2378,2378) covariance matrix to see where these two points are located on the (41, 58) grid? Thank you very much in advance B. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070724/1884bb5c/attachment.htm From charvey165 at yahoo.com Wed Jul 25 05:30:37 2007 From: charvey165 at yahoo.com (chris harvey) Date: Tue, 24 Jul 2007 20:30:37 -0700 (PDT) Subject: [Tutor] putting python to use Message-ID: <341583.66826.qm@web50908.mail.re2.yahoo.com> Hi, I am very very new to python language. if this is to simple im sorry. I have had linux mandrake for 2 weeks now and i have been learning. I got my apache server running to find it has no GUI. I was disapointed till i remembered i was learning python. I wondered if a python script could be used to make /combind the server start and the config file take info from the script. that make sense? something like. /usr/sbin/advxrun2.0 # starts server then open (path) apache.config for input ? you get the idea i think. im very new so be gental with me and thanks for any working code in advance. i dont want to cheet. i need to do it myself but i am a bit lost on the frontend. chris ____________________________________________________________________________________ Get the Yahoo! toolbar and be alerted to new email wherever you're surfing. http://new.toolbar.yahoo.com/toolbar/features/mail/index.php From nibudh at gmail.com Wed Jul 25 09:27:11 2007 From: nibudh at gmail.com (nibudh) Date: Wed, 25 Jul 2007 17:27:11 +1000 Subject: [Tutor] function declaration problems perhaps? Message-ID: <77f8f7c30707250027p2ec10c25u330734a96e79eeb2@mail.gmail.com> Hi list, I've just been writing a small script to parse some xml files and output tab separated values into a separate file. I was surprised to see that my function "processXML(fpart)" was failing with an error along the lines of "processXML not defined" I looked over my code (all 41 lines!) and couldn't find anything, then on a hunch i moved the def statement _above_ the rest of my code and hey presto it worked. I vaguely understand why this is happening, but can someone explain it to me. If this makes no sense then tell me that too :-) cheers, nibudh. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070725/5fd770cd/attachment.htm From alan.gauld at btinternet.com Wed Jul 25 10:37:47 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 25 Jul 2007 09:37:47 +0100 Subject: [Tutor] function declaration problems perhaps? References: <77f8f7c30707250027p2ec10c25u330734a96e79eeb2@mail.gmail.com> Message-ID: "nibudh" wrote > I looked over my code (all 41 lines!) and couldn't find anything, > then on a > hunch i moved the def statement _above_ the rest of my code and hey > presto > it worked. > > I vaguely understand why this is happening, but can someone explain > it to > me. Its pretty simple. Python processes the file top to bottom. If it comes upon a name that it doesn't recofgnise it generates an error. Thus: ############# print foo(42) def foo(x): return x * 2 ############## will generate an error because at the point where the print statement tries to execute foo(42), foo does not exist! This is one good reason to avoid putting executable code in the main body of a file but to always wrap it in a function like so: ############## def main() print foo(42) def foo(x): return x * 2 if __name__ == "__main__": main() ############### Now the code doesn't get executed until the last line of the file by which time all definitions have been executed and the program will work correctly. This also makes the module inherently more reusable since it can be imported without the main code being executed (the purpose of the if expression.) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From purdeaandrew at gmail.com Wed Jul 25 10:40:52 2007 From: purdeaandrew at gmail.com (Andrew Purdea) Date: Wed, 25 Jul 2007 11:40:52 +0300 Subject: [Tutor] comparing lists, __lt__ and __gt__ Message-ID: Hello! I can see that lists have implemented these methods in jython.. But i can not find any documentation on this. It looks like python compares each element, and and when it finds a difference, it returns. Where can i find documenation on this? Will this behaviour remain in python for future releases? Thanks Regards, Andrew -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070725/4775ff2d/attachment.htm From kent37 at tds.net Wed Jul 25 13:27:28 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Jul 2007 07:27:28 -0400 Subject: [Tutor] function declaration problems perhaps? In-Reply-To: References: <77f8f7c30707250027p2ec10c25u330734a96e79eeb2@mail.gmail.com> Message-ID: <46A733A0.5090007@tds.net> Alan Gauld wrote: > "nibudh" wrote > >> I looked over my code (all 41 lines!) and couldn't find anything, >> then on a >> hunch i moved the def statement _above_ the rest of my code and hey >> presto >> it worked. >> >> I vaguely understand why this is happening, but can someone explain >> it to >> me. > > Its pretty simple. > Python processes the file top to bottom. If it comes upon > a name that it doesn't recofgnise it generates an error. A key concept to understand is that def (and class and import) are executable statements that have no effect until they are actually executed. The effect of executing a def is to create a function object and bind it to the name given in the def. Before the def is executed, the name is not bound to anything and can't be used. This is a shift from less-dynamic languages such as Java and C, where functions exist from the time a module is loaded. One consequence of executable def is that you can, for example, have conditional defs: if has_foo: def bar(): # Implementation of bar using foo else: def bar(): # Implementation of bar without using foo Similar techniques can be used with imports. This can be handy for writing code that is backwards compatible. For example here is some code that tries to import ElementTree from its Python 2.5 library package and from the effbot distribution: try: import xml.etree.ElementTree as ET # in python >=2.5 except ImportError: try: import elementtree.ElementTree as ET # effbot's pure Python module except ImportError: raise ImportError("Can't import ElementTree") If this code successfully executes, the ElementTree module will be available as ET. Kent From kent37 at tds.net Wed Jul 25 13:59:51 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Jul 2007 07:59:51 -0400 Subject: [Tutor] Logging module In-Reply-To: <7c25bb490707241310g3c888f44x20c02c4bde688d0b@mail.gmail.com> References: <7c25bb490707241310g3c888f44x20c02c4bde688d0b@mail.gmail.com> Message-ID: <46A73B37.8030500@tds.net> jay wrote: > Hello, > > I'm trying to setup simple Syslog logging in python using the logging > module. I would like to use a config file, but so far haven't been able > to get the correct configuration. Actually, I don't get any warnings or > errors, program runs fine, but nothing is logged anywhere. I have my > syslog LOCAL6 setup to go to /var/log/scripts.log, and that worked fine > during testing of the syslog module. But logging gives me more > flexibility, I'd rather use that. > > Anyone with some experience using this module? The documentation, at > least to me, is a bit confusing, and I haven't found a good example on > the web yet. I haven't used logging config files, but I don't see anything obviously wrong here. A couple of ideas to try: - make sure logging.conf can be found by print os.path.exists('logging.conf') - turn on console logging in the config file and see if that works - try to configure the syslog handler in code instead of in a file, then translate the successful configuration to a file. Kent > > ---main.py--- > #!/usr/bin/env python > > import logging, logging.config > > logging.config.fileConfig('logging.conf') > > log = logging.getLogger() > log.info('here we go, testing logger') > --- end main.py --- > > --- logging.conf --- > [formatters] > keys: detailed,simple > > [handlers] > keys: console,syslog > > [loggers] > keys: root > > [formatter_simple] > format: %(name)s:%(levelname)s: %(message)s > > [formatter_detailed] > format: %(name)s:%(levelname)s %(module)s:%(lineno)d: %(message)s > > [handler_console] > class: StreamHandler > args: [] > formatter: simple > > [handler_syslog] > class: handlers.SysLogHandler > args: [('localhost', handlers.SYSLOG_UDP_PORT), > handlers.SysLogHandler.LOG_LOCAL6 ] > formatter: detailed > > [logger_root] > level: INFO > handlers: syslog > > ---- end logging.conf --- > > Thanks for any help! > > jay > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From Dean.Gardner at barco.com Wed Jul 25 14:11:10 2007 From: Dean.Gardner at barco.com (Gardner, Dean) Date: Wed, 25 Jul 2007 14:11:10 +0200 Subject: [Tutor] Text matching and replacing In-Reply-To: References: Message-ID: Cheers for the critique I'll take you points on board .....especially this schoolboy error def findTestDirectories(path): os.chdir(path) directory_listing = os.listdir(os.getcwd()) ------------------ Change this to directory_listing = os.listdir(path) Why look up the current directory when you have *just* set what it is? -------------------------------------------------------- One thing to note about the re expression is that the products are not these were just substitutes. In reality these are product names with no commonality e.g. ('baked beans'|'tuna'|'salad') So with that in mind is the way I have set the re way the best way or is there an another more pythonic way. As an aside I don't believe there were any tips in there to help solve the problems I have...again any help would be warmly appreciated. Cheers Dean Message: 3 Date: Tue, 24 Jul 2007 14:18:46 -0500 From: "Tiger12506" Subject: Re: [Tutor] Text matching and replacing To: Message-ID: <015201c7ce27$78b87770$f3fce004 at JSLAPTOP> Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original def findTestDirectories(path): os.chdir(path) directory_listing = os.listdir(os.getcwd()) ------------------ Change this to directory_listing = os.listdir(path) Why look up the current directory when you have *just* set what it is? ---------------- test_record_directories = [] for directory in directory_listing: if "TestRecords" in directory: test_record_directories.append(directory) -------------------------- This whole block could be turned into a list comprehension test_record directories = [di for di in directory_listing if "TestRecords" in di] ------------------------- return test_record_directories def findProductFromComments(records_from_record_file): ''' Attempt to find products run against in the comment field if we find one. Write it to the newly created product run field ''' searchText = re.compile(r'(|||)', re.IGNORECASE) --------------------------------------- Woah! Regular expression could use work. Try: re.compile(r'', re.IGNORECASE) This will match product #s 1-9 If you want to match all product numbers to infinity put a * after \d -------------------------------------- for record in records_from_record_file: if searchText.findall(record) !=[]: ----------------------------------- if searchText.findall(record): is sufficient --------------------------------- print record.split("\n\n") def amendProductField(dir): fileList = os.listdir(dir) currPath = os.getcwd()+"\\"+dir+"\\" -------------------- This could be currPath = os.path.join(os.getcwd(), dir) ------------------ dict_of_amended_records = {} list_of_amended_records = [] for file in fileList: if "CVS" in file: pass else: f = open(currPath+"\\"+file) --------------------------- And again ~ f = open(os.path.join(currPath,file)) -------------------------- if debug: print "opening %s for reading" %file fileContents = f.read() fileContents = fileContents.split("\n\n") findProductFromComments(fileContents) for record in fileContents: record+="\nProductRun:\n\n" list_of_amended_records.append(record) dict_of_amended_records[file] = list_of_amended_records list_of_amended_records = [] #writeUpdatedRecordsToFile(currPath,dict_of_amended_records) test_dir = findTestDirectories("C:\\Sandbox") if debug: print "Opening %s for amending" %test_dir[0] #for directory in test_dir: #amendProductField(directory) amendProductField(test_dir[0]) Current Record: TestedDate: 2005-04-30 TestId: 001591 Branch: xxxx Version: 3351 SpecId: Specification-0000-0966 Cpu: Pentium 4 OperatingSystem: Windows 2000 CpuCount: Single Tester: someone Comment: Run on MinutesTaken: 5 PassOrFail: Pass Desired Record: TestedDate: 2005-04-30 TestId: 001591 Branch: xxxx Version: 3351 SpecId: Specification-0000-0966 Cpu: Pentium 4 OperatingSystem: Windows 2000 CpuCount: Single Tester: someone Comment: Run on MinutesTaken: 5 PassOrFail: Pass Product: Dean Gardner DISCLAIMER: Unless indicated otherwise, the information contained in this message is privileged and confidential, and is intended only for the use of the addressee(s) named above and others who have been specifically authorized to receive it. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this message and/or attachments is strictly prohibited. The company accepts no liability for any damage caused by any virus transmitted by this email. Furthermore, the company does not warrant a proper and complete transmission of this information, nor does it accept liability for any delays. If you have received this message in error, please contact the sender and delete the message. Thank you. ------------------------------------------------------------------------ -------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > DISCLAIMER: Unless indicated otherwise, the information contained in this message is privileged and confidential, and is intended only for the use of the addressee(s) named above and others who have been specifically authorized to receive it. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this message and/or attachments is strictly prohibited. The company accepts no liability for any damage caused by any virus transmitted by this email. Furthermore, the company does not warrant a proper and complete transmission of this information, nor does it accept liability for any delays. If you have received this message in error, please contact the sender and delete the message. Thank you. From nibudh at gmail.com Wed Jul 25 16:05:38 2007 From: nibudh at gmail.com (nibudh) Date: Thu, 26 Jul 2007 00:05:38 +1000 Subject: [Tutor] function declaration problems perhaps? In-Reply-To: <46A733A0.5090007@tds.net> References: <77f8f7c30707250027p2ec10c25u330734a96e79eeb2@mail.gmail.com> <46A733A0.5090007@tds.net> Message-ID: <77f8f7c30707250705y5aec8e35vf4c9221fbc54725a@mail.gmail.com> Hi Kent and Alan, Thanks for the responses. It really got me thinking! To test what i thought i knew, i wrote a "hello world" script in perl and python. in perl this works: #!/usr/bin/env perl hello("World"); sub hello { print "Hello ". $_[0] . "\n"; } but in python: #!/usr/bin/env python hello('World') def hello(name): print "Hello" + name That doesn't. I have a vague recollection that ASP works in a similar way to python hence the "hunch" i had earlier but i could be wrong. It's been a while since i've done programming. I can see how the property of being executable (defs and imports) could be handy, but right now I'm still getting to grips with the language proper. Thanks again for the explanations and I'll keep them in mind as i experiment some more with python. nibudh. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070726/d5135979/attachment.htm From bgailer at alum.rpi.edu Wed Jul 25 16:15:42 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 25 Jul 2007 07:15:42 -0700 Subject: [Tutor] location of points in a covariance matrix In-Reply-To: References: Message-ID: <46A75B0E.2050107@alum.rpi.edu> Beanan O Loughlin wrote: > Hi all, I'm a meteorology postgrad working with python for the first time. > > I have found the location minimum in a large covariance matrix. this > value corresponds to the covariance of two points on a latitude, > longitude grid. > > I need to find a method to locate these two points on the lat,lon grid. Usually multi-dimensional arrays are stored in "row-major" order. So the subscripts of an array of shape 2,3,4 (planes, rows. columns) would look like: 1,1,1 1,1,2 1,1,3 1,1 4 1,2,1 1,2,2 1,2,3 1,2,4 1,3,1 1,3,2 1,3,3 1,3,4 2,1,1 2,1,2 2,1,3 2,1 4 2,2,1 2,2,2 2,2,3 2,2,4 2,3,1 2,3,2 2,3,3 2,3,4 When you reshape it to 2,12 the elements remain "in place", and the subscripts now are: 1,1 1,2 1,3 1,4 1,5 1,6 1,7 1,8 1,9 1,10 1,11 1,12 2,1 2,2 2,3 2,4 2,5 2,6 2,7 2,8 2,9 2,10 2,11 2,12 Is that enough of a hint? > > this is the code i have used, where 'se' is a 3-D array of data > > > >>> nt,nlat,nlon = shape(se) > >>>nt,nlat,nlon # 3-D array of data taken > 1464 times, over 41 latitudes and 58 longitudes > (1464, 41, 58) > >>> > >>> > >>>m=reshape(se,(nt,nlat*nlon)) # reshape to (time,latitude > longitude data point) where 2378 = 41*58 > >>> > >>>shape(m) > (1464,2378) > >>> > >>> > >>>covmat=cov(m) # calculate covariance matrix > >>> > >>>shape(covmat) > (2378,2378) > > >>>def min(R): > U = triu(R) #just use one half of > the diagonal matrix > n = U.shape[0] > U.flat[::n+1] = 1000000000.0 #give the diagonal elements a > large value so they wont be selected > k = argmin(U.flat) #find the min value of > the flattened array > i, j = divmod(k,n) #calculate the index of > the minimum data > return i, j, R[i,j] > > >>> > >>> min(covmat) > (7, 1914, -2.3016361721151051) > > so the minimum is found at (7,1914) in the covariance matrix and has a > value of - 2.3 > > This min point corresponds to the covariance between two 'lat,lon' > data points in my (41,58) sample grid. > > Is there a way i can move back from my (2378,2378) covariance matrix > to see where these two points are located on the (41, 58) grid? > > Thank you very much in advance > > B. > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From bgailer at alum.rpi.edu Wed Jul 25 16:27:32 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 25 Jul 2007 07:27:32 -0700 Subject: [Tutor] comparing lists, __lt__ and __gt__ In-Reply-To: References: Message-ID: <46A75DD4.5010706@alum.rpi.edu> Andrew Purdea wrote: > Hello! > I can see that lists have implemented these methods in jython.. > But i can not find any documentation on this. It looks like python > compares each element, and and when it finds a difference, it returns. > Where can i find documenation on this? In python 2.5 reference 3.4.1: *__lt__*( self, other) *__le__*( self, other) *__eq__*( self, other) *__ne__*( self, other) *__gt__*( self, other) *__ge__*( self, other) New in version 2.1. These are the so-called ``rich comparison'' methods, and are called for comparison operators in preference to __cmp__() below. The correspondence between operator symbols and method names is as follows: |xy| call |x.__ne__(y)|, |x>y| calls |x.__gt__(y)|, and |x>=y| calls |x.__ge__(y)|. These methods can return any value, but if the comparison operator is used in a Boolean context, the return value should be interpretable as a Boolean value, else a TypeError will be raised. By convention, |False| is used for false and |True| for true. There are no implied relationships among the comparison operators. The truth of |x==y| does not imply that |x!=y| is false. Accordingly, when defining __eq__(), one should also define __ne__() so that the operators will behave as expected. There are no reflected (swapped-argument) versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other's reflection, __le__() and __ge__() are each other's reflection, and __eq__() and __ne__() are their own reflection. Arguments to rich comparison methods are never coerced. A rich comparison method may return |NotImplemented| if it does not implement the operation for a given pair of arguments. > Will this behaviour remain in python for future releases? I certainly hope so. A LOT of programs would suffer if not. I certainly have not seen any PEPs that discuss replacing or eliminating these. -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From kent37 at tds.net Wed Jul 25 16:34:11 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Jul 2007 10:34:11 -0400 Subject: [Tutor] comparing lists, __lt__ and __gt__ In-Reply-To: References: Message-ID: <46A75F63.5060004@tds.net> Andrew Purdea wrote: > Hello! > I can see that lists have implemented these methods in jython.. > But i can not find any documentation on this. It looks like python > compares each element, and and when it finds a difference, it returns. > Where can i find documenation on this? Will this behaviour remain in > python for future releases? Good question! The only doc I can find on this behavior is this: http://docs.python.org/lib/comparisons.html which just says that the comparison operation exists. There doesn't seem to be any documentation on how comparison works with sequences. I think it is pretty safe to count on the current behaviour of < and > for lists. I'll put in a documentation bug on this - the meaning of these operations (and ==) should be explicit in the docs. Kent From alan.gauld at btinternet.com Wed Jul 25 16:49:29 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 25 Jul 2007 15:49:29 +0100 Subject: [Tutor] function declaration problems perhaps? References: <77f8f7c30707250027p2ec10c25u330734a96e79eeb2@mail.gmail.com> <46A733A0.5090007@tds.net> <77f8f7c30707250705y5aec8e35vf4c9221fbc54725a@mail.gmail.com> Message-ID: "nibudh" wrote > in perl this works: > > #!/usr/bin/env perl > hello("World"); > > sub hello { > print "Hello ". $_[0] . "\n"; > } Perl executes differently to Python in that it does a compilation stage before executing. Therefore Perl knows about all the function definitions prior to executing any code. Python compiles modules which it imports but not scripts which it executes. > I have a vague recollection that ASP works in a similar way to > python hence > the "hunch" i had earlier but i could be wrong. It's been a while > since i've > done programming. Most interpreted languages work this way. Even the original versions of C worked that way although I thiunk more recent (ANSI/ISO compliant?) versions no longer need the strict ordering, and Pascal also does it that way even though they are pure compiled languages. In the case of Pascal it is because Pascal is designed to be a single pass comilation language - which is why Borland's Object Pascal comiles so quickly in Delphi! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From titleistfour at gmail.com Wed Jul 25 16:36:24 2007 From: titleistfour at gmail.com (jay) Date: Wed, 25 Jul 2007 09:36:24 -0500 Subject: [Tutor] Logging module In-Reply-To: <46A73B37.8030500@tds.net> References: <7c25bb490707241310g3c888f44x20c02c4bde688d0b@mail.gmail.com> <46A73B37.8030500@tds.net> Message-ID: <7c25bb490707250736y5b5abcc3g2ed70b043e0d0458@mail.gmail.com> Thanks for the reply Kent. I found the problem. It was rather simple actually. I didn't have remote logging enabled for syslog. Even though I was logging to localhost, for some reason, it wouldn't work until I gave syslogd a -r at startup. Thanks jay On 7/25/07, Kent Johnson wrote: > > jay wrote: > > Hello, > > > > I'm trying to setup simple Syslog logging in python using the logging > > module. I would like to use a config file, but so far haven't been able > > to get the correct configuration. Actually, I don't get any warnings or > > errors, program runs fine, but nothing is logged anywhere. I have my > > syslog LOCAL6 setup to go to /var/log/scripts.log, and that worked fine > > during testing of the syslog module. But logging gives me more > > flexibility, I'd rather use that. > > > > Anyone with some experience using this module? The documentation, at > > least to me, is a bit confusing, and I haven't found a good example on > > the web yet. > > I haven't used logging config files, but I don't see anything obviously > wrong here. A couple of ideas to try: > - make sure logging.conf can be found by > print os.path.exists('logging.conf') > - turn on console logging in the config file and see if that works > - try to configure the syslog handler in code instead of in a file, then > translate the successful configuration to a file. > > Kent > > > > > ---main.py--- > > #!/usr/bin/env python > > > > import logging, logging.config > > > > logging.config.fileConfig('logging.conf') > > > > log = logging.getLogger() > > log.info('here we go, testing logger') > > --- end main.py --- > > > > --- logging.conf --- > > [formatters] > > keys: detailed,simple > > > > [handlers] > > keys: console,syslog > > > > [loggers] > > keys: root > > > > [formatter_simple] > > format: %(name)s:%(levelname)s: %(message)s > > > > [formatter_detailed] > > format: %(name)s:%(levelname)s %(module)s:%(lineno)d: %(message)s > > > > [handler_console] > > class: StreamHandler > > args: [] > > formatter: simple > > > > [handler_syslog] > > class: handlers.SysLogHandler > > args: [('localhost', handlers.SYSLOG_UDP_PORT), > > handlers.SysLogHandler.LOG_LOCAL6 ] > > formatter: detailed > > > > [logger_root] > > level: INFO > > handlers: syslog > > > > ---- end logging.conf --- > > > > Thanks for any help! > > > > jay > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > 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/20070725/4d8abdfd/attachment.html From kent37 at tds.net Wed Jul 25 17:59:24 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Jul 2007 11:59:24 -0400 Subject: [Tutor] function declaration problems perhaps? In-Reply-To: References: <77f8f7c30707250027p2ec10c25u330734a96e79eeb2@mail.gmail.com> <46A733A0.5090007@tds.net> <77f8f7c30707250705y5aec8e35vf4c9221fbc54725a@mail.gmail.com> Message-ID: <46A7735C.5070003@tds.net> Alan Gauld wrote: > "nibudh" wrote > >> in perl this works: >> >> #!/usr/bin/env perl >> hello("World"); >> >> sub hello { >> print "Hello ". $_[0] . "\n"; >> } > > > Perl executes differently to Python in that it does a compilation > stage > before executing. Therefore Perl knows about all the function > definitions > prior to executing any code. Python compiles modules which it imports > but not scripts which it executes. Python compiles all scripts to bytecode. For imported modules it saves the compiled bytecode in a .pyc file, but not for directly-executed scripts. However this has no bearing on the current thread; for both imported modules and executed scripts, a function must be defined before it can be called. Kent From bgailer at alum.rpi.edu Wed Jul 25 18:19:51 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 25 Jul 2007 09:19:51 -0700 Subject: [Tutor] function declaration problems perhaps? In-Reply-To: References: <77f8f7c30707250027p2ec10c25u330734a96e79eeb2@mail.gmail.com> <46A733A0.5090007@tds.net> <77f8f7c30707250705y5aec8e35vf4c9221fbc54725a@mail.gmail.com> Message-ID: <46A77827.5050000@alum.rpi.edu> Alan Gauld wrote: > "nibudh" wrote > > >> in perl this works: >> >> #!/usr/bin/env perl >> hello("World"); >> >> sub hello { >> print "Hello ". $_[0] . "\n"; >> } >> > > > Perl executes differently to Python in that it does a compilation > stage > before executing. Therefore Perl knows about all the function > definitions > prior to executing any code. Python compiles modules which it imports > but not scripts which it executes. > Not exactly. When Python imports a module that is new* it "compiles" it into bytecode. No recognition of names or objects takes place in this step. The bytecode is saved in a file with extension .pyc. Then Python executes the bytecode. Any function definitions that get executed create function objects that are available to subsequently executed code. Running a script does exactly the same thing, except the bytecode is not saved in a file. The bottom line is: a function definition must be executed before the function can be used. This is true of ANY Python object. *new means that no .pyc file exists or the modification time of the .py is more recent than that of the .pyc. > >> I have a vague recollection that ASP works in a similar way to >> python hence >> the "hunch" i had earlier but i could be wrong. It's been a while >> since i've >> done programming. >> > > Most interpreted languages work this way. > Even the original versions of C worked that way although I thiunk more > recent (ANSI/ISO compliant?) versions no longer need the strict > ordering, > and Pascal also does it that way even though they are pure compiled > languages. In the case of Pascal it is because Pascal is designed to > be a single pass comilation language - which is why Borland's Object > Pascal comiles so quickly in Delphi! > > -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From alan.gauld at btinternet.com Wed Jul 25 19:21:08 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 25 Jul 2007 18:21:08 +0100 Subject: [Tutor] function declaration problems perhaps? References: <77f8f7c30707250027p2ec10c25u330734a96e79eeb2@mail.gmail.com> <46A733A0.5090007@tds.net> <77f8f7c30707250705y5aec8e35vf4c9221fbc54725a@mail.gmail.com> <46A7735C.5070003@tds.net> Message-ID: "Kent Johnson" wrote >> Perl executes differently to Python in that it does a compilation >> stage before executing. Therefore Perl knows about all the function >> definitions prior to executing any code. Python compiles modules >> which it imports >> but not scripts which it executes. > > Python compiles all scripts to bytecode. Doh! Yes of course it does, stoopid me. > scripts. However this has no bearing on the current thread; for both > imported modules and executed scripts, a function must be defined > before > it can be called. Yes, the bearing is in the way that Perl compiles its code. Perl builds a name tree from the entire file before executing so it doesn't rely on the order of definition, Python seems to compile and execute code in a sequential manner and therefore relies on the sequence being right. I'm not sure if the undefined name errors come from the compilation or from the execution - does anyone else. I confess i've never looked deeply into how Python actually does its complile/execute cycle. Alan G. From kent37 at tds.net Wed Jul 25 20:14:48 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Jul 2007 14:14:48 -0400 Subject: [Tutor] function declaration problems perhaps? In-Reply-To: References: <77f8f7c30707250027p2ec10c25u330734a96e79eeb2@mail.gmail.com> <46A733A0.5090007@tds.net> <77f8f7c30707250705y5aec8e35vf4c9221fbc54725a@mail.gmail.com> <46A7735C.5070003@tds.net> Message-ID: <46A79318.7010705@tds.net> Alan Gauld wrote: > "Kent Johnson" wrote >> scripts. However this has no bearing on the current thread; for both >> imported modules and executed scripts, a function must be defined >> before >> it can be called. > > Yes, the bearing is in the way that Perl compiles its code. > Perl builds a name tree from the entire file before executing > so it doesn't rely on the order of definition, Python seems > to compile and execute code in a sequential manner and > therefore relies on the sequence being right. It executes code in a sequential manner, and names are bound during execution, not compilation. That is the key difference. I guess you could say that the compiler doesn't forward any names to the execution phase; when a module starts executing, the only names in the module namespace are ['__builtins__', '__doc__', '__file__', '__name__'] You can see this if you import a module whose contents are just print dir() Any other names must be bound by executing code. > I'm not sure if the undefined name errors come from the compilation > or from the execution - does anyone else. I confess i've never looked > deeply into how Python actually does its complile/execute cycle. They come from execution. See my separate post about def, etc. being executable statements. Kent From bgailer at alum.rpi.edu Wed Jul 25 20:35:32 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 25 Jul 2007 11:35:32 -0700 Subject: [Tutor] function declaration problems perhaps? In-Reply-To: References: <77f8f7c30707250027p2ec10c25u330734a96e79eeb2@mail.gmail.com> <46A733A0.5090007@tds.net> <77f8f7c30707250705y5aec8e35vf4c9221fbc54725a@mail.gmail.com> <46A7735C.5070003@tds.net> Message-ID: <46A797F4.2040502@alum.rpi.edu> Alan Gauld wrote: > "Kent Johnson" wrote > > >>> Perl executes differently to Python in that it does a compilation >>> stage before executing. Therefore Perl knows about all the function >>> definitions prior to executing any code. Python compiles modules >>> which it imports >>> but not scripts which it executes. >>> >> Python compiles all scripts to bytecode. >> > > Doh! Yes of course it does, stoopid me. > > >> scripts. However this has no bearing on the current thread; for both >> imported modules and executed scripts, a function must be defined >> before >> it can be called. >> > > Yes, the bearing is in the way that Perl compiles its code. > Perl builds a name tree from the entire file before executing > so it doesn't rely on the order of definition, Python seems > to compile and execute code in a sequential manner and > therefore relies on the sequence being right. > > I'm not sure if the undefined name errors come from the compilation > or from the execution - does anyone else. I confess i've never looked > deeply into how Python actually does its complile/execute cycle. > Compiling to bytecode raises syntax, deprecation and indentation errors. All others AKAIK are raised during execution > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From dkuhlman at rexx.com Wed Jul 25 20:35:53 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 25 Jul 2007 11:35:53 -0700 Subject: [Tutor] function declaration problems perhaps? In-Reply-To: References: <46A733A0.5090007@tds.net> <46A7735C.5070003@tds.net> Message-ID: <20070725183553.GA99683@cutter.rexx.com> On Wed, Jul 25, 2007 at 06:21:08PM +0100, Alan Gauld wrote: > > I'm not sure if the undefined name errors come from the compilation > or from the execution - does anyone else. I confess i've never looked > deeply into how Python actually does its complile/execute cycle. > A couple of points that might help: 1. In python it's all execution. Yes, Kent is right that Python is compiled to byte code. But, Alan is right to ignore that in trying to understand what happens. In particular, "class" and "def" statements execute, and when they do they bind a name to a class or function object in the local namespace. 2. It's all about look-up. Every variable reference causes Python to do a look-up in the current namespace (and enclosing namespaces, which is another subject). So, you need to ask whether at that time a given name has been created in the current namespace. Some examples ... The following works because func2 is not called (looked up) until func1 is executed, which is after func2 is defined: # Test 1 def func1(): func2() def func2(): print 'hello' func1() The following does *not* work, because func1 executes *before* func2 is defined, which means that func2 is needed before it is defined: # Test 2 def func1(): func2() func1() def func2(): print 'hello' And, (admittedly a rare case), the following does *not* work because when the statement "class A(B)" executes, B is not yet defined and is needed. This is an example of a name (B) being needed when another object (A) is defined (when the "class A(B)" is executed): # Test 3 class A(B): pass class B(object): pass By the way, this is an important and fundamental subject about Python. When I teach classes on Python, I always need to explain Python's execution model, and I always struggle with it. So, anything you can tell me that would help me teach this will be much appreciated. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From keridee at jayco.net Wed Jul 25 23:31:37 2007 From: keridee at jayco.net (Tiger12506) Date: Wed, 25 Jul 2007 16:31:37 -0500 Subject: [Tutor] Text matching and replacing References: Message-ID: <001d01c7cf03$326e00f0$d9fce004@JSLAPTOP> > Cheers for the critique I'll take you points on board .....especially > this schoolboy error It's not an error, really. It will work. Just... not intuitive Errors are things that do not work. > One thing to note about the re expression is that the products are not > these were just substitutes. In reality these are product > names with no commonality e.g. ('baked beans'|'tuna'|'salad') > > So with that in mind is the way I have set the re way the best way or is > there an another more pythonic way. I can't tell you one way or the other, (and I have a hard time determining that which makes something more or less pythonic) but i have noticed that using re expressions for fixed patterns like that (no special identifiers, etc.) is considered overkill. It is easier to use string methods. > As an aside I don't believe there were any tips in there to help solve > the problems I have...again any help would be warmly appreciated. However, the answer to your problem may be that you could rely on re expressions more than you are. What I like about regular expressions is the sheer power. Watch. import re teststring = """ Name: Jacob Schmidt Address: 1234 Fake Street City: Nowhere State: Indiana Zip Code: 14241 Name: Tiger Power Address: 4321 Mysterious Lane City: Jersey State: Indiana Zip Code: 14051-1390 """ pat = re.compile(r".*Name: (.*)\nAddress: (.*)\nCity: (.*)\nState: (.*)\nZip Code: (\d{5}(?:-\d{4})?).*") lst = pat.findall(teststring) for x in lst: print x ############################################## I'm sure this will help you some. :-) JS From keridee at jayco.net Thu Jul 26 00:03:01 2007 From: keridee at jayco.net (Tiger12506) Date: Wed, 25 Jul 2007 17:03:01 -0500 Subject: [Tutor] Logging module References: <7c25bb490707241310g3c888f44x20c02c4bde688d0b@mail.gmail.com><46A73B37.8030500@tds.net> <7c25bb490707250736y5b5abcc3g2ed70b043e0d0458@mail.gmail.com> Message-ID: <007601c7cf07$94fc9390$d9fce004@JSLAPTOP> > I found the problem. It was rather simple actually. I didn't have remote > logging enabled for syslog. Even though I was logging to localhost, for > some reason, it wouldn't work until I gave syslogd a -r at startup. > Thanks localhost is still remote, in that sockets are used to reach it. The implementation doesn't know the difference between 127.0.0.1 and 241.12.31.7 because it's easier than making a special case. JS From tmikk at umn.edu Wed Jul 25 22:48:04 2007 From: tmikk at umn.edu (Tonu Mikk) Date: Wed, 25 Jul 2007 15:48:04 -0500 Subject: [Tutor] Livewires Python course In-Reply-To: <20070725183553.GA99683@cutter.rexx.com> References: <46A733A0.5090007@tds.net> <46A7735C.5070003@tds.net> <20070725183553.GA99683@cutter.rexx.com> Message-ID: <46A7B704.2080509@umn.edu> Hello, I am at a very beginning on trying to learn Python. So far I have read first few chapters of Alan Gauld tutorials, and completed all the exercises of Guido van Robot (http://gvr.sourceforge.net/). I also began reading and coding the Livewires course exercises (http://www.livewires.org.uk/python/). I have gotten through the first 4 exercise, but got stuck with the last one where we build a robot game. The Livewires coding exercise uses modules that can be downloaded from their website. Would anyone be willing to install Livewires modules on their computer and assist me with the coding? I have specific questions, but the code could be difficult to read because it takes advantage of the imported modules. Thank you, Tonu From kent37 at tds.net Wed Jul 25 23:21:10 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Jul 2007 17:21:10 -0400 Subject: [Tutor] Livewires Python course In-Reply-To: <46A7B704.2080509@umn.edu> References: <46A733A0.5090007@tds.net> <46A7735C.5070003@tds.net> <20070725183553.GA99683@cutter.rexx.com> <46A7B704.2080509@umn.edu> Message-ID: <46A7BEC6.9050309@tds.net> Tonu Mikk wrote: > I also > began reading and coding the Livewires course exercises > (http://www.livewires.org.uk/python/). I have gotten through the first > 4 exercise, but got stuck with the last one where we build a robot > game. The Livewires coding exercise uses modules that can be downloaded > from their website. Would anyone be willing to install Livewires > modules on their computer and assist me with the coding? I have > specific questions, but the code could be difficult to read because it > takes advantage of the imported modules. Go ahead and post your questions. I have tried LiveWires (long ago!) and there may be others on the list. Kent From keridee at jayco.net Thu Jul 26 00:33:05 2007 From: keridee at jayco.net (Tiger12506) Date: Wed, 25 Jul 2007 17:33:05 -0500 Subject: [Tutor] function declaration problems perhaps? References: <46A733A0.5090007@tds.net> <46A7735C.5070003@tds.net> <20070725183553.GA99683@cutter.rexx.com> Message-ID: <015701c7cf0b$c8510010$d9fce004@JSLAPTOP> > By the way, this is an important and fundamental subject about > Python. When I teach classes on Python, I always need to explain > Python's execution model, and I always struggle with it. So, > anything you can tell me that would help me teach this will be much > appreciated. > > Dave The way I keep it clear is simple. If python needs the value of the name (it has to look it up) then it had better be defined. Otherwise ~ It doesn't matter! Think of it like assignment. x = 1 Does python need to know the current value of x? No. Then x does not have to be previously defined. f() Does python need to know the current value of f? Yes. It has to know that f is a function, and where the address is, etc. def f1(): f() Does python need to know the current value of f? No. Not until f1 is executed. Does this help? Only one rule to remember. ;-) ~Does python need to know the value of _this_ variable?~ JS From carroll at tjc.com Thu Jul 26 00:33:43 2007 From: carroll at tjc.com (Terry Carroll) Date: Wed, 25 Jul 2007 15:33:43 -0700 (PDT) Subject: [Tutor] How to determine if every character in one string is inanother string? In-Reply-To: <78b3a9580707240134y19f0b0fbtff7c6b9c3f5592c1@mail.gmail.com> Message-ID: On Tue, 24 Jul 2007, wesley chun wrote: > i don't have any time myself either (getting ready for OSCON talk), > but i'm not sure what terry's OP was about... looking for a > well-written piece of code, a faster-performing snippet, or both? i > think he was just unsatissfied with his 1st attempt. Exactly. It worked fine, but just seemed unpythonic to me. To use an analogy, not long ago I thought the best way to see if string X contained string Y was: if X.find(Y) != -1 Which works just fine. But another poster pointed out: if Y in X: Which is much more elegant/pythonic; but I didn't know you could do that with one string over another. For some reason, I had thought Y would have to exactly match one iterable element in X (e.g., one element of a list, or one character of a string) for that to work. Similarly, I was thinking that while that first attempt of mine worked, its apparent-to-me lameness suggested that there was a more idiomatic approach, and I wanted to find out what that was. Seeing the different approaches put forward by the various contributors was pretty interesting, though, I must say. From alan.gauld at btinternet.com Thu Jul 26 01:01:34 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Jul 2007 00:01:34 +0100 Subject: [Tutor] How to determine if every character in one string is inanother string? References: <78b3a9580707240134y19f0b0fbtff7c6b9c3f5592c1@mail.gmail.com> Message-ID: "Terry Carroll" wrote > if Y in X: > > Which is much more elegant/pythonic; but I didn't know you could do > that > with one string over another. For some reason, I had thought Y > would have > to exactly match one iterable element in X (e.g., one element of a > list, > or one character of a string) for that to work. FWIW I believe that 'in' did only work for single characters up until version 2.X so your ideas may have been based on experiences with an earlier Python version. Alan G. From rabidpoobear at gmail.com Thu Jul 26 01:10:22 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 25 Jul 2007 18:10:22 -0500 Subject: [Tutor] Livewires Python course In-Reply-To: <46A7BEC6.9050309@tds.net> References: <46A733A0.5090007@tds.net> <46A7735C.5070003@tds.net> <20070725183553.GA99683@cutter.rexx.com> <46A7B704.2080509@umn.edu> <46A7BEC6.9050309@tds.net> Message-ID: <46A7D85E.1070901@gmail.com> Kent Johnson wrote: > Tonu Mikk wrote: > >> I also >> began reading and coding the Livewires course exercises >> (http://www.livewires.org.uk/python/). I have gotten through the first >> 4 exercise, but got stuck with the last one where we build a robot >> game. The Livewires coding exercise uses modules that can be downloaded >> from their website. Would anyone be willing to install Livewires >> modules on their computer and assist me with the coding? I have >> specific questions, but the code could be difficult to read because it >> takes advantage of the imported modules. >> > > Go ahead and post your questions. I have tried LiveWires (long ago!) and > there may be others on the list. > Yes, but please next time you start a thread don't do it as a reply to another thread. My e-mail client threw your e-mail in with the 'function declaration problems' thread, which, if I had decided I didn't need to watch that thread anymore, would've resulted in your question getting overlooked. So overall your questions get less exposure that way, as well as breaking the threading of some mail clients. Let us know what specific questions you have. -Luke From kent37 at tds.net Thu Jul 26 01:25:48 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Jul 2007 19:25:48 -0400 Subject: [Tutor] How to determine if every character in one string is inanother string? In-Reply-To: References: <78b3a9580707240134y19f0b0fbtff7c6b9c3f5592c1@mail.gmail.com> Message-ID: <46A7DBFC.9080108@tds.net> Alan Gauld wrote: > "Terry Carroll" wrote > >> if Y in X: > > FWIW I believe that 'in' did only work for single characters up until > version 2.X so your ideas may have been based on experiences with > an earlier Python version. Yes, it changed in Python 2.3. Kent From tmikk at umn.edu Thu Jul 26 03:07:16 2007 From: tmikk at umn.edu (Tonu Mikk) Date: Wed, 25 Jul 2007 20:07:16 -0500 Subject: [Tutor] Livewires questions Message-ID: <46A7F3C4.5060002@umn.edu> Thanks for offering to help! I am following the Livewires exercise (attached file "5-robots.pdf"). I have gotten as far as page 7. Attached is also my code so far in robotsarecoming-teleport.py. Question 1. I was checking for collision of a robot and player first in this way: def check_collisions(): if player_x == robot_x+0.5 and player_y == robot_y+0.5: print 'You have been caught' This was working fine. I then tried to create a definition like this: def collided(): player_x == robot_x+0.5 and player_y == robot_y+0.5 and then check for collisions in this way (as in my code): def check_collisions(): if collided() == 1: print 'You have been caught' But this isn't printing out anything when the player and robot collide. I think I need to pass a variable of collided somehow, but I am not sure how. I also tried following: def check_collisions(): if collided() print 'You have been caught' but this isn't working either. Question 2. I created a if statement to check if the "t" key is pressed on a keyboard. If it is, I want the player to be placed on another location on the grid. However nothing happens when I press the "t" key. I am not sure why. Question 3. I think there is something strange about how I check that my player is within the boundaries of the grid. When it gets close to the edges of the grid, it can sometimes disappear past it even though I thought I had prevented this from happening. Thank you again for looking at this. The attached bit of code has taken a long time to create. I admire all who can program :-). Tonu -------------- next part -------------- A non-text attachment was scrubbed... Name: 5-robots.pdf Type: application/pdf Size: 89939 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070725/75d75458/attachment-0001.pdf -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: robotsarecoming-teleport.py Url: http://mail.python.org/pipermail/tutor/attachments/20070725/75d75458/attachment.asc From rabidpoobear at gmail.com Thu Jul 26 05:14:45 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 25 Jul 2007 22:14:45 -0500 Subject: [Tutor] Livewires questions In-Reply-To: <46A7F3C4.5060002@umn.edu> References: <46A7F3C4.5060002@umn.edu> Message-ID: <46A811A5.7040806@gmail.com> Tonu Mikk wrote: > Thanks for offering to help! I am following the Livewires exercise > (attached file "5-robots.pdf"). I have gotten as far as page 7. > Attached is also my code so far in robotsarecoming-teleport.py. > Question 1. I was checking for collision of a robot and player first > in this way: > > def check_collisions(): > if player_x == robot_x+0.5 and player_y == robot_y+0.5: > print 'You have been caught' > > This was working fine. I then tried to create a definition like this: > > def collided(): > player_x == robot_x+0.5 and player_y == robot_y+0.5 I haven't looked at your code yet, but this doesn't seem like a very good way to check for collisions, unless the player moves on a grid of 0.5 at a time, and you guarantee that you can check if the player collided with a robot on every move. even so, doesn't this only collide with the robot if the player hits the bottom-right corner? > > and then check for collisions in this way (as in my code): > def check_collisions(): > if collided() == 1: > print 'You have been caught' The reason this isn't working is because your function 'collided' doesn't return anything. Consider this example: def foo(): "Hello" What do you expect to happen when you call foo()? 1) "Hello" won't be printed, because there is no 'print' statement here. 2) "Hello" won't be returned, because you have no return statement. So what does happen, then? well, foo() creates a string in memory with "Hello" stored in it, but there are no variables referenced to it, so nothing happens. Basically, the only thing foo() accomplishes is that it wastes memory until "Hello" is garbage collected and deleted. Now consider this: def foo(): a == b and b == c What do you expect to happen here? It's similar to the above example. a == b is evaluated. if it's true, b == c is evaluated. if it's true, then the value True is there, but it's not assigned to any variables, so it just disappears. Can you see now why your code doesn't work? Here's an example of a function you'd want to look at to give you an idea of what to do: def foo(): return a < b > But this isn't printing out anything when the player and robot > collide. I think I need to pass a variable of collided somehow, but I > am not sure how. I also tried following: > def check_collisions(): > if collided() > print 'You have been caught' > but this isn't working either. This is because collided() is not returning anything. Try this: print collided() you will get this output: None > > Question 2. I created a if statement to check if the "t" key is > pressed on a keyboard. If it is, I want the player to be placed on > another location on the grid. However nothing happens when I press > the "t" key. I am not sure why. Instead of changing the player's location, print "YOU PRESSED T" instead, and if you see that in the console, you know there's a problem with your repositioning code. If you don't see that, you know it's a problem with your input code. If you can't diagnose further than that, let us know. > > Question 3. I think there is something strange about how I check that > my player is within the boundaries of the grid. When it gets close to > the edges of the grid, it can sometimes disappear past it even though > I thought I had prevented this from happening. It's probably similar to the thing I was mentioning above. Imagine that you have this case: you're checking if the player is hitting 0.5, 0.5 now if the player can move by acceleration, etc... and you can't guarantee that it moves exactly in .5 increments, the player may very well move to the position .51,.51 and from there, to .49, .49 which would negate your test. Even if you check a range of values (for example, 0.0 - 0.5 in the x axis and 0.0 - 0.5 in the y axis) the player could theoretically jump right over this boundary (unless you restrict his maximum movement speed.) The best way to check would be: Say you have the player's coordinates playerx, playery and your player-permitted space is 0,0 to 1024, 768 I would suggest something like this: newx, newy = (playerx + movex, playery + movey) if newx >= 0 and newx < 1024: playerx = newx if newy >= 0 and newy < 768: playery = newy This will only allow the player to move to wherever he's moving IFF he's not moving out of bounds. Otherwise, he just stays where he is. Alternatively, you could check the boundaries, and if he's outside, set him to the boundary. That way you could have the player walk right up to the wall, which isn't allowed in my code (depending how fast the player moves) For example, if the player moves at 1.5, and he's at the position 1.4, he won't be able to move any closer to the wall. > > > Thank you again for looking at this. The attached bit of code has > taken a long time to create. I admire all who can program :-). Hey, I'm going to send this e-mail now, so everyone on the list (you included) will be able to read it, but I'm going to send another one in a second with comments on your code (Unless you don't want ;) > Tonu -Luke From cuell at math.usask.ca Thu Jul 26 05:32:20 2007 From: cuell at math.usask.ca (cuell) Date: Wed, 25 Jul 2007 21:32:20 -0600 Subject: [Tutor] What exactly is [::-1]? Message-ID: <46A815C4.5020205@math.usask.ca> In order to reverse the order of an array, I discovered that I'm supposed to use [::-1]. >>> a = array([1., 2., 3.]) >>> a array([ 1., 2., 3.]) >>> a[::-1] array([ 3., 2., 1.]) >>> I would like to know what exactly the index notation of [::-1] is, where it comes from and if there are other variants. Thank you for your help. I lurk about on this list and have learned a fair bit. -- Charles Cuell cuell at math.usask.ca http://math.usask.ca/~cuell From rabidpoobear at gmail.com Thu Jul 26 05:38:37 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 25 Jul 2007 22:38:37 -0500 Subject: [Tutor] What exactly is [::-1]? In-Reply-To: <46A815C4.5020205@math.usask.ca> References: <46A815C4.5020205@math.usask.ca> Message-ID: <46A8173D.5030501@gmail.com> cuell wrote: > In order to reverse the order of an array, I discovered that I'm > supposed to use [::-1]. > I don't know if 'supposed to' is the correct term. You could just as easily get away with using ['a','b','c'].reverse(). However, below you're using 'array' and I'm not sure exacly what this is. Does it have to do with the built-in array module or one of the numeric/numpy variants? > >>> a = array([1., 2., 3.]) > >>> a > array([ 1., 2., 3.]) > >>> a[::-1] > array([ 3., 2., 1.]) > >>> > > I would like to know what exactly the index notation of [::-1] is, where > it comes from and if there are other variants. > This is called list slicing. Look into it to figure out what all this stuff means. I could send you a link but I'd just google 'python list slicing' to find it, so I'll leave that as an exercise for the reader. > Thank you for your help. I lurk about on this list and have learned a > fair bit. > Good to hear :) -Luke From rabidpoobear at gmail.com Thu Jul 26 06:42:58 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 25 Jul 2007 23:42:58 -0500 Subject: [Tutor] Livewires questions In-Reply-To: <46A7F3C4.5060002@umn.edu> References: <46A7F3C4.5060002@umn.edu> Message-ID: <46A82652.9070207@gmail.com> As promised, here's some comments on your code. > from livewires import * > begin_graphics() > allow_moveables() > def place_player(): > global player_x > global player_y > global player_shape > player_y = random_between(0,47) > player_x = random_between(0,63) > player_shape = circle(10*player_x, 10*player_y, 5, filled=1) > In general, you should try to avoid global usage like this. You'd want to have a player class, probably. However, the way this tutorial is going, it seems like this is what it expects you to do. It mentions classes further near the end of the tutorial, so don't worry about it. for now, we'll just go with what you've got. > def place_robot(): > global robot_x > global robot_y > global robot_shape > robot_y = random_between(0,47)-0.5 > robot_x = random_between(0,63)-0.5 > I'm not too clear why you're subtracting 0.5 here. Doesn't this make the robot's center on the grid lines, rather than having the robot occupy a full square on the grid? I guess that's the intended behavior, huh? > robot_shape = box(10*robot_x, 10*robot_y,10*robot_x+10,10*robot_y+10) > def move_player(): > while 1: > global player_x > global player_y > > if 't' in keys: > place_player() > break > You can't reuse your place_player function here, because you put the initialization (the creation) of the graphics that represent the player _inside_ of the place_player function. Well, technically you could, but it would be better instead to use move_to(player_shape, x, y) because this doesn't overwrite the old player_shape circle. Also, will this work if the player presses "T"? > if '8' in keys: > move_to(player_shape,player_x*10 ,player_y*10 + 10) > player_y = player_y + 1 > if player_y > 47: > player_y = player_y -1 > else: > pass > 'if' statements don't have to have an 'else' clause. else: pass is just a waste of 2 lines. 'pass' does nothing, and since the 'else' is not required, you may as well leave it off. > break > if '7' in keys: > move_to(player_shape,player_x*10 - 10,player_y*10 +10) > player_x = player_x -1 > player_y = player_y + 1 > if player_x < 1 or player_y > 47: > player_x = player_x+1 > player_y = player_y-1 > else: > pass > break > if '9' in keys: > move_to(player_shape,player_x*10 + 10,player_y*10 + 10) > player_x = player_x +1 > player_y = player_y +1 > if player_x > 63 or player_y >47: > player_x = player_x -1 > player_y = player_y -1 > else: > pass > break > if '4' in keys: > move_to(player_shape,player_x*10 - 10,player_y*10) > player_x = player_x - 1 > if player_x < 1 : > player_x = player_x+1 > else: > pass > break > if '5' in keys: > break > if '6' in keys: > move_to(player_shape,player_x*10+10,player_y*10) > player_x = player_x + 1 > if player_x > 63: > player_x = player_x-1 > else: > pass > break > if '1' in keys: > move_to(player_shape,player_x*10-10,player_y*10-10) > player_x = player_x -1 > player_y = player_y -1 > if player_x < 1 or player_y < 1: > player_x = player_x +1 > player_y = player_y +1 > else: > pass > break > if '2' in keys: > move_to(player_shape,player_x*10,player_y*10-10) > player_y = player_y -1 > if player_y < 1: > player_y = player_y+1 > else: > pass > break > if '3' in keys: > move_to(player_shape,player_x*10+10,player_y*10-10) > player_x = player_x +1 > player_y = player_y -1 > if player_x > 63 or player_y < 1: > player_x = player_x -1 > player_y = player_y +1 > else: > pass > break > This big block of movement code can be shortened into a few lines. I am not sure how much python you know, so if any of this doesn't make sense, let me know. Think of it this way: step 1: look to see if they pressed a key that we want to process. step 2: if so, figure out how we need to move the player (based on input) step 3: check if this movement will move him out of bounds. step 4: perform the movement. Now that we have this pattern of evaluating our problem, we can reduce the code. First, what kind of data structures are we going to need? This is how I'm going to do it: movement = {} for x in range(3): for y in range(1,4): #this goes from 0 - 9, I was just too lazy to puzzle out a more efficient #way to do it. movement[str(3*x+y)] = [ [-1,0,1][y-1], [-1,0,1][x] ] this code creates the following data structure: {'1': [-1, -1], '3': [1, -1], '2': [0, -1], '5': [0, 0], '4': [-1, 0], '7': [-1, 1], '6': [1, 0], '9': [1, 1], '8': [0, 1]} You could just assign this to movement right off the bat, I just wanted to generate it programmatically. (for some reason I thought it would take a long time to type out ) So now that we have that, we know what offset to add to the player position. okay, so now that we have all our offset data, we can start. #step 1: look to see if the key they pressed is one we want to process. for key in keys: if key in movement.keys(): #step 2: how much do we need to move the player? newx = player_x + movement[key][0] newy = player_y + movement[key][1] #step 3: check to see if movement will still be in bounds. if newx >= 0 and newx < 64: #step 4: perform the movement player_x = newx if newy >= 0 and newy < 48: player_y = newy So our new code is this: movement = {'1': [-1, -1], '3': [1, -1], '2': [0, -1], '5': [0, 0], '4': [-1, 0], '7': [-1, 1], '6': [1, 0], '9': [1, 1], '8': [0, 1]} for key in keys: if key in movement.keys(): newx = player_x + movement[key][0] newy = player_y + movement[key][1] if newx >= 0 and newx < 64: player_x = newx if newy >= 0 and newy < 48: player_y = newy As you can see, it's a bit shorter :) > def move_robot(): > while 1: > global robot_x > global robot_y > if robot_x + 0.5< player_x and robot_y +0.5< player_y: > move_to(robot_shape,robot_x*10+10,robot_y*10+10) > robot_x = robot_x +1 > robot_y = robot_y +1 > break > if robot_x+0.5< player_x and robot_y+0.5 == player_y: > move_to(robot_shape,robot_x*10+10,robot_y*10) > robot_x = robot_x +1 > break > if robot_x+0.5 < player_x and robot_y+0.5 > player_y: > move_to(robot_shape,robot_x*10+10,robot_y*10-10) > robot_x = robot_x +1 > robot_y = robot_y -1 > break > if robot_x +0.5== player_x and robot_y +0.5> player_y: > move_to(robot_shape,robot_x*10,robot_y*10-10) > robot_y = robot_y -1 > break > if robot_x+0.5> player_x and robot_y +0.5> player_y: > move_to(robot_shape,robot_x*10-10,robot_y*10-10) > robot_x = robot_x -1 > robot_y = robot_y -1 > break > if robot_x +0.5> player_x and robot_y +0.5== player_y: > move_to(robot_shape,robot_x*10-10,robot_y*10) > robot_x = robot_x -1 > break > if robot_x +0.5> player_x and robot_y +0.5< player_y: > move_to(robot_shape,robot_x*10-10,robot_y*10+10) > robot_x = robot_x -1 > robot_y = robot_y +1 > break > if robot_x +0.5== player_x and robot_y+0.5 < player_y: > move_to(robot_shape,robot_x*10,robot_y*10+10) > robot_y = robot_y +1 > break > This is slightly different than the above, because you're checking against the player position instead . but if we think about it, let's say that the robot is up and to the right of the player. robot = 5, 5 player = 4, 6 now if you observe this, you can come to the following conclusions: the operation playerx - robotx will have 3 possible outcomes: 1) positive, if player is to the right of robot. 2) negative, if (which is the case here) player is to the left of robot. 3) 0, if player is vertically aligned with robot. A similar situation exists for the y-axis. playery - roboty 1) positive if player is below robot, 2) negative if player is above robot, 3) 0, if player is horizontally aligned with robot. Note that you could use the equations robotx - playerx, and roboty - playery, but the equations we chose here have a special property: if they are positive, that means you need to ADD to the offset of the robot, if they are negative you need to SUBTRACT from the offset of the robot, and if they are 0 you need to do neither. So this big block of code reduces to offsetx = player_x - robot_x +0.5 offsety = player_y - robot_y+0.5 if offsetx > 0: robot_x += 1 elif offsetx < 0: robot_x -= 1 if offsety > 0: robot_y += 1 elif offsety < 0: robot_y -= 1 note here that we don't have to check if the robot is in bounds here, because he's moving toward the player at all times, so he can't go out of bounds. > def collided(): > player_x == robot_x+0.5 and player_y == robot_y+0.5 > as stated before, this should be: def collided(): return player_x == robot_x+0.5 and player_y == robot_y+0.5 > def really_place_player(): > place_player() > while collided(): > place_player > this is not a function call. You need to change this to place_player(). > def check_collisions(): > if collided() == 1: > This is the same as if collided(): > print 'You have been caught' > > place_robot() > really_place_player() > while 1: > global keys > keys = keys_pressed() > if '1'in keys: > move_player() > move_robot() > check_collisions() > if '2' in keys: > move_player() > move_robot() > check_collisions() > if '3' in keys: > move_player() > move_robot() > check_collisions() > if '4' in keys: > move_player() > move_robot() > check_collisions() > if '5' in keys: > move_player() > move_robot() > check_collisions() > if '6' in keys: > move_player() > move_robot() > check_collisions() > if '7' in keys: > move_player() > move_robot() > check_collisions() > if '8' in keys: > move_player() > move_robot() > check_collisions() > if '9' in keys: > move_player() > move_robot() > check_collisions() > Similar to above, you can reduce this in a few ways: first, for key in keys: if key in ['1', '2', '3', '4', '5', '6', '7', '8', '9']: move_player() move_robot() check_collisions() secondly, you could reuse movement: for key in keys: if key in movement.keys(): # ... etc ... third, you could try to convert it to an int for key in keys: try: key = int(key) except ValueError: continue if key != 0: move_player() move_robot() check_collisions() > if 'q' in keys: > break > time.sleep(0.5) > ##finished=0 > ##while not yet finished: > ## move_player() > end_graphics() > Also, I just realized that you're using a while loop inside of your move_player and move_robots function. But you only call these functions if you KNOW that a movement key was pressed. Basically, this means that one of your 'if' conditions will ALWAYS be true inside of your while: loops, and you'll break out of it. The only reason why you might want this is that it would immediately exit as soon as it finds the first key that was pressed, but the same thing could be performed using an if-elif chain. But I doubt you want this to happen. Also there are other problems - eg. your keys is assigned to the keys that were currently pressed, so if during the time.sleep(0.5) I might press and then release a key, and it would be lost in your code. A great first attempt, though. :) Always good to see more people pickin' up Python. The code with the changes I mentioned included is attached to this e-mail. Also, note that I didn't test this code ( I don't have livewires installed) so if any of it doesn't work, let me know. -Luke -------------- next part -------------- A non-text attachment was scrubbed... Name: temp.py Type: text/x-python Size: 1981 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070725/0de2db01/attachment.py From rdm at rcblue.com Thu Jul 26 07:59:26 2007 From: rdm at rcblue.com (Dick Moores) Date: Wed, 25 Jul 2007 22:59:26 -0700 Subject: [Tutor] What exactly is [::-1]? In-Reply-To: <46A8173D.5030501@gmail.com> References: <46A815C4.5020205@math.usask.ca> <46A8173D.5030501@gmail.com> Message-ID: <20070726060711.4A1031E4002@bag.python.org> At 08:38 PM 7/25/2007, Luke Paireepinart wrote: > > I would like to know what exactly the index notation of [::-1] is, where > > it comes from and if there are other variants. > > >This is called list slicing. Look into it to figure out what all this >stuff means. >I could send you a link but I'd just google 'python list slicing' to >find it, so I'll leave that as an exercise for the reader. I don't find Google of help with this. Could someone supply a link? Dick Moores From rabidpoobear at gmail.com Thu Jul 26 08:23:55 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 26 Jul 2007 01:23:55 -0500 Subject: [Tutor] What exactly is [::-1]? In-Reply-To: <46a8384b.060e240a.4e2e.ffffc525SMTPIN_ADDED@mx.google.com> References: <46A815C4.5020205@math.usask.ca> <46A8173D.5030501@gmail.com> <46a8384b.060e240a.4e2e.ffffc525SMTPIN_ADDED@mx.google.com> Message-ID: <46A83DFB.3010806@gmail.com> Dick Moores wrote: > At 08:38 PM 7/25/2007, Luke Paireepinart wrote: >> > I would like to know what exactly the index notation of [::-1] is, >> where >> > it comes from and if there are other variants. >> > >> This is called list slicing. Look into it to figure out what all this >> stuff means. >> I could send you a link but I'd just google 'python list slicing' to >> find it, so I'll leave that as an exercise for the reader. > > I don't find Google of help with this. Could someone supply a link? Wow, it was actually quite a bit harder to Google than I thought :) well, some experimentation leads me to believe this is the syntax for list slicing: x[ i : j ] slices from i to j x[ i : ] slices from i to the end of the list x[ : j ] slices from the beginning of the list to j x[ : ] slices from the beginning of the list to the unspecified parameter (the end of the list) in other words, you can use this to make a copy. x[ : : ] This seems to work the same as the above. (note that in both cases, : and ::, the list is just a one-level-deep copy. so the list [[1,2,3],[4,5,6]] can't be copied fully with this.) however, x[ : : k ] is a copy (same as above) that uses k as a step. Here are some examples that should make it make sense. >>> x = [1,2,3,4,5,6,7,8,9] >>> x[::1] [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> x[::2] [1, 3, 5, 7, 9] >>> x[::5] [1, 6] >>> x[::-5] [9, 4] >>> x[::-1] [9, 8, 7, 6, 5, 4, 3, 2, 1] To summarize, the negative/positiveness of this parameter k denotes whether the step is from beginning to end, or from end to beginning. so if it's negative, the step will start at the last element, then step |k| toward the beginning, then grab that element ( if such an element exists) and proceed in this manner. This is all gleaned from experimentation, so it shouldn't be taken as the Word. HTH, -Luke > > Dick Moores > > > From wescpy at gmail.com Thu Jul 26 08:28:09 2007 From: wescpy at gmail.com (wesley chun) Date: Wed, 25 Jul 2007 23:28:09 -0700 Subject: [Tutor] What exactly is [::-1]? In-Reply-To: <46A83DFB.3010806@gmail.com> References: <46A815C4.5020205@math.usask.ca> <46A8173D.5030501@gmail.com> <46a8384b.060e240a.4e2e.ffffc525SMTPIN_ADDED@mx.google.com> <46A83DFB.3010806@gmail.com> Message-ID: <78b3a9580707252328w550b25e7sd06e8bcdf37a9bc@mail.gmail.com> when you use the 3rd element, it's called the extended slice syntax. here are a few more examples: >>> x = 'python programming' >>> x[::-1] 'gnimmargorp nohtyp' >>> x[2:12:2] 'to rg' >>> ironically, this feature has been available in the interpreter for many years, but it wasn't until circa 2.3 that it was available via Python syntax. it was also odd that i could use the extended slice syntax with Jython (formerly JPython) 1.1 when it wasn't available in the standard C Python back in the day. hope this helps! -- 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 john at fouhy.net Thu Jul 26 08:37:10 2007 From: john at fouhy.net (John Fouhy) Date: Thu, 26 Jul 2007 18:37:10 +1200 Subject: [Tutor] What exactly is [::-1]? In-Reply-To: <46A83DFB.3010806@gmail.com> References: <46A815C4.5020205@math.usask.ca> <46A8173D.5030501@gmail.com> <46a8384b.060e240a.4e2e.ffffc525SMTPIN_ADDED@mx.google.com> <46A83DFB.3010806@gmail.com> Message-ID: <5e58f2e40707252337p76516685sd181ec6029be3a04@mail.gmail.com> On 26/07/07, Luke Paireepinart wrote: > Wow, it was actually quite a bit harder to Google than I thought :) > well, some experimentation leads me to believe this is the syntax for > list slicing: [...] It's in the docs, albeit rather tersely: http://www.python.org/doc/current/lib/typesseq.html -- John. From alan.gauld at btinternet.com Thu Jul 26 09:17:24 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Jul 2007 08:17:24 +0100 Subject: [Tutor] What exactly is [::-1]? References: <46A815C4.5020205@math.usask.ca> <46A8173D.5030501@gmail.com> <20070726060711.4A1031E4002@bag.python.org> Message-ID: "Dick Moores" wrote >>I could send you a link but I'd just google 'python list slicing' to >>find it, so I'll leave that as an exercise for the reader. > > I don't find Google of help with this. Could someone supply a link? Not sure why it didn't help you Dick, but it led me to: http://docs.python.org/lib/typesseq.html Which is admittedly sparing in its explanation but does at least describe the three values involved and their defaults. The tutorial also threw up this: http://docs.python.org/tut/node5.html Which describes basic slicing (using only 2 indices) of strings and also has a link to the previous reference page. Finally I tried googling for 'python slicing' and got this as my first hit: http://docs.python.org/ref/slicings.html Which is the language lawyers version! 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 Thu Jul 26 09:20:27 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Jul 2007 08:20:27 +0100 Subject: [Tutor] What exactly is [::-1]? References: <46A815C4.5020205@math.usask.ca> <46A8173D.5030501@gmail.com><46a8384b.060e240a.4e2e.ffffc525SMTPIN_ADDED@mx.google.com> <46A83DFB.3010806@gmail.com> Message-ID: "Luke Paireepinart" wrote > well, some experimentation leads me to believe this is the syntax > for > list slicing: The referemnce link I poosted gives the exact syntax plus this description: ------------------ The semantics for a simple slicing are as follows. The primary must evaluate to a sequence object. The lower and upper bound expressions, if present, must evaluate to plain integers; defaults are zero and the sys.maxint, respectively. If either bound is negative, the sequence's length is added to it. The slicing now selects all items with index k such that i <= k < j where i and j are the specified lower and upper bounds. This may be an empty sequence. It is not an error if i or j lie outside the range of valid indexes (such items don't exist so they aren't selected). -------------------- For s[i:j:k} where the primary is i, the secondary j and the index k... 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 Thu Jul 26 09:24:26 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Jul 2007 08:24:26 +0100 Subject: [Tutor] What exactly is [::-1]? References: <46A815C4.5020205@math.usask.ca> <46A8173D.5030501@gmail.com><46a8384b.060e240a.4e2e.ffffc525SMTPIN_ADDED@mx.google.com><46A83DFB.3010806@gmail.com> <78b3a9580707252328w550b25e7sd06e8bcdf37a9bc@mail.gmail.com> Message-ID: "wesley chun" wrote > when you use the 3rd element, it's called the extended slice syntax. The ref manual describes use of the third value as simple slicing, for extended slicing it says this: ---------------------- The semantics for an extended slicing are as follows. The primary must evaluate to a mapping object, and it is indexed with a key that is constructed from the slice list, as follows. If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items; otherwise, the conversion of the lone slice item is the key. The conversion of a slice item that is an expression is that expression. The conversion of an ellipsis slice item is the built-in Ellipsis object. The conversion of a proper slice is a slice object (see section 3.2) whose start, stop and step attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, substituting None for missing expressions. ----------------------- I've read it three times now and stioll have no idea what its on about! Some ex[erimentation needed I think, but no time now. :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Thu Jul 26 09:43:21 2007 From: rdm at rcblue.com (Dick Moores) Date: Thu, 26 Jul 2007 00:43:21 -0700 Subject: [Tutor] What exactly is [::-1]? In-Reply-To: References: <46A815C4.5020205@math.usask.ca> <46A8173D.5030501@gmail.com> <20070726060711.4A1031E4002@bag.python.org> Message-ID: <20070726074336.7F4C11E400A@bag.python.org> At 12:17 AM 7/26/2007, Alan Gauld wrote: >"Dick Moores" wrote > > >>I could send you a link but I'd just google 'python list slicing' to > >>find it, so I'll leave that as an exercise for the reader. > > > > I don't find Google of help with this. Could someone supply a link? > >Not sure why it didn't help you Dick, but it led me to: > >http://docs.python.org/lib/typesseq.html > >Which is admittedly sparing in its explanation but does at >least describe the three values involved and their defaults. > >The tutorial also threw up this: > >http://docs.python.org/tut/node5.html > >Which describes basic slicing (using only 2 indices) of strings >and also has a link to the previous reference page. > >Finally I tried googling for 'python slicing' and got this as my first >hit: > >http://docs.python.org/ref/slicings.html > >Which is the language lawyers version! Alan, I don't see an explanation of [::-1] anywhere in those 3 links. There needs to be a clear description and better examples somewhere in the docs, IMO. My thanks to Luke and Wesley. Dick From alan.gauld at btinternet.com Thu Jul 26 10:04:05 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Jul 2007 09:04:05 +0100 Subject: [Tutor] What exactly is [::-1]? References: <46A815C4.5020205@math.usask.ca> <46A8173D.5030501@gmail.com><20070726060711.4A1031E4002@bag.python.org> <20070726074336.7F4C11E400A@bag.python.org> Message-ID: "Dick Moores" wrote >>Not sure why it didn't help you Dick, but it led me to: >> >>http://docs.python.org/lib/typesseq.html >> > > Alan, I don't see an explanation of [::-1] anywhere in those 3 > links. > There needs to be a clear description and better examples somewhere > in the docs, IMO. I agree the explanation is 'terse' but it does explain that the syntax is S[i:j:k] and that any/all of the values can be ommitted and what their defaults are. It also explains the significance of -1 as a value. So [::-1] is simply i, j taking defaults and -1 for k So its equivalent to S[0:len(S):-1] But I agree there could be a few more examples of the use of the k element. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Jul 26 12:40:27 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Jul 2007 06:40:27 -0400 Subject: [Tutor] What exactly is [::-1]? In-Reply-To: References: <46A815C4.5020205@math.usask.ca> <46A8173D.5030501@gmail.com><46a8384b.060e240a.4e2e.ffffc525SMTPIN_ADDED@mx.google.com><46A83DFB.3010806@gmail.com> <78b3a9580707252328w550b25e7sd06e8bcdf37a9bc@mail.gmail.com> Message-ID: <46A87A1B.9040107@tds.net> Alan Gauld wrote: > "wesley chun" wrote > >> when you use the 3rd element, it's called the extended slice syntax. > > The ref manual describes use of the third value as simple slicing, > for extended slicing it says this: > I've read it three times now and stioll have no idea what its on > about! Extended slicing is used by Numeric and its successors to slice multi-dimensional arrays on multiple dimensions. An extended slice is a simple slice for each dimension of the array, separated by commas. See http://numpy.scipy.org/numpydoc/numpy-6.html#pgfId-36074 AFAIK extended slicing is not supported by any standard Python data types, it was added specifically for Numeric. When an object is indexed with an extended slice, the object's __getitem__() method is passed a tuple of slice objects. It's then up to the object to make sense of it: In [1]: class ext(object): ...: def __getitem__(self, key): ...: print repr(key) ...: ...: In [2]: e=ext() In [3]: e[3] 3 In [4]: e[1:4] slice(1, 4, None) In [5]: e[1:4,2:5] (slice(1, 4, None), slice(2, 5, None)) Kent From tnoyeaux at msn.com Thu Jul 26 15:49:07 2007 From: tnoyeaux at msn.com (Tony Noyeaux) Date: Thu, 26 Jul 2007 09:49:07 -0400 Subject: [Tutor] Sum of Scores Message-ID: The projects are moving along. I've created a very simplistic cricket game to learn a few things. The user is asked whether to play Aggressive or Defensively. Once they pick... a random is picked based on their choice,.. and various scores happen until they get out. Ignore the realism at this point,.. just getting the basic mechanics working first. Works fine no problem. I want to be able to calculate in the program,.. the total score,.. either at each successive score,... or when they finally get out. Not sure how to do that at this point. So the output would look something like this. You Hit a 2, you now have scored 2 runs You hit a 4, you now have scored 6 runs You hit a "Out", you are dismissed for 6 runs total. After i get this worked out.. will tweak the actual formulas for the randoms, maybe put in multiple outs etc,.. changeable strategy at each out etc, and high scores list towards the end. First things first,... and the project at hand. How do i ... post the totals... as listed above, to the working code below. Thanks as always Tony Noyeaux --------------------------------------------------------------------------------- import random score = Nonestrat = raw_input("Will you play (a)aggressive or (b)defensive?")if strat == "a": while score != "Out": score = random.choice(["1","2","3","4","4","6","6","Out","Out","Out","Out"]) print scoreelse: while score != "Out": score = random.choice(["1","1","2","2","3","4","6","Out"]) print "You hit a "+score ---------------------------------------------------------------------------------- _________________________________________________________________ PC Magazine?s 2007 editors? choice for best web mail?award-winning Windows Live Hotmail. http://imagine-windowslive.com/hotmail/?locale=en-us&ocid=TXT_TAGHM_migration_HMWL_mini_pcmag_0707 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070726/ae8aeb9e/attachment.htm From titleistfour at gmail.com Thu Jul 26 16:27:22 2007 From: titleistfour at gmail.com (jay) Date: Thu, 26 Jul 2007 09:27:22 -0500 Subject: [Tutor] Finding the caller Message-ID: <7c25bb490707260727g5a6bc89qba891130f5b7785@mail.gmail.com> Hello all, If I import a module, which has a bunch of simple functions in it, is there an easy way to find the direct caller from inside one of those functions? I'm looking to know which script has imported and thus called the library function. Thanks! jay -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070726/e14b6a2f/attachment.html From andreas at kostyrka.org Thu Jul 26 16:57:35 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 26 Jul 2007 16:57:35 +0200 Subject: [Tutor] Finding the caller In-Reply-To: <7c25bb490707260727g5a6bc89qba891130f5b7785@mail.gmail.com> References: <7c25bb490707260727g5a6bc89qba891130f5b7785@mail.gmail.com> Message-ID: <46A8B65F.8080303@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 sys._getframe. Andreas jay wrote: > Hello all, > > If I import a module, which has a bunch of simple functions in it, is > there an easy way to find the direct caller from inside one of those > functions? I'm looking to know which script has imported and thus > called the library function. Thanks! > > jay > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGqLZeHJdudm4KnO0RAkV+AJ42mi3wqHp3vX1IBOQVeqIIiS7E7ACdHeRV E/oiSDLtQ408sNFQCIorMWo= =zY8c -----END PGP SIGNATURE----- From kent37 at tds.net Thu Jul 26 17:05:19 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Jul 2007 11:05:19 -0400 Subject: [Tutor] Finding the caller In-Reply-To: <7c25bb490707260727g5a6bc89qba891130f5b7785@mail.gmail.com> References: <7c25bb490707260727g5a6bc89qba891130f5b7785@mail.gmail.com> Message-ID: <46A8B82F.5030603@tds.net> jay wrote: > Hello all, > > If I import a module, which has a bunch of simple functions in it, is > there an easy way to find the direct caller from inside one of those > functions? I'm looking to know which script has imported and thus > called the library function. Thanks! http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 Kent From titleistfour at gmail.com Thu Jul 26 17:11:51 2007 From: titleistfour at gmail.com (jay) Date: Thu, 26 Jul 2007 10:11:51 -0500 Subject: [Tutor] Finding the caller In-Reply-To: <46A8B82F.5030603@tds.net> References: <7c25bb490707260727g5a6bc89qba891130f5b7785@mail.gmail.com> <46A8B82F.5030603@tds.net> Message-ID: <7c25bb490707260811l190d389cq1490dd52732cb06d@mail.gmail.com> Thanks Kent and Andreas That is exactly what I needed! Very nice indeed... jay On 7/26/07, Kent Johnson wrote: > > jay wrote: > > Hello all, > > > > If I import a module, which has a bunch of simple functions in it, is > > there an easy way to find the direct caller from inside one of those > > functions? I'm looking to know which script has imported and thus > > called the library function. Thanks! > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070726/c43aa078/attachment.htm From Mike.Hansen at atmel.com Thu Jul 26 17:31:52 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Thu, 26 Jul 2007 09:31:52 -0600 Subject: [Tutor] while Loop In-Reply-To: References: <469E386D.8040002@gmail.com><469E653E.8080402@gmail.com> Message-ID: <57B026980605A64F9B23484C5659E32E8F59E7@poccso.US.ad.atmel.com> > -----Original Message----- > Subject: Re: [Tutor] while Loop > > Oops, didn't notice the uppercase U, thanks Luke. > > ----- Original Message ----- > Subject: Re: [Tutor] while Loop > > > >> define it with usedPocketsOne = 192000? > > no, I said UsedPocketsOne was not defined. Note the > different starting > > letter. > > Python is case senstitive, meaning usedPocketsOne is not > the same as > > UsedPocketsOne. > > So yes, you defined usedPocketsOne with the assignment to > 192000, but > > you did not define UsedPocketsOne. > > I've been out of the office for the last week, so I'm catching up. You might use something like PyChecker, PyLint, or PyFlakes. Those utilities would catch errors like this. I have a hotkey in VIM that kicks off PyFlakes on the current buffer. Also, I'm not 100% sure, but I think Komodo IDE would catch this as well. Mike From tmikk at umn.edu Thu Jul 26 18:55:11 2007 From: tmikk at umn.edu (Tonu Mikk) Date: Thu, 26 Jul 2007 11:55:11 -0500 Subject: [Tutor] Livewires questions In-Reply-To: <46A811A5.7040806@gmail.com> References: <46A7F3C4.5060002@umn.edu> <46A811A5.7040806@gmail.com> Message-ID: <46A8D1EF.3050807@umn.edu> Luke, thank you for your quick and complete response. Based on your suggestions I have already made some progress! BTW, I am so glad that I can ask this list my Python questions and get help. I began feeling quite stuck and not knowing where to turn for help. So, thank you for the great service! Luke Paireepinart wrote: > Tonu Mikk wrote: >> Thanks for offering to help! I am following the Livewires exercise >> (attached file "5-robots.pdf"). I have gotten as far as page 7. >> Attached is also my code so far in robotsarecoming-teleport.py. >> Question 1. I was checking for collision of a robot and player first >> in this way: >> >> def check_collisions(): >> if player_x == robot_x+0.5 and player_y == robot_y+0.5: >> print 'You have been caught' >> >> This was working fine. I then tried to create a definition like this: >> >> def collided(): >> player_x == robot_x+0.5 and player_y == robot_y+0.5 > I haven't looked at your code yet, but this doesn't seem like a very > good way to check for collisions, > unless the player moves on a grid of 0.5 at a time, and you guarantee > that you can check if the player collided with a robot on every move. > even so, doesn't this only collide with the robot if the player hits > the bottom-right corner? Yes, this indeed looks strange. I believe it is particular to this Livewires exercise. The reason it is strange is that I am comparing a position of two different shapes, a circle and a square. The position for the circle is in the center of the circle and it is defined by player_x and player_y coordinates. The position of the square is defined by the first two coordinates that make up a square robot_x and robot_y. The circle radius is 0.5. It took me a loooong time to figure out how to write my code so that when the robot sits exactly on top of the player, there is a message "you have been caught" :-) . When I run the code, the robot will sit on top of the player and I can have the message printed - yeaaah! > >> >> and then check for collisions in this way (as in my code): >> def check_collisions(): >> if collided() == 1: >> print 'You have been caught' > The reason this isn't working is because your function 'collided' > doesn't return anything. > Consider this example: > > def foo(): > "Hello" > > What do you expect to happen when you call foo()? > 1) "Hello" won't be printed, because there is no 'print' statement here. > 2) "Hello" won't be returned, because you have no return statement. > So what does happen, then? > well, foo() creates a string in memory with "Hello" stored in it, but > there are no variables referenced to it, so nothing happens. > Basically, the only thing foo() accomplishes is that it wastes memory > until "Hello" is garbage collected and deleted. > > Now consider this: > def foo(): > a == b and b == c > > What do you expect to happen here? > It's similar to the above example. > a == b is evaluated. > if it's true, b == c is evaluated. > if it's true, then the value True is there, but it's not assigned to > any variables, so it just disappears. > Can you see now why your code doesn't work? > > Here's an example of a function you'd want to look at to give you an > idea of what to do: > > def foo(): > return a < b >> But this isn't printing out anything when the player and robot >> collide. I think I need to pass a variable of collided somehow, but >> I am not sure how. I also tried following: >> def check_collisions(): >> if collided() >> print 'You have been caught' >> but this isn't working either. > This is because collided() is not returning anything. > Try this: > print collided() > you will get this output: > None Based on your guidance, I figured it out. I need to use a return statement, which I had not encountered before. Now I wrote my definitions in this way: def collided(): if player_x == robot_x+0.5 and player_y == robot_y+0.5: return True Then I use that value in another definition like this: def check_collisions(): if collided() == 1: print "You have been caught" Which is displaying the message when the robot sits on top of the player. >> >> Question 2. I created a if statement to check if the "t" key is >> pressed on a keyboard. If it is, I want the player to be placed on >> another location on the grid. However nothing happens when I press >> the "t" key. I am not sure why. > Instead of changing the player's location, print "YOU PRESSED T" > instead, and if you see that in the console, you know there's a > problem with your repositioning code. If you don't see that, you know > it's a problem with your input code. > If you can't diagnose further than that, let us know. It is great suggestion to use a print statement for testing! I tried it and I did not get a printed message either. I will need to think about it some more. I believe your other email will give me some ideas here. >> >> Question 3. I think there is something strange about how I check >> that my player is within the boundaries of the grid. When it gets >> close to the edges of the grid, it can sometimes disappear past it >> even though I thought I had prevented this from happening. > It's probably similar to the thing I was mentioning above. > Imagine that you have this case: > you're checking if the player is hitting 0.5, 0.5 > now if the player can move by acceleration, etc... and you can't > guarantee that it moves exactly in .5 increments, the player may very > well move to the position .51,.51 and from there, to .49, .49 which > would negate your test. > Even if you check a range of values (for example, 0.0 - 0.5 in the x > axis and 0.0 - 0.5 in the y axis) > the player could theoretically jump right over this boundary (unless > you restrict his maximum movement speed.) > The best way to check would be: > Say you have the player's coordinates > playerx, playery > and your player-permitted space is 0,0 to 1024, 768 > I would suggest something like this: > newx, newy = (playerx + movex, playery + movey) > if newx >= 0 and newx < 1024: > playerx = newx > if newy >= 0 and newy < 768: > playery = newy > > This will only allow the player to move to wherever he's moving IFF > he's not moving out of bounds. > Otherwise, he just stays where he is. > Alternatively, you could check the boundaries, and if he's outside, > set him to the boundary. > That way you could have the player walk right up to the wall, which > isn't allowed in my code (depending how fast the player moves) > For example, if the player moves at 1.5, and he's at the position 1.4, > he won't be able to move any closer to the wall. > Thanks for this suggestion. I will likely need to re-write how I check for boundaries. Currently I was checking for boundaries after I moved the player. I did this by not letting the player_x and player_y coordinates to be changed if the player was going to go beyond boundaries. It seems I need to put in a check for boundaries before I move the player. >> >> >> Thank you again for looking at this. The attached bit of code has >> taken a long time to create. I admire all who can program :-). > Hey, I'm going to send this e-mail now, so everyone on the list (you > included) will be able to read it, but I'm going to send another one > in a second with comments on your code (Unless you don't want ;) Yes, I do want you to comment on the code, absolutely, which I see you so generously did in another email. Thank you, Tonu From cuell at snoopy.usask.ca Thu Jul 26 19:32:57 2007 From: cuell at snoopy.usask.ca (Charles Cuell) Date: Thu, 26 Jul 2007 11:32:57 -0600 (CST) Subject: [Tutor] Thanks re: [::-1] In-Reply-To: References: Message-ID: Thanks to everybody that worked to clarify the meaning of [::-1]. My main concern was that it looked like the notation came out of nowhere and, as such, was inconsistent with the usual slice notation. The documentation did make it clear, since the full slicing notation is s[i:j:k], leaving out the i and j to indicate starting at the beginning and stopping at the end results in s[::k]. The one odd thing about Python's slice notation is that the -1 means to start from the end and work backwards. My first inclination would have been to assume that -1 means to start at i and go to j by steps of -1 (only nonempy if j < i). Thanks again. Charles Cuell cuell at math.usask.ca From keridee at jayco.net Thu Jul 26 21:33:13 2007 From: keridee at jayco.net (Tiger12506) Date: Thu, 26 Jul 2007 14:33:13 -0500 Subject: [Tutor] Livewires questions References: <46A7F3C4.5060002@umn.edu> <46A811A5.7040806@gmail.com> <46A8D1EF.3050807@umn.edu> Message-ID: <000601c7cfbb$d2be0150$e5fce004@JSLAPTOP> > Based on your guidance, I figured it out. I need to use a return > statement, which I had not encountered before. Now I wrote my > definitions in this way: > > def collided(): > if player_x == robot_x+0.5 and player_y == robot_y+0.5: > return True This could be simplified more. Here's an example as a hint. These two functions are the same. def f(): if a == b and c == d: return True def g(): return (a==b and c == d) > Then I use that value in another definition like this: > > def check_collisions(): > if collided() == 1: > print "You have been caught" And ~ if collided(): print "You have been caught" From tmikk at umn.edu Thu Jul 26 20:42:03 2007 From: tmikk at umn.edu (Tonu Mikk) Date: Thu, 26 Jul 2007 13:42:03 -0500 Subject: [Tutor] Livewires questions In-Reply-To: <000601c7cfbb$d2be0150$e5fce004@JSLAPTOP> References: <46A7F3C4.5060002@umn.edu> <46A811A5.7040806@gmail.com> <46A8D1EF.3050807@umn.edu> <000601c7cfbb$d2be0150$e5fce004@JSLAPTOP> Message-ID: <46A8EAFB.8070107@umn.edu> Tiger12506 wrote: >> Based on your guidance, I figured it out. I need to use a return >> statement, which I had not encountered before. Now I wrote my >> definitions in this way: >> >> def collided(): >> if player_x == robot_x+0.5 and player_y == robot_y+0.5: >> return True >> > > This could be simplified more. > Here's an example as a hint. These two functions are the same. > > def f(): > if a == b and c == d: > return True > > def g(): > return (a==b and c == d) > > I got it. I will do it like this: def collided(): return (player_x == robot_x+0.5 and player_y == robot_y+0.5) Thank you, Tonu -- Tonu Mikk Educational Technology Consultant Digital Media Center - dmc.umn.edu tmikk at umn.edu 612 625-9221 From brunson at brunson.com Thu Jul 26 20:47:48 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 26 Jul 2007 12:47:48 -0600 Subject: [Tutor] Livewires questions In-Reply-To: <000601c7cfbb$d2be0150$e5fce004@JSLAPTOP> References: <46A7F3C4.5060002@umn.edu> <46A811A5.7040806@gmail.com> <46A8D1EF.3050807@umn.edu> <000601c7cfbb$d2be0150$e5fce004@JSLAPTOP> Message-ID: <46A8EC54.6020807@brunson.com> Tiger12506 wrote: >> Based on your guidance, I figured it out. I need to use a return >> statement, which I had not encountered before. Now I wrote my >> definitions in this way: >> >> def collided(): >> if player_x == robot_x+0.5 and player_y == robot_y+0.5: >> return True >> Granting that I have not looked at any of the Livewires modules, I just wanted to say... A general check for collision would probably involve the distance formula from geometry collided( (x1,y1), (x2,y2) ): return( sqrt( (x1-x2)**2 + (y1-y2)**2 ) < 1 ) but could probably be simplified to something like: def collided( (x1,y1), (x2,y2) ): return( abs( x1 - x2 ) < .5 and abs( y1 - y2 ) < .5 ) > > This could be simplified more. > Here's an example as a hint. These two functions are the same. > > def f(): > if a == b and c == d: > return True > > def g(): > return (a==b and c == d) > > > >> Then I use that value in another definition like this: >> >> def check_collisions(): >> if collided() == 1: >> print "You have been caught" >> > > And ~ > > if collided(): > print "You have been caught" > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From brunson at brunson.com Thu Jul 26 20:49:59 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 26 Jul 2007 12:49:59 -0600 Subject: [Tutor] Livewires questions In-Reply-To: <46A8EAFB.8070107@umn.edu> References: <46A7F3C4.5060002@umn.edu> <46A811A5.7040806@gmail.com> <46A8D1EF.3050807@umn.edu> <000601c7cfbb$d2be0150$e5fce004@JSLAPTOP> <46A8EAFB.8070107@umn.edu> Message-ID: <46A8ECD7.4060404@brunson.com> Tonu Mikk wrote: > Tiger12506 wrote: > >>> Based on your guidance, I figured it out. I need to use a return >>> statement, which I had not encountered before. Now I wrote my >>> definitions in this way: >>> >>> def collided(): >>> if player_x == robot_x+0.5 and player_y == robot_y+0.5: >>> return True >>> >>> >> >> This could be simplified more. >> Here's an example as a hint. These two functions are the same. >> >> def f(): >> if a == b and c == d: >> return True >> >> def g(): >> return (a==b and c == d) >> >> >> > I got it. I will do it like this: > def collided(): > return (player_x == robot_x+0.5 and player_y == robot_y+0.5) > > I believe that will only work if the robot collides with the player from the southeast. I'm not sure of the rules of the game, but if that's not the case, then see my previous note. From greg.lindstrom at novasyshealth.com Thu Jul 26 20:44:41 2007 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Thu, 26 Jul 2007 13:44:41 -0500 Subject: [Tutor] Running Python on Gentoo Message-ID: <46A8EB99.4070506@novasyshealth.com> Hello, I am running python 2.4.2 on Gentoo Unix and am having problems running programs. I have a script, hello.py as such: #! /usr/bin/python print 'hello, world' that I save and add executable permission. Then at the prompt I type in.. $ ./hello.py -bash: ./hello.py: /usr/bin/python: bad interpreter: Permission denied If I type $ python hello.py I get "hello, world" as expected. I was hoping that the "shabang" would have the script execute. Am I missing something? Can you help me? BTW, when I type /usr/bin/python at the prompt I get the python interpreter, so at least that's working. Thanks, --greg From swimlappy at gmail.com Thu Jul 26 21:02:36 2007 From: swimlappy at gmail.com (jason) Date: Thu, 26 Jul 2007 14:02:36 -0500 Subject: [Tutor] Pass variable on command line Message-ID: <3216224d0707261202r77ace818n596aaa0eefbd83f6@mail.gmail.com> Hello, I have a situation where I have 2 lists List1 = ['blue', 'red', green'] List2 = ['red', 'yellow', 'orange'] And I would like to pass the list name on the command line like so ./test.py List1 I know I can get the argument using sys.argv[1] But how can I then use the values in that list inside my program? If I do a VALUES = sys.argv[1], then I get List1 as the values. I want the actual list elements. Is this possible? Thank you Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070726/73f5aa3b/attachment.html From tmikk at umn.edu Thu Jul 26 21:20:29 2007 From: tmikk at umn.edu (Tonu Mikk) Date: Thu, 26 Jul 2007 14:20:29 -0500 Subject: [Tutor] Livewires questions In-Reply-To: <46A8EC54.6020807@brunson.com> References: <46A7F3C4.5060002@umn.edu> <46A811A5.7040806@gmail.com> <46A8D1EF.3050807@umn.edu> <000601c7cfbb$d2be0150$e5fce004@JSLAPTOP> <46A8EC54.6020807@brunson.com> Message-ID: <46A8F3FD.7090908@umn.edu> Eric Brunson wrote: > Tiger12506 wrote: > >>> Based on your guidance, I figured it out. I need to use a return >>> statement, which I had not encountered before. Now I wrote my >>> definitions in this way: >>> >>> def collided(): >>> if player_x == robot_x+0.5 and player_y == robot_y+0.5: >>> return True >>> >>> > > Granting that I have not looked at any of the Livewires modules, I just > wanted to say... > > A general check for collision would probably involve the distance > formula from geometry > > collided( (x1,y1), (x2,y2) ): > return( sqrt( (x1-x2)**2 + (y1-y2)**2 ) < 1 ) > > but could probably be simplified to something like: > > def collided( (x1,y1), (x2,y2) ): > return( abs( x1 - x2 ) < .5 and abs( y1 - y2 ) < .5 ) > > Thanks Eric for your suggestions. I believe Livewires modules have simplified collision checking for programming novices like myself. There are two shapes that I am working with, a circle and a square. The position of the circle is defined by the center coordinates whereas the position of the square is defined by the lower left corner of the square. When my circle is 0.5 points in diameter, I can add this much to both x and y coordinates of the square which will then give me the point where the square is sitting on top of the circle. It took me a long time to figure this out. I had to re-read the Graphics guide sheet that came with Livewires multiple times to try to get it to work correctly. I believe this part of my code is OK. Tonu From khamid.nurdiev at gmail.com Thu Jul 26 21:23:50 2007 From: khamid.nurdiev at gmail.com (Khamid Nurdiev) Date: Fri, 27 Jul 2007 00:23:50 +0500 Subject: [Tutor] Running Python on Gentoo In-Reply-To: <46A8EB99.4070506@novasyshealth.com> References: <46A8EB99.4070506@novasyshealth.com> Message-ID: Yes, I have the same problem with running python scripts from console in Debian, the line "#! /usr/bin/python" doesn't help. I have to type "python script.py" in order to run the script.py file. On 7/26/07, Greg Lindstrom wrote: > > Hello, > I am running python 2.4.2 on Gentoo Unix and am having problems running > programs. I have a script, hello.py as such: > > #! /usr/bin/python > print 'hello, world' > > that I save and add executable permission. Then at the prompt I type in.. > > $ ./hello.py > -bash: ./hello.py: /usr/bin/python: bad interpreter: Permission denied > > If I type > $ python hello.py > I get "hello, world" as expected. > > I was hoping that the "shabang" would have the script execute. Am I > missing something? Can you help me? BTW, when I type /usr/bin/python > at the prompt I get the python interpreter, so at least that's working. > > Thanks, > --greg > > _______________________________________________ > 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/20070727/d7c785c8/attachment.html From cbc at unc.edu Thu Jul 26 21:18:23 2007 From: cbc at unc.edu (Chris Calloway) Date: Thu, 26 Jul 2007 15:18:23 -0400 Subject: [Tutor] Thanks re: [::-1] In-Reply-To: References: Message-ID: <46A8F37F.9000404@unc.edu> Charles Cuell wrote: > The one odd thing about Python's slice notation is that the -1 means to > start from the end and work backwards. My first inclination would have > been to assume that -1 means to start at i and go to j by steps of -1 > (only nonempy if j < i). A negative step attribute does not change the semantics of the start and stop (read only) attributes of slice objects: >>> m = range(10) >>> m[2:7:-1] [] >>> m[7:2:-1] [7, 6, 5, 4, 3] >>> m[-3:-8:-1] [7, 6, 5, 4, 3] >>> So your first inclination was correct! :) i does go to j by steps of k. -- Sincerely, Chris Calloway http://www.seacoos.org office: 332 Chapman Hall phone: (919) 962-4323 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From brunson at brunson.com Thu Jul 26 21:31:58 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 26 Jul 2007 13:31:58 -0600 Subject: [Tutor] Pass variable on command line In-Reply-To: <3216224d0707261202r77ace818n596aaa0eefbd83f6@mail.gmail.com> References: <3216224d0707261202r77ace818n596aaa0eefbd83f6@mail.gmail.com> Message-ID: <46A8F6AE.9010203@brunson.com> jason wrote: > Hello, > > I have a situation where I have 2 lists > > List1 = ['blue', 'red', green'] > List2 = ['red', 'yellow', 'orange'] > > And I would like to pass the list name on the command line like so > > ./test.py List1 > > I know I can get the argument using sys.argv[1] > > But how can I then use the values in that list inside my program? > > If I do a VALUES = sys.argv[1], then I get List1 as the values. I > want the actual list elements.\\ The easiest way to do this would be to define your lists in a dictionary: lists = { 'List1': ['blue', 'red', green'], 'List2': ['red', 'yellow', 'orange'] } if len(sys.argv) > 1 and sys.argv[1] in lists: VALUES = lists[sys.argv[1]] > > Is this possible? > > Thank you > > Jason > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From brunson at brunson.com Thu Jul 26 21:33:54 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 26 Jul 2007 13:33:54 -0600 Subject: [Tutor] Running Python on Gentoo In-Reply-To: References: <46A8EB99.4070506@novasyshealth.com> Message-ID: <46A8F722.4000002@brunson.com> What does the command "which python" say? Khamid Nurdiev wrote: > Yes, I have the same problem with running python scripts from console > in Debian, the line "#! /usr/bin/python" doesn't help. I have to type > "python script.py" in order to run the script.py file. > > On 7/26/07, *Greg Lindstrom* > wrote: > > Hello, > I am running python 2.4.2 on Gentoo Unix and am having problems > running > programs. I have a script, hello.py as such: > > #! /usr/bin/python > print 'hello, world' > > that I save and add executable permission. Then at the prompt I > type in.. > > $ ./hello.py > -bash: ./hello.py: /usr/bin/python: bad interpreter: Permission denied > > If I type > $ python hello.py > I get "hello, world" as expected. > > I was hoping that the "shabang" would have the script execute. Am I > missing something? Can you help me? BTW, when I type /usr/bin/python > at the prompt I get the python interpreter, so at least that's > working. > > Thanks, > --greg > > _______________________________________________ > 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 > From carroll at tjc.com Thu Jul 26 21:34:17 2007 From: carroll at tjc.com (Terry Carroll) Date: Thu, 26 Jul 2007 12:34:17 -0700 (PDT) Subject: [Tutor] Pass variable on command line In-Reply-To: <3216224d0707261202r77ace818n596aaa0eefbd83f6@mail.gmail.com> Message-ID: On Thu, 26 Jul 2007, jason wrote: > Hello, > > I have a situation where I have 2 lists > > List1 = ['blue', 'red', green'] > List2 = ['red', 'yellow', 'orange'] > > And I would like to pass the list name on the command line like so > > ./test.py List1 > > I know I can get the argument using sys.argv[1] > > But how can I then use the values in that list inside my program? If you must do this, make a dictionary of the lists: d = {"List1": List1, "List2": List2} and index into it from your argument: l = d[sys.argv[1]] From cbc at unc.edu Thu Jul 26 21:37:54 2007 From: cbc at unc.edu (Chris Calloway) Date: Thu, 26 Jul 2007 15:37:54 -0400 Subject: [Tutor] What exactly is [::-1]? In-Reply-To: <46A87A1B.9040107@tds.net> References: <46A815C4.5020205@math.usask.ca> <46A8173D.5030501@gmail.com><46a8384b.060e240a.4e2e.ffffc525SMTPIN_ADDED@mx.google.com><46A83DFB.3010806@gmail.com> <78b3a9580707252328w550b25e7sd06e8bcdf37a9bc@mail.gmail.com> <46A87A1B.9040107@tds.net> Message-ID: <46A8F812.3090802@unc.edu> Kent Johnson wrote: > AFAIK extended slicing is not supported by any standard Python data > types, it was added specifically for Numeric. Numeric *is* responsible for getting *one* of the two forms of extended slicing added (the one with multiple slices or ellipses separated by commas) and yes, that *one form* isn't supported by any builtin or "standard" global module Python data types. The *other* form of extended slicing, the one with two colons (and no commas) is supported by typeseq objects, though. The phrase "extended slicing" probably ought to be clarified in the documentation as having two distinct forms (stepped and multiple). This is a root of considerable confusion for people reading about extended slicing in the standard documentation. Extended slicing is really talking about two ways of creating a *slice object* (and there are other ways of creating slice objects). And not all slice objects are created equally as far as typeseq and array module objects are concerned. A sensible solution would be to refer to the stepped form as a simple slice and realize that both "stepped simple" slices and comma-extended slices create slice objects in Python 2.3 and later. I don't know how wise it would be to further confuse the issue by changing the documentation at this point. It's a judgment call. Using stepped slicing with numpy/Numeric/numarray style arrays is also very different from using it with the standard array module and typeseq objects. With typeseq objects, the two colon extended slicing provides a reversed *copy* of the typeseq object as opposed to the .reverse method which reverses a typeseq object *in place* (and has no return value): >>> a = [0,1,2,3,4] >>> b = a[::-1] >>> a[2] = 6 >>> a.reverse() >>> a [4, 3, 6, 1, 0] >>> b [4, 3, 2, 1, 0] >>> Same with the array module (a copy is made): >>> import array >>> e = array.array('i',[0,1,2,3,4]) >>> f = e[::-1] >>> e[2] = 23 >>> e.reverse() >>> e array('i', [4, 3, 23, 1, 0]) >>> f array('i', [4, 3, 2, 1, 0]) >>> However, with numpy/Numeric/numarray style arrays, extended slicing gives you a "view" of the original array, somewhat similar to using .reverse() on typeseq objects (but still different because the original array is unchanged). Changes to the original array will be *reflected* in the view objects of that original array (unlike in the example copied objects above): >>> import numpy >>> c = numpy.array([0, 1, 2, 3, 4]) >>> d = c[::-1] >>> c[2] = 9 >>> c array([0, 1, 9, 3, 4]) >>> d array([4, 3, 9, 1, 0]) >>> To get a reversed *copy* of numpy/Numeric/numarray style arrays, you'll need to use their .copy() method on the extended slice. numpy/Numeric/numarray style arrays have no .reverse() method as typeseq and array module objects do: >>> g = c[::-1].copy() >>> c[2] = 42 >>> c array([ 0, 1, 42, 3, 4]) >>> g array([4, 3, 9, 1, 0]) >>> c.reverse() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'numpy.ndarray' object has no attribute 'reverse' >>> So that extended slicing of the form [::-1] is kind of necessary with numpy/Numeric/numarray style arrays in order to "reverse" the object. Just remember, double colon extended slicing has a different effect on typeseq and array module objects (by making a copy). -- Sincerely, Chris Calloway http://www.seacoos.org office: 332 Chapman Hall phone: (919) 962-4323 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From bgailer at alum.rpi.edu Thu Jul 26 21:42:49 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 26 Jul 2007 12:42:49 -0700 Subject: [Tutor] What exactly is [::-1]? In-Reply-To: References: <46A815C4.5020205@math.usask.ca> <46A8173D.5030501@gmail.com><46a8384b.060e240a.4e2e.ffffc525SMTPIN_ADDED@mx.google.com><46A83DFB.3010806@gmail.com> <78b3a9580707252328w550b25e7sd06e8bcdf37a9bc@mail.gmail.com> Message-ID: <46A8F939.4050405@alum.rpi.edu> Alan Gauld wrote: > The ref manual ... for extended slicing says: > > ---------------------- > The semantics for an extended slicing are as follows. The primary must > evaluate to a mapping object d = {} > It is indexed with a key that is constructed from the slice list, as follows. Note that slice_list ::= slice_item ("," slice_item )* [","] slice_item ::= expression | proper_slice | ellipsis > If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items d[1,2] = 3 > otherwise, the conversion of the lone slice item is the key. This is the usual application of a key where slice_item is an expression d[313] = 4 > The conversion of a slice item that is an expression is that expression. The conversion of an ellipsis slice item is the built-in Ellipsis object. print d {(1, 2): 3, Ellipsis: 4, 313: 4} Now consider: slice_item ::= expression | proper_slice | ellipsis We took care of the cases where slice_item is expression or ellipsis. How to apply a slice_list consisting of slice_item(s) that are proper_slices to a mapping object??? -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From greg.lindstrom at novasyshealth.com Thu Jul 26 21:38:43 2007 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Thu, 26 Jul 2007 14:38:43 -0500 Subject: [Tutor] Running Python on Gentoo In-Reply-To: <46A8F722.4000002@brunson.com> References: <46A8EB99.4070506@novasyshealth.com> <46A8F722.4000002@brunson.com> Message-ID: <46A8F843.7030208@novasyshealth.com> Eric Brunson wrote: > > What does the command "which python" say? glindstrom at bender ~ $ which python /usr/bin/python HTH, --greg From swimlappy at gmail.com Thu Jul 26 21:41:34 2007 From: swimlappy at gmail.com (jason) Date: Thu, 26 Jul 2007 14:41:34 -0500 Subject: [Tutor] Pass variable on command line In-Reply-To: <46A8F6AE.9010203@brunson.com> References: <3216224d0707261202r77ace818n596aaa0eefbd83f6@mail.gmail.com> <46A8F6AE.9010203@brunson.com> Message-ID: <3216224d0707261241t14fac3c6y93bb666248b696ca@mail.gmail.com> Ok, I see now. A dictionary using the list elements as values. This will work for me. Thanks! jason On 7/26/07, Eric Brunson wrote: > > jason wrote: > > Hello, > > > > I have a situation where I have 2 lists > > > > List1 = ['blue', 'red', green'] > > List2 = ['red', 'yellow', 'orange'] > > > > And I would like to pass the list name on the command line like so > > > > ./test.py List1 > > > > I know I can get the argument using sys.argv[1] > > > > But how can I then use the values in that list inside my program? > > > > If I do a VALUES = sys.argv[1], then I get List1 as the values. I > > want the actual list elements.\\ > > The easiest way to do this would be to define your lists in a dictionary: > > > lists = { 'List1': ['blue', 'red', green'], 'List2': ['red', 'yellow', > 'orange'] } > > if len(sys.argv) > 1 and sys.argv[1] in lists: > VALUES = lists[sys.argv[1]] > > > > > > Is this possible? > > > > Thank you > > > > Jason > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > 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/20070726/66d8db1f/attachment.htm From brunson at brunson.com Thu Jul 26 21:48:44 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 26 Jul 2007 13:48:44 -0600 Subject: [Tutor] Running Python on Gentoo In-Reply-To: <46A8F843.7030208@novasyshealth.com> References: <46A8EB99.4070506@novasyshealth.com> <46A8F722.4000002@brunson.com> <46A8F843.7030208@novasyshealth.com> Message-ID: <46A8FA9C.5000703@brunson.com> Greg Lindstrom wrote: > Eric Brunson wrote: > >> What does the command "which python" say? >> > glindstrom at bender ~ $ which python > /usr/bin/python > > HTH, > --greg > > > Wow, Gentoo sucks more than I thought. ;-) I can't think of why that wouldn't work, unless you have some odd, non-printing character at the end of your interpreter line. Do other interpreters work? Try: #!/usr/bin/perl print "Perl Sucks!!!\n"; or: #!/usr/bin/expect puts "I hate TCL" From andreas at kostyrka.org Thu Jul 26 21:47:52 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 26 Jul 2007 21:47:52 +0200 Subject: [Tutor] Pass variable on command line In-Reply-To: References: Message-ID: <46A8FA68.5030100@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Alternatively, I prefer something nicer: import optparse p = optparse.OptionParser(usage="%prog [options]") p.add_option("--list1", action="store_const", const=["blue", "red", "green"], dest="worklist", help="use the first setting") p.add_option("--list2", action="store_const", const=["red", "yellow", "orange"], dest="worklist", help="use the second setting") opt, args = p.parse_args() if opt.worklist is None or len(args) != 0: p.print_help() raise SystemExit(2) This looks longer, but gives you a nice commandline parse that does not bomb out if you do not provide any argument, that is easy to expand, etc. [caveat: the code above is typed into my mailer, so untested, and from memory :) ] Andreas Terry Carroll wrote: > On Thu, 26 Jul 2007, jason wrote: > >> Hello, >> >> I have a situation where I have 2 lists >> >> List1 = ['blue', 'red', green'] >> List2 = ['red', 'yellow', 'orange'] >> >> And I would like to pass the list name on the command line like so >> >> ./test.py List1 >> >> I know I can get the argument using sys.argv[1] >> >> But how can I then use the values in that list inside my program? > > If you must do this, make a dictionary of the lists: > > d = {"List1": List1, "List2": List2} > > and index into it from your argument: > > l = d[sys.argv[1]] > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGqPpoHJdudm4KnO0RAu7AAJwN6Zn4j7XcYQJvLAcEfA6G9l9IngCg4wBt QqB35uZDGZrSoqvJ+TT/Gww= =yOcf -----END PGP SIGNATURE----- From brunson at brunson.com Thu Jul 26 21:49:56 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 26 Jul 2007 13:49:56 -0600 Subject: [Tutor] Livewires questions In-Reply-To: <46A8F3FD.7090908@umn.edu> References: <46A7F3C4.5060002@umn.edu> <46A811A5.7040806@gmail.com> <46A8D1EF.3050807@umn.edu> <000601c7cfbb$d2be0150$e5fce004@JSLAPTOP> <46A8EC54.6020807@brunson.com> <46A8F3FD.7090908@umn.edu> Message-ID: <46A8FAE4.4040608@brunson.com> Tonu Mikk wrote: > Eric Brunson wrote: > >> Tiger12506 wrote: >> >> >>>> Based on your guidance, I figured it out. I need to use a return >>>> statement, which I had not encountered before. Now I wrote my >>>> definitions in this way: >>>> >>>> def collided(): >>>> if player_x == robot_x+0.5 and player_y == robot_y+0.5: >>>> return True >>>> >>>> >>>> >> Granting that I have not looked at any of the Livewires modules, I just >> wanted to say... >> >> A general check for collision would probably involve the distance >> formula from geometry >> >> collided( (x1,y1), (x2,y2) ): >> return( sqrt( (x1-x2)**2 + (y1-y2)**2 ) < 1 ) >> >> but could probably be simplified to something like: >> >> def collided( (x1,y1), (x2,y2) ): >> return( abs( x1 - x2 ) < .5 and abs( y1 - y2 ) < .5 ) >> >> >> > Thanks Eric for your suggestions. I believe Livewires modules have > simplified collision checking for programming novices like myself. > There are two shapes that I am working with, a circle and a square. The > position of the circle is defined by the center coordinates whereas the > position of the square is defined by the lower left corner of the > square. When my circle is 0.5 points in diameter, I can add this much > to both x and y coordinates of the square which will then give me the > point where the square is sitting on top of the circle. It took me a > long time to figure this out. I had to re-read the Graphics guide sheet > that came with Livewires multiple times to try to get it to work > correctly. I believe this part of my code is OK. > > Good deal and good luck. From bhaaluu at gmail.com Thu Jul 26 22:39:11 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 26 Jul 2007 16:39:11 -0400 Subject: [Tutor] Sum of Scores In-Reply-To: References: Message-ID: Greetings, Disclaimer: This source code is written by a Python Newbie. Use at your own risk! =) Here is a snippet that might work for one batter: #!/usr/bin/env python # cricket.py # 2007-07-26 # b h a a l u u at g m a i l dot c o m import random def batterUp(): score=[1,2,3,4,6,'Out'] totalScore=0 while 1: hit=random.choice(score) if hit != score[-1]: totalScore=totalScore+hit print "You batted",hit,"Total runs:",totalScore else: totalScore=totalScore+0 print "You're OUT! Total runs:",totalScore break batterUp() # end criket.py Notice that the list, score , has integers and a string in it. I use the integers to add to the running score, and use the string 'Out' to stop the while loop. I just did this, and it ran okay the few times I tried it. YMMV. =) Happy Programming! -- bhaaluu at gmail dot com On 7/26/07, Tony Noyeaux wrote: > > The projects are moving along. > > I've created a very simplistic cricket game to learn a few things. > > The user is asked whether to play Aggressive or Defensively. > > Once they pick... a random is picked based on their choice,.. and various > scores happen until they get out. > > Ignore the realism at this point,.. just getting the basic mechanics > working first. > > Works fine no problem. > > I want to be able to calculate in the program,.. the total score,.. either > at each successive score,... or when they finally get out. Not sure how to > do that at this point. > > So the output would look something like this. > > You Hit a 2, you now have scored 2 runs > You hit a 4, you now have scored 6 runs > You hit a "Out", you are dismissed for 6 runs total. > > After i get this worked out.. will tweak the actual formulas for the > randoms, maybe put in multiple outs etc,.. changeable strategy at each out > etc, and high scores list towards the end. > > First things first,... and the project at hand. > > How do i ... post the totals... as listed above, to the working code below. > > > Thanks as always > > Tony Noyeaux > > --------------------------------------------------------------------------------- > import random > score = None > strat = raw_input("Will you play (a)aggressive or (b)defensive?") > if strat == "a": > while score != "Out": > score = > random.choice(["1","2","3","4","4","6","6","Out","Out","Out","Out"]) > print score > else: > while score != "Out": > score = > random.choice(["1","1","2","2","3","4","6","Out"]) > print "You hit a "+score > ---------------------------------------------------------------------------------- > > ________________________________ > PC Magazine's 2007 editors' choice for best web mail?award-winning Windows > Live Hotmail. Check it out! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From bgailer at alum.rpi.edu Thu Jul 26 22:51:00 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 26 Jul 2007 13:51:00 -0700 Subject: [Tutor] Extended slicing applied to mapping objects (was What exactly is [::-1]?) In-Reply-To: <46A8F939.4050405@alum.rpi.edu> References: <46A815C4.5020205@math.usask.ca> <46A8173D.5030501@gmail.com><46a8384b.060e240a.4e2e.ffffc525SMTPIN_ADDED@mx.google.com><46A83DFB.3010806@gmail.com> <78b3a9580707252328w550b25e7sd06e8bcdf37a9bc@mail.gmail.com> <46A8F939.4050405@alum.rpi.edu> Message-ID: <46A90934.80904@alum.rpi.edu> Bob Gailer wrote: > Alan Gauld wrote: > >> The ref manual ... for extended slicing says: >> >> ---------------------- >> The semantics for an extended slicing are as follows. The primary must >> evaluate to a mapping object >> > d = {} > >> It is indexed with a key that is constructed from the slice list, as follows. >> > Note that (CORRECTION removed the html tags) > slice_list ::= slice_item ("," slice_item)* [","] > slice_item ::= expression | proper_slice | ellipsis > > >> If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items >> > d[1,2] = 3 > >> otherwise, the conversion of the lone slice item is the key. >> > This is the usual application of a key where slice_item is an expression > > d[313] = 4 > >> The conversion of a slice item that is an expression is that expression. The conversion of an ellipsis slice item is the built-in Ellipsis object. >> > print d > {(1, 2): 3, Ellipsis: 4, 313: 4} > > Now consider: > > slice_item ::= expression | > proper_slice | ellipsis > > > > > We took care of the cases where slice_item is expression or ellipsis. > > How to apply a slice_list consisting of slice_item(s) that are > proper_slices to a mapping object??? > > -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From timmichelsen at gmx-topmail.de Thu Jul 26 22:51:15 2007 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Thu, 26 Jul 2007 22:51:15 +0200 Subject: [Tutor] adapting a converter openoffice Message-ID: Hello, I am Python learning in an early stage. I am currently trying to code a converter for openoffice based on PyODConverter: http://www.artofsolving.com/opensource/pyodconverter My goal is to be able to run my script from anywhere in the system (put it in Path) and then convert a file from/to openoffice formats to other formats such as doc/pdf etc. My main problem is how to issue system commands and then run the above script. PyODConverter needs OpenOffice.org to be running as a service which can be initiated through the following command on the command line (linux shell): soffice -headless -accept="socket,port=8100;urp;" once the service is up and running the conversion process is really straight forward: python DocumentConverter.py test.odt test.pdf where DocumentConverter.py is the ready-to-use converter program downloadable at http://www.artofsolving.com/opensource/pyodconverter I want to be able to convert the files anywhere without the need to start the OOo service seperately. Therefore I tried to add this code on top of the original converter: ###get OOo service started first: import os code = os.system('soffice -headless -accept="socket,port=8100;urp;"') # Just execute the command, return a success/fail code when I execute this script nothing happens and I would have to cancel it. Is there any way to start the OOo service from a python script? Thanks in advance for your help! Timmie From dkuhlman at rexx.com Thu Jul 26 23:33:53 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 26 Jul 2007 14:33:53 -0700 Subject: [Tutor] Running Python on Gentoo In-Reply-To: <46A8FA9C.5000703@brunson.com> References: <46A8EB99.4070506@novasyshealth.com> <46A8F722.4000002@brunson.com> <46A8F843.7030208@novasyshealth.com> <46A8FA9C.5000703@brunson.com> Message-ID: <20070726213353.GA90872@cutter.rexx.com> On Thu, Jul 26, 2007 at 01:48:44PM -0600, Eric Brunson wrote: > > Do other interpreters work? > > Try: > > #!/usr/bin/perl > print "Perl Sucks!!!\n"; > > or: Or, try: #!/usr/bin/env python Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From rabidpoobear at gmail.com Thu Jul 26 23:34:02 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 26 Jul 2007 16:34:02 -0500 Subject: [Tutor] Livewires questions In-Reply-To: <46A8D1EF.3050807@umn.edu> References: <46A7F3C4.5060002@umn.edu> <46A811A5.7040806@gmail.com> <46A8D1EF.3050807@umn.edu> Message-ID: <46A9134A.6090106@gmail.com> Tonu Mikk wrote: > Luke, thank you for your quick and complete response. Based on your > suggestions I have already made some progress! BTW, I am so glad that > I can ask this list my Python questions and get help. I began feeling > quite stuck and not knowing where to turn for help. So, thank you for > the great service! Sure! I'm happy to he;lp :) > > [snip] > It took me a loooong time to figure out how to write my code so that > when the robot sits exactly on top of the player, there is a message > "you have been caught" :-) . When I run the code, the robot will sit > on top of the player and I can have the message printed - yeaaah! Awesome, congrats! > [snip] > Thanks for this suggestion. I will likely need to re-write how I > check for boundaries. Currently I was checking for boundaries after I > moved the player. I did this by not letting the player_x and player_y > coordinates to be changed if the player was going to go beyond > boundaries. It seems I need to put in a check for boundaries before I > move the player. That should have worked as well. > Yes, I do want you to comment on the code, absolutely, which I see you > so generously did in another email. >_> Yes, I tend to ramble a bit when explaining things. > Thank you, > Tonu That's what I'm here for, all you guys' smiling faces ;) -Luke From rabidpoobear at gmail.com Thu Jul 26 23:29:09 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 26 Jul 2007 16:29:09 -0500 Subject: [Tutor] adapting a converter openoffice In-Reply-To: References: Message-ID: <46A91225.5030102@gmail.com> Tim Michelsen wrote: > Hello, > I am Python learning in an early stage. > > I am currently trying to code a converter for openoffice based on > PyODConverter: > http://www.artofsolving.com/opensource/pyodconverter > > My goal is to be able to run my script from anywhere in the system (put > it in Path) and then convert a file from/to openoffice formats to other > formats such as doc/pdf etc. > > My main problem is how to issue system commands and then run the above > script. > > [snip] > I tried to add this code on top of the original converter: > > ###get OOo service started first: > import os > code = os.system('soffice -headless -accept="socket,port=8100;urp;"') # > Just execute the command, return a success/fail code > > when I execute this script nothing happens and I would have to cancel it. > > Is there any way to start the OOo service from a python script? > My first hunch would be that the command is running as a background service (daemon) so it's not returning control to your program from the os.system call because the execution hasn't completed yet. Try doing a ps -ax or whatever, to see what processes you have running, after you start your python program and before you quit it. If you see an instance of soffice running, try terminating it and see if your program continues to execute (and probably raises errors). If this is the case, you will want to use one of the other os commands, or subprocess, so that the soffice program will continue to run but you'll get control back in your program. The only caveat to that approach would be that the soffice app continuing to run is dependent upon your python program continuing to run. I.E. when you exit the python program, the soffice instance that it started (if it started one) will be ended. Although, you could probably just allow the python program to continue to run. Not sure, I don't know anything about linux and I haven't had to do something similar to this before. hope that he;lps. -Luke From alan.gauld at btinternet.com Thu Jul 26 23:47:15 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Jul 2007 22:47:15 +0100 Subject: [Tutor] Thanks re: [::-1] References: Message-ID: "Charles Cuell" wrote > The one odd thing about Python's slice notation is that the -1 means > to > start from the end and work backwards. My first inclination would > have > been to assume that -1 means to start at i and go to j by steps > of -1 > (only nonempy if j < i). I mentally resolve this by thinking of sequences as being circular. Thus the -1 character is the last one - the one before the first. But that doesn't work for the step size k, you just have to realise that the minus sign there means work backwards and therefore start from the second parameter. However... >>> 'abcdefgh'[3:1:-1] 'dc' >>> 'abcdefgh'[1:3:-1] '' >>> 'abcdefgh'[::-1] 'hgfedcba' It seems that if you do provide values for j,k the first must be bigger than the second to work so Python is being slightly more intelligent about the default values than I initially thought, but the docs do say: ---------------- If i or j are omitted or None, they become ``end'' values (which end depends on the sign of k). --------------- How interesting. And thank goodness for the >>> prompt. - the ultimate arbiter and test... Alan G. From alan.gauld at btinternet.com Thu Jul 26 23:53:04 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Jul 2007 22:53:04 +0100 Subject: [Tutor] adapting a converter openoffice References: Message-ID: "Tim Michelsen" wrote > > Therefore I tried to add this code on top of the original converter: > > ###get OOo service started first: > import os > code = > os.system('soffice -headless -accept="socket,port=8100;urp;"') > when I execute this script nothing happens and I would have to > cancel it. When you say nothing happemed I assume you mean the script never terminated? If so I suspect your command needs to be run in the background by placing an ampersand at the end, like so: code = os.system('soffice -headless -accept="socket,port=8100;urp;" &') That should result in os.system returning with an exit code. HTH, Alan G. From kent37 at tds.net Thu Jul 26 14:13:24 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Jul 2007 08:13:24 -0400 Subject: [Tutor] Code like a Pythonista Message-ID: <46A88FE4.8040702@tds.net> For anyone who has wondered, how do I learn to write Python like an expert? What do I read after I finish the tutorial? Check out David Goodger's "Code Like a Pythonista" http://python.net/~goodger/projects/pycon/2007/idiomatic/ Kent From keridee at jayco.net Fri Jul 27 01:25:15 2007 From: keridee at jayco.net (Tiger12506) Date: Thu, 26 Jul 2007 18:25:15 -0500 Subject: [Tutor] Sum of Scores References: Message-ID: <009401c7cfdc$3c3b4320$d6fce004@JSLAPTOP> Note that OP constructed his list so that some values are weighted according to the user's decision (Aggressive or defensive), Just let's not forget that brilliance~ ;-) Suggestions below. > Here is a snippet that might work for one batter: > > #!/usr/bin/env python > # cricket.py > # 2007-07-26 > # b h a a l u u at g m a i l dot c o m > import random > > def batterUp(): > score=[1,2,3,4,6,'Out'] > totalScore=0 > while 1: > hit=random.choice(score) > if hit != score[-1]: > totalScore=totalScore+hit > print "You batted",hit,"Total runs:",totalScore > else: > totalScore=totalScore+0 > print "You're OUT! Total runs:",totalScore > break > > batterUp() > # end criket.py > > Notice that the list, score , has integers and a string in it. > I use the integers to add to the running score, and use the > string 'Out' to stop the while loop. I just did this, and it ran > okay the few times I tried it. YMMV. =) This is one situation where the python concept of ask forgiveness later is convenient. For example. ########### def play(): score = [1,2,3,4,6,'Out'] totalScore = 0 while 1: hit = random.choice(score) try: totalScore += int(hit) print "You batted a %s; Total runs: %d" % (hit,totalScore) except ValueError: print "You're OUT! Total runs:", totalScore break ############ And a way that is even better of which I just thought ;-) Use a special value to mean 'out'. This avoids the string problem. A value of zero makes the comparisons with if even simpler. ######### def play(): scores = [1,1,2,2,3,4,6,0,0] #Zero means "out" totalScore = 0 while 1: hit = random.choice(scores) totalScore += hit if hit: # The magic check - even makes sense, if no hit, then "out" print "You batted a %d, Total runs: %d" % (hit, totalScore) else: print "You're OUT! Total runs: %d" % totalScore ########## A sneaky application of a form of encapsulation that OOP people like to use. ;-) (So you only have to have one play function) ####### aggr_scores = [1,2,3,4,4,6,6,0,0,0] defe_scores = [1,1,1,2,2,3,4,6,0,0] user_choice = raw_input("Which?\n\t(a) Aggressive\n\t(b) Defensive\n\nYour choice: ") if user_choice == 'a': scores = aggr_scores elif user_choice == 'b': scores = defe_scores else: print "Please choose a or b" play() ######## Or even better. ######### score_lookup = {'a':[1,2,3,4,4,6,6,0,0,0], 'b':[1,1,1,2,2,3,4,6,0,0]} # raw_input here scores = score_lookup[user_choice] play() ############# HTH, JS From timmichelsen at gmx-topmail.de Fri Jul 27 00:44:50 2007 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Fri, 27 Jul 2007 00:44:50 +0200 Subject: [Tutor] adapting a converter openoffice In-Reply-To: References: Message-ID: > When you say nothing happemed I assume you mean the script > never terminated? Yes, you are right. it does not terminate and only blocks the screen. As stated on the site the script needs some special parameters of Openoffice. Therefore, until I step further, I wrap it around a shell script that I will put in my PATH: #!/bin/bash ###licence ##which licence applies for this script? If not changed it will be released under GPL: #This shell script is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. # #This shell script is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # #You should have received a copy of the GNU General Public License along with this shell script ; if not, write to the #Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #or read the text online: http://www.gnu.org/licenses/gpl.txt ###script description ##convert from/to openoffice document formats using a script from ##http://www.artofsolving.com/opensource/pyodconverter ##see also: http://www.linux.com/articles/61713 #start OpenOffice as a service soffice -headless -accept="socket,port=8100;urp;" #get variables # @1 = SOURCE # @2 = DESTINATION #convert command # /opt/local/pyodconverter $SOURCE $DESTINATION cd /opt/local/pyodconverter/ python ./DocumentConverter.py $1 $2 exit Maybe one day I will be able to do this in python using pyodconverter as a class... From amonroe at columbus.rr.com Thu Jul 26 23:55:52 2007 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu, 26 Jul 2007 17:55:52 -0400 Subject: [Tutor] Sum of Scores In-Reply-To: References: Message-ID: <741198400118.20070726175552@columbus.rr.com> > I want to be able to calculate in the program,.. the total score,.. > either at each successive score,... or when they finally get out. > Not sure how to do that at this point. You're on the right track. You need an additional variable to hold the running total. Alan From bhaaluu at gmail.com Fri Jul 27 00:50:58 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 26 Jul 2007 18:50:58 -0400 Subject: [Tutor] Sum of Scores In-Reply-To: <009401c7cfdc$3c3b4320$d6fce004@JSLAPTOP> References: <009401c7cfdc$3c3b4320$d6fce004@JSLAPTOP> Message-ID: Greetings, Beautiful! Thank you SO much for all the variations. I'm so sure I'll have much to learn from them. This is exactly the kind of stuff I'm currently studying. I have a question for the list. After I posted my snippet, I added time to import, and a time.sleep(1) line to the code. The reason I did this is because I'm under the (possibly mistaken?) impression that random uses the computer time as a random number generator 'seed', for generating pseudo-random numbers? Perhaps this is a question for the 'language lawyers'? Cheers! -- bhaaluu at gmail dot com On 7/26/07, Tiger12506 wrote: > Note that OP constructed his list so that some values are weighted according > to the user's decision (Aggressive or defensive), Just let's not forget that > brilliance~ ;-) > > Suggestions below. > > > Here is a snippet that might work for one batter: > > > > #!/usr/bin/env python > > # cricket.py > > # 2007-07-26 > > # b h a a l u u at g m a i l dot c o m > > import random > > > > def batterUp(): > > score=[1,2,3,4,6,'Out'] > > totalScore=0 > > while 1: > > hit=random.choice(score) > > if hit != score[-1]: > > totalScore=totalScore+hit > > print "You batted",hit,"Total runs:",totalScore > > else: > > totalScore=totalScore+0 > > print "You're OUT! Total runs:",totalScore > > break > > > > batterUp() > > # end criket.py > > > > Notice that the list, score , has integers and a string in it. > > I use the integers to add to the running score, and use the > > string 'Out' to stop the while loop. I just did this, and it ran > > okay the few times I tried it. YMMV. =) > > This is one situation where the python concept of ask forgiveness later is > convenient. > For example. > > ########### > def play(): > score = [1,2,3,4,6,'Out'] > totalScore = 0 > while 1: > hit = random.choice(score) > try: > totalScore += int(hit) > print "You batted a %s; Total runs: %d" % (hit,totalScore) > except ValueError: > print "You're OUT! Total runs:", totalScore > break > ############ > > And a way that is even better of which I just thought ;-) > Use a special value to mean 'out'. This avoids the string problem. > A value of zero makes the comparisons with if even simpler. > > ######### > def play(): > scores = [1,1,2,2,3,4,6,0,0] #Zero means "out" > totalScore = 0 > while 1: > hit = random.choice(scores) > totalScore += hit > if hit: # The magic check - even makes sense, if no hit, then > "out" > print "You batted a %d, Total runs: %d" % (hit, totalScore) > else: > print "You're OUT! Total runs: %d" % totalScore > ########## > > A sneaky application of a form of encapsulation that OOP people like to use. > ;-) > (So you only have to have one play function) > > ####### > aggr_scores = [1,2,3,4,4,6,6,0,0,0] > defe_scores = [1,1,1,2,2,3,4,6,0,0] > > user_choice = raw_input("Which?\n\t(a) Aggressive\n\t(b) Defensive\n\nYour > choice: ") > if user_choice == 'a': > scores = aggr_scores > elif user_choice == 'b': > scores = defe_scores > else: > print "Please choose a or b" > > play() > ######## > > Or even better. > > ######### > score_lookup = {'a':[1,2,3,4,4,6,6,0,0,0], > 'b':[1,1,1,2,2,3,4,6,0,0]} > > # raw_input here > > scores = score_lookup[user_choice] > play() > ############# > > HTH, > JS > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Fri Jul 27 00:57:46 2007 From: rdm at rcblue.com (Dick Moores) Date: Thu, 26 Jul 2007 15:57:46 -0700 Subject: [Tutor] What exactly is [::-1]? In-Reply-To: <46A8F812.3090802@unc.edu> References: <46A815C4.5020205@math.usask.ca> <46A8173D.5030501@gmail.com> <46a8384b.060e240a.4e2e.ffffc525SMTPIN_ADDED@mx.google.com> <46A83DFB.3010806@gmail.com> <78b3a9580707252328w550b25e7sd06e8bcdf37a9bc@mail.gmail.com> <46A87A1B.9040107@tds.net> <46A8F812.3090802@unc.edu> Message-ID: <20070726225753.72F2D1E4003@bag.python.org> At 12:37 PM 7/26/2007, Chris Calloway wrote: >The *other* form of extended slicing, the one with two colons (and no >commas) is supported by typeseq objects, though. What are typeseq objects. Searching the python site on "typeseq" draws a blank. Dick Moores From rabidpoobear at gmail.com Fri Jul 27 01:26:12 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 26 Jul 2007 18:26:12 -0500 Subject: [Tutor] Sum of Scores In-Reply-To: References: <009401c7cfdc$3c3b4320$d6fce004@JSLAPTOP> Message-ID: <46A92D94.3090804@gmail.com> bhaaluu wrote: > Greetings, > > Beautiful! Thank you SO much for all the variations. > I'm so sure I'll have much to learn from them. This > is exactly the kind of stuff I'm currently studying. > > I have a question for the list. > After I posted my snippet, I added time to import, > and a time.sleep(1) line to the code. The reason > I did this is because I'm under the (possibly mistaken?) > impression that random uses the computer > time as a random number generator 'seed', > for generating pseudo-random numbers? > It uses time, it may also use other things. However, this is only to initialize the random number generator. You only need one seed and from that you can generate an infinitely long string of pseudo-random numbers. In other words, the only way you'd end up getting the same value is if you ran the program, quit it, then ran it again, in less than a second. (or possibly reloaded the module) But you can call the random functions in your code as often as you want safely. > Perhaps this is a question for the 'language lawyers'? > Not sure what this means. -Luke From keridee at jayco.net Fri Jul 27 03:24:46 2007 From: keridee at jayco.net (Tiger12506) Date: Thu, 26 Jul 2007 20:24:46 -0500 Subject: [Tutor] What exactly is [::-1]? References: <46A815C4.5020205@math.usask.ca> <46A8173D.5030501@gmail.com><46a8384b.060e240a.4e2e.ffffc525SMTPIN_ADDED@mx.google.com><46A83DFB.3010806@gmail.com><78b3a9580707252328w550b25e7sd06e8bcdf37a9bc@mail.gmail.com> <46A87A1B.9040107@tds.net><46A8F812.3090802@unc.edu> <20070726225753.72F2D1E4003@bag.python.org> Message-ID: <001d01c7cfec$f9d5ac30$d6fce004@JSLAPTOP> > What are typeseq objects. Searching the python site on "typeseq" draws a > blank. > > Dick Moores I believe that means "sequence" type. list tuple string are the builtins I debated with myself about dict, decided that it doesn't fit the description. That should be all ordered sequence types. JS From keridee at jayco.net Fri Jul 27 03:36:15 2007 From: keridee at jayco.net (Tiger12506) Date: Thu, 26 Jul 2007 20:36:15 -0500 Subject: [Tutor] Sum of Scores References: <009401c7cfdc$3c3b4320$d6fce004@JSLAPTOP> <46A92D94.3090804@gmail.com> Message-ID: <002401c7cfee$9a191690$d6fce004@JSLAPTOP> > bhaaluu wrote: >> Greetings, >> >> Beautiful! Thank you SO much for all the variations. >> I'm so sure I'll have much to learn from them. This >> is exactly the kind of stuff I'm currently studying. I assume this is for me. Thank you kindly! :-) >> I have a question for the list. >> After I posted my snippet, I added time to import, >> and a time.sleep(1) line to the code. The reason >> I did this is because I'm under the (possibly mistaken?) >> impression that random uses the computer >> time as a random number generator 'seed', >> for generating pseudo-random numbers? >> > It uses time, it may also use other things. > However, this is only to initialize the random number generator. > You only need one seed and from that you can generate an infinitely long > string of pseudo-random numbers. Not infinitely long. From the docs - [Quote] Almost all module functions depend on the basic function random(), which generates a random float uniformly in the semi-open range [0.0, 1.0). Python uses the Mersenne Twister as the core generator. It produces 53-bit precision floats and has a period of 2**19937-1. The underlying implementation in C is both fast and threadsafe. The Mersenne Twister is one of the most extensively tested random number generators in existence. However, being completely deterministic, it is not suitable for all purposes, and is completely unsuitable for cryptographic purposes. [/Quote] So only if you use the random functions 4.3154247973881626480552355163379e+6001 times would the pattern repeat itself. Until then, you're safe. ;-) > In other words, the only way you'd end up getting the same value is if > you ran the program, quit it, then ran it again, in less than a second. > (or possibly reloaded the module) This freaked me out for a bit with a c program I wrote a while back. It was a screen saver built upon random values. I would double click its icon, and accidently jerk the mouse, double click it again. I thought I noticed that the two screens were the same. A little research brought me to that tidbit of information. I'm not sure if reloading the module would or not. I would think that the seeding of the generator would occur at import of the random module. In which case, it would only happen once because import modules are not imported twice in the same session. (see recent threads) > But you can call the random functions in your code as often as you want > safely. >> Perhaps this is a question for the 'language lawyers'? >> > Not sure what this means. I believe it means 'those who know the language inside and out' like a lawyer must know the law. JS From carroll at tjc.com Fri Jul 27 02:49:11 2007 From: carroll at tjc.com (Terry Carroll) Date: Thu, 26 Jul 2007 17:49:11 -0700 (PDT) Subject: [Tutor] Sum of Scores In-Reply-To: <002401c7cfee$9a191690$d6fce004@JSLAPTOP> Message-ID: On Thu, 26 Jul 2007, Tiger12506 wrote: > > But you can call the random functions in your code as often as you want > > safely. > >> Perhaps this is a question for the 'language lawyers'? > >> > > Not sure what this means. > > I believe it means 'those who know the language inside and out' like a > lawyer must know the law. A little more subtle. The Jargon File explains it best: language lawyer: n. A person, usually an experienced or senior software engineer, who is intimately familiar with many or most of the numerous restrictions and features (both useful and esoteric) applicable to one or more computer programming languages. A language lawyer is distinguished by the ability to show you the five sentences scattered through a 200-plus-page manual that together imply the answer to your question "if only you had thought to look there." http://www.catb.org/jargon/html/L/language-lawyer.html So it's more about the ability to know and correctly interpret the docs, especially in the area of how the different provisions interact. If you've ever seen an attorney work through the question "does our contract let us do FOO?" -- well, I'd feel sorry for you if so, because that's time you're never getting back, but you'd see the similarity. Now excuse me, I have a contract to go look through. From rabidpoobear at gmail.com Fri Jul 27 05:03:09 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 26 Jul 2007 22:03:09 -0500 Subject: [Tutor] Sum of Scores In-Reply-To: <002401c7cfee$9a191690$d6fce004@JSLAPTOP> References: <009401c7cfdc$3c3b4320$d6fce004@JSLAPTOP> <46A92D94.3090804@gmail.com> <002401c7cfee$9a191690$d6fce004@JSLAPTOP> Message-ID: <46A9606D.5070709@gmail.com> Tiger12506 wrote: >> bhaaluu wrote: >> >>> Greetings, >>> >>> Beautiful! Thank you SO much for all the variations. >>> I'm so sure I'll have much to learn from them. This >>> is exactly the kind of stuff I'm currently studying. >>> > > I assume this is for me. Thank you kindly! :-) > > >>> I have a question for the list. >>> After I posted my snippet, I added time to import, >>> and a time.sleep(1) line to the code. The reason >>> I did this is because I'm under the (possibly mistaken?) >>> impression that random uses the computer >>> time as a random number generator 'seed', >>> for generating pseudo-random numbers? >>> >>> >> It uses time, it may also use other things. >> However, this is only to initialize the random number generator. >> You only need one seed and from that you can generate an infinitely long >> string of pseudo-random numbers. >> > > Not infinitely long. From the docs - > > [Quote] > Almost all module functions depend on the basic function random(), which > generates a random float uniformly in the semi-open range [0.0, 1.0). Python > uses the Mersenne Twister as the core generator. It produces 53-bit > precision floats and has a period of 2**19937-1. The underlying > implementation in C is both fast and threadsafe. The Mersenne Twister is one > of the most extensively tested random number generators in existence. > However, being completely deterministic, it is not suitable for all > purposes, and is completely unsuitable for cryptographic purposes. > [/Quote] > > So only if you use the random functions > 4.3154247973881626480552355163379e+6001 > times would the pattern repeat itself. Until then, you're safe. ;-) > Well, I was trying to emphasize that it was, for pretty much all intents and purposes, infinite. via timeit, my computer can perform approximately 4000000 random.random()s per second. >>> x = timeit.Timer('random.random()','import random') >>> x.timeit(4000000) 1.0523957653835794 4*10**6001 / 4*10**6 is still 10**5095 seconds before the period is repeated (and remember this is when i'm trying to cause a repetition, not using the module normally!) The relationship between seconds and years is >>> 60*60*24*365.25 31579200.0 i.e. 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 365.25 days per year. Therefore, it would take my computer >>> (10**5095) / int(60*60*24*365.25) years (which is too long to post in this e-mail) in fact, it's so large I am having a hard time believing I didn't make a mistake in my calculations somewhere. somewhere on the order of a centillion**quadrillion years. (a centillion is 10**303 or 100000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000 0000 and a quadrillion is 10**15 or 1000000000000000. In other words, approx. (very approximately :)) 10**4545 years) Because the possibility of my computer even existing after that long is effectively zero, I consider the pattern to never repeat :) >> In other words, the only way you'd end up getting the same value is if >> you ran the program, quit it, then ran it again, in less than a second. >> (or possibly reloaded the module) >> > > This freaked me out for a bit with a c program I wrote a while back. It was > a screen saver built upon random values. I would double click its icon, and > accidently jerk the mouse, double click it again. I thought I noticed that > the two screens were the same. A little research brought me to that tidbit > of information. > > I'm not sure if reloading the module would or not. I would think that the > seeding of the generator would occur at import of the random module. In > which case, it would only happen once because import modules are not > imported twice in the same session. (see recent threads) > by reloading I didn't mean importing it again. I meant reload()ing it. Well, we can test this pretty easily. >>> import random >>> for x in range(10): reload(random) print random.random() 0.322316243317 0.223659531704 0.991195051657 0.0349410934903 0.586833655938 0.0090626236054 0.0650813786008 0.198508992645 0.0567290580105 0.0446836944247 Nope, I guess reloading it doesn't cause it to reuse the same seed. See, I thought reload was just a forced 'import'. But maybe it has some complexity behind it, as per it not reloading() if the module hasn't changed? The docstring isn't a whole lot of help on this: >>> help(reload) Help on built-in function reload in module __builtin__: reload(...) reload(module) -> module Reload the module. The module must have been successfully imported before. From keridee at jayco.net Fri Jul 27 10:13:20 2007 From: keridee at jayco.net (Tiger12506) Date: Fri, 27 Jul 2007 03:13:20 -0500 Subject: [Tutor] Sum of Scores References: <009401c7cfdc$3c3b4320$d6fce004@JSLAPTOP> <46A92D94.3090804@gmail.com> <002401c7cfee$9a191690$d6fce004@JSLAPTOP> <46A9606D.5070709@gmail.com> Message-ID: <001401c7d026$02865080$c3fce004@JSLAPTOP> Hmmm... interesting tie to another post... >>> x = timeit.Timer('random.random()','import random') >>> x.timeit(3000000) 1.0161026052194018 >>> y = timeit.Timer('random()','from random import random') >>> y.timeit(4600000) 1.0004307810070827 Dictionary lookups do take HUGE amounts of time. Interesting. Anyway... I've got it down to Your numbers with a little more precision gave me 3.4e5987 yrs. and mine 3.0e5987 yrs. That's a hell of a lot of years! Remember that everyone! If you want your code to run forever and to eternity, copy variables to the local namespace first; you get a lot more accomplished (well... whatever) ;-) Anyway, the frivolity aside, I can get it to repeat every ten seconds. ;-) Set the computer clock. (okay, maybe i'm just in a silly mood. But seriously, that's why the docs say that it is NOT meant for cryptography - not that that matters to the OP, snicker; What have I been drinking????) > Well, I was trying to emphasize that it was, for pretty much all intents > and purposes, infinite. Nope-nope-nope you're wrong :-)~ The daring cracker enters the room, his heart quickening as the door hinge creaks with the sound of the smallest ever mouse. His dark clothing masks him from the lit room visible through the window on the adjacent wall. A woman, working late, sits in a comfortable office chair, her face glowing from the reflection of her computer screen. A cup of Java (pun intended) indicates to anyone watching that she is overworked, and under-paid. Each step he takes brings him closer to his target. The big boss gave him a pay cut so that this new PC could sit on his boss's desk. The cracker's jealously seems to almost permeate the room. Vengeance shouts out louder than the compressor of the air conditioner in the north window. The cracker intinctively looks up to see if his emotions betrayed his presence. But the woman in the other room continues her scrolling through endless lines of buggy, hard to read, unmaintainable, bloated, and otherwise ridiculously foolish code that could have been so easily fixed if the same 'big boss' had ordered the project in Python. Soon, a floppy disk is pulled out of a black jacket pocket. No one has ever run the program on the floppy before. Taking the disk, the cracker inserts it into the drive, starts the machine, swears under his breath when he reads "Non-System disk or disk error. Replace and strike any." Striking the 'any' key, he quickly shoves the floppy disk back in. He wants this over with. Again, he looks to see if he has been detected; still he is safe. Opening the folder containing the floppy drive, he groans silently as the annoying Windows Firewall flashes an update notice. "See..." he thinks to himself, "Micro$oft *can* actually restrict viruses from entering their OS." He fights with the window, impatiently waiting for countless libraries to load and free, until the UI responds and he can send it a WM_CLOSE message. Smirking evily, the cracker double-clicks the executable 'pink_fuzzy_bunny.exe' and resists the urge to laugh maniacally as he watches the computer clock freeze and not move. Ingenious--his plan--All it takes to freeze time is to contantly set it to the same second in history. Time. Forever frozen. He frowns as he realizes that in so doing, he provides the only effective means for keeping those pesky Windows notices out of his boss's hair. "No matter" --he thinks, "He will have worse troubles in due time." Again he suppresses a maniacal laugh. . . . Monday morning brings a bright and cheerful man into an office, his office. The door creaks a little as he opens it, and the air conditioner buzzing in the north wall window is refreshing to him after the heat from outside. The man waves cheerfully at a woman through the glass in the adjacent wall, whom looks up only for an instant to scowl. The man, who recently bought his new PC, smiles proudly as he turns it on. His new python program which he keeps on the desktop is his early attempt at a cricket game simulation. He lovingly double-clicks the icon, and runs the program several times. Each successive time his grin grows smaller and smaller until his face is more than troubled. Why is his program producing the same output every time? A scream is heard in the office "NOOOOOOO!!!!!!!!" The boss runs from the building, never to notice the clock in the bottom-right hand corner which still shows the caption '10:33 PM'. Somewhere, someplace a cracker lies in bed, a silly grin on his face. His objective, he knows, has been accomplished. > Because the possibility of my computer even existing after that long is > effectively zero, I consider the pattern to never repeat :) Ahhh... Your computer ~ sitting on a pedestal in the middle of nowhere in AD 3.0e5988, the last shrine to the ancient past-- A technological marvel to the ape like creatures whom are all that remain of the once all powerful race of human beings. Our ape, named Jogg, looks at the bright computer screen, jumps back in fear as the ancient Windows Beep function is called and the foreign noise hits him. What is this? There is a message there. ... ... File "", line 2, in find File "", line 2, in find File "", line 2, in find RuntimeError: maximum recursion depth exceeded >>> Damn. I guess we will never know. (okay... maybe nobody spiked my Mt. Dew, but maybe because it's after 3:00 am) JS From rdm at rcblue.com Fri Jul 27 10:20:00 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 27 Jul 2007 01:20:00 -0700 Subject: [Tutor] Code like a Pythonista In-Reply-To: <46A88FE4.8040702@tds.net> References: <46A88FE4.8040702@tds.net> Message-ID: <20070727082009.80DE61E4005@bag.python.org> At 05:13 AM 7/26/2007, Kent Johnson wrote: >For anyone who has wondered, how do I learn to write Python like an >expert? What do I read after I finish the tutorial? Check out David >Goodger's "Code Like a Pythonista" >http://python.net/~goodger/projects/pycon/2007/idiomatic/ Kent, The handout is excellent! Thanks! But the slideshow at , isn't. Dick Moores From David.Barton at nottingham.ac.uk Fri Jul 27 10:51:54 2007 From: David.Barton at nottingham.ac.uk (Barton David) Date: Fri, 27 Jul 2007 09:51:54 +0100 Subject: [Tutor] Shelve del not reducing file size Message-ID: Hi, I've hit a snag with Python's shelve module. By way of example... _____ from shelve import DbfilenameShelf as StoreFile import os sf=StoreFile("mytest.db",writeback=False) # but same problem if writeback=True for i in range(10000): sf[str(i)]="TESTOBJECT" sf.sync() print len(sf) sf.close() predeletesize=os.path.getsize("mytest.db") print predeletesize sf=StoreFile("mytest.db",writeback=False) # but same problem if writeback=True for i in range(5000): del sf[str(i)] sf.sync() print len(sf) sf.close() postdeletesize=os.path.getsize("mytest.db") print postdeletesize _____ So why, when I run this, does predeletesize!=postdeletesize? I gather that with most database types you have to invoke a special command like VACUUM to perform cleanups after table deletions etc so, since shelve uses database backends, is this related to that? Is there a way to tell (e.g.) a DBfilenameShelf to do this? Or am I stuck with having to delete the entire file and save it again? Running PythonWin 2.5.1 on XP. thanks Dave This message has been checked for viruses but the contents of an attachment may still contain software viruses, which could damage your computer system: you are advised to perform your own checks. Email communications with the University of Nottingham may be monitored as permitted by UK legislation. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070727/20a5c4f1/attachment.html From andreas at kostyrka.org Fri Jul 27 11:49:28 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 27 Jul 2007 11:49:28 +0200 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: References: Message-ID: <46A9BFA8.2020209@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 That's in the nature of the underlying database library used for the shelve. Most dbm implemention on Unix are using a sparse file that is used as hashmap. E.g. compare ls -l versus du of the database file. Now if this is the case, there is no way (with the exception of rewriting the whole file cleverly from scratch, e.g. with cp - --sparse=always) to release the unused space. (I don't think that even Linux detects 0 byte filled pages and frees them.) Andreas Barton David wrote: > Hi, > > I've hit a snag with Python's shelve module. By way of example... > > _____ > from shelve import DbfilenameShelf as StoreFile > import os > > sf=StoreFile("mytest.db",writeback=False) # but same problem if > writeback=True > for i in range(10000): > sf[str(i)]="TESTOBJECT" > sf.sync() > print len(sf) > sf.close() > predeletesize=os.path.getsize("mytest.db") > print predeletesize > > sf=StoreFile("mytest.db",writeback=False) # but same problem if > writeback=True > for i in range(5000): > del sf[str(i)] > sf.sync() > print len(sf) > sf.close() > postdeletesize=os.path.getsize("mytest.db") > print postdeletesize > _____ > > So why, when I run this, does predeletesize!=postdeletesize? > I gather that with most database types you have to invoke a special > command like VACUUM to perform cleanups after table deletions etc > so, since shelve uses database backends, is this related to that? Is > there a way to tell (e.g.) a DBfilenameShelf to do this? Or am I stuck > with having to delete the entire file and save it again? > > > Running PythonWin 2.5.1 on XP. > > thanks > Dave > > This message has been checked for viruses but the contents of an > attachment may still contain software viruses, which could damage your > computer system: you are advised to perform your own checks. Email > communications with the University of Nottingham may be monitored as > permitted by UK legislation. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGqb+nHJdudm4KnO0RAtxDAKDCcZUJ8uy6bGJ1mL/kUEnswUL3oACg3ihz iQjQTZFdetdzYME6XmrfXRQ= =Xxwv -----END PGP SIGNATURE----- From David.Barton at nottingham.ac.uk Fri Jul 27 12:54:34 2007 From: David.Barton at nottingham.ac.uk (Barton David) Date: Fri, 27 Jul 2007 11:54:34 +0100 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: <46A9BFA8.2020209@kostyrka.org> Message-ID: *sigh* I'm really going off Python. OK, thanks Andreas. This message has been checked for viruses but the contents of an attachment may still contain software viruses, which could damage your computer system: you are advised to perform your own checks. Email communications with the University of Nottingham may be monitored as permitted by UK legislation. From kent37 at tds.net Fri Jul 27 14:06:33 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Jul 2007 08:06:33 -0400 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: References: Message-ID: <46A9DFC9.1070901@tds.net> Barton David wrote: > *sigh* I'm really going off Python. In what way is it Python's fault that the dbm database doesn't reclaim disk space? Kent From David.Barton at nottingham.ac.uk Fri Jul 27 14:37:01 2007 From: David.Barton at nottingham.ac.uk (Barton David) Date: Fri, 27 Jul 2007 13:37:01 +0100 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: <46A9DFC9.1070901@tds.net> Message-ID: I mean no offense and lay no blame. It's simply that I feel like I've been led up a nice gentle beach and suddenly I'm dodging boulders at the bottom of a cliff. I've learned to program with Python (and can hardly conceive of a better language to be honest)- and I still think the core language is great: elegant, easy to use and brilliantly documented. But the more I explore the standard library and third party modules, the more I run into trouble: a chaotic library structure that seems to conceal capabilities rather than promote them, similar modules that don't work in similar ways, a whole new level of opaque programming lingo that makes me feel excluded, behaviours that I don't understand, don't want, and that I can't find documentation to explain, and so on. I guess it's not Python's fault: I'm guess I'm just too stupid. But I'm just getting really disenchanted. Sorry. -----Original Message----- From: Kent Johnson [mailto:kent37 at tds.net] Sent: 27 July 2007 13:07 To: Barton David Cc: tutor at python.org Subject: Re: [Tutor] Shelve del not reducing file size Barton David wrote: > *sigh* I'm really going off Python. In what way is it Python's fault that the dbm database doesn't reclaim disk space? Kent This message has been checked for viruses but the contents of an attachment may still contain software viruses, which could damage your computer system: you are advised to perform your own checks. Email communications with the University of Nottingham may be monitored as permitted by UK legislation. From kent37 at tds.net Fri Jul 27 15:10:44 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Jul 2007 09:10:44 -0400 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: References: Message-ID: <46A9EED4.2090002@tds.net> If it's any solace, there is a small minority of Python users who agree with you. There *are* rough edges in the library modules and the library docs. The great majority of Python users seem to find them good enough and are pleased and amazed at what you can do with the batteries included. A minority find the warts, omissions and inconsistencies to be very frustrating, and not because they (the users) are dumb. IIRC some prominent carpers on comp.lang.python are Kay Schluehr, Paul Rubin and John Nagle. I'm curious, what is plan B? Do you have something better than Python to try? I guess the above-named people are still with Python because the benefits outweigh the warts. Kent Barton David wrote: > But the more I explore the standard library and third party modules, the > more I run into trouble: a chaotic library structure that seems to > conceal capabilities rather than promote them, similar modules that > don't work in similar ways, a whole new level of opaque programming > lingo that makes me feel excluded, behaviours that I don't understand, > don't want, and that I can't find documentation to explain, and so on. > > I guess it's not Python's fault: I'm guess I'm just too stupid. But I'm > just getting really disenchanted. Sorry. > > > -----Original Message----- > From: Kent Johnson [mailto:kent37 at tds.net] > Sent: 27 July 2007 13:07 > To: Barton David > Cc: tutor at python.org > Subject: Re: [Tutor] Shelve del not reducing file size > > Barton David wrote: >> *sigh* I'm really going off Python. > > In what way is it Python's fault that the dbm database doesn't reclaim > disk space? > > Kent From andreas at kostyrka.org Fri Jul 27 15:26:28 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 27 Jul 2007 15:26:28 +0200 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: References: Message-ID: <46A9F284.7060103@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Barton David wrote: > I mean no offense and lay no blame. It's simply that I feel like I've > been led up a nice gentle beach and suddenly I'm dodging boulders at the > bottom of a cliff. > > I've learned to program with Python (and can hardly conceive of a better > language to be honest)- and I still think the core language is great: > elegant, easy to use and brilliantly documented. > > But the more I explore the standard library and third party modules, the > more I run into trouble: a chaotic library structure that seems to > conceal capabilities rather than promote them, similar modules that > don't work in similar ways, a whole new level of opaque programming > lingo that makes me feel excluded, behaviours that I don't understand, > don't want, and that I can't find documentation to explain, and so on. > > I guess it's not Python's fault: I'm guess I'm just too stupid. But I'm > just getting really disenchanted. Sorry. No, the Python documentation is sometimes brief. And some places are not really documented (like some dusty corners in the hotshot profiler). But OTOH, it's also hard on newbies, because it usually documents but does not explain what a module does, e.g., it often expects the reader to know the protocols involved, sometimes it expects the reader to know computer science basics. Andreas > > > -----Original Message----- > From: Kent Johnson [mailto:kent37 at tds.net] > Sent: 27 July 2007 13:07 > To: Barton David > Cc: tutor at python.org > Subject: Re: [Tutor] Shelve del not reducing file size > > Barton David wrote: >> *sigh* I'm really going off Python. > > In what way is it Python's fault that the dbm database doesn't reclaim > disk space? > > Kent > > This message has been checked for viruses but the contents of an attachment > may still contain software viruses, which could damage your computer system: > you are advised to perform your own checks. Email communications with the > University of Nottingham may be monitored as permitted by UK legislation. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGqfKEHJdudm4KnO0RArCBAJ9aaV4B4Q1qpl2jivQqX7adcWZ0FQCfY9nF 7SnuvfumY0AlGsYkJ4LgGBE= =5Chn -----END PGP SIGNATURE----- From David.Barton at nottingham.ac.uk Fri Jul 27 15:50:11 2007 From: David.Barton at nottingham.ac.uk (Barton David) Date: Fri, 27 Jul 2007 14:50:11 +0100 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: <46A9EED4.2090002@tds.net> Message-ID: Sadly I can't think of a plan B, hence the frustration! Python, as far as I know, is as good as it gets. And I don't have the courage or the capability to improve it myself. So all I can really do is clasp my hands together and helplessly plead: "Won't Somebody, Please, Think of the Children!" (Meaning struggling non-pro users like me, of course) As far as I'm concerned, the core language has matured to be elegant and terrificly newbie-friendly, but the extended functionality (the standard library) absolutely has not. It disappoints me that Guido and many other developers *seem* to be more concerned with strategies for revamping the former than they are with strategies for improving the latter. If Kay Schluehr, Paul Rubin and John Nagle are opposing this trend and being dismissed as 'carpers' then I fear Python has lost sight of the 'friendliness' it once seemed to aspired to. -----Original Message----- From: Kent Johnson [mailto:kent37 at tds.net] Sent: 27 July 2007 14:11 To: Barton David Cc: tutor at python.org Subject: Re: [Tutor] Shelve del not reducing file size If it's any solace, there is a small minority of Python users who agree with you. There *are* rough edges in the library modules and the library docs. The great majority of Python users seem to find them good enough and are pleased and amazed at what you can do with the batteries included. A minority find the warts, omissions and inconsistencies to be very frustrating, and not because they (the users) are dumb. IIRC some prominent carpers on comp.lang.python are Kay Schluehr, Paul Rubin and John Nagle. I'm curious, what is plan B? Do you have something better than Python to try? I guess the above-named people are still with Python because the benefits outweigh the warts. Kent This message has been checked for viruses but the contents of an attachment may still contain software viruses, which could damage your computer system: you are advised to perform your own checks. Email communications with the University of Nottingham may be monitored as permitted by UK legislation. From andreas at kostyrka.org Fri Jul 27 16:06:22 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 27 Jul 2007 16:06:22 +0200 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: References: Message-ID: <46A9FBDE.5020401@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Barton David wrote: > Sadly I can't think of a plan B, hence the frustration! Python, as far > as I know, is as good as it gets. And I don't have the courage or the > capability to improve it myself. > > So all I can really do is clasp my hands together and helplessly plead: > "Won't Somebody, Please, Think of the Children!" > > (Meaning struggling non-pro users like me, of course) > > As far as I'm concerned, the core language has matured to be elegant and > terrificly newbie-friendly, but the extended functionality (the standard > library) absolutely has not. It disappoints me that Guido and many other > developers *seem* to be more concerned with strategies for revamping the > former than they are with strategies for improving the latter. If Kay > Schluehr, Paul Rubin and John Nagle are opposing this trend and being > dismissed as 'carpers' then I fear Python has lost sight of the > 'friendliness' it once seemed to aspired to. Stop. The standard library is not perfect, but it's better than what many other languages come with. Second, you should not fear improving stuff yourself, that's one of the benefits of Python that it's easy to read. Furthermore, it's an unsolved problem. IMHO, learning a new language, even something atypical (nonimperative) like Prolog takes seldom more than 1-2 days. Learning the runtime environment/standard library/add on libraries take at least a magnitude longer. Learning the idiomatic way to do something takes again even longer. Additionally, the language core is very very thought out, with glacial enhancements. "Fixing" the standard library OTOH would involve renaming and removing names, which would make huge collections of programs break. Not a good thing :( Andreas I know no language that beats this pattern. > > > > -----Original Message----- > From: Kent Johnson [mailto:kent37 at tds.net] > Sent: 27 July 2007 14:11 > To: Barton David > Cc: tutor at python.org > Subject: Re: [Tutor] Shelve del not reducing file size > > If it's any solace, there is a small minority of Python users who agree > with you. There *are* rough edges in the library modules and the library > docs. The great majority of Python users seem to find them good enough > and are pleased and amazed at what you can do with the batteries > included. A minority find the warts, omissions and inconsistencies to be > very frustrating, and not because they (the users) are dumb. IIRC some > prominent carpers on comp.lang.python are Kay Schluehr, Paul Rubin and > John Nagle. > > I'm curious, what is plan B? Do you have something better than Python to > try? I guess the above-named people are still with Python because the > benefits outweigh the warts. > > Kent > > > This message has been checked for viruses but the contents of an attachment > may still contain software viruses, which could damage your computer system: > you are advised to perform your own checks. Email communications with the > University of Nottingham may be monitored as permitted by UK legislation. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGqfvcHJdudm4KnO0RAsh7AKCXgnJGwMngrhup6LYFcAf6fRIKwgCcCfCc UEM+K4XWqNpauhq94WwmXlE= =1FEE -----END PGP SIGNATURE----- From kent37 at tds.net Fri Jul 27 16:13:02 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Jul 2007 10:13:02 -0400 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: References: Message-ID: <46A9FD6E.5090408@tds.net> Well, 'carpers' was my word but there is some truth to it. For example this recent exchange: http://groups.google.com/group/comp.lang.python/browse_frm/thread/77285bd20fafbf2b/b0ffd482e925f0c0?hl=en#b0ffd482e925f0c0 which made it into QOTW in Python-URL, inspiring this rejoinder: http://groups.google.com/group/comp.lang.python/browse_frm/thread/6348bfbb69642a4a/1d7f98c3c82fd64b?hl=en#1d7f98c3c82fd64b Ultimately it seems to come down to - Python is open source - Python developers are largely unpaid volunteers working on what interests them - If you want something to change, you can -- do it yourself -- convince someone to volunteer to do it -- pay someone to do it So far cleaning up the std lib has not attracted any of these three options. Kent Barton David wrote: > Sadly I can't think of a plan B, hence the frustration! Python, as far > as I know, is as good as it gets. And I don't have the courage or the > capability to improve it myself. > > So all I can really do is clasp my hands together and helplessly plead: > "Won't Somebody, Please, Think of the Children!" > > (Meaning struggling non-pro users like me, of course) > > As far as I'm concerned, the core language has matured to be elegant and > terrificly newbie-friendly, but the extended functionality (the standard > library) absolutely has not. It disappoints me that Guido and many other > developers *seem* to be more concerned with strategies for revamping the > former than they are with strategies for improving the latter. If Kay > Schluehr, Paul Rubin and John Nagle are opposing this trend and being > dismissed as 'carpers' then I fear Python has lost sight of the > 'friendliness' it once seemed to aspired to. > > > > -----Original Message----- > From: Kent Johnson [mailto:kent37 at tds.net] > Sent: 27 July 2007 14:11 > To: Barton David > Cc: tutor at python.org > Subject: Re: [Tutor] Shelve del not reducing file size > > If it's any solace, there is a small minority of Python users who agree > with you. There *are* rough edges in the library modules and the library > docs. The great majority of Python users seem to find them good enough > and are pleased and amazed at what you can do with the batteries > included. A minority find the warts, omissions and inconsistencies to be > very frustrating, and not because they (the users) are dumb. IIRC some > prominent carpers on comp.lang.python are Kay Schluehr, Paul Rubin and > John Nagle. > > I'm curious, what is plan B? Do you have something better than Python to > try? I guess the above-named people are still with Python because the > benefits outweigh the warts. > > Kent > > > This message has been checked for viruses but the contents of an attachment > may still contain software viruses, which could damage your computer system: > you are advised to perform your own checks. Email communications with the > University of Nottingham may be monitored as permitted by UK legislation. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From David.Barton at nottingham.ac.uk Fri Jul 27 16:49:24 2007 From: David.Barton at nottingham.ac.uk (Barton David) Date: Fri, 27 Jul 2007 15:49:24 +0100 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: <46A9FD6E.5090408@tds.net> Message-ID: Andreas Kostyrka wrote: > Additionally, the language core is very very thought out, with glacial > enhancements. "Fixing" the standard library OTOH would involve renaming > and removing names, which would make huge collections of programs break. > Not a good thing :( Yes agreed. My comments there were primarily about the future of python (i.e. Python 3000). Kent Johnson wrote: > Ultimately it seems to come down to > - Python is open source > - Python developers are largely unpaid volunteers working on what interests them > - If you want something to change, you can > -- do it yourself > -- convince someone to volunteer to do it > -- pay someone to do it > > So far cleaning up the std lib has not attracted any of these three options. Yes of course. But not *all* Python developers are unpaid. And even if they were- this ship isn't rudderless. It could be steered towards standard library overhaul (in Py3000) if Guido so decreed (and if he laid out a nice appealing framework, perhaps). But I guess if everybody thinks it's ok or nobody thinks it can be improved then that isn't going to happen. Andreas Kostyrka wrote: > Stop. Somehow that one word just sums it all up! Yeah I'll stop. It's not like I'm out to upset anybody. But please, somebody up there, Think of the Children, eh? This message has been checked for viruses but the contents of an attachment may still contain software viruses, which could damage your computer system: you are advised to perform your own checks. Email communications with the University of Nottingham may be monitored as permitted by UK legislation. From brunson at brunson.com Fri Jul 27 17:39:47 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 27 Jul 2007 09:39:47 -0600 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: <46A9F284.7060103@kostyrka.org> References: <46A9F284.7060103@kostyrka.org> Message-ID: <46AA11C3.3030402@brunson.com> Andreas Kostyrka wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > > > Barton David wrote: > >> I mean no offense and lay no blame. It's simply that I feel like I've >> been led up a nice gentle beach and suddenly I'm dodging boulders at the >> bottom of a cliff. >> >> I've learned to program with Python (and can hardly conceive of a better >> language to be honest)- and I still think the core language is great: >> elegant, easy to use and brilliantly documented. >> >> But the more I explore the standard library and third party modules, the >> more I run into trouble: a chaotic library structure that seems to >> conceal capabilities rather than promote them, similar modules that >> don't work in similar ways, a whole new level of opaque programming >> lingo that makes me feel excluded, behaviours that I don't understand, >> don't want, and that I can't find documentation to explain, and so on. >> >> I guess it's not Python's fault: I'm guess I'm just too stupid. But I'm >> just getting really disenchanted. Sorry. >> > > No, the Python documentation is sometimes brief. And some places are not > really documented (like some dusty corners in the hotshot profiler). But > OTOH, it's also hard on newbies, because it usually documents but does > not explain what a module does, e.g., it often expects the reader to > know the protocols involved, sometimes it expects the reader to know > computer science basics. > It seems like new programmers today expect to be spoonfed their information like they were in grammar school. They don't know what it is to hack a Makefile to get a package to compile or break out an RFC to understand a protocol. If you don't understand something and the documentation is lacking, then strap on a pair and read the source, write some test cases, dig a little. In our environment most of the code you'd have to read is just more Python, anyway. Just me being a grouchy old programmer. In my day we had to program in 4 feet of snow, uphill... both ways! > Andreas > > >> >> >> -----Original Message----- >> From: Kent Johnson [mailto:kent37 at tds.net] >> Sent: 27 July 2007 13:07 >> To: Barton David >> Cc: tutor at python.org >> Subject: Re: [Tutor] Shelve del not reducing file size >> >> Barton David wrote: >> >>> *sigh* I'm really going off Python. >>> >> In what way is it Python's fault that the dbm database doesn't reclaim >> disk space? >> >> Kent >> >> >> From david at graniteweb.com Fri Jul 27 17:57:11 2007 From: david at graniteweb.com (David Rock) Date: Fri, 27 Jul 2007 10:57:11 -0500 Subject: [Tutor] Running Python on Gentoo In-Reply-To: <46A8EB99.4070506@novasyshealth.com> References: <46A8EB99.4070506@novasyshealth.com> Message-ID: <20070727155711.GB31819@wdfs.graniteweb.com> * Greg Lindstrom [2007-07-26 13:44]: > Hello, > I am running python 2.4.2 on Gentoo Unix and am having problems running > programs. I have a script, hello.py as such: > > #! /usr/bin/python > print 'hello, world' > > that I save and add executable permission. Then at the prompt I type in.. > > $ ./hello.py > -bash: ./hello.py: /usr/bin/python: bad interpreter: Permission denied > > If I type > $ python hello.py > I get "hello, world" as expected. > > I was hoping that the "shabang" would have the script execute. Am I > missing something? Can you help me? BTW, when I type /usr/bin/python > at the prompt I get the python interpreter, so at least that's working. Are you using any hardened gentoo kernels or anything like that, or is it a "normal" gentoo build? I don't think this is a python problem, but rather a permissions problem at a level OTHER than the filesystem. I found this in the gentoo forums: http://forums.gentoo.org/viewtopic-t-549470-highlight-interpreter+permission+denied.html Are you using any "trusted path execution" in the kernel? This would potentially be something that could happen with ANY lniux system, not just gentoo. FWIW, I am having the same problem (even though I never actually tried on this system before) :-) -- David Rock david at graniteweb.com From David.Barton at nottingham.ac.uk Fri Jul 27 18:05:19 2007 From: David.Barton at nottingham.ac.uk (Barton David) Date: Fri, 27 Jul 2007 17:05:19 +0100 Subject: [Tutor] Shelve del not reducing file size Message-ID: Eric Brunson wrote: > It seems like new programmers today expect to be spoonfed their > information like they were in grammar school. They don't know what it > is to hack a Makefile to get a package to compile or break out an RFC to > understand a protocol. If you don't understand something and the > documentation is lacking, then strap on a pair and read the source, > write some test cases, dig a little. In our environment most of the > code you'd have to read is just more Python, anyway. > > Just me being a grouchy old programmer. In my day we had to program in > 4 feet of snow, uphill... both ways! heh. Well give me some credit. I taught myself to program, from scratch, without access to (or time for) any courses whatsoever, while doing a PhD in genetics. I've been using it for about 5 years now and I know the core language and certain standard modules pretty well. I doubt I would have got as far as I have if Python wasn't so newbie-friendly. My only complaint is that I'm starting to feel like I won't get much further than that without a computer science degree. This message has been checked for viruses but the contents of an attachment may still contain software viruses, which could damage your computer system: you are advised to perform your own checks. Email communications with the University of Nottingham may be monitored as permitted by UK legislation. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070727/d9ed5a86/attachment.htm From david at graniteweb.com Fri Jul 27 18:07:03 2007 From: david at graniteweb.com (David Rock) Date: Fri, 27 Jul 2007 11:07:03 -0500 Subject: [Tutor] Running Python on Gentoo In-Reply-To: <20070727155711.GB31819@wdfs.graniteweb.com> References: <46A8EB99.4070506@novasyshealth.com> <20070727155711.GB31819@wdfs.graniteweb.com> Message-ID: <20070727160703.GC31819@wdfs.graniteweb.com> Just to follow up on what _my_ environment looks like (and the probable cause in my case, anyway) Security Options -> GRsecurity -> Executable Protections -> Trusted Path Execution (TPE) CONFIG_GRKERNSEC_TPE: If you say Y here, you will be able to choose a gid to add to the supplementary groups of users you want to mark as "untrusted." These users will not be able to execute any files that are not in root-owned directories writable only by root. If the sysctl option is enabled, a sysctl option with name "tpe" is created. Now I just need to find how to turn that off. I did want it more secure :-) -- David Rock david at graniteweb.com From brunson at brunson.com Fri Jul 27 18:33:33 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 27 Jul 2007 10:33:33 -0600 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: References: Message-ID: <46AA1E5D.9050305@brunson.com> Barton David wrote: > > *Eric Brunson* wrote: > > > It seems like new programmers today expect to be spoonfed their > > information like they were in grammar school. They don't know what it > > is to hack a Makefile to get a package to compile or break out an > RFC to > > understand a protocol. If you don't understand something and the > > documentation is lacking, then strap on a pair and read the source, > > write some test cases, dig a little. In our environment most of the > > code you'd have to read is just more Python, anyway. > > > > Just me being a grouchy old programmer. In my day we had to program in > > 4 feet of snow, uphill... both ways! > > heh. Well give me some credit. I taught myself to program, from > scratch, without access to (or time for) any courses whatsoever, while > doing a PhD in genetics. I've been using it for about 5 years now and > I know the core language and certain standard modules pretty well. I > doubt I would have got as far as I have if Python wasn't so > newbie-friendly. My only complaint is that I'm starting to feel like I > won't get much further than that without a computer science degree. I'll disagree with you on that, if you can get a PhD in genetics then programming should be a snap... with the right attitude. My BS was in Applied Mathematics and I've never taken a formal programming class since 11th grade high school. But, I've been doing it for about 20 years and there comes a point when you realize that you've read all the tutorials you can, internalized all the documentation that has been written and you *are* actually the smartest person in the room. At that point you have to look other places for your documentation, like the source code or the RFCs. I keep mentioning RFCs because I answer a lot of questions about using this to send mail or that to talk to an HTTP server or another thing to pull a file off FTP. Most of python's protocol libraries are a very thin layer over the top of the actual network protocol, so in order to use any but the most common operations, you have to understand the underlying protocol. So, what do you do? Read the RFC for SMTP? Or complain that there's not a single function call that allows you to automatically connect to a non-WKS port to send uuencoded emails using custom headers? You seem like a smart guy that's having a bad day, so I'm cutting you slack. You'll get to a point in programming where the only thing left before you is the epi-genome and I've got news for you, there's no documentation on the dark matter. Personally, I seldom use the low level interfaces provided by the standard libraries except to write high level wrapper functions that meet the needs of my environment and the task at hand. So, keep your chin up, you're not alone. :-) > > This message has been checked for viruses but the contents of an > attachment may still contain software viruses, which could damage your > computer system: you are advised to perform your own checks. Email > communications with the University of Nottingham may be monitored as > permitted by UK legislation. > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From keridee at jayco.net Fri Jul 27 19:39:05 2007 From: keridee at jayco.net (Tiger12506) Date: Fri, 27 Jul 2007 12:39:05 -0500 Subject: [Tutor] Shelve del not reducing file size References: Message-ID: <004201c7d075$0ad4fcb0$51fce004@JSLAPTOP> > ...some credit. I taught myself to program, from scratch, without access > to (or time for) any courses whatsoever... 5 years now...core > language...certain standard modules pretty well... complaint...won't get > much further...without a computer science degree. Wow. I'm so *shocked*. Most python programmers are self-taught. Usually, the best are self-taught. Five years for the core language and some standard modules!?! Are you kidding me? If it takes you that long, then you are out of your field, and lucky you can handle what you can. Some advice: Never, ever try to learn anything like C/C++. Or at least don't leave any knives around to tempt you. Some people need degrees, most people don't. It all depends on what they are capable of understanding. From the sound of it, you are lucky you haven't jumped off a bridge yet. Python is simple. Easy enough for teenagers to focus long enough to follow even the source of the standard libraries, not just the interfaces. JS PS - I'm somewhat sorry I feel the need to throw in my two bits. This little debate has continued for long enough, and should end. Btw, try not to complain about one language's characteristics without having a thorough understanding of what else is out there. Python's standard library is 'newbie-friendly'. If you doubt it, try emulating what you can already do in python in another language. From sebastien at solutions-linux.org Fri Jul 27 19:38:56 2007 From: sebastien at solutions-linux.org (Sebastien Noel) Date: Fri, 27 Jul 2007 13:38:56 -0400 Subject: [Tutor] Remove certain tags in html files Message-ID: <46AA2DB0.7000301@solutions-linux.org> Hi, I'm doing a little script with the help of the BeautifulSoup HTML parser and uTidyLib (HTML Tidy warper for python). Essentially what it does is fetch all the html files in a given directory (and it's subdirectories) clean the code with Tidy (removes deprecated tags, change the output to be xhtml) and than BeautifulSoup removes a couple of things that I don't want in the files (Because I'm stripping the files to bare bone, just keeping layout information). Finally, I want to remove all trace of layout tables (because the new layout will be in css for positioning). Now, there is tables to layout things on the page and tables to represent tabular data, but I think it would be too hard to make a script that finds out the difference. My question, since I'm quite new to python, is about what tool I should use to remove the table, tr and td tags, but not what's enclosed in it. I think BeautifulSoup isn't good for that because it removes what's enclosed as well. Is re the good module for that? Basically, if I make an iteration that scans the text and tries to match every occurrence of a given regular expression, would it be a good idea? Now, I'm quite new to the concept of regular expressions, but would it ressemble something like this: re.compile("")? Thanks for the help. From brunson at brunson.com Fri Jul 27 20:03:48 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 27 Jul 2007 12:03:48 -0600 Subject: [Tutor] Remove certain tags in html files In-Reply-To: <46AA2DB0.7000301@solutions-linux.org> References: <46AA2DB0.7000301@solutions-linux.org> Message-ID: <46AA3384.6050902@brunson.com> Sebastien Noel wrote: > Hi, > > I'm doing a little script with the help of the BeautifulSoup HTML parser > and uTidyLib (HTML Tidy warper for python). > > Essentially what it does is fetch all the html files in a given > directory (and it's subdirectories) clean the code with Tidy (removes > deprecated tags, change the output to be xhtml) and than BeautifulSoup > removes a couple of things that I don't want in the files (Because I'm > stripping the files to bare bone, just keeping layout information). > > Finally, I want to remove all trace of layout tables (because the new > layout will be in css for positioning). Now, there is tables to layout > things on the page and tables to represent tabular data, but I think it > would be too hard to make a script that finds out the difference. > > My question, since I'm quite new to python, is about what tool I should > use to remove the table, tr and td tags, but not what's enclosed in it. > I think BeautifulSoup isn't good for that because it removes what's > enclosed as well. > You want to look at htmllib: http://docs.python.org/lib/module-htmllib.html If you've used a SAX parser for XML, it's similar. Your parser parses the file and every time it hit a tag, it runs a callback which you've defined. You can assign a default callback that simply prints out the tag as parsed, then a custom callback for each tag you want to clean up. It took me a little time to wrap my head around it the first time I used it, but once you "get it" it's *really* powerful and really easy to implement. Read the docs and play around a little bit, then if you have questions, post back and I'll see if I can dig up some examples I've written. e. > Is re the good module for that? Basically, if I make an iteration that > scans the text and tries to match every occurrence of a given regular > expression, would it be a good idea? > > Now, I'm quite new to the concept of regular expressions, but would it > ressemble something like this: re.compile("")? > > Thanks for the help. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From brunson at brunson.com Fri Jul 27 20:27:44 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 27 Jul 2007 12:27:44 -0600 Subject: [Tutor] Remove certain tags in html files In-Reply-To: <46AA3384.6050902@brunson.com> References: <46AA2DB0.7000301@solutions-linux.org> <46AA3384.6050902@brunson.com> Message-ID: <46AA3920.6070608@brunson.com> Eric Brunson wrote: > Sebastien Noel wrote: > >> Hi, >> >> I'm doing a little script with the help of the BeautifulSoup HTML parser >> and uTidyLib (HTML Tidy warper for python). >> >> Essentially what it does is fetch all the html files in a given >> directory (and it's subdirectories) clean the code with Tidy (removes >> deprecated tags, change the output to be xhtml) and than BeautifulSoup >> removes a couple of things that I don't want in the files (Because I'm >> stripping the files to bare bone, just keeping layout information). >> >> Finally, I want to remove all trace of layout tables (because the new >> layout will be in css for positioning). Now, there is tables to layout >> things on the page and tables to represent tabular data, but I think it >> would be too hard to make a script that finds out the difference. >> >> My question, since I'm quite new to python, is about what tool I should >> use to remove the table, tr and td tags, but not what's enclosed in it. >> I think BeautifulSoup isn't good for that because it removes what's >> enclosed as well. >> >> > > You want to look at htmllib: http://docs.python.org/lib/module-htmllib.html > I'm sorry, I should have pointed you to HTMLParser: http://docs.python.org/lib/module-HTMLParser.html It's a bit more straightforward than the HTMLParser defined in htmllib. Everything I was talking about below pertains to the HTMLParser module and not the htmllib module. > If you've used a SAX parser for XML, it's similar. Your parser parses > the file and every time it hit a tag, it runs a callback which you've > defined. You can assign a default callback that simply prints out the > tag as parsed, then a custom callback for each tag you want to clean up. > > It took me a little time to wrap my head around it the first time I used > it, but once you "get it" it's *really* powerful and really easy to > implement. > > Read the docs and play around a little bit, then if you have questions, > post back and I'll see if I can dig up some examples I've written. > > e. > > >> Is re the good module for that? Basically, if I make an iteration that >> scans the text and tries to match every occurrence of a given regular >> expression, would it be a good idea? >> >> Now, I'm quite new to the concept of regular expressions, but would it >> ressemble something like this: re.compile("")? >> >> Thanks for the help. >> _______________________________________________ >> 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 > From luke.jordan at gmail.com Fri Jul 27 20:38:35 2007 From: luke.jordan at gmail.com (Luke Jordan) Date: Fri, 27 Jul 2007 13:38:35 -0500 Subject: [Tutor] shelves behaving badly Message-ID: i've implemented a database as a shelve of record class instances. some of the fields in each record are dictionaries. i needed to parse info from 3 different reports into the dictionary fields in each record instance. i wrote the code to do this and tinkered it to fit the different reports (i.e. information being in different columns, etc.). for 2 of the reports, it runs fine. the required info turns up in the shelve after i run the code, and i can exit and reenter python, open the shelve, and it's all still there, where it should be. i've quadruple checked the code for the third report, and it looks like it should work. in fact it runs, and reports back that it did everything i told it to do; this includes checking results as they occur at runtime. however, when i reopen the shelve, none of that data is there. writeback is set to True, and I didn't forget to close the shelve at the end of my code. Now, if I open the shelve in the same shell as the script ran in, right after I run it, I get the updated shelve. but any other method of opening the shelve results in the shelve missing the data from the third report. Any ideas what's going on here? -- Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070727/7825acf0/attachment.htm From carroll at tjc.com Fri Jul 27 21:02:33 2007 From: carroll at tjc.com (Terry Carroll) Date: Fri, 27 Jul 2007 12:02:33 -0700 (PDT) Subject: [Tutor] Code like a Pythonista In-Reply-To: <20070727082009.80DE61E4005@bag.python.org> Message-ID: On Fri, 27 Jul 2007, Dick Moores wrote: > The handout is excellent! Thanks! > > But the slideshow at > , > isn't. You have to use the page-up and -down keys; or the spacebar (at least on Windows under Firefox). Took me a while to figure that out. From alan.gauld at btinternet.com Fri Jul 27 21:04:04 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Jul 2007 20:04:04 +0100 Subject: [Tutor] Shelve del not reducing file size References: <46A9DFC9.1070901@tds.net> Message-ID: "Barton David" wrote > I've learned to program with Python (and can hardly conceive of a > better > language to be honest)- and I still think the core language is > great: > elegant, easy to use and brilliantly documented. Completely agree. > But the more I explore the standard library and third party modules, > the > more I run into trouble: And again I completely agree. But its not just python, it's an endemic thing in Open Source projects, Python is far from the worst offender here. Lots of people want to write code but not many want to be librarians and technical authors! But if you come from the world of serious commercial development tools (ie not the toy compilers etc sold by Borland and Microsoft for PC development) then the chaos of the libraries and documentation can be truly shocking. But that's why you pay $10,000+ for a good C Unix or VAX/VMS compiler, and the same again for the IDE to drive it... And you wanted a library for financials/scientific/stats/numeric/graphics? That;ll vbe about the same again... but the quality of the code and documentation will be good and on a big project that makes it worth it. But if you don't have the $50,000(*) or so that it would take to get what Python delivers for free then you learn to put up with the bad documentation and inconsistent libraries etc - or better still volunteer to tidy it up! :-) > I guess it's not Python's fault: I'm guess I'm just too stupid. But > I'm > just getting really disenchanted. Sorry. No not too stupid just expecting a bit much from something that is ultimately an essentially "amateur"(**) tool. (*)I just noticed your domain so you probably pay academic rates for these things which are a good deal lower! (Although still more than most univesities are willing to fork out for!) (*)This is in the literal sense of 'done for fun not profit', it does not suggest that the programmers are any way less skilful than "professionals", quite the opposite is often the case. -- 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 Jul 27 21:20:23 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Jul 2007 20:20:23 +0100 Subject: [Tutor] Shelve del not reducing file size References: <46A9F284.7060103@kostyrka.org> <46AA11C3.3030402@brunson.com> Message-ID: "Eric Brunson" wrote > It seems like new programmers today expect to be spoonfed their > information like they were in grammar school. I think its true they expect a lot of tutorial stuff, probably because of the number of idiot guides to programming in languages like VB/PHP etc. Also relatively few of todays programmers are formally trained (college or higher) in programming, math, computers, etc. In fact many seem to consider it surprising that people might expect them to need University level training to program some so "simple" as a computer! It's just typing after all... :-) > is to hack a Makefile to get a package to compile or break out an > RFC to > understand a protocol. Many try but can't understand the terminology. One of the things I tried to do in my tutorial is teach enough of the jargon that newvbies could read an RFC or a language reference and understand it! > If you don't understand something and the > documentation is lacking, then strap on a pair and read the source, I admit thats always been a last resort for me. I was brought up in a mainframe and embedded systems environment where documentation was almost always excellent, accurate and complete. Similarly designs were documented such that you rarely needed to refer to the code to find bugs until you were down to a single procedure/function, and often a particular segment of that (a case statement say). When I moved to Unix I was initially shocked to discover that most big Unix sites had a copy of the AT&T or BSD code and it was considered normal to resolve issues by reading it! Then I got involved with PCs and discovered that not only the OS but the BIOS code came with it (the original IBM PC I mean - the one that cost $2500 for a single 5.25 floppy disk version!) Reading assembler wasn't a problem but the idea that I might need to just to get the floppy disk to work was astounding! > Just me being a grouchy old programmer. In my day we had to program > in > 4 feet of snow, uphill... both ways! Actually I often feel that todays programming is like that. And in many ways its much harder with the web - a truly terrible programming environment! and GUIs - how many frameworks do you know? and tools that do their best to hide what's going on - IDEs that don't let you see or modify the dependency tree? I don't think the problems facing programmers today are, in balance, harder or easier than they were when I started programming 25-30 years ago but they are different. Alan G. Scratching his grey beard :-) From kent37 at tds.net Fri Jul 27 21:24:28 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Jul 2007 15:24:28 -0400 Subject: [Tutor] Code like a Pythonista In-Reply-To: References: Message-ID: <46AA466C.1040509@tds.net> Terry Carroll wrote: > On Fri, 27 Jul 2007, Dick Moores wrote: > >> The handout is excellent! Thanks! >> >> But the slideshow at >> , >> isn't. > > You have to use the page-up and -down keys; or the spacebar (at least on > Windows under Firefox). Took me a while to figure that out. For navigation I use left and right arrows or mouse-over the bottom-right of the screen to get a nav panel. But when I get to the screen "Whitespace 1" there is nothing but white space under the title. Appropriate in a way but not very enlightening :-) I'm on Firefox Mac but I saw this also last night with FF on Linux. I don't know if it is this particular presentation that has trouble or if it is with S5 itself. From alan.gauld at btinternet.com Fri Jul 27 21:33:53 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Jul 2007 20:33:53 +0100 Subject: [Tutor] Shelve del not reducing file size References: <46AA1E5D.9050305@brunson.com> Message-ID: "Eric Brunson" wrote >> newbie-friendly. My only complaint is that I'm starting to feel >> like I >> won't get much further than that without a computer science degree. > > I'll disagree with you on that, if you can get a PhD in genetics > then > programming should be a snap... I'm not sure I agree. There is a reason that CS is a degree subject, and that you can get PhDs in it too. There is a lot of advanced programming stuff that does need specialist training to *do it well*. Of course you can do virtually anything with a buit of brute force. But without actually understanding concepts like boolean algenra, lambda and predicate calculii, algorithm design, finite state automata thery etc much will either be inelegant or just cut n paste. I often see comments lie software engineering is different to other engineering because theres no mathematical basis. Thats plain false, and although the basis is less complete and certainly not a unified whole almost every aspect of programming can be validated and proved mathemaically. Programs can be designed and specified formally. But most programmers aren't trained. And those that are are discourageed from doing so because its quicker to "just hack it" As an applied mathematics man you probably know most of that stuff at some levelk. Not surprising since CS started off as a branch of math after all. BTW This trend has been true in almost every engineering discipline and the only thing that corrects it is when companies and programmes start getting sued and put in prison for writing faulty software. (Just like civil engineers were when bridges started falling down, and Electrical engineers were when householders got electrocuted switching on lamps!) > written and you *are* actually the smartest person in the room. At > that > point you have to look other places for your documentation, like the > source code or the RFCs. Absolutely true. Not good but its where we are. (And continuing the simile, the same is true in electronics, sometimes you just have to reverse engineer the circuit board! but you never do it for fun!) (*)BTW My own position is that I majored in Electrical/Electronic engineering but early on decided software was my interest so took every CS related class going. I also spent a lot of time doing background reading (and still do) on the formal math side of CS - formal logic etc being one of those areas where I have an almost constant learning curve. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From brunson at brunson.com Fri Jul 27 21:34:04 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 27 Jul 2007 13:34:04 -0600 Subject: [Tutor] Remove certain tags in html files In-Reply-To: <46AA3920.6070608@brunson.com> References: <46AA2DB0.7000301@solutions-linux.org> <46AA3384.6050902@brunson.com> <46AA3920.6070608@brunson.com> Message-ID: <46AA48AC.4030505@brunson.com> Man, the docs on the HTMLParser module are really sparse. Attached is some code I just whipped out that will parse and HTML file, supress the ouput of the tags you mention and spew the html back out. It's just a rough thing, you'll still have to read the docs and make sure to expand on some of the things it's doing, but I think it'll handle 95% of what it comes across. Be sure to override all the "handle_*()" methods I didn't. My recommendation would be to shove your HTML through BeautifulSoup to ensure it is well formed, then run it through the html parser to do whatever you want to change it, then through tidy to make it look nice. If you wanted to take the time, you could probably write the entire tidy process in the parser. I got a fair ways there, but decided it was too long to be instructional, so I pared it back to what I've included. Hope this gets you started, e. Eric Brunson wrote: > Eric Brunson wrote: > >> Sebastien Noel wrote: >> >> >>> Hi, >>> >>> I'm doing a little script with the help of the BeautifulSoup HTML parser >>> and uTidyLib (HTML Tidy warper for python). >>> >>> Essentially what it does is fetch all the html files in a given >>> directory (and it's subdirectories) clean the code with Tidy (removes >>> deprecated tags, change the output to be xhtml) and than BeautifulSoup >>> removes a couple of things that I don't want in the files (Because I'm >>> stripping the files to bare bone, just keeping layout information). >>> >>> Finally, I want to remove all trace of layout tables (because the new >>> layout will be in css for positioning). Now, there is tables to layout >>> things on the page and tables to represent tabular data, but I think it >>> would be too hard to make a script that finds out the difference. >>> >>> My question, since I'm quite new to python, is about what tool I should >>> use to remove the table, tr and td tags, but not what's enclosed in it. >>> I think BeautifulSoup isn't good for that because it removes what's >>> enclosed as well. >>> >>> >>> >> You want to look at htmllib: http://docs.python.org/lib/module-htmllib.html >> >> > > I'm sorry, I should have pointed you to HTMLParser: > http://docs.python.org/lib/module-HTMLParser.html > > It's a bit more straightforward than the HTMLParser defined in htmllib. > Everything I was talking about below pertains to the HTMLParser module > and not the htmllib module. > > >> If you've used a SAX parser for XML, it's similar. Your parser parses >> the file and every time it hit a tag, it runs a callback which you've >> defined. You can assign a default callback that simply prints out the >> tag as parsed, then a custom callback for each tag you want to clean up. >> >> It took me a little time to wrap my head around it the first time I used >> it, but once you "get it" it's *really* powerful and really easy to >> implement. >> >> Read the docs and play around a little bit, then if you have questions, >> post back and I'll see if I can dig up some examples I've written. >> >> e. >> >> >> >>> Is re the good module for that? Basically, if I make an iteration that >>> scans the text and tries to match every occurrence of a given regular >>> expression, would it be a good idea? >>> >>> Now, I'm quite new to the concept of regular expressions, but would it >>> ressemble something like this: re.compile("")? >>> >>> Thanks for the help. >>> _______________________________________________ >>> 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 >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- A non-text attachment was scrubbed... Name: replacetags.py Type: text/x-python Size: 660 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070727/6c7650ef/attachment.py From carroll at tjc.com Fri Jul 27 21:39:46 2007 From: carroll at tjc.com (Terry Carroll) Date: Fri, 27 Jul 2007 12:39:46 -0700 (PDT) Subject: [Tutor] Code like a Pythonista In-Reply-To: <46AA466C.1040509@tds.net> Message-ID: On Fri, 27 Jul 2007, Kent Johnson wrote: > For navigation I use left and right arrows or mouse-over the > bottom-right of the screen to get a nav panel. But when I get to the > screen "Whitespace 1" there is nothing but white space under the title. Same here, but as I press the PgDn key (or the right arrow -- thanks for that) it fills in, a line at a time: - 4 spaces per indentation level. - No hard tabs. - Never mix tabs and spaces. - One blank line between functions. - Two blank lines between classes. Then on to "Whitespace 2" with similar behavior. And now I note little navigation icons like << and >> at the bottom right, too, which only show up when moused over. From alan.gauld at btinternet.com Fri Jul 27 21:43:59 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Jul 2007 20:43:59 +0100 Subject: [Tutor] Shelve del not reducing file size References: <004201c7d075$0ad4fcb0$51fce004@JSLAPTOP> Message-ID: "Tiger12506" wrote > Some people need degrees, most people don't. It all depends on what > they are > capable of understanding. It also depends what they are doing. Most programmers don't build complex state machines, nor do they build safety critical systems. 90% or more of all programs don't need a degree, but somecthings do need formal training and the language is basically irrelevant. degrees dopnm;t teach languages, they teach the underlying theory. > understanding of what else is out there. Python's standard library > is > 'newbie-friendly'. If you doubt it, try emulating what you can > already do in > python in another language. Actually you an do what you do in Python in practically any general purpose language, it just takes a few more lines of code (OK a lot more lines in some cases) But Pythons library is not newbie friendly, sorry. How does a newbie know when to use pickle v cpickle? or urllib v urllib2? And which of the xml parsers? And as for thev mess that is glob/os/path/shutil? Its not clear to me even after 10 years of using Python which function sits where and why. And what about the confusion over system(), popen(),commands(),spawn(), subprocess() etc. or why is there time and datetime? Sure it makes sense once you've played with Python for a while it makes some sense and you learn the role of history. But for a newbie thats not a friendly scenario ad many other languages are far better organised - Smalltalk being one example! And the C++ standard library is another. Even the Java standard library, much as I dislike Java, is better organised and more consistent! -- 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 Jul 27 21:48:09 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Jul 2007 20:48:09 +0100 Subject: [Tutor] Remove certain tags in html files References: <46AA2DB0.7000301@solutions-linux.org> Message-ID: "Sebastien Noel" wrote > My question, since I'm quite new to python, is about what tool I > should > use to remove the table, tr and td tags, but not what's enclosed in > it. > I think BeautifulSoup isn't good for that because it removes what's > enclosed as well. BS can do what you want, you must be missing something. One of the most basic examples of using BS is to print an HTML file as plain text - ie stripping just the tags. So it must be possible. Can you put together a short example of the code you are using? You an use lower level parsers but BS is geneally easier, but until we know what you are doing its hard to guess what might be wrong. Alan G. From brunson at brunson.com Fri Jul 27 21:51:48 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 27 Jul 2007 13:51:48 -0600 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: References: <46AA1E5D.9050305@brunson.com> Message-ID: <46AA4CD4.9010607@brunson.com> One thing I don't think people realize, or at least don't talk about often enough, is that good programming, like good art, takes talent. I can draw a cat to make my 2yo happy or sketch my house well enough that someone could pick it out driving down the street, but if I paint every day for the next 100 years, I'll never be a Picasso or a Monet. I remember back when the web was starting to prosper, offices would hand their secretary a copy of FrontPage and tell them to make a web page for the company and *bam* she's a web designer. The fact is, good web design takes talent. You can go to school for math, engineering, architecture, art, music or computer science, but that's not going to turn the average student into a John Nash, a Gustave Eiffel, a Frank Lloyd-Wright, a Vincent Van Gogh, an Eddie van Halen or an Alan Turing. Of course, there are plenty of people that make a living at those occupations that aren't the towering persona's of the field, but having talent will get you good faster and having no talent means you're going to have to work hard to achieve mediocrity. Now *this* thread has gone seriously philosophical... Alan Gauld wrote: > "Eric Brunson" wrote > > >>> newbie-friendly. My only complaint is that I'm starting to feel >>> like I >>> won't get much further than that without a computer science degree. >>> >> I'll disagree with you on that, if you can get a PhD in genetics >> then >> programming should be a snap... >> > > I'm not sure I agree. There is a reason that CS is a degree subject, > and that you can get PhDs in it too. There is a lot of advanced > programming > stuff that does need specialist training to *do it well*. Of course > you > can do virtually anything with a buit of brute force. But without > actually > understanding concepts like boolean algenra, lambda and predicate > calculii, > algorithm design, finite state automata thery etc much will either be > inelegant > or just cut n paste. > > I often see comments lie software engineering is different to other > engineering because theres no mathematical basis. Thats plain false, > and although the basis is less complete and certainly not a unified > whole almost every aspect of programming can be validated and proved > mathemaically. Programs can be designed and specified formally. > But most programmers aren't trained. And those that are are > discourageed from doing so because its quicker to "just hack it" > As an applied mathematics man you probably know most of that > stuff at some levelk. Not surprising since CS started off as a branch > of math after all. > > BTW This trend has been true in almost every engineering discipline > and the only thing that corrects it is when companies and programmes > start getting sued and put in prison for writing faulty software. > (Just like > civil engineers were when bridges started falling down, and Electrical > engineers were when householders got electrocuted switching on lamps!) > > >> written and you *are* actually the smartest person in the room. At >> that >> point you have to look other places for your documentation, like the >> source code or the RFCs. >> > > Absolutely true. Not good but its where we are. > (And continuing the simile, the same is true in electronics, sometimes > you just have to reverse engineer the circuit board! but you never do > it > for fun!) > > (*)BTW My own position is that I majored in Electrical/Electronic > engineering > but early on decided software was my interest so took every CS related > class going. I also spent a lot of time doing background reading (and > still do) > on the formal math side of CS - formal logic etc being one of those > areas where > I have an almost constant learning curve. > > From tmikk at umn.edu Fri Jul 27 21:54:39 2007 From: tmikk at umn.edu (Tonu Mikk) Date: Fri, 27 Jul 2007 14:54:39 -0500 Subject: [Tutor] Livewires questions In-Reply-To: <46A82652.9070207@gmail.com> References: <46A7F3C4.5060002@umn.edu> <46A82652.9070207@gmail.com> Message-ID: <46AA4D7F.7070901@umn.edu> Luke Paireepinart wrote: >> def place_robot(): >> global robot_x >> global robot_y >> global robot_shape >> robot_y = random_between(0,47)-0.5 >> robot_x = random_between(0,63)-0.5 >> > I'm not too clear why you're subtracting 0.5 here. > Doesn't this make the robot's center on the grid lines, rather than > having the robot occupy a full square on the grid? > I guess that's the intended behavior, huh? This is particular to Livewires module I believe. I am dealing with the circle (player) whose position is defined by the center of the circle and a square (robot) whose position is defined by the first two coordinates of the square. I subtract 0.5 here so that when the random numbers picked for both the circle and the the square are the same, then visually the square is right on top of the circle. > >> robot_shape = box(10*robot_x, >> 10*robot_y,10*robot_x+10,10*robot_y+10) >> def move_player(): >> while 1: >> global player_x >> global player_y >> if 't' in keys: >> place_player() >> break >> > You can't reuse your place_player function here, because you put the > initialization (the creation) of the graphics that represent the > player _inside_ of the place_player function. Well, technically you > could, but it would be better instead to use move_to(player_shape, x, > y) because this doesn't overwrite the old player_shape circle. > Also, will this work if the player presses "T"? Ok, I made some progress on the pressing of the "T" key, but it is still not entirely correct. The reason why pressing the 't' key was not working initially was because I had omitted the 't' key in the main while loop. As a result, the code never executed the move_player code when I pressed the 't' key. Now if I execute the code above, I get a new player circle placed on the grid, but the old player stays there as well. I somewhat expected this because I am not getting rid of the old player by calling place_player() function. How could I eliminate the old player circle from the grid? When I use the move_to(player_shape, player_x*10, player_y*10), then the player just stays in the same place. This too I expect, since by using move_to, I am not calling new player_x and player_y coordinates. >> if '8' in keys: >> move_to(player_shape,player_x*10 ,player_y*10 + 10) >> player_y = player_y + 1 >> if player_y > 47: >> player_y = player_y -1 >> else: >> pass >> > 'if' statements don't have to have an 'else' clause. > else: > pass > is just a waste of 2 lines. 'pass' does nothing, and since the 'else' > is not required, you may as well leave it off. I thought so too. Part of the problem I had with testing my code was that I was using the PythonWin editor that comes with ActivePython. Often the PythonWin editor would crash and I wasn't always sure if it was because of my code, or because of the editor itself. It somehow seemed that when I had the else: pass in the code, the editor behaved better. I have since then started to use IDLE which works much better. Thank you for pointing this out BTW. It takes some of the guess work out :-). >> >> > This big block of movement code can be shortened into a few lines. > I am not sure how much python you know, so if any of this doesn't make > sense, let me know. I am just a newbie in Python. I like the way you were able to think about the code to make the code much more succinct. I will need to learn a bit more before I understand it exactly. For now, I will try to stick with my long, ugly, inefficient code, that I have puzzled together and understand. Your example has not gone wasted however, it will be used later when I am more familiar with Python and try to improve my code. >> > Also, I just realized that you're using a while loop inside of your > move_player and move_robots function. > But you only call these functions if you KNOW that a movement key was > pressed. > Basically, this means that one of your 'if' conditions will ALWAYS be > true inside of your while: loops, and you'll break out of it. > > The only reason why you might want this is that it would immediately > exit as soon as it finds the first key that was pressed, but the > same thing could be performed using an if-elif chain. But I doubt you > want this to happen. I will experiment with the if statements there. Is it better to use if-elif chain over the while loop when both can work? > > Also there are other problems - eg. your keys is assigned to the keys > that were currently pressed, so if during the time.sleep(0.5) I might > press and then release a key, and it would be lost in your code. Yes, I see this when I run the code. Unfortunately, I don't know how else to do it since it is the only way that they show in the Livewires exercise. I am OK it being imperfect for now. > The code with the changes I mentioned included is attached to this > e-mail. > Also, note that I didn't test this code ( I don't have livewires > installed) so if any of it doesn't work, let me know. > I ran the code that you had included, thank you for this. It did produce the player and the robot on the grid, but the keyboard commands did not work. I wasn't entire sure why, but I thought I would let you know. Thanks again for your help. If you have suggestions on the 't' key, please share them. This seems to be the one issue preventing me from going forward. Tonu From sebastien at solutions-linux.org Fri Jul 27 21:54:45 2007 From: sebastien at solutions-linux.org (Sebastien Noel) Date: Fri, 27 Jul 2007 15:54:45 -0400 Subject: [Tutor] Remove certain tags in html files In-Reply-To: <46AA48AC.4030505@brunson.com> References: <46AA2DB0.7000301@solutions-linux.org> <46AA3384.6050902@brunson.com> <46AA3920.6070608@brunson.com> <46AA48AC.4030505@brunson.com> Message-ID: <46AA4D85.4060802@solutions-linux.org> Thanks a lot for this. Someone on the comp.lang.python usenet channel also suggested using BeautifulSoup with holding the content of a table for example, extracting the table, than putting back the content. Also seems like a good idea. I will look at both possibilities. Eric Brunson wrote: > > Man, the docs on the HTMLParser module are really sparse. > > Attached is some code I just whipped out that will parse and HTML > file, supress the ouput of the tags you mention and spew the html back > out. It's just a rough thing, you'll still have to read the docs and > make sure to expand on some of the things it's doing, but I think > it'll handle 95% of what it comes across. Be sure to override all > the "handle_*()" methods I didn't. > > My recommendation would be to shove your HTML through BeautifulSoup to > ensure it is well formed, then run it through the html parser to do > whatever you want to change it, then through tidy to make it look nice. > > If you wanted to take the time, you could probably write the entire > tidy process in the parser. I got a fair ways there, but decided it > was too long to be instructional, so I pared it back to what I've > included. > > Hope this gets you started, > e. > > Eric Brunson wrote: >> Eric Brunson wrote: >> >>> Sebastien Noel wrote: >>> >>>> Hi, >>>> >>>> I'm doing a little script with the help of the BeautifulSoup HTML >>>> parser and uTidyLib (HTML Tidy warper for python). >>>> >>>> Essentially what it does is fetch all the html files in a given >>>> directory (and it's subdirectories) clean the code with Tidy >>>> (removes deprecated tags, change the output to be xhtml) and than >>>> BeautifulSoup removes a couple of things that I don't want in the >>>> files (Because I'm stripping the files to bare bone, just keeping >>>> layout information). >>>> >>>> Finally, I want to remove all trace of layout tables (because the >>>> new layout will be in css for positioning). Now, there is tables to >>>> layout things on the page and tables to represent tabular data, but >>>> I think it would be too hard to make a script that finds out the >>>> difference. >>>> >>>> My question, since I'm quite new to python, is about what tool I >>>> should use to remove the table, tr and td tags, but not what's >>>> enclosed in it. I think BeautifulSoup isn't good for that because >>>> it removes what's enclosed as well. >>>> >>> You want to look at htmllib: >>> http://docs.python.org/lib/module-htmllib.html >>> >> >> I'm sorry, I should have pointed you to HTMLParser: >> http://docs.python.org/lib/module-HTMLParser.html >> >> It's a bit more straightforward than the HTMLParser defined in >> htmllib. Everything I was talking about below pertains to the >> HTMLParser module and not the htmllib module. >> >> >>> If you've used a SAX parser for XML, it's similar. Your parser >>> parses the file and every time it hit a tag, it runs a callback >>> which you've defined. You can assign a default callback that simply >>> prints out the tag as parsed, then a custom callback for each tag >>> you want to clean up. >>> >>> It took me a little time to wrap my head around it the first time I >>> used it, but once you "get it" it's *really* powerful and really >>> easy to implement. >>> >>> Read the docs and play around a little bit, then if you have >>> questions, post back and I'll see if I can dig up some examples I've >>> written. >>> >>> e. >>> >>> >>>> Is re the good module for that? Basically, if I make an iteration >>>> that scans the text and tries to match every occurrence of a given >>>> regular expression, would it be a good idea? >>>> >>>> Now, I'm quite new to the concept of regular expressions, but would >>>> it ressemble something like this: re.compile("")? >>>> >>>> Thanks for the help. >>>> _______________________________________________ >>>> 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 >>> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > From sebastien at solutions-linux.org Fri Jul 27 22:04:45 2007 From: sebastien at solutions-linux.org (Sebastien Noel) Date: Fri, 27 Jul 2007 16:04:45 -0400 Subject: [Tutor] Remove certain tags in html files In-Reply-To: References: <46AA2DB0.7000301@solutions-linux.org> Message-ID: <46AA4FDD.9080002@solutions-linux.org> Here is the code to deal with 1 given file (the code to iterate all the files as working, and I will glue both together when the second one does what I want.): It's a little long, but I wanted to put it all so you maybe I can get some tips to speed things up because it's pretty slow. import BeautifulSoup, tidy file = open("index.htm", "r") soup = BeautifulSoup.BeautifulSoup(file) file.close() #remove unnecessary things (scripts, styles, ...) for script in soup("script"): soup.script.extract() for style in soup("style"): soup.style.extract() #remove comments comments = soup.findAll(text=lambda text:isinstance(text, BeautifulSoup.Comment)) [comment.extract() for comment in comments] #the following removes things specific to the pages I'm working with, don't mind the langcanada things #I was just too lazy to change the name of this variable each time #I think this is an area that could be done differently to get more speed langcanada = soup.findAll("img", src="graphics/button_f.jpg") [img.parent.parent.extract() for img in langcanada] langcanada = soup.findAll("img", src="graphics/button_e.jpg") [img.parent.parent.extract() for img in langcanada] langcanada = soup.findAll("img", src="http://u1.extreme-dm.com/i.gif") [img.parent.parent.extract() for img in langcanada] langcanada = soup.findAll("a", href="research/disclaimer.htm") [img.parent.extract() for img in langcanada] comments = soup.findAll(text=" ") [comment.extract() for comment in comments] langcanada = soup.findAll("img", id="logo") [img.parent.parent.parent.extract() for img in langcanada] langcanada = soup.findAll("img", id="about") [img.parent.parent.parent.extract() for img in langcanada] langcanada = soup.findAll("img", src="images/navbgrbtm.jpg") [img.parent.parent.parent.parent.extract() for img in langcanada] langcanada = soup.findAll("img", src="images/navbgrtop.jpg") [img.parent.parent.parent.parent.extract() for img in langcanada] #delete class attributes for divs in range(len(soup.findAll("div"))): le_div = soup.findAll("div")[divs] del le_div["class"] for paras in range(len(soup.findAll("p"))): le_par = soup.findAll("p")[paras] del (le_par["class"]) for imgs in range(len(soup.findAll("img"))): le_img = soup.findAll("img")[imgs] del (le_img["hspace"]) del (le_img["vspace"]) del (le_img["border"]) # Add some class attributes for h1s in range(len(soup.findAll("h1"))): le_h1 = soup.findAll("h1")[h1s] le_h1["class"] = "heading1_main" for h2s in range(len(soup.findAll("h2"))): le_h2 = soup.findAll("h2")[h2s] le_h2["class"] = "heading2_main" for h3s in range(len(soup.findAll("h3"))): le_h3 = soup.findAll("h3")[h3s] le_h3["class"] = "heading3_main" for h4s in range(len(soup.findAll("h4"))): le_h4 = soup.findAll("h4")[h4s] le_h4["class"] = "heading4_main" for h5s in range(len(soup.findAll("h5"))): le_h5 = soup.findAll("h5")[h5s] le_h5["class"] = "heading5_main" # links, makes difference between internal and external ones for links in range(len(soup.findAll("a"))): le_link = soup.findAll("a")[links] le_href = le_link["href"] if le_href.startswith("""http://caslt.org""") or le_href.startswith("""http://www.caslt.org"""): le_link["class"] = "caslt_link" elif le_href.startswith("""http://"""): le_link["class"] = "external_link" else: le_link["class"] = "caslt_link" del (soup.body["onload"]) # This is what needs to be done: ###### change tables to divs ###### remove all td tags ###### remove all tr tags # Tidying soup = soup.prettify() erreurs = "" tidy_options = {"tidy-mark": 0, "wrap": 0, "wrap-attributes": 0, "indent": "auto", "output-xhtml": 1, "doctype": "loose", "input-encoding": "utf8", "output-encoding": "utf8", "break-before-br": 1, "clean": 1, "logical-emphasis": 1, "drop-font-tags": 1, "enclose-text": 1, "alt-text": " ", "write-back": 1, "error-file": erreurs, "show-warnings": 0, "quiet": 1, "drop-empty-paras": 1, "drop-proprietary-attributes": 1, "join-classes": 1, "join-styles": 1, "show-body-only": 1, "word-2000": 1, "force-output": 1} soup_tidy = tidy.parseString(soup, **tidy_options) outputfile = open("index2.htm", "w") outputfile.write(str(soup_tidy)) outputfile.close() Alan Gauld wrote: > "Sebastien Noel" wrote > > >> My question, since I'm quite new to python, is about what tool I >> should >> use to remove the table, tr and td tags, but not what's enclosed in >> it. >> I think BeautifulSoup isn't good for that because it removes what's >> enclosed as well. >> > > BS can do what you want, you must be missing something. One of the > most basic examples of using BS is to print an HTML file as plain text > - ie stripping just the tags. So it must be possible. > > Can you put together a short example of the code you are using? > > You an use lower level parsers but BS is geneally easier, but until > we know what you are doing its hard to guess what might be wrong. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From andreas at kostyrka.org Fri Jul 27 22:06:05 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 27 Jul 2007 22:06:05 +0200 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: References: <004201c7d075$0ad4fcb0$51fce004@JSLAPTOP> Message-ID: <46AA502D.40901@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Alan Gauld wrote: > "Tiger12506" wrote > >> Some people need degrees, most people don't. It all depends on what >> they are >> capable of understanding. > > It also depends what they are doing. > Most programmers don't build complex state machines, nor do they > build safety critical systems. 90% or more of all programs don't > need a degree, but somecthings do need formal training and the > language is basically irrelevant. degrees dopnm;t teach languages, > they teach the underlying theory. Exactly. That's also why CS is not a major for everyone. My university when I had the priviledge had an awful portion of mathematics. (My motto was, that the only way to have more math courses would be to study something with mathematics in the title *g*) Worse from the perspective of many students that expected to learn "programming" was the fact, that you were expected to know programming already. Or learn it in your own spare time. Well, the official party line was that one does not need any knowledge beforehand, but the reality was slightly different. And the reality is that learning a programming language has always been a trivial thing. (These graphical IDE stuff is hard. Nobody takes away my emacs/vi :) ) > >> understanding of what else is out there. Python's standard library >> is >> 'newbie-friendly'. If you doubt it, try emulating what you can >> already do in >> python in another language. > > Actually you an do what you do in Python in practically any general > purpose > language, it just takes a few more lines of code (OK a lot more lines > in > some cases) But Pythons library is not newbie friendly, sorry. How > does > a newbie know when to use pickle v cpickle? or urllib v urllib2? And > which > of the xml parsers? And as for thev mess that is glob/os/path/shutil? Well, personally that's where the missing formal training and experience shows. Ok, don't talk about urllib/urllib2, it's a mess. OTOH, it's really hard to clean up, because changing/removing names in these old legacy modules would break existing code. (And the correct answer for URL retrieval is neither urllib/urllib2, it's pyCurl ;) ). The cPickle/Pickle question is AFAIR documented, BUT other pitfalls with Pickles in general are not. And one needs different XML parsers, well, simple, because parsing XML is not a problem with one single perfect solution, so one needs to select the perfect one. OTOH, as a newbie, it really does not matter if one uses urllib or urllib2. It does not really matter which XML parser one uses, usually. And the only drawback of choosing Pickle over cPickle might be performance. Sometimes an issue for newbies, but often not. > Its not clear to me even after 10 years of using Python which function > sits where and why. And what about the confusion over system(), > popen(),commands(),spawn(), subprocess() etc. or why is there time Mistakes of history. Plus a number of these warts come from the ports to certain inferior operating systems. And really hard to fix, because it involves breaking compatibility, in a way that might lead to subtle runtime bugs. time versus datetime is easy to understand => time is POSIX time management functions, while datetime is a generic language specific data type meant to represent dates, timestamps, etc. > and datetime? Sure it makes sense once you've played with Python > for a while it makes some sense and you learn the role of history. > But for a newbie thats not a friendly scenario ad many other languages > are far better organised - Smalltalk being one example! And the C++ > standard > library is another. Even the Java standard library, much as I dislike > Java, is > better organised and more consistent! You think that there are no overlapping APIs in Java? Historic "mistakes"? Andreas -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGqlAtHJdudm4KnO0RAqdGAKDpljkn5MrKzK6HPqOpQYZQmR3ybQCfRUx1 WSQWeILzgfhpHl0iGBadSss= =egdH -----END PGP SIGNATURE----- From kent37 at tds.net Fri Jul 27 22:33:06 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Jul 2007 16:33:06 -0400 Subject: [Tutor] Code like a Pythonista In-Reply-To: References: Message-ID: <46AA5682.9060501@tds.net> Terry Carroll wrote: > On Fri, 27 Jul 2007, Kent Johnson wrote: > >> For navigation I use left and right arrows or mouse-over the >> bottom-right of the screen to get a nav panel. But when I get to the >> screen "Whitespace 1" there is nothing but white space under the title. > > Same here, but as I press the PgDn key (or the right arrow -- thanks for > that) it fills in, a line at a time: Oh, OK, it's a reveal. AFAICT it doesn't work if you use the mouse buttons, only if you navigate with the keyboard. Kent From alan.gauld at btinternet.com Fri Jul 27 22:59:37 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Jul 2007 21:59:37 +0100 Subject: [Tutor] Shelve del not reducing file size References: <004201c7d075$0ad4fcb0$51fce004@JSLAPTOP> <46AA502D.40901@kostyrka.org> Message-ID: "Andreas Kostyrka" wrote > was, that the only way to have more math courses would be to study > something with mathematics in the title *g*) Thats true of most engineering courses. Although I studied Electrical engineering the only compulsory subject for each of the 5 years(if you took it to Masters) was math! You could actually drop all of the pure electricaltheory by fifth year but you couldn't drop math... But thats because math is the language of enginering, regardless of whether its building bridges, oscillators or programs. You don't need much math to build a garden shed, but you need a lot to build the Tacoma Narrows bridge... Similarly you don't need much math to build a GUI friont end to a database, but you need quite a lot to build the control program for a nuclear reactor. (and the consequences of getting it wrong are usually worse too!) > of many students that expected to learn "programming" was the fact, > that > you were expected to know programming already. Really? We had a pretty good basic Pascal course in first year. After that you knew how to program so after that it was just learning new languages so no need for extra training. Most of it after that was on techniques like data structures, parallel processing, graphics, relational data theory, intrerruipt handling, assembler I/O techniques, simulation and control theory etc etc. The stuff you need to design programs not write them. > cPickle/Pickle question is AFAIR documented, But not in a manner totally clear to a newbie. An experienced programmer will figure out that a C implementation is faster but what does that meabn when your only reference is a few weeks of Python? And why is there two modules if one is better? Why not just replace the Python one completely? > simple, because parsing XML is not a problem with one single perfect > solution, so one needs to select the perfect one. But how does a newbie know which solution where? There is little or no guidance about that in the docs > OTOH, as a newbie, it really does not matter if one uses urllib or > urllib2. But its confusing and unsettling that there is a choice. especially when the zen of python claims there is only ione way to do it! Not in the library there ain't - even if you are Dutch! >> sits where and why. And what about the confusion over system(), >> popen(),commands(),spawn(), subprocess() etc. or why is there time > Mistakes of history. Sure but again the newbie just sees a mess. > Plus a number of these warts come from the ports to > certain inferior operating systems. Granted but thats not the main reason, its just history and the open source culture of contributing modules. Now dopn;t get me wrong, I'd rather have the batteries than build my own, but we should not forget just how hard this is for a newbie. > time versus datetime is easy to understand => time is POSIX time POSIX whassat? Newbies again. >> library is another. Even the Java standard library, much as I >> dislike >> Java, is better organised and more consistent! > > You think that there are no overlapping APIs in Java? Historic > "mistakes"? There are overlaps - Swing v AWT etc being a prime example. But the organisation of the library into packages is much better controlled. By separating the old/new Java at least keeps things relatively tidy and can say use the stuff here and not the stuff over there. Pythons essentially flat (and that is improving slowly) structure is just messy. Alan G From alan.gauld at btinternet.com Fri Jul 27 23:17:58 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Jul 2007 22:17:58 +0100 Subject: [Tutor] Remove certain tags in html files References: <46AA2DB0.7000301@solutions-linux.org> <46AA4FDD.9080002@solutions-linux.org> Message-ID: Sebastien Noel" wrote > comments = soup.findAll(text=" ") > [comment.extract() for comment in comments] Umm, why comments here and not langcanada? Just curious... > # Add some class attributes > for h1s in range(len(soup.findAll("h1"))): > le_h1 = soup.findAll("h1")[h1s] > le_h1["class"] = "heading1_main" > > for h2s in range(len(soup.findAll("h2"))): > le_h2 = soup.findAll("h2")[h2s] > le_h2["class"] = "heading2_main" You could abstract this into a function with a few parametes and put it into a loop, and thus save a load of typing! OK, Too much code to go through in detail, can you do a simple example where you try to remove some tags and it doesn't work? Also did you look at the ReplaceWith method? That may help you if you use something like a SPAN or DIV tag... I didn't see you writing anything back in that code but then I was just scanning it and may have missed it... You extract them from the parse tree but do you ever write the modified tree out? Alan G From andreas at kostyrka.org Fri Jul 27 23:30:19 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 27 Jul 2007 23:30:19 +0200 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: References: <004201c7d075$0ad4fcb0$51fce004@JSLAPTOP> <46AA502D.40901@kostyrka.org> Message-ID: <46AA63EB.9090002@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Alan Gauld wrote: > "Andreas Kostyrka" wrote > >> was, that the only way to have more math courses would be to study >> something with mathematics in the title *g*) > > Thats true of most engineering courses. > Although I studied Electrical engineering the only compulsory subject > for each of the 5 years(if you took it to Masters) was math! You could > actually drop all of the pure electricaltheory by fifth year but you > couldn't > drop math... But thats because math is the language of enginering, > regardless of whether its building bridges, oscillators or programs. > You don't need much math to build a garden shed, but you need > a lot to build the Tacoma Narrows bridge... Similarly you don't need > much math to build a GUI friont end to a database, but you need > quite a lot to build the control program for a nuclear reactor. (and > the > consequences of getting it wrong are usually worse too!) I would question even that one can write a good GUI frontend to a database without the theory behind it. Database design has a number of important theoretical foundations (relational algebra, normal forms), and without understanding these, and their implications for your db model, you might end up with a bad GUI. > >> of many students that expected to learn "programming" was the fact, >> that >> you were expected to know programming already. > > Really? We had a pretty good basic Pascal course in first year. After > that you knew how to program so after that it was just learning new > languages so no need for extra training. Most of it after that was on Well, the advanced stuff was there. But the Modula2 introduction to programming was a joke, most students did not even understand the concept of local variables and procedure parameters after one semester. OTOH, I might be a bad judge on programming progress, at that time I was young and a C++ tutor in the parallel introduction to programming course at the second university in town ;) > techniques like data structures, parallel processing, graphics, > relational > data theory, intrerruipt handling, assembler I/O techniques, > simulation > and control theory etc etc. The stuff you need to design programs not > write them. > >> cPickle/Pickle question is AFAIR documented, > > But not in a manner totally clear to a newbie. An experienced > programmer will figure out that a C implementation is faster but > what does that meabn when your only reference is a few weeks > of Python? And why is there two modules if one is better? Why > not just replace the Python one completely? Well, here we come to the point where the complexity is higher than what most newbies can grasp. But that's not really unique to programming or Python, most high school level math courses do not teach the whole truth. At least not in the beginning. Andreas -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGqmPqHJdudm4KnO0RAlyEAKDdwfKqvhh7C+zET8q9MCGBHtg3LACfTmLa 2gDDp5r2ZzU/H0Kwj5UsOPg= =ypyp -----END PGP SIGNATURE----- From slewin at rogers.com Fri Jul 27 23:29:15 2007 From: slewin at rogers.com (scott) Date: Fri, 27 Jul 2007 17:29:15 -0400 Subject: [Tutor] Which GUI? Message-ID: <46AA63AB.3080209@rogers.com> Hi, now that I have a very basic understanding of Python I would like to take a look at programming in a GUI. Which GUI is generally the easiest to learn? -- Your friend, Scott Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) From brunson at brunson.com Fri Jul 27 23:40:53 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 27 Jul 2007 15:40:53 -0600 Subject: [Tutor] Which GUI? In-Reply-To: <46AA63AB.3080209@rogers.com> References: <46AA63AB.3080209@rogers.com> Message-ID: <46AA6665.3040907@brunson.com> scott wrote: > Hi, > > now that I have a very basic understanding of Python I would like to > take a look at programming in a GUI. Which GUI is generally the easiest > to learn? > > Easiest depends on your background. I was a Mac developer back in the day, so WXPython was easy for me. If you're a KDE programmer, then PyQT is probably your cup of tee. Similarly, GTK programmers will probably like PyGTK. I cannot make any statements about Tkinter, since I eschew everything TCL related. From keridee at jayco.net Sat Jul 28 00:55:50 2007 From: keridee at jayco.net (Tiger12506) Date: Fri, 27 Jul 2007 17:55:50 -0500 Subject: [Tutor] Shelve del not reducing file size References: <004201c7d075$0ad4fcb0$51fce004@JSLAPTOP><46AA502D.40901@kostyrka.org> Message-ID: <003d01c7d0a1$4ad7b0b0$51fce004@JSLAPTOP> >> cPickle/Pickle question is AFAIR documented, > > But not in a manner totally clear to a newbie. An experienced > programmer will figure out that a C implementation is faster but > what does that meabn when your only reference is a few weeks > of Python? And why is there two modules if one is better? Why > not just replace the Python one completely? I remember being a newbie. :-) I read in the docs where cPickle was faster. I also read that Pickle is only necessary for subclassing. As I had little idea what subclassing was, i knew that using cPickle would be to my advantage. However, seeing that the documentation was describing the Pickle module, I used it. No issue. >> simple, because parsing XML is not a problem with one single perfect >> solution, so one needs to select the perfect one. What the hell is XML? If i knew what it was, maybe i would have a reason to parse it, as a newbie. >> OTOH, as a newbie, it really does not matter if one uses urllib or >> urllib2. > > But its confusing and unsettling that there is a choice. > especially when the zen of python claims there is only ione way > to do it! Not in the library there ain't - even if you are Dutch! Why is a choice confusing? Why, why why? That's the problem with these clever language descriptions like the zen. It claims that there is only one way to do it. So when the average newbie actually finds more than one way, it's "total meltdown". They don't have open minds. Why are they trying to create? sigh. At any rate, I remember wondering which to use. Reading the documentation (in the capacity of a newbie) I determined which one looked more promising, more applicable, less complex. When I had a question, I found resources (like this python list). Also, noticing that comp.lang.python was often discussing things that i didn't understand, i didn't ask my questions there. I used techniques that are used to find information. No, not special techniques for surfing the net, just ordinary common sense. Is this a sense of talent? Do people (non-programmer-destined) not have this? >>> sits where and why. And what about the confusion over system(), >>> popen(),commands(),spawn(), subprocess() etc. or why is there time >> Mistakes of history. > > Sure but again the newbie just sees a mess. True. Skimming over it long ago, i noticed os.system() which would execute a command that i would normally execute on the command line. I was content with that. It executed the program. Why would I (the newbie) argue? >> Plus a number of these warts come from the ports to >> certain inferior operating systems. > > Granted but thats not the main reason, its just history and the > open source culture of contributing modules. Now dopn;t get me wrong, > I'd rather have the batteries than build my own, but we should not > forget > just how hard this is for a newbie. > >> time versus datetime is easy to understand => time is POSIX time > > POSIX whassat? Newbies again. Yeah POSIX whassat?!? Agreed. But I personally felt that it was stupid to put dates and time into the same module, into the same class, so I used time. And it served me. When it didn't, I asked questions, did research~ What do they teach in high schools now? Note to newbies: Ask questions, do research. Google. There. Your whole high school career made absolutely useless. Again, I feel prompted to mention C/C++ (which seemed like a mess of computer terms and gibberish), Perl (which seemed useless), Ruby (which I could never get to run), etc. Python is Soooo simple. JS From slewin at rogers.com Sat Jul 28 00:17:06 2007 From: slewin at rogers.com (scott) Date: Fri, 27 Jul 2007 18:17:06 -0400 Subject: [Tutor] [Bulk] Re: Which GUI? In-Reply-To: <46AA6665.3040907@brunson.com> References: <46AA63AB.3080209@rogers.com> <46AA6665.3040907@brunson.com> Message-ID: <46AA6EE2.1050705@rogers.com> Eric Brunson wrote: > Easiest depends on your background. I was a Mac developer back in the day, so WXPython was easy for me. If you're a KDE programmer, then PyQT is probably your cup of tee. Similarly, GTK programmers will probably like PyGTK. I cannot make any statements about Tkinter, since I eschew everything TCL related. I have not done any GUI programming at all using any GUI language. So, I'm not anything, not yet anyway :) I know I don't want to program using PyQT because of the licencing issues; I prefer something that is completely open source. I know I will eventually poke around a couple different GUI languages, but, would prefer to start with what is easiest to learn for a new programmer. -- Your friend, Scott Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) From rdm at rcblue.com Sat Jul 28 00:32:00 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 27 Jul 2007 15:32:00 -0700 Subject: [Tutor] Code like a Pythonista In-Reply-To: References: <20070727082009.80DE61E4005@bag.python.org> Message-ID: <20070727223212.682AC1E400A@bag.python.org> At 12:02 PM 7/27/2007, Terry Carroll wrote: >On Fri, 27 Jul 2007, Dick Moores wrote: > > > The handout is excellent! Thanks! > > > > But the slideshow at > > > , > > isn't. > >You have to use the page-up and -down keys; or the spacebar (at least on >Windows under Firefox). Took me a while to figure that out. Ah. Thanks. Dick From carroll at tjc.com Sat Jul 28 00:46:02 2007 From: carroll at tjc.com (Terry Carroll) Date: Fri, 27 Jul 2007 15:46:02 -0700 (PDT) Subject: [Tutor] Which GUI? In-Reply-To: <46AA63AB.3080209@rogers.com> Message-ID: On Fri, 27 Jul 2007, scott wrote: > now that I have a very basic understanding of Python I would like to > take a look at programming in a GUI. Which GUI is generally the easiest > to learn? As between Tkinter and wxPython, I started on Tkinter, but have been won over to wxPython, although I've only played with it so far. The problem with wxPython is that it's poorly documented, but there's a book out on it now that you should beg, borrow or steal if you plan on using it. Lessee: "wxPython in Action," see http://www.wxpython.org/ There's a lot of tutorials on Tkinter, but none worked very well for me, probably because it's such a shift in approach to think in a GUI-like way. The big advantage of Tkinter is that it's already distributed with Python, so you already have it installed. I've heard good things about PythonCard (which is built on top of wxPython) but never tried it. http://pythoncard.sourceforge.net/ From keridee at jayco.net Sat Jul 28 02:19:44 2007 From: keridee at jayco.net (Tiger12506) Date: Fri, 27 Jul 2007 19:19:44 -0500 Subject: [Tutor] Which GUI? References: Message-ID: <002001c7d0ad$034ac5a0$4cfce004@JSLAPTOP> > As between Tkinter and wxPython, I started on Tkinter, but have been won > over to wxPython, although I've only played with it so far. The problem > with wxPython is that it's poorly documented, but there's a book out on it > now that you should beg, borrow or steal if you plan on using it. Tkinter is easier to program from the start, but I quickly discarded it for wxPython. Reasons: The windows looked foreign, and childish, because as a newbie at the time I didn't want to take the time making things pretty (padx = ...) wxPython uses 'native looking windows' meaning that windows you create with wxPython will look like other windows on your machine. (In XP, for example, round edges, blue, thick, 3d looking) wxPython seems very powerful and thorough. It is also more modern. I would suggest starting with Tkinter to get a feel for what it takes to create a GUI and drive it, then when you become comfortable, switch to something more professional looking/powerful. > The big advantage of Tkinter is that it's already distributed with Python, > so you already have it installed. Yep. Definite advantage. > I've heard good things about PythonCard (which is built on top of > wxPython) but never tried it. http://pythoncard.sourceforge.net/ Can be error-prone (the resource editor sometimes freezes) and confusing (Uses a technique including importing the same module within itself?!?), but if you follow the example programs, you can get running code easily. Advantage is graphical control placement, as in a resource editor. The disadvantage of that is that an extra file is created to contain the resource information. As for being newbie friendly~~ Not as straight-forward as Tkinter to code, but easier to visualize because of the graphical control placement not available with Tkinter. Perhaps the errors have been fixed since I tested it out last. Cheers, JS From alan.gauld at btinternet.com Sat Jul 28 01:58:30 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Jul 2007 00:58:30 +0100 Subject: [Tutor] Which GUI? References: <002001c7d0ad$034ac5a0$4cfce004@JSLAPTOP> Message-ID: "Tiger12506" wrote >> As between Tkinter and wxPython, I started on Tkinter, but have >> been won >> over to wxPython, although I've only played with it so far. I'm in transition. The problem I find with wxPython is the two-stage create widget/bind widget style and I find the layout management slightly more cumbersome. But OTOH if i was starting from scratch instead of having 10 years of Tkinter (and Delphi) background I might think differently! >> with wxPython is that it's poorly documented, but there's a book >> out on it >> now that you should beg, borrow or steal if you plan on using it. Agreed. Until the book came out I only played with wxPython briefly. > Tkinter is easier to program from the start, but I quickly discarded > it for > wxPython. I think Tkinter is easier to throw a quick GUI on top of an existing script - and to be fair thats all Tk was originally designed to do for Tcl... wxPython has a richer widget set - although the (poorly documented) Tix module closes the gap considerably. > The windows looked foreign, and childish, because as a newbie at > the time I didn't want to take the time making things pretty I've never found the look a problem, but I've seen enough complaints to know it matters a lot to some folk. Finally wxPython does come with some tools that are genuinely useful in their own right - ALa Mode is much better than IDLE IMHO! And PyCrust is now my standard interpreter shell. If you do want a very quick feel for Tkinter and a comparison with wxPython take a look at my GUI topic in my tutorial. Its about as brief as it can get... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jfabiani at yolo.com Sat Jul 28 02:00:38 2007 From: jfabiani at yolo.com (johnf) Date: Fri, 27 Jul 2007 17:00:38 -0700 Subject: [Tutor] Which GUI? In-Reply-To: <46AA63AB.3080209@rogers.com> References: <46AA63AB.3080209@rogers.com> Message-ID: <200707271700.39014.jfabiani@yolo.com> On Friday 27 July 2007 14:29, scott wrote: > Hi, > > now that I have a very basic understanding of Python I would like to > take a look at programming in a GUI. Which GUI is generally the easiest > to learn? You might want to check out Dabo (www.dabodev.com) which uses wxPython but provides a much easier user interface (includes data binding if needed). -- John Fabiani From David.Barton at nottingham.ac.uk Sat Jul 28 02:10:58 2007 From: David.Barton at nottingham.ac.uk (Barton David) Date: Sat, 28 Jul 2007 01:10:58 +0100 Subject: [Tutor] Shelve del not reducing file size References: <46AA1E5D.9050305@brunson.com> Message-ID: Eric Brunson wrote: > You seem like a smart guy that's having a bad day, so I'm cutting you > slack. Thanks Eric. Yes I did indeed have a bad day (and it got much much worse), and this is most definitely a case of a bad workman blaming his tools. I apologise to all concerned for voicing my frustrations: it was clearly ill-advised. Still.. call me idealistic but I feel like a good toolmaker should try to listen to her clients. I am not a dedicated programmer. I have other stuff on my plate. I probably wouldn't be a programmer at all if Python wasn't (in the early stages) so fabulously friendly. Alan Gauld wrote: > But Pythons library is not newbie friendly, sorry. How does > a newbie know when to use pickle v cpickle? or urllib v urllib2? And > which of the xml parsers? And as for thev mess that is glob/os/path/shutil? > Its not clear to me even after 10 years of using Python which function > sits where and why. And what about the confusion over system(), > popen(),commands(),spawn(), subprocess() etc. or why is there time > and datetime? Sure it makes sense once you've played with Python > for a while it makes some sense and you learn the role of history. This is very much how this particular 'newbie' has experienced things. I'm not here to damn Python, but to praise it, for opening my eyes to a whole bunch of stuff. But you know when I teach biology and genetics, and the kids don't get it, I feel like the onus is on me to improve my teaching. And if I code a tool for people in my lab, and they can't use it, then I feel like I've got some work to do, either in teaching or in making the tool easier to use. That's just me, Tiger, and I'm sorry it makes you spit venom. Not my intention at all. But it's Alan's hand that I want to shake, because as far as I can tell, he's looking to the future, to the next generation, to the ugly reality and the bright potential, and quite frankly, you're not. This message has been checked for viruses but the contents of an attachment may still contain software viruses, which could damage your computer system: you are advised to perform your own checks. Email communications with the University of Nottingham may be monitored as permitted by UK legislation. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070728/7823daf6/attachment.html From maseriyer at yahoo.com Sat Jul 28 04:26:30 2007 From: maseriyer at yahoo.com (Iyer) Date: Fri, 27 Jul 2007 19:26:30 -0700 (PDT) Subject: [Tutor] os.path.exists(path) returns false when the path actually exists! Message-ID: <71094.5166.qm@web50709.mail.re2.yahoo.com> os.path.exists(path) returns false when the path actually exists! When I do this: >>> os.path.exists("c:\\winnt\\file_name") I get this: >>> False Actually the file exists in c:\winnt, and I can confirm it exists there, but os.path.exists isn't returning True, when it should be.. Is this a bug ? iyer --------------------------------- Park yourself in front of a world of choices in alternative vehicles. Visit the Yahoo! Auto Green Center. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070727/50217b3a/attachment.html From brunson at brunson.com Sat Jul 28 04:32:36 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 27 Jul 2007 20:32:36 -0600 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: References: <46AA1E5D.9050305@brunson.com> Message-ID: <46AAAAC4.8060108@brunson.com> Python is like democracy. It isn't perfect, but it's the best thing come up with so far. ;-) Barton David wrote: > Eric Brunson wrote: > > You seem like a smart guy that's having a bad day, so I'm cutting you > > slack. > > Thanks Eric. Yes I did indeed have a bad day (and it got much much worse), > and this is most definitely a case of a bad workman blaming his tools. I > apologise to all concerned for voicing my frustrations: it was clearly > ill-advised. > Still.. call me idealistic but I feel like a good toolmaker should try > to listen to her > clients. > > I am not a dedicated programmer. I have other stuff on my plate. I > probably > wouldn't be a programmer at all if Python wasn't (in the early stages) so > fabulously friendly. > > Alan Gauld wrote: > > But Pythons library is not newbie friendly, sorry. How does > > a newbie know when to use pickle v cpickle? or urllib v urllib2? And > > which of the xml parsers? And as for thev mess that is > glob/os/path/shutil? > > Its not clear to me even after 10 years of using Python which function > > sits where and why. And what about the confusion over system(), > > popen(),commands(),spawn(), subprocess() etc. or why is there time > > and datetime? Sure it makes sense once you've played with Python > > for a while it makes some sense and you learn the role of history. > > This is very much how this particular 'newbie' has experienced things. I'm > not here to damn Python, but to praise it, for opening my eyes to a whole > bunch of stuff. But you know when I teach biology and genetics, and the > kids don't get it, I feel like the onus is on me to improve my > teaching. And > if I code a tool for people in my lab, and they can't use it, then I > feel like > I've got some work to do, either in teaching or in making the tool > easier to > use. > > That's just me, Tiger, and I'm sorry it makes you spit venom. Not my > intention at all. But it's Alan's hand that I want to shake, because as > far as I can tell, he's looking to the future, to the next generation, to > the ugly reality and the bright potential, and quite frankly, you're not. > > This message has been checked for viruses but the contents of an > attachment may still contain software viruses, which could damage your > computer system: you are advised to perform your own checks. Email > communications with the University of Nottingham may be monitored as > permitted by UK legislation. > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From maseriyer at yahoo.com Sat Jul 28 04:42:25 2007 From: maseriyer at yahoo.com (Iyer) Date: Fri, 27 Jul 2007 19:42:25 -0700 (PDT) Subject: [Tutor] os.path.exists(path) returns false when the path actually exists! In-Reply-To: <20070727223541.7f8366c6@lavos> Message-ID: <955680.13552.qm@web50708.mail.re2.yahoo.com> Adam wrote: >From the library documentation: Return True if path refers to an existing path. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists. So the better question is, does is this file a broken symbolic link or can os.stat() be executed on it? How do I find if it is a broken symbolic link in Windows 2000 ? os.stat(path) returns an OSError saying that there is no such file or directory --------------------------------- Shape Yahoo! in your own image. Join our Network Research Panel today! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070727/189211f6/attachment.htm From strider1551 at gmail.com Sat Jul 28 04:35:41 2007 From: strider1551 at gmail.com (Adam A. Zajac) Date: Fri, 27 Jul 2007 22:35:41 -0400 Subject: [Tutor] os.path.exists(path) returns false when the path actually exists! In-Reply-To: <71094.5166.qm@web50709.mail.re2.yahoo.com> References: <71094.5166.qm@web50709.mail.re2.yahoo.com> Message-ID: <20070727223541.7f8366c6@lavos> > os.path.exists(path) returns false when the path actually exists! > > When I do this: > > >>> os.path.exists("c:\\winnt\\file_name") > > I get this: > >>> False > > Actually the file exists in c:\winnt, and I can confirm it exists > there, but os.path.exists isn't returning True, when it should be.. > Is this a bug ? From the library documentation: Return True if path refers to an existing path. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists. So the better question is, does is this file a broken symbolic link or can os.stat() be executed on it? From hugonz-lists at h-lab.net Sat Jul 28 09:56:07 2007 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sat, 28 Jul 2007 02:56:07 -0500 Subject: [Tutor] os.path.exists(path) returns false when the path actually exists! In-Reply-To: <955680.13552.qm@web50708.mail.re2.yahoo.com> References: <955680.13552.qm@web50708.mail.re2.yahoo.com> Message-ID: <46AAF697.9030402@h-lab.net> Iyer wrote: > > Adam wrote: > > From the library documentation: > Return True if path refers to an existing path. Returns False for > broken symbolic links. On some platforms, this function may return > False if permission is not granted to execute os.stat() on the > requested file, even if the path physically exists. > > So the better question is, does is this file a broken symbolic link or > can os.stat() be executed on it? > > > How do I find if it is a broken symbolic link in Windows 2000 ? > > os.stat(path) returns an OSError saying that there is no such file or > directory Just to check, try to do away with the backslashes. Windows will accept a path with forward slashes just as well: os.path.exists("c:/winnt/file_name") Hugo From andreas at kostyrka.org Sat Jul 28 10:02:16 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sat, 28 Jul 2007 10:02:16 +0200 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: References: <46AA1E5D.9050305@brunson.com> Message-ID: <46AAF808.8020607@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Barton David wrote: > Eric Brunson wrote: >> You seem like a smart guy that's having a bad day, so I'm cutting you >> slack. > > Thanks Eric. Yes I did indeed have a bad day (and it got much much worse), > and this is most definitely a case of a bad workman blaming his tools. I > apologise to all concerned for voicing my frustrations: it was clearly > ill-advised. > Still.. call me idealistic but I feel like a good toolmaker should try > to listen to her > clients. Believe me, the Python developers are sure listening. Only that "cleaning up the mess" has associated costs, that are usually not acceptable. If it comes to "not breaking existing programs" or "cleaning up the stdlib so it's nicer", "not breaking existing programs" is way higher priority. There are also a number of things to consider: a) adding a keyword is less of an issue, as breaks programs potentially with SyntaxErrors before they run. Easy to notice, and easy to fix usually. b) adding a name in some module is usually not a problems. The only issue could be imports like that: abc = 1 from module import * where module adds "abc" would clobber the abc in the customer module. OTOH, there are really few modules where it is considered usual and ok to use the star form of import. c) removing (or renaming, as that removes the old name too) in the library breaks programs, and worse it breaks them only when the name is used. Despite rigorous testing, you cannot catch these every time. So the above observations explain why there is an urllib and urllib2, removing urllib would imply that many many programs would break. Worse some would break in production. (btw, some functions in urllib are still not duplicated, so just removing urllib wouldn't be an option anyway) So I have to ask all the nice-to-the-newbie guys, what is your take on this? Should we break existing and deployed applications, so that the stdlib can look nicer to a newbie? And that is an issue, less for Windows where one has to install Python yourself, but on Linux boxes one usually uses the OS provided python version. One fast apt-get upgrade, and deployed application can trip over any incompatibilities. > > I am not a dedicated programmer. I have other stuff on my plate. I probably > wouldn't be a programmer at all if Python wasn't (in the early stages) so > fabulously friendly. It's still fabulously newbie friendly. And that's why it's one of the languages that many non-developers are using, usually engineers and scientists. :) Andreas -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGqvgHHJdudm4KnO0RAgeLAJ9MZmtpy6rFmdDp/Oh2BrSZLs16GwCbBJzr LQyRTHL+egu6qVeI0Dh2sBY= =Miln -----END PGP SIGNATURE----- From shriphanip at gmail.com Sat Jul 28 12:02:42 2007 From: shriphanip at gmail.com (Shriphani Palakodety) Date: Sat, 28 Jul 2007 15:32:42 +0530 Subject: [Tutor] ideas for college app. In-Reply-To: References: Message-ID: <46AB1442.8040606@gmail.com> Hello all, I am looking for a few ideas for my college app. Can someone give me a few ideas i could work on? I would like to use these to learn more of python and to become a true expert at it. From rabidpoobear at gmail.com Sat Jul 28 11:38:17 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 28 Jul 2007 04:38:17 -0500 Subject: [Tutor] Sum of Scores In-Reply-To: <001401c7d026$02865080$c3fce004@JSLAPTOP> References: <009401c7cfdc$3c3b4320$d6fce004@JSLAPTOP> <46A92D94.3090804@gmail.com> <002401c7cfee$9a191690$d6fce004@JSLAPTOP> <46A9606D.5070709@gmail.com> <001401c7d026$02865080$c3fce004@JSLAPTOP> Message-ID: On 7/27/07, Tiger12506 wrote: > > Hmmm... interesting tie to another post... > > >>> x = timeit.Timer('random.random()','import random') > >>> x.timeit(3000000) > 1.0161026052194018 > >>> y = timeit.Timer('random()','from random import random') > >>> y.timeit(4600000) > 1.0004307810070827 > > Dictionary lookups do take HUGE amounts of time. Interesting. > > Anyway... I've got it down to > Your numbers with a little more precision gave me > 3.4e5987 yrs. > > and mine > > 3.0e5987 yrs. > > That's a hell of a lot of years! Remember that everyone! If you want your > code to run forever and to eternity, copy variables to the local namespace > first; you get a lot more accomplished (well... whatever) ;-) > > Anyway, the frivolity aside, I can get it to repeat every ten seconds. ;-) > Set the computer clock. (okay, maybe i'm just in a silly mood. But > seriously, > that's why the docs say that it is NOT meant for cryptography - not that > that matters > to the OP, snicker; What have I been drinking????) > > > Well, I was trying to emphasize that it was, for pretty much all intents > > and purposes, infinite. > > Nope-nope-nope you're wrong :-)~ The way I understood the 'period' of the random function was that after x calls to the function, you would start getting the same pattern of results as you did to begin with, in _the same running process_ of a program. This is a separate situation from having the clock be exactly the same and getting the same random values on program start - we already knew that would happen, because the seed hadn't changed. Unless I understand the period wrong, but I don't think so. The daring cracker enters the room, his heart quickening as the door hinge > creaks with the sound of the smallest ever mouse. His dark clothing masks > him from the lit room visible through the window on the adjacent wall. A > woman, working late, sits in a comfortable office chair, her face glowing > from the reflection of her computer screen. A cup of Java (pun intended) > indicates to anyone watching that she is overworked, and under-paid. > > Each step he takes brings him closer to his target. The big boss gave him > a > pay cut so that this new PC could sit on his boss's desk. The cracker's > jealously seems to almost permeate the room. Vengeance shouts out louder > than the compressor of the air conditioner in the north window. The > cracker > intinctively looks up to see if his emotions betrayed his presence. But > the > woman in the other room continues her scrolling through endless lines of > buggy, hard to read, unmaintainable, bloated, and otherwise ridiculously > foolish code that could have been so easily fixed if the same 'big boss' > had > ordered the project in Python. > > Soon, a floppy disk is pulled out of a black jacket pocket. No one has > ever > run the program on the floppy before. Taking the disk, the cracker inserts > it into the drive, starts the machine, swears under his breath when he > reads > "Non-System disk or disk error. Replace and strike any." > > Striking the 'any' key, he quickly shoves the floppy disk back in. He > wants > this over with. Again, he looks to see if he has been detected; still he > is > safe. Opening the folder containing the floppy drive, he groans silently > as > the annoying Windows Firewall flashes an update notice. "See..." he thinks > to himself, "Micro$oft *can* actually restrict viruses from entering their > OS." He fights with the window, impatiently waiting for countless > libraries > to load and free, until the UI responds and he can send it a WM_CLOSE > message. > > Smirking evily, the cracker double-clicks the executable > 'pink_fuzzy_bunny.exe' and resists the urge to laugh maniacally as he > watches the computer clock freeze and not move. Ingenious--his plan--All > it > takes to freeze time is to contantly set it to the same second in history. > Time. Forever frozen. He frowns as he realizes that in so doing, he > provides > the only effective means for keeping those pesky Windows notices out of > his > boss's hair. "No matter" --he thinks, "He will have worse troubles in due > time." Again he suppresses a maniacal laugh. > > . . . > > Monday morning brings a bright and cheerful man into an office, his > office. > The door creaks a little as he opens it, and the air conditioner buzzing > in > the north wall window is refreshing to him after the heat from outside. > The > man waves cheerfully at a woman through the glass in the adjacent wall, > whom > looks up only for an instant to scowl. The man, who recently bought his > new > PC, smiles proudly as he turns it on. His new python program which he > keeps > on the desktop is his early attempt at a cricket game simulation. He > lovingly double-clicks the icon, and runs the program several times. Each > successive time his grin grows smaller and smaller until his face is more > than troubled. Why is his program producing the same output every time? A > scream is heard in the office "NOOOOOOO!!!!!!!!" > The boss runs from the building, never to notice the clock in the > bottom-right hand corner which still shows the caption '10:33 PM'. > > Somewhere, someplace a cracker lies in bed, a silly grin on his face. His > objective, he knows, has been accomplished. nice story. > Because the possibility of my computer even existing after that long is > > effectively zero, I consider the pattern to never repeat :) > > Ahhh... > Your computer ~ sitting on a pedestal in the middle of nowhere in AD > 3.0e5988, the last shrine to the ancient past-- A technological marvel to > the ape like creatures whom are all that remain of the once all powerful > race of human beings. > > Our ape, named Jogg, looks at the bright computer screen, jumps back in > fear > as the ancient Windows Beep function is called and the foreign noise hits > him. What is this? There is a message there. > > ... > ... > File "", line 2, in find > File "", line 2, in find > File "", line 2, in find > RuntimeError: maximum recursion depth exceeded > >>> > > Damn. I guess we will never know. > > (okay... maybe nobody spiked my Mt. Dew, but maybe because it's after 3:00 > am) as a side note - are you going to enter the September Pyweek? You should! It's a lot of fun. -Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070728/e7872428/attachment.htm From kent37 at tds.net Sat Jul 28 12:49:27 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 28 Jul 2007 06:49:27 -0400 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: <46AAF808.8020607@kostyrka.org> References: <46AA1E5D.9050305@brunson.com> <46AAF808.8020607@kostyrka.org> Message-ID: <46AB1F37.70509@tds.net> Andreas Kostyrka wrote: > Believe me, the Python developers are sure listening. Only that > "cleaning up the mess" has associated costs, that are usually not > acceptable. If it comes to "not breaking existing programs" or "cleaning > up the stdlib so it's nicer", "not breaking existing programs" is way > higher priority. FWIW there is talk of some minor cleanup of the library for Python 3000: http://www.python.org/dev/peps/pep-3001/ http://www.python.org/dev/peps/pep-3108/ These are very modest changes - primarily removing obsolete modules and cleaning up the names to match current conventions. Kent From kent37 at tds.net Sat Jul 28 12:57:00 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 28 Jul 2007 06:57:00 -0400 Subject: [Tutor] putting python to use In-Reply-To: <341583.66826.qm@web50908.mail.re2.yahoo.com> References: <341583.66826.qm@web50908.mail.re2.yahoo.com> Message-ID: <46AB20FC.3@tds.net> chris harvey wrote: > Hi, > I am very very new to python language. if this is to > simple im sorry. I have had linux mandrake for 2 weeks > now and i have been learning. > I got my apache server running to find it has no GUI. > I was disapointed till i remembered i was learning > python. > I wondered if a python script could be used to make > /combind the server start and the config file take > info from the script. that make sense? > something like. > > > /usr/sbin/advxrun2.0 # starts server then > open (path) apache.config for input ? > I don't really understand what you want to do. If you want to write a script that runs other programs, look at os.system() http://docs.python.org/lib/os-process.html#l2h-2761 What do you mean by "open (path) apache.config for input" ? Kent From alan.gauld at btinternet.com Sat Jul 28 15:45:17 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Jul 2007 14:45:17 +0100 Subject: [Tutor] Shelve del not reducing file size References: <004201c7d075$0ad4fcb0$51fce004@JSLAPTOP> <46AA502D.40901@kostyrka.org> <46AA63EB.9090002@kostyrka.org> Message-ID: "Andreas Kostyrka" wrote >> a lot to build the Tacoma Narrows bridge... Similarly you don't >> need >> much math to build a GUI friont end to a database, but you need > > I would question even that one can write a good GUI frontend to a > database without the theory behind it. Database design has a number > of > important theoretical foundations .... But the math is in the design of the database. If it already exists the GUI design is usually more a matter of good usability design. There might be a bit of SQL going on but usually a data browser GUI doesn't need anything sophisticated, that should be hidden in an application (with API) or in a set of stored proceduresbin the database itself. > Well, the advanced stuff was there. But the Modula2 introduction to > programming was a joke, most students did not even understand the > concept of local variables and procedure parameters after one > semester. Thats bad. As I say our Pascal course was a fairly dull but complete introduction to elementary programming including file handling and dynamic data structures. Our final program was Conways game of Life which had to be able to be paused and saved to disk, and later restored... Ahhh, the memories! Alan G. From keridee at jayco.net Sat Jul 28 17:33:36 2007 From: keridee at jayco.net (Tiger12506) Date: Sat, 28 Jul 2007 10:33:36 -0500 Subject: [Tutor] os.path.exists(path) returns false when the pathactually exists! References: <955680.13552.qm@web50708.mail.re2.yahoo.com> Message-ID: <006001c7d12c$adc60330$76fce004@JSLAPTOP> > Adam wrote: > >>From the library documentation: > Return True if path refers to an existing path. Returns False for > broken symbolic links. On some platforms, this function may return > False if permission is not granted to execute os.stat() on the > requested file, even if the path physically exists. > > So the better question is, does is this file a broken symbolic link or > can os.stat() be executed on it? > > How do I find if it is a broken symbolic link in Windows 2000 ? > > os.stat(path) returns an OSError saying that there is no such file or > directory Wow. I've never heard of this. What are the file's attributes? What does it say about the file when you right-click Properties? Hmmm... what's going on here? Permission not granted to execute os.stat()? Why wouldn't anyone have permission to do that? A broken symbolic link... That means a hard link that has been cut-off right? (Hard-links are like pointers to files in NTFS) ~ so if the file's been moved, that hard link will point to nothing, being broken, right? Does anyone know about this? I'm curious. JS From keridee at jayco.net Sat Jul 28 17:39:39 2007 From: keridee at jayco.net (Tiger12506) Date: Sat, 28 Jul 2007 10:39:39 -0500 Subject: [Tutor] putting python to use References: <341583.66826.qm@web50908.mail.re2.yahoo.com> <46AB20FC.3@tds.net> Message-ID: <007b01c7d12d$861783d0$76fce004@JSLAPTOP> >> >> /usr/sbin/advxrun2.0 # starts server then >> open (path) apache.config for input ? >> > > I don't really understand what you want to do. If you want to write a > script that runs other programs, look at os.system() > http://docs.python.org/lib/os-process.html#l2h-2761 > > What do you mean by "open (path) apache.config for input" ? > > Kent Well, assuming that he wants to Open apache.config for input, I would guess that he needs to be able to open the file, and be able to parse it's contents. If that's the case, a sample of the contents would be nice~ most config files are alike, but there are a few gotchas out there. JS From keridee at jayco.net Sat Jul 28 17:48:54 2007 From: keridee at jayco.net (Tiger12506) Date: Sat, 28 Jul 2007 10:48:54 -0500 Subject: [Tutor] Sum of Scores References: <009401c7cfdc$3c3b4320$d6fce004@JSLAPTOP> <46A92D94.3090804@gmail.com> <002401c7cfee$9a191690$d6fce004@JSLAPTOP> <46A9606D.5070709@gmail.com> <001401c7d026$02865080$c3fce004@JSLAPTOP> Message-ID: <00c101c7d12e$d14be020$76fce004@JSLAPTOP> >> > Well, I was trying to emphasize that it was, for pretty much all >> > intents >> > and purposes, infinite. >> >> Nope-nope-nope you're wrong :-)~ > > > The way I understood the 'period' of the random function was that after x > calls to the function, you would start getting the same pattern of results > as you did to begin with, in _the same running process_ of a program. > This is a separate situation from having the clock be exactly the same and > getting the same random values on program start - we already knew that > would > happen, because the seed hadn't changed. > Unless I understand the period wrong, but I don't think so. No, you understand it just fine. The story was to illustrate the special case. It has nothing to do with whether or not it's the same running process. Two process started within the same second produce the same 'random' results. So, as the story goes, the big boss's computer time is locked, runs for *nearly* an eternity, and at that point the pattern starts repeating. I was just being nit-picky and silly. I told you it was late :-) > as a side note - are you going to enter the September Pyweek? You should! > It's a lot of fun. > -Luke Hmmm.... what's that? I'll google. JS From brunson at brunson.com Sat Jul 28 17:32:20 2007 From: brunson at brunson.com (Eric Brunson) Date: Sat, 28 Jul 2007 09:32:20 -0600 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: References: <004201c7d075$0ad4fcb0$51fce004@JSLAPTOP> <46AA502D.40901@kostyrka.org> <46AA63EB.9090002@kostyrka.org> Message-ID: <46AB6184.1050609@brunson.com> Alan Gauld wrote: > "Andreas Kostyrka" wrote > > >>> a lot to build the Tacoma Narrows bridge... Similarly you don't >>> need >>> much math to build a GUI friont end to a database, but you need >>> >> I would question even that one can write a good GUI frontend to a >> database without the theory behind it. Database design has a number >> of >> important theoretical foundations .... >> > > But the math is in the design of the database. If it already exists > the > GUI design is usually more a matter of good usability design. There > might be a bit of SQL going on but usually a data browser GUI doesn't > need anything sophisticated, that should be hidden in an application > (with API) or in a set of stored proceduresbin the database itself. > I'm definitely a believer that if you get the data model correct first, the software almost writes itself. I've usually found that when I have trouble accessing the data I want, I didn't design the schema correctly. > >> Well, the advanced stuff was there. But the Modula2 introduction to >> programming was a joke, most students did not even understand the >> concept of local variables and procedure parameters after one >> semester. >> > > Thats bad. As I say our Pascal course was a fairly dull but complete > introduction to elementary programming including file handling and > dynamic data structures. Our final program was Conways game of Life > which had to be able to be paused and saved to disk, and later > restored... > > Ahhh, the memories! > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From thorsten at thorstenkampe.de Sat Jul 28 11:57:49 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 28 Jul 2007 17:57:49 +0800 Subject: [Tutor] os.path.exists(path) returns false when the pathactually exists! References: <955680.13552.qm@web50708.mail.re2.yahoo.com> <006001c7d12c$adc60330$76fce004@JSLAPTOP> Message-ID: * Tiger12506 (Sat, 28 Jul 2007 10:33:36 -0500) > > So the better question is, does is this file a broken symbolic link or > > can os.stat() be executed on it? > > > > How do I find if it is a broken symbolic link in Windows 2000 ? > > > > os.stat(path) returns an OSError saying that there is no such file or > > directory > > Wow. I've never heard of this. What are the file's attributes? What does it > say about the file when you right-click Properties? Hmmm... what's going on > here? Permission not granted to execute os.stat()? Why wouldn't anyone have > permission to do that? > > A broken symbolic link... That means a hard link that has been cut-off > right? No, symbolic links and hard links are totally different. > (Hard-links are like pointers to files in NTFS) ~ so if the file's > been moved, that hard link will point to nothing, being broken, right? Thre are no "broken hard links"... From thorsten at thorstenkampe.de Sat Jul 28 12:01:21 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 28 Jul 2007 18:01:21 +0800 Subject: [Tutor] Shelve del not reducing file size References: <46A9DFC9.1070901@tds.net> Message-ID: * Kent Johnson (Fri, 27 Jul 2007 08:06:33 -0400) > Barton David wrote: > > *sigh* I'm really going off Python. > > In what way is it Python's fault that the dbm database doesn't reclaim > disk space? It's actually how most databases work. Even a simple Outlook pst file (which is a database, too) works this way. I thought everyone knows or heard about this. Thorsten From picioslug at gmail.com Sat Jul 28 19:50:39 2007 From: picioslug at gmail.com (Picio) Date: Sat, 28 Jul 2007 19:50:39 +0200 Subject: [Tutor] build a really simple "json" api from a db Message-ID: <825bef0c0707281050n46aa8817q4ec55541080e3a0c@mail.gmail.com> Hello, I'd like to know the necessary steps to build a json api for two table on my db. The design will be: an ajax app asking for data to my server, that fetches those data from a db then build the answer in json. Ajax n the client will then use json data to do some staff. I'd like to build this API in python. What pieces of software I need? (simplejson?) I've seen this snippet on the djangosnippet site. http://www.djangosnippets.org/snippets/154/ Is It the right way. Daniele -- http://picio.gotdns.com ...Il mio blog su NSLU2 From alan.gauld at btinternet.com Sat Jul 28 20:18:32 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Jul 2007 19:18:32 +0100 Subject: [Tutor] build a really simple "json" api from a db References: <825bef0c0707281050n46aa8817q4ec55541080e3a0c@mail.gmail.com> Message-ID: "Picio" wrote > Hello, I'd like to know the necessary steps to build a json api for > two table on my db. Since you seem to be using Django are you sure that isn't built in? I use Turbo Gears and JSON is a standard feature turned on by an option in a method. Django is quite similar to TG in most respects so I'll be surprised if it can't do JSON directly. > I've seen this snippet on the djangosnippet site. > http://www.djangosnippets.org/snippets/154/ > Is It the right way. If its on the Django web site and you are using Django then probably! :-) It certainly looks like a recommendation to me. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From brunson at brunson.com Sat Jul 28 21:55:34 2007 From: brunson at brunson.com (Eric Brunson) Date: Sat, 28 Jul 2007 13:55:34 -0600 (MDT) Subject: [Tutor] Shelve del not reducing file size In-Reply-To: References: <46A9DFC9.1070901@tds.net> Message-ID: <1477.71.237.11.99.1185652534.squirrel@www.comfortechassist.com> On Sat, July 28, 2007 4:01 am, Thorsten Kampe wrote: > * Kent Johnson (Fri, 27 Jul 2007 08:06:33 -0400) > >> Barton David wrote: >> >>> *sigh* I'm really going off Python. >>> >> >> In what way is it Python's fault that the dbm database doesn't reclaim >> disk space? > > It's actually how most databases work. Even a simple Outlook pst file > (which is a database, too) works this way. I thought everyone knows or > heard about this. I don't even think mysql reclaims disk space unless you intervene. From sarliz73 at yahoo.com Sat Jul 28 22:17:08 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Sat, 28 Jul 2007 13:17:08 -0700 (PDT) Subject: [Tutor] comparing lists, __lt__ and __gt__ Message-ID: <830834.2766.qm@web35113.mail.mud.yahoo.com> First off, Kent, thanks for posting that! I know it's in the Python library but it does help to have a bookmark for things I know I'll need pretty soon. Second... What if there is a '<<' or '>>'? Does that just mean the same thing (maybe a little over emphasized.. ;) I thought I saw this when I was learning boolean expressions, but I don't recall. ----- Original Message ---- From: Kent Johnson kent37 at tds.net Good question! The only doc I can find on this behavior is this: http://docs.python.org/lib/comparisons.html which just says that the comparison operation exists. There doesn't seem to be any documentation on how comparison works with sequences. I think it is pretty safe to count on the current behaviour of < and > for lists. I'll put in a documentation bug on this - the meaning of these operations (and ==) should be explicit in the docs. Kent ____________________________________________________________________________________ Get the free Yahoo! toolbar and rest assured with the added security of spyware protection. http://new.toolbar.yahoo.com/toolbar/features/norton/index.php -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070728/a478c1ac/attachment.html From andreas at kostyrka.org Sat Jul 28 23:48:43 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sat, 28 Jul 2007 23:48:43 +0200 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: <1477.71.237.11.99.1185652534.squirrel@www.comfortechassist.com> References: <46A9DFC9.1070901@tds.net> <1477.71.237.11.99.1185652534.squirrel@www.comfortechassist.com> Message-ID: <46ABB9BB.5080505@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Eric Brunson wrote: > On Sat, July 28, 2007 4:01 am, Thorsten Kampe wrote: >> * Kent Johnson (Fri, 27 Jul 2007 08:06:33 -0400) >> >>> Barton David wrote: >>> >>>> *sigh* I'm really going off Python. >>>> >>> In what way is it Python's fault that the dbm database doesn't reclaim >>> disk space? >> It's actually how most databases work. Even a simple Outlook pst file >> (which is a database, too) works this way. I thought everyone knows or >> heard about this. > > I don't even think mysql reclaims disk space unless you intervene. As this thread got already very philosophical, I'd like to add that the jury is still out if mysql is a RDBMS. I personally interpret it as a datafile access library that tries to pretend to be a database system :) Andreas -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGq7m7HJdudm4KnO0RAr6CAKCTSLxA5blSX19IVfpN1RVywRZvSACghExR iRDi3pk+NBPhIcQdd1QkP70= =eS7Q -----END PGP SIGNATURE----- From alan.gauld at btinternet.com Sun Jul 29 00:03:05 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Jul 2007 23:03:05 +0100 Subject: [Tutor] comparing lists, __lt__ and __gt__ References: <830834.2766.qm@web35113.mail.mud.yahoo.com> Message-ID: "Sara Johnson" wrote > What if there is a '<<' or '>>'? > Does that just mean the same thing (maybe a little over emphasized.. > ;) The double chevron operator is for bit-shifting its not a camparison operation. So no operator override function exists. > I thought I saw this when I was learning boolean expressions, > but I don't recall. Possibly, because its often used to manipulate bitpatterns in conjunction with bitwise boolean comparisons (and/or/xor etc) 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 Sun Jul 29 00:11:56 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Jul 2007 23:11:56 +0100 Subject: [Tutor] Shelve del not reducing file size References: <46A9DFC9.1070901@tds.net> <1477.71.237.11.99.1185652534.squirrel@www.comfortechassist.com> Message-ID: "Eric Brunson" wrote > On Sat, July 28, 2007 4:01 am, Thorsten Kampe wrote: >>> In what way is it Python's fault that the dbm database doesn't >>> reclaim >>> disk space? >> >> It's actually how most databases work. Even a simple Outlook pst >> file >> (which is a database, too) works this way. I thought everyone knows >> or >> heard about this. > > I don't even think mysql reclaims disk space unless you intervene. Its actually more efficient for databases to do this, because when they grow beyond the size of the file they need to reallocate extra disk space which is slow but because they hold onto space from deleted records the space is usually there ready for reuse. Unix does the same thing with RAM too. If you run a process which grabs lots of memory and then frees it again you will see the process memory useage climb, but never drop! This can be a problem if the process grabs a lot of RAM on initialisation but then frees it all up again during normal operation. We used to have a GUI that grabbed around 200MB on startup but actually only used around 8-12 in normal use, but its memory footprint was alway 200M! HTH, Alan G. From sarliz73 at yahoo.com Sun Jul 29 01:32:05 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Sat, 28 Jul 2007 16:32:05 -0700 (PDT) Subject: [Tutor] comparing lists, __lt__ and __gt__ Message-ID: <967982.72462.qm@web35110.mail.mud.yahoo.com> Thanks Alan. That said, any idea what it means in this context? for key in skeys: fracmiss=1.*numberMissing(z[key].values())/nsites #note decimal multiplication, 1.* outstring="%s has %4.1f%% missing" % (key,100*fracmiss) if fracmiss >>0 ----- Original Message ---- From: Alan Gauld To: tutor at python.org Sent: Saturday, July 28, 2007 5:03:05 PM Subject: Re: [Tutor] comparing lists, __lt__ and __gt__ "Sara Johnson" wrote > What if there is a '<<' or '>>'? > Does that just mean the same thing (maybe a little over emphasized.. > ;) The double chevron operator is for bit-shifting its not a camparison operation. So no operator override function exists. > I thought I saw this when I was learning boolean expressions, > but I don't recall. Possibly, because its often used to manipulate bitpatterns in conjunction with bitwise boolean comparisons (and/or/xor etc) 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 ____________________________________________________________________________________ Be a better Heartthrob. Get better relationship answers from someone who knows. Yahoo! Answers - Check it out. http://answers.yahoo.com/dir/?link=list&sid=396545433 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070728/df153b1e/attachment.htm From alan.gauld at btinternet.com Sun Jul 29 02:11:36 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 29 Jul 2007 01:11:36 +0100 Subject: [Tutor] comparing lists, __lt__ and __gt__ References: <967982.72462.qm@web35110.mail.mud.yahoo.com> Message-ID: "Sara Johnson" wrote > Thanks Alan. That said, any idea what it means in this context? > > for key in skeys: > fracmiss=1.*numberMissing(z[key].values())/nsites #note > decimal multiplication, 1.* > outstring="%s has %4.1f%% missing" % (key,100*fracmiss) > if fracmiss >>0 None whatsoever, it looks like an error to me! That having been saisd their is another use for >> which is to append output to a file, as in: print 'hello world' >> myfile sends the string to myfile instead of to stdout. (Although I couldn't get this to work when I tried it!) Alan G. ----- Original Message ---- From: Alan Gauld To: tutor at python.org Sent: Saturday, July 28, 2007 5:03:05 PM Subject: Re: [Tutor] comparing lists, __lt__ and __gt__ "Sara Johnson" wrote > What if there is a '<<' or '>>'? > Does that just mean the same thing (maybe a little over emphasized.. > ;) The double chevron operator is for bit-shifting its not a camparison operation. So no operator override function exists. > I thought I saw this when I was learning boolean expressions, > but I don't recall. Possibly, because its often used to manipulate bitpatterns in conjunction with bitwise boolean comparisons (and/or/xor etc) 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 ____________________________________________________________________________________ Be a better Heartthrob. Get better relationship answers from someone who knows. Yahoo! Answers - Check it out. http://answers.yahoo.com/dir/?link=list&sid=396545433 -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rabidpoobear at gmail.com Sun Jul 29 02:13:38 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 28 Jul 2007 19:13:38 -0500 Subject: [Tutor] Sum of Scores In-Reply-To: <00c101c7d12e$d14be020$76fce004@JSLAPTOP> References: <009401c7cfdc$3c3b4320$d6fce004@JSLAPTOP> <46A92D94.3090804@gmail.com> <002401c7cfee$9a191690$d6fce004@JSLAPTOP> <46A9606D.5070709@gmail.com> <001401c7d026$02865080$c3fce004@JSLAPTOP> <00c101c7d12e$d14be020$76fce004@JSLAPTOP> Message-ID: <46ABDBB2.70702@gmail.com> Tiger12506 wrote: >>>> Well, I was trying to emphasize that it was, for pretty much all >>>> intents >>>> and purposes, infinite. >>>> >>> Nope-nope-nope you're wrong :-)~ >>> >> The way I understood the 'period' of the random function was that after x >> calls to the function, you would start getting the same pattern of results >> as you did to begin with, in _the same running process_ of a program. >> This is a separate situation from having the clock be exactly the same and >> getting the same random values on program start - we already knew that >> would >> happen, because the seed hadn't changed. >> Unless I understand the period wrong, but I don't think so. >> > > No, you understand it just fine. The story was to illustrate the special > case. It has nothing to do with whether or not it's the same running > process. Two process started within the same second produce the same > 'random' results. So, as the story goes, the big boss's computer time is > locked, runs for *nearly* an eternity, and at that point the pattern starts > repeating. > So normally, after the period is up, it would choose a new seed? or does it repeat after the period whether or not the time has changed? > I was just being nit-picky and silly. I told you it was late :-) > > > as a side note - are you going to enter the September Pyweek? You > should! > >> It's a lot of fun. >> -Luke >> > > Hmmm.... what's that? I'll google. > It's a whole lot of fun. And everyone's really nice. SO even if you don't have time to finish a game, it's enjoyable and a learning experience just to hang out with everyone on IRC. Also, you should have time to learn pygame for the competition if you don't know how to use it already. Of course you could use pyglet or pyOpenGL or something instead, if you wanted. > JS > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From rabidpoobear at gmail.com Sun Jul 29 02:54:23 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 28 Jul 2007 19:54:23 -0500 Subject: [Tutor] Livewires questions In-Reply-To: References: <46A7F3C4.5060002@umn.edu> <46A82652.9070207@gmail.com> <46AA4D7F.7070901@umn.edu> Message-ID: <46ABE53F.6070200@gmail.com> Luke Paireepinart wrote: > > > I ran the code that you had included, thank you for this. It did > produce the player and the robot on the grid, but the keyboard > commands > did not work. I wasn't entire sure why, but I thought I would let > you know. > > > Sure, sure. I'm glad it at least ran. I don't have livewires > installed so I wasn't able to test any of the code I wrote. > > Thanks again for your help. If you have suggestions on the 't' key, > please share them. This seems to be the one issue preventing me from > going forward. > > > I need to go to sleep right now, but tomorrow afternoon I should have > some free time and if so, I'll install livewires and give you more > suggestions. > > Tonu > > Actually, I may not have time for this after all. I'm in the final throes of a Differential Equations class (it's really accelerated to fit all in one month) and even on weekends I have to study for it. Luckily it's done in 9 class days (we do class 12-1:40 M-F, so that puts the Final on Thursday) so I will gladly offer any help you need after that time. But until then, I'm not sure when I'll be able to do anything. P.S. I forgot to hit reply-all on the previous e-mail, which is why I left it intact. From brunson at brunson.com Sun Jul 29 03:19:49 2007 From: brunson at brunson.com (Eric Brunson) Date: Sat, 28 Jul 2007 19:19:49 -0600 Subject: [Tutor] Shelve del not reducing file size In-Reply-To: <46ABB9BB.5080505@kostyrka.org> References: <46A9DFC9.1070901@tds.net> <1477.71.237.11.99.1185652534.squirrel@www.comfortechassist.com> <46ABB9BB.5080505@kostyrka.org> Message-ID: <46ABEB35.4010600@brunson.com> Andreas Kostyrka wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > > > Eric Brunson wrote: > >> On Sat, July 28, 2007 4:01 am, Thorsten Kampe wrote: >> >>> * Kent Johnson (Fri, 27 Jul 2007 08:06:33 -0400) >>> >>> >>>> Barton David wrote: >>>> >>>> >>>>> *sigh* I'm really going off Python. >>>>> >>>>> >>>> In what way is it Python's fault that the dbm database doesn't reclaim >>>> disk space? >>>> >>> It's actually how most databases work. Even a simple Outlook pst file >>> (which is a database, too) works this way. I thought everyone knows or >>> heard about this. >>> >> I don't even think mysql reclaims disk space unless you intervene. >> > > As this thread got already very philosophical, I'd like to add that the > jury is still out if mysql is a RDBMS. I personally interpret it as a > datafile access library that tries to pretend to be a database system :) > I had 13 years of Oracle experience under my belt when I tried MySQL version 3.x. Then it was a toy database and barely worth my attention. We're now using 5.0 and it is definitely no longer simply pretending to be a database. At work we have a system that is storing over 1.5 billion records and makes our Oracle installations pale in comparison. Another system is running distributed in a cluster running multiple masters in ring replication. Oracle was either impressed or threatened enough to buy the rights to InnoDB, that has to say something about the state of MySQL. With the addition of stored procedures, triggers and views in 5.0, it has definitely met all but my most esoteric needs. I'm not saying MySQL is perfect, I have several bugs and feature requests logged with MySQL that I'm still waiting to be addressed, but if you haven't used it lately, you're missing out. > Andreas > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.2 (GNU/Linux) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iD8DBQFGq7m7HJdudm4KnO0RAr6CAKCTSLxA5blSX19IVfpN1RVywRZvSACghExR > iRDi3pk+NBPhIcQdd1QkP70= > =eS7Q > -----END PGP SIGNATURE----- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bgailer at alum.rpi.edu Sun Jul 29 03:22:13 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 28 Jul 2007 18:22:13 -0700 Subject: [Tutor] ideas for college app. In-Reply-To: <46AB1442.8040606@gmail.com> References: <46AB1442.8040606@gmail.com> Message-ID: <46ABEBC5.8000000@alum.rpi.edu> Shriphani Palakodety wrote: > Hello all, > I am looking for a few ideas for my college app. Can someone give me a > few ideas i could work on? I would like to use these to learn more of > python and to become a true expert at it. > I don't understand what you want. Probably others also don't, as there has been no response. Could you be a lot more explicit? -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From rdm at rcblue.com Sun Jul 29 04:54:29 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 28 Jul 2007 19:54:29 -0700 Subject: [Tutor] ideas for college app. In-Reply-To: <46AB1442.8040606@gmail.com> References: <46AB1442.8040606@gmail.com> Message-ID: <20070729025444.621591E4008@bag.python.org> At 03:02 AM 7/28/2007, Shriphani Palakodety wrote: >Hello all, >I am looking for a few ideas for my college app. Can someone give me a >few ideas i could work on? I would like to use these to learn more of >python and to become a true expert at it. Are there any set requirements for your "college app"? What does "college app" mean? Dick Moores From sarliz73 at yahoo.com Sun Jul 29 04:57:30 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Sat, 28 Jul 2007 19:57:30 -0700 (PDT) Subject: [Tutor] attribute error Message-ID: <659191.19978.qm@web35113.mail.mud.yahoo.com> I thought 'sort()' was a function you could use as long as the dict or key had some value. When is this not right? ____________________________________________________________________________________ Park yourself in front of a world of choices in alternative vehicles. Visit the Yahoo! Auto Green Center. http://autos.yahoo.com/green_center/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070728/076bbfb5/attachment.htm From bgailer at alum.rpi.edu Sun Jul 29 05:14:58 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 28 Jul 2007 20:14:58 -0700 Subject: [Tutor] attribute error In-Reply-To: <659191.19978.qm@web35113.mail.mud.yahoo.com> References: <659191.19978.qm@web35113.mail.mud.yahoo.com> Message-ID: <46AC0632.4080401@alum.rpi.edu> Sara Johnson wrote: > I thought 'sort()' was a function you could use as long as the dict or > key had some value. When is this not right? Please give us some context for the question. Code fragment, traceback. sort is a method of mutable sequence types (lists, ...) myList = [1, 3, 2] myList.sort() # returns None print myList [1, 2, 3] -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From sarliz73 at yahoo.com Sun Jul 29 06:19:15 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Sat, 28 Jul 2007 21:19:15 -0700 (PDT) Subject: [Tutor] attribute error Message-ID: <624756.77213.qm@web35105.mail.mud.yahoo.com> I scrapped that other attempt. I keep hitting brick walls. However, is there an indentation error here? I may just be too frustrated to see it. for key in skeys: fracmiss=1.*numberMissing(z[key].values())/nsites #note decimal multiplication, 1.* outstring="%s has %4.1f%% missing" % (key,100*fracmiss) if fracmiss>0.: print outstring ----- Original Message ---- From: Bob Gailer To: Sara Johnson Cc: Python Sent: Saturday, July 28, 2007 10:14:58 PM Subject: Re: [Tutor] attribute error Sara Johnson wrote: > I thought 'sort()' was a function you could use as long as the dict or > key had some value. When is this not right? Please give us some context for the question. Code fragment, traceback. sort is a method of mutable sequence types (lists, ...) myList = [1, 3, 2] myList.sort() # returns None print myList [1, 2, 3] -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ____________________________________________________________________________________ Choose the right car based on your needs. Check out Yahoo! Autos new Car Finder tool. http://autos.yahoo.com/carfinder/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070728/3f77929a/attachment.htm From sarliz73 at yahoo.com Sun Jul 29 06:48:46 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Sat, 28 Jul 2007 21:48:46 -0700 (PDT) Subject: [Tutor] attribute error --Disregard Message-ID: <889581.70503.qm@web35108.mail.mud.yahoo.com> Disregard this post. Sorry for the added message in everyone's inbox. ----- Original Message ---- From: Sara Johnson To: Python Sent: Saturday, July 28, 2007 11:19:15 PM Subject: Re: [Tutor] attribute error I scrapped that other attempt. I keep hitting brick walls. However, is there an indentation error here? I may just be too frustrated to see it. for key in skeys: fracmiss=1.*numberMissing(z[key].values())/nsites #note decimal multiplication, 1.* outstring="%s has %4.1f%% missing" % (key,100*fracmiss) if fracmiss>0.: print outstring ----- Original Message ---- From: Bob Gailer To: Sara Johnson Cc: Python Sent: Saturday, July 28, 2007 10:14:58 PM Subject: Re: [Tutor] attribute error Sara Johnson wrote: > I thought 'sort()' was a function you could use as long as the dict or > key had some value. When is this not right? Please give us some context for the question. Code fragment, traceback. sort is a method of mutable sequence types (lists, ...) myList = [1, 3, 2] myList.sort() # returns None print myList [1, 2, 3] -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor Shape Yahoo! in your own image. Join our Network Research Panel today! ____________________________________________________________________________________ Pinpoint customers who are looking for what you sell. http://searchmarketing.yahoo.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070728/449cc743/attachment.html From alan.gauld at btinternet.com Sun Jul 29 09:23:55 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 29 Jul 2007 08:23:55 +0100 Subject: [Tutor] attribute error References: <624756.77213.qm@web35105.mail.mud.yahoo.com> Message-ID: "Sara Johnson" wrote > However, is there an indentation error here? Not that I can see. Is there an error? If so can you send the traceback? Its very hard to answer questions without any context. > I may just be too frustrated to see it. > > for key in skeys: > fracmiss=1.*numberMissing(z[key].values())/nsites #note > decimal multiplication, 1.* This is a mess. Why have that long comment when all that's needed is to add the zero?! (and some spaces to make it legible...) fracmiss = 1.0 * numberMissing( z[key].values() ) / nsites outstring = "%s has %4.1f%% missing" % (key, 100 * fracmiss) if fracmiss > 0.0: print outstring It looks OK apart from the poor style but I don't see anything that is an error. What are you seeing? On the style front, if you want to force a result to a float it's more conventional to use the float() conversion function: fracmiss = float( numberMissing( z[key].values() ) / nsites ) And comparing to 0.0 doesn't really add anything except two characters, it could just as well be plain old 0. if fracmiss > 0: HTH, Alan G. From tpc247 at gmail.com Sun Jul 29 10:56:19 2007 From: tpc247 at gmail.com (tpc247 at gmail.com) Date: Sun, 29 Jul 2007 01:56:19 -0700 Subject: [Tutor] don't repeat yourself; question about code optimization CORRECTION In-Reply-To: <46A4DB07.6010300@alum.rpi.edu> References: <46A1870D.2030000@alum.rpi.edu> <46A4DB07.6010300@alum.rpi.edu> Message-ID: On 7/23/07, Bob Gailer wrote: > > A correction to the code at the end. The test of self.total_num_of_items > should precede the pop(0) Bob, I spent today studying what you've been telling me and I put the finishing touches to make your code pass my battery of tests. It still is repetitive, i.e., table.append(tuple(row)), but I've found guidance in what Alan had to say about code readability and easy maintenance, and am no longer going to press the matter: class Table_Creator(object): def __init__(self, total_num_of_items, max_num_of_items_per_row): self.given_items = range(total_num_of_items) self.max_num_of_items_per_row = max_num_of_items_per_row def create_grid(self): table = [] while True: row = [] while len(row) < self.max_num_of_items_per_row: if not self.given_items: if row: table.append(tuple(row)) return table row.append(self.given_items.pop(0)) table.append(tuple(row)) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070729/bc5de4a9/attachment-0001.htm From tpc247 at gmail.com Sun Jul 29 11:29:22 2007 From: tpc247 at gmail.com (tpc247 at gmail.com) Date: Sun, 29 Jul 2007 02:29:22 -0700 Subject: [Tutor] don't repeat yourself; question about code optimization In-Reply-To: References: Message-ID: On 7/23/07, Alan Gauld wrote: > > The prime directive of coding is make it readable! > The DRY principle is just that a principle. If repeating makes for > more maintainable or readable code then repeat yourself. > > Remember 80% of the cost of software is in maintenance not initial > development. DRY is one way to improve maintainablility > PS The most serious problem with your code from my perpspective > is that your variable names are way too long. That affects maintenance > and readability more that the repetition (and in the case of email it > causes line wrapping that makes it even worse!) > > Finally the class is not a good class in an OOP sense since it is > nearly a verb. > It is better done as a simple function in my view, just pass in the > parameters to > the create method. Like this: > > def create_table(num_items, row_size): > start = 0 > table = [] > num_rows = num_items/row_size > for n in range(num_rows): > row = [num for num in range(start,start+row_size)] > table.append(tuple(row)) > start += row_size > return table > > Or better still build a table class that knows how to create > itself, but also knows how to maniplulate itself too - doing whatever > it is you intend doing to the table you just created! This reflects > another > programming "rule" - the law of demeter" - one of the fundamentals of > OOP. Alan, I spent today going over what you took the time to patiently illustrate to me, and I believe I learned the following things: - code readability and ease of maintenance are the primary goals of a computer programmer - classes that are very nearly verbs should be converted to functions, unless you can write a class that knows how to create and manipulate itself, following the law of demeter About the last bit of code, where you propose to create the table using list comprehension, I did want to capture partial rows, so I put the finishing touches to your work so it could. When I subjected the code to a battery of tests, it failed in the following way: def create_table(num_items, row_size): start = 0 table = [] num_rows = (num_items/row_size) + (num_items%row_size) for n in range(num_rows): row = [num for num in range(num_items)[start:start+row_size]] table.append(tuple(row)) start += row_size return table def test_harness(): assert create_table(3, 1) == [(0,), (1,), (2,)] assert create_table(4, 1) == [(0,), (1,), (2,), (3,)] assert create_table(1, 2) == [(0,)] assert create_table(2, 2) == [(0, 1)] assert create_table(4, 2) == [(0, 1), (2, 3)] assert create_table(5, 2) == [(0, 1), (2, 3), (4, )] assert create_table(5, 3) == [(0, 1, 2), (3, 4)] assert create_table(7, 4) == [(0, 1, 2, 3), (4, 5, 6)] assert create_table(5, 3) == [(0, 1, 2), (3, 4)] AssertionError I know that my method of calculating the number of rows is faulty, but I'm not sure how to correct it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070729/ff5a2e42/attachment.html From brunson at brunson.com Sun Jul 29 17:50:35 2007 From: brunson at brunson.com (Eric Brunson) Date: Sun, 29 Jul 2007 09:50:35 -0600 Subject: [Tutor] don't repeat yourself; question about code optimization CORRECTION In-Reply-To: References: <46A1870D.2030000@alum.rpi.edu> <46A4DB07.6010300@alum.rpi.edu> Message-ID: <46ACB74B.9070408@brunson.com> tpc247 at gmail.com wrote: > > > On 7/23/07, *Bob Gailer* > wrote: > > A correction to the code at the end. The test of > self.total_num_of_items > should precede the pop(0) > > > > Bob, I spent today studying what you've been telling me and I put the > finishing touches to make your code pass my battery of tests. It > still is repetitive, i.e., table.append(tuple(row)), I see you're also repeating the use of "=" quite a bit, as well as multiple uses of the word "if". Maybe you could work on that. Sorry for the sarcasm, but there's a big different between repeating an assignment and a type coersion versus a multi line block of code that could be converted to a function. :-) > but I've found guidance in what Alan had to say about code readability > and easy maintenance, and am no longer going to press the matter: > > class Table_Creator(object): > def __init__(self, total_num_of_items, max_num_of_items_per_row): > self.given_items = range(total_num_of_items) > self.max_num_of_items_per_row = max_num_of_items_per_row > > def create_grid(self): > table = [] > while True: > row = [] > while len(row) < self.max_num_of_items_per_row: > if not self.given_items: > if row: > table.append(tuple(row)) > return table > row.append(self.given_items.pop(0)) > table.append(tuple(row)) > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Sun Jul 29 18:01:34 2007 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 29 Jul 2007 16:01:34 +0000 (GMT) Subject: [Tutor] don't repeat yourself; question about code optimization Message-ID: <684731.65086.qm@web86106.mail.ird.yahoo.com> > assert create_table(5, 3) == [(0, 1, 2), (3, 4)] > AssertionError > > I know that my method of calculating the number of rows is faulty, > but I'm not sure how to correct it. num_rows = (num_items/row_size) + (num_items%row_size) This uses integer division then adds the remainder, so for your example of 5,3 we get 5/3 = 1 5%3 = 2 So rows = 3 - wrong! All you want to do is add one if the modulus is not zero, so num_rows = (num_items/row_size) if num_items % row_size > 0: num_rows += 1 Should do what you want. HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070729/f722cead/attachment.htm From sarliz73 at yahoo.com Sun Jul 29 18:45:41 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Sun, 29 Jul 2007 09:45:41 -0700 (PDT) Subject: [Tutor] attribute error Message-ID: <131408.20376.qm@web35115.mail.mud.yahoo.com> ----- Original Message ---- From: Alan Gauld alan.gauld at btinternet.com >> for key in skeys: >> fracmiss=1.*numberMissing(z[key].values())/nsites #note decimal multiplication, 1.* >This is a mess. Why have that long comment when all that's needed >is to add the zero?! (and some spaces to make it legible...) I wish I could take credit for that. At least it would feel like progress. I didn't write it. All I'm trying to do now is sort it alphabetically, and then attempt to append it with another list and sort that. While I didn't write that, I always thought with floats you needed a 0.0. I do have some percentages that are less than 1% but more than 0.0. >fracmiss = 1.0 * numberMissing( z[key].values() ) / nsites >outstring = "%s has %4.1f%% missing" % (key, 100 * fracmiss) >if fracmiss > 0.0: print outstring >It looks OK apart from the poor style but I don't see anything that is >an error. What are you seeing? I pasted a part of the script in some other part of the program unknowingly. Still getting used to Vi/Vim. Thanks Alan! Sara ____________________________________________________________________________________ Sick sense of humor? Visit Yahoo! TV's Comedy with an Edge to see what's on, when. http://tv.yahoo.com/collections/222 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070729/242f2a7c/attachment.html From bgailer at alum.rpi.edu Sun Jul 29 18:47:00 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 29 Jul 2007 09:47:00 -0700 Subject: [Tutor] don't repeat yourself; question about code optimization CORRECTION In-Reply-To: References: <46A1870D.2030000@alum.rpi.edu> <46A4DB07.6010300@alum.rpi.edu> Message-ID: <46ACC484.7060100@alum.rpi.edu> tpc247 at gmail.com wrote: > > > On 7/23/07, *Bob Gailer* > wrote: > > A correction to the code at the end. The test of > self.total_num_of_items > should precede the pop(0) > > > > Bob, I spent today studying what you've been telling me and I put the > finishing touches to make your code pass my battery of tests. It > still is repetitive, i.e., table.append(tuple(row)), but I've found > guidance in what Alan had to say about code readability and easy > maintenance, and am no longer going to press the matter: > > class Table_Creator(object): > def __init__(self, total_num_of_items, max_num_of_items_per_row): > self.given_items = range(total_num_of_items) > self.max_num_of_items_per_row = max_num_of_items_per_row > > def create_grid(self): > table = [] > while True: > row = [] > while len(row) < self.max_num_of_items_per_row: > if not self.given_items: > if row: > table.append(tuple(row)) > return table > row.append(self.given_items.pop(0)) > table.append(tuple(row)) A bit more juggling leads to more simplification: def create_grid(self): table = [] while self.given_items: row = [] while len(row) < self.max_num_of_items_per_row and self.given_items: row.append(self.given_items.pop(0)) table.append(tuple(row)) return table Testing self.given_items twice is unavoidable. -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From tmikk at umn.edu Sun Jul 29 21:31:22 2007 From: tmikk at umn.edu (Tonu Mikk) Date: Sun, 29 Jul 2007 14:31:22 -0500 Subject: [Tutor] Livewires questions In-Reply-To: <46ABE53F.6070200@gmail.com> References: <46A7F3C4.5060002@umn.edu> <46A82652.9070207@gmail.com> <46AA4D7F.7070901@umn.edu> <46ABE53F.6070200@gmail.com> Message-ID: <46ACEB0A.2040707@umn.edu> Luke Paireepinart wrote: >> >> >> Sure, sure. I'm glad it at least ran. I don't have livewires >> installed so I wasn't able to test any of the code I wrote. >> >> Thanks again for your help. If you have suggestions on the 't' key, >> please share them. This seems to be the one issue preventing me >> from >> going forward. >> >> Tonu >> >> > Actually, I may not have time for this after all. I'm in the final > throes of a Differential Equations class (it's really accelerated to > fit all in one month) and even on weekends I have to study for it. > Luckily it's done in 9 class days (we do class 12-1:40 M-F, so that > puts the Final on Thursday) so I will gladly offer any help you need > after that time. > But until then, I'm not sure when I'll be able to do anything. > P.S. I forgot to hit reply-all on the previous e-mail, which is why I > left it intact. Luke, Good luck with the class. It seems a challenging one judging by the name :-). I was able to get the player to be moved into a different location on the grid when the "t" key is pressed. The answer was, as it often is, in reading the manual :-), in this case the Graphics worksheet that talks about removing objects which is a bit of the Livewires magic. Here is my code that removed the player from the board and placed it in a new location when the 't' keys is pressed: if 't' in keys: remove_from_screen (player_shape) place_player() break I will now venture forth with the rest of the instructions in the exercise. Thank you all for helping me over the hump! Tonu From picioslug at gmail.com Sun Jul 29 21:36:56 2007 From: picioslug at gmail.com (Picio) Date: Sun, 29 Jul 2007 21:36:56 +0200 Subject: [Tutor] build a really simple "json" api from a db In-Reply-To: References: <825bef0c0707281050n46aa8817q4ec55541080e3a0c@mail.gmail.com> Message-ID: <825bef0c0707291236w27046440pe4d9a0ca536163c5@mail.gmail.com> The beginning idea was to build a json API myself. Since I need only to generate json from a db, maybe Django is too much. I'm a Django beginner. I don't know Turbogears. I've not found anything like: "how to build a json api". Maybe MySqldb+simplejson is the enough? Or Is It more simple to learn how to use Django to create a json api? 2007/7/28, Alan Gauld : > > "Picio" wrote > > > Hello, I'd like to know the necessary steps to build a json api for > > two table on my db. > > Since you seem to be using Django are you sure that isn't built in? > > I use Turbo Gears and JSON is a standard feature turned on by > an option in a method. Django is quite similar to TG in most respects > so I'll be surprised if it can't do JSON directly. > > > I've seen this snippet on the djangosnippet site. > > http://www.djangosnippets.org/snippets/154/ > > Is It the right way. > > If its on the Django web site and you are using Django then > probably! :-) > > It certainly looks like a recommendation to me. > > -- > 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 > -- http://picio.gotdns.com ...Il mio blog su NSLU2 From sarliz73 at yahoo.com Sun Jul 29 22:46:09 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Sun, 29 Jul 2007 13:46:09 -0700 (PDT) Subject: [Tutor] attribute error Message-ID: <368845.75914.qm@web35105.mail.mud.yahoo.com> Is this the correct traceback? Output okay except it will not sort alphabetically. **************** Traceback (most recent call last): File "./mymods.py", line 83, in ? outfile2.sort() AttributeError: 'file' object has no attribute 'sort' ********************* Here's the code. I did not write most of this, I'm only modifying it. In fact, I'm only responsible for the last two lines. ************ #reverse the dictionary of dictionaries, making new dictonary z: z={} #initialize empty dictionary skeys=h[keys[0]].keys() #get the "sub-keys" for i in skeys: #use sub-keys as new main-keys z[i]={} for j in keys: #use main-keys as new sub-keys z[i][j]=h[j][i] #use the new dictionary to find number of missing values: print "\n fraction of sites with missing measurements:" nsites=len(h.keys()) outfile2=open('missmeas.dat','w') for key in skeys: fracmiss=1.*numberMissing(z[key].values())/nsites outstring="%s has %4.1f%% missing" % (key,100*fracmiss) if fracmiss>0.: print outstring ----- Original Message ---- From: Alan Gauld To: tutor at python.org Sent: Sunday, July 29, 2007 2:23:55 AM Subject: Re: [Tutor] attribute error "Sara Johnson" wrote > However, is there an indentation error here? Not that I can see. Is there an error? If so can you send the traceback? Its very hard to answer questions without any context. > I may just be too frustrated to see it. > > for key in skeys: > fracmiss=1.*numberMissing(z[key].values())/nsites #note > decimal multiplication, 1.* This is a mess. Why have that long comment when all that's needed is to add the zero?! (and some spaces to make it legible...) fracmiss = 1.0 * numberMissing( z[key].values() ) / nsites outstring = "%s has %4.1f%% missing" % (key, 100 * fracmiss) if fracmiss > 0.0: print outstring It looks OK apart from the poor style but I don't see anything that is an error. What are you seeing? On the style front, if you want to force a result to a float it's more conventional to use the float() conversion function: fracmiss = float( numberMissing( z[key].values() ) / nsites ) And comparing to 0.0 doesn't really add anything except two characters, it could just as well be plain old 0. if fracmiss > 0: HTH, Alan G. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ____________________________________________________________________________________ Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070729/2241d311/attachment.html From sarliz73 at yahoo.com Sun Jul 29 22:49:58 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Sun, 29 Jul 2007 13:49:58 -0700 (PDT) Subject: [Tutor] attribute error - quick addition Message-ID: <619518.68253.qm@web35109.mail.mud.yahoo.com> Sorry...I forgot a few more lines at the end of the code. Starts with "outfile2write..." I also added outfile2.sort() Is this the correct traceback? Output okay except it will not sort alphabetically. **************** Traceback (most recent call last): File "./mymods.py", line 83, in ? outfile2.sort() AttributeError: 'file' object has no attribute 'sort' ********************* Here's the code. I did not write most of this, I'm only modifying it. In fact, I'm only responsible for the last two lines. ************ #reverse the dictionary of dictionaries, making new dictonary z: z={} #initialize empty dictionary skeys=h[keys[0]].keys() #get the "sub-keys" for i in skeys: #use sub-keys as new main-keys z[i]={} for j in keys: #use main-keys as new sub-keys z[i][j]=h[j][i] #use the new dictionary to find number of missing values: print "\n fraction of sites with missing measurements:" nsites=len(h.keys()) outfile2=open('missmeas.dat','w') for key in skeys: fracmiss=1.*numberMissing(z[key].values())/nsites outstring="%s has %4.1f%% missing" % (key,100*fracmiss) if fracmiss>0.: print outstring outfile2.write(outstring+'\n') #notice explicit newline \n outfile2.sort() outfile2.close() ----- Original Message ---- From: Alan Gauld To: tutor at python.org Sent: Sunday, July 29, 2007 2:23:55 AM Subject: Re: [Tutor] attribute error "Sara Johnson" wrote > However, is there an indentation error here? Not that I can see. Is there an error? If so can you send the traceback? Its very hard to answer questions without any context. > I may just be too frustrated to see it. > > for key in skeys: > fracmiss=1.*numberMissing(z[key].values())/nsites #note > decimal multiplication, 1.* This is a mess. Why have that long comment when all that's needed is to add the zero?! (and some spaces to make it legible...) fracmiss = 1.0 * numberMissing( z[key].values() ) / nsites outstring = "%s has %4.1f%% missing" % (key, 100 * fracmiss) if fracmiss > 0.0: print outstring It looks OK apart from the poor style but I don't see anything that is an error. What are you seeing? On the style front, if you want to force a result to a float it's more conventional to use the float() conversion function: fracmiss = float( numberMissing( z[key].values() ) / nsites ) And comparing to 0.0 doesn't really add anything except two characters, it could just as well be plain old 0. if fracmiss > 0: HTH, Alan G. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor Pinpoint customers who are looking for what you sell. ____________________________________________________________________________________ Yahoo! oneSearch: Finally, mobile search that gives answers, not web links. http://mobile.yahoo.com/mobileweb/onesearch?refer=1ONXIC -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070729/b4625fa3/attachment.htm From bhaaluu at gmail.com Sun Jul 29 23:36:54 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Sun, 29 Jul 2007 17:36:54 -0400 Subject: [Tutor] data structures and algorithms with object-oriented design patterns in python Message-ID: Greetings, While searching for information about Python Data Structures I came across this site and thought it might be interesting for others on the list as well: http://www.brpreiss.com/books/opus7/ Data Structures and Algorithms with Object-Oriented Design Patterns in Python. Bruno Preiss. Copyright (c) 2003 by Bruno R. Preiss. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the author. It can be read online. Happy Programming! -- bhaaluu at gmail dot com From slow67 at gmail.com Sun Jul 29 23:37:32 2007 From: slow67 at gmail.com (bill nieuwendorp) Date: Sun, 29 Jul 2007 14:37:32 -0700 Subject: [Tutor] what is the * operator called in this context? Message-ID: <60fbe7f30707291437i20e1ddb1ncdeb016d0d4e63d5@mail.gmail.com> when ever I need to use the struct module I always store my values in a list or a dict, then I do something like the code below import struct list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] length =len(list) struct.pack(">%di"%(length), *[i for i in list]) now I can not remember where I came up with that, I thought I read it in the python docs somewhere but I can not find any mention of it now. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070729/b5822b76/attachment.html From slow67 at gmail.com Mon Jul 30 00:25:59 2007 From: slow67 at gmail.com (bill nieuwendorp) Date: Sun, 29 Jul 2007 15:25:59 -0700 Subject: [Tutor] what is the * operator called in this context? In-Reply-To: <60fbe7f30707291437i20e1ddb1ncdeb016d0d4e63d5@mail.gmail.com> References: <60fbe7f30707291437i20e1ddb1ncdeb016d0d4e63d5@mail.gmail.com> Message-ID: <60fbe7f30707291525q570f8a7t4bd3909a6b49a9ee@mail.gmail.com> of course I take one more look through the docs after I send the origonal message and stumble upon it right away. http://www.python.org/doc/2.5/tut/node6.html#SECTION006740000000000000000 On 7/29/07, bill nieuwendorp wrote: > > when ever I need to use the struct module > I always store my values in a list or a dict, then > I do something like the code below > > import struct > list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > length =len(list) > struct.pack(">%di"%(length), *[i for i in list]) > > now I can not remember where I came up with that, > I thought I read it in the python docs somewhere > but I can not find any mention of it now. > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070729/859225ca/attachment.htm From kent37 at tds.net Mon Jul 30 00:49:16 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 29 Jul 2007 18:49:16 -0400 Subject: [Tutor] what is the * operator called in this context? In-Reply-To: <60fbe7f30707291437i20e1ddb1ncdeb016d0d4e63d5@mail.gmail.com> References: <60fbe7f30707291437i20e1ddb1ncdeb016d0d4e63d5@mail.gmail.com> Message-ID: <46AD196C.3020008@tds.net> bill nieuwendorp wrote: > when ever I need to use the struct module > I always store my values in a list or a dict, then > I do something like the code below > > import struct > list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > length =len(list) > struct.pack(">%di"%(length), *[i for i in list]) You don't need the list comprehension here, just write struct.pack(">%di"%(length), *list) Kent From alan.gauld at btinternet.com Mon Jul 30 01:51:25 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 30 Jul 2007 00:51:25 +0100 Subject: [Tutor] attribute error References: <368845.75914.qm@web35105.mail.mud.yahoo.com> Message-ID: "Sara Johnson" wrote Is this the correct traceback? Output okay except it will not sort alphabetically. **************** Traceback (most recent call last): File "./mymods.py", line 83, in ? outfile2.sort() AttributeError: 'file' object has no attribute 'sort' ********************* If its the error you are asking about then yes it will be the correct traceback. Now what do you not understand? The error tells you that the object outfile2 has no attribute sort. > Here's the code. Actually the code below is not the code thats producing the error since the call to outfile2.sort() is not there. However it does show that outfile2 is a file and files do not have a sort attribute so the error is correct. But without knowing what you are trying to sort I can't go any further. Alan G. ************ #reverse the dictionary of dictionaries, making new dictonary z: z={} #initialize empty dictionary skeys=h[keys[0]].keys() #get the "sub-keys" for i in skeys: #use sub-keys as new main-keys z[i]={} for j in keys: #use main-keys as new sub-keys z[i][j]=h[j][i] #use the new dictionary to find number of missing values: print "\n fraction of sites with missing measurements:" nsites=len(h.keys()) outfile2=open('missmeas.dat','w') for key in skeys: fracmiss=1.*numberMissing(z[key].values())/nsites outstring="%s has %4.1f%% missing" % (key,100*fracmiss) if fracmiss>0.: print outstring From alan.gauld at btinternet.com Mon Jul 30 01:56:42 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 30 Jul 2007 00:56:42 +0100 Subject: [Tutor] attribute error References: <131408.20376.qm@web35115.mail.mud.yahoo.com> Message-ID: "Sara Johnson" wrote > I always thought with floats you needed a 0.0. > I do have some percentages that are less than 1% but more than 0.0. If you already have a float value then you can compare it to an int and save the typing. zero means the same in a float comparison as 0.0 If you were trying to do float arithmetic, especially division, you need to exress at least one of the values as a float. The code you originally posted did that by just having a decimal point at the end - which is terrible style - but its more conventional (ie. more readable) to add .0 But >fracmiss = 1.0 * numberMissing( z[key].values() ) / nsites In this case mutiplying by 1.0 seems to be a clumsy way to ensure a float result when >fracmiss = float(numberMissing( z[key].values() )) / nsites would achieve the same and be more explicit as to purpose. Alan G From alan.gauld at btinternet.com Mon Jul 30 02:00:12 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 30 Jul 2007 01:00:12 +0100 Subject: [Tutor] attribute error - quick addition References: <619518.68253.qm@web35109.mail.mud.yahoo.com> Message-ID: "Sara Johnson" wrote > Sorry...I forgot a few more lines at the end of the code. Starts > with "outfile2write..." > I also added outfile2.sort() OK, at leasrt we see where the error occcurs. The problem emains that you are trying to sort a file which doesn't have a sort method. You need to sort the data before saving it. Alan G. ================ outfile2=open('missmeas.dat','w') for key in skeys: fracmiss=1.*numberMissing(z[key].values())/nsites outstring="%s has %4.1f%% missing" % (key,100*fracmiss) if fracmiss>0.: print outstring outfile2.write(outstring+'\n') #notice explicit newline \n outfile2.sort() outfile2.close() From kent37 at tds.net Mon Jul 30 04:35:05 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 29 Jul 2007 22:35:05 -0400 Subject: [Tutor] Notes on sorting Message-ID: <46AD4E59.7050506@tds.net> At my local Python user group meeting I have a regular spot on the agenda called Kent's Korner where I present not-quite-beginner material. This month was on sorting; my notes are here: http://personalpages.tds.net/~kent37/kk/00007.html You can see past notes at http://personalpages.tds.net/~kent37/kk/ Kent From amitsaxena69 at gmail.com Mon Jul 30 10:50:54 2007 From: amitsaxena69 at gmail.com (Amit Saxena) Date: Mon, 30 Jul 2007 14:20:54 +0530 Subject: [Tutor] How can I execute a PL/SQL Procedure directly through python rather than executing it through Command Prompt Message-ID: <82c58b390707300150i53cd2754ud4a91dba9c8cea7e@mail.gmail.com> Hi Can anybody help me in how to connect Python to oracle and then to execute an already existing PL/SQL Procedure through Python. -- Thanks and Regards, Amit Saxena Senior QA Engineer Ketera Direct: +91 4199 5028 Mobile: +91 99001 18641 asaxena at ketera.com ? Visit us at http://www.ketera.com ? Watch the demo at http://www.ketera.com/resources/demos.html -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070730/7afcafb9/attachment.htm From gslindstrom at gmail.com Mon Jul 30 13:40:19 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Mon, 30 Jul 2007 06:40:19 -0500 Subject: [Tutor] How can I execute a PL/SQL Procedure directly through Message-ID: >Can anybody help me in how to connect Python to oracle and then to execute >an already existing PL/SQL Procedure through Python. What platform are you running? Windows? Linux? Mac? I've used Oracle and plSql for years and will be happy to help out once I know what you need. --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070730/8b0b13bc/attachment.html From amitsaxena69 at gmail.com Mon Jul 30 13:45:27 2007 From: amitsaxena69 at gmail.com (Amit Saxena) Date: Mon, 30 Jul 2007 17:15:27 +0530 Subject: [Tutor] How can I execute a PL/SQL Procedure directly through In-Reply-To: References: Message-ID: <82c58b390707300445k107698cck6168d0a043c5e598@mail.gmail.com> I m on Windows Platform, was trying to use cx_oracle library but no success On 7/30/07, Greg Lindstrom wrote: > > >Can anybody help me in how to connect Python to oracle and then to > execute > >an already existing PL/SQL Procedure through Python. > > What platform are you running? Windows? Linux? Mac? > > I've used Oracle and plSql for years and will be happy to help out once I > know what you need. > > --greg > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Thanks and Regards, Amit Saxena Senior QA Engineer Ketera Direct: +91 4199 5028 Mobile: +91 99001 18641 asaxena at ketera.com ? Visit us at http://www.ketera.com ? Watch the demo at http://www.ketera.com/resources/demos.html -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070730/fdfabb89/attachment.htm From gslindstrom at gmail.com Mon Jul 30 14:05:38 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Mon, 30 Jul 2007 07:05:38 -0500 Subject: [Tutor] How can I execute a PL/SQL Procedure directly through In-Reply-To: <82c58b390707300445k107698cck6168d0a043c5e598@mail.gmail.com> References: <82c58b390707300445k107698cck6168d0a043c5e598@mail.gmail.com> Message-ID: My Oracle connection is set up using the adodb module ( http://adodb.sourceforge.net/). I don't remember why we set it up that way...we haven't touched this part of our code for almost 2 years!. from cx_Oracle import makedsn import adodb db = adodb.NewADOConnection('oci8') connection_string = makedsn(ip, port, database) <== your values here, of course db.Connect(connection _string, username, password) <== and here, too query = "SELECT name_of_pgSQL_routine(%(argument1)s, %(argument2)s)" results = db.execute(query, locals()) and go from there. Let me know if yo have other questions. HTH, --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070730/305a25c4/attachment.htm From amitsaxena69 at gmail.com Mon Jul 30 15:28:20 2007 From: amitsaxena69 at gmail.com (Amit Saxena) Date: Mon, 30 Jul 2007 18:58:20 +0530 Subject: [Tutor] How can I execute a PL/SQL Procedure directly through In-Reply-To: References: <82c58b390707300445k107698cck6168d0a043c5e598@mail.gmail.com> Message-ID: <82c58b390707300628j6a36ff94i77973beed5589ec@mail.gmail.com> I m still not able to run a Procedure from cx_Oracle import makedsn import adodb db = adodb.NewADOConnection('oci8') connection_string = makedsn("10.200.91.27", 1521, "scorpio") #<== your values here, of course db.Connect(connection_string, "kcmdev", "devkcm") #<== and here, too #query = "SELECT * from USER_ROLE where ROLE_FK = 29" results = db.Execute("metadata.sql") print results is giving an error saying Traceback (most recent call last): File "D:/Python/sql.py", line 9, in results = db.Execute("metadata.sql") File "C:\Python25\Lib\site-packages\adodb\adodb.py", line 274, in Execute c = self._query(sql,params) File "C:\Python25\Lib\site-packages\adodb\adodb.py", line 265, in _query raise sys.exc_info()[0] ,str(err)+': '+sql DatabaseError: ORA-00900: invalid SQL statement : metadata.sql On 7/30/07, Greg Lindstrom wrote: > > My Oracle connection is set up using the adodb module ( > http://adodb.sourceforge.net/). I don't remember why we set it up that > way...we haven't touched this part of our code for almost 2 years!. > > from cx_Oracle import makedsn > import adodb > > db = adodb.NewADOConnection('oci8') > connection_string = makedsn(ip, port, database) <== your values here, of > course > db.Connect(connection _string, username, password) <== and here, too > > query = "SELECT name_of_pgSQL_routine(%(argument1)s, %(argument2)s)" > results = db.execute(query, locals()) > > and go from there. Let me know if yo have other questions. > > HTH, > > --greg > > > -- Thanks and Regards, Amit Saxena Senior QA Engineer Ketera Direct: +91 4199 5028 Mobile: +91 99001 18641 asaxena at ketera.com ? Visit us at http://www.ketera.com ? Watch the demo at http://www.ketera.com/resources/demos.html -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070730/c1d4ed45/attachment.html From gslindstrom at gmail.com Mon Jul 30 15:34:48 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Mon, 30 Jul 2007 08:34:48 -0500 Subject: [Tutor] How can I execute a PL/SQL Procedure directly through In-Reply-To: <82c58b390707300628j6a36ff94i77973beed5589ec@mail.gmail.com> References: <82c58b390707300445k107698cck6168d0a043c5e598@mail.gmail.com> <82c58b390707300628j6a36ff94i77973beed5589ec@mail.gmail.com> Message-ID: On 7/30/07, Amit Saxena wrote: > > > I m still not able to run a Procedure > > from cx_Oracle import makedsn > import adodb > > db = adodb.NewADOConnection('oci8') > connection_string = makedsn("10.200.91.27 ", 1521, "scorpio") #<== your > values here, of course > db.Connect(connection_string, "kcmdev", "devkcm") #<== and here, too > > #query = "SELECT * from USER_ROLE where ROLE_FK = 29" > results = db.Execute("metadata.sql") > print results > > > is giving an error saying > > Traceback (most recent call last): > File "D:/Python/sql.py", line 9, in > results = db.Execute("metadata.sql") > File "C:\Python25\Lib\site-packages\adodb\adodb.py", line 274, in > Execute > c = self._query(sql,params) > File "C:\Python25\Lib\site-packages\adodb\adodb.py", line 265, in _query > > raise sys.exc_info()[0] ,str(err)+': '+sql > DatabaseError: ORA-00900: invalid SQL statement > : metadata.sql > What is in metadata.sql? If it is a PL/SQL query, then you should "SELECT metadata()". If is a file containing sql (is the pl/sql you wish to execute in this file?) then I'm not sure how to proceed. Is the PL/SQL you wish to run saved in Oracle? Can you show us what's in the metadata.sql file? --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070730/2ee34b1f/attachment.htm From amitsaxena69 at gmail.com Mon Jul 30 15:37:33 2007 From: amitsaxena69 at gmail.com (Amit Saxena) Date: Mon, 30 Jul 2007 19:07:33 +0530 Subject: [Tutor] How can I execute a PL/SQL Procedure directly through In-Reply-To: References: <82c58b390707300445k107698cck6168d0a043c5e598@mail.gmail.com> <82c58b390707300628j6a36ff94i77973beed5589ec@mail.gmail.com> Message-ID: <82c58b390707300637q759b4198p75f44da61c5b78c5@mail.gmail.com> It is a complete PL/SQL Cursor which is written in this "metadata.sql" file On 7/30/07, Greg Lindstrom wrote: > > > > On 7/30/07, Amit Saxena wrote: > > > > > > I m still not able to run a Procedure > > > > from cx_Oracle import makedsn > > import adodb > > > > db = adodb.NewADOConnection('oci8') > > connection_string = makedsn(" 10.200.91.27 ", 1521, "scorpio") #<== > > your values here, of course > > db.Connect(connection_string, "kcmdev", "devkcm") #<== and here, too > > > > #query = "SELECT * from USER_ROLE where ROLE_FK = 29" > > results = db.Execute("metadata.sql") > > print results > > > > > > is giving an error saying > > > > Traceback (most recent call last): > > File "D:/Python/sql.py", line 9, in > > results = db.Execute("metadata.sql") > > File "C:\Python25\Lib\site-packages\adodb\adodb.py", line 274, in > > Execute > > c = self._query(sql,params) > > File "C:\Python25\Lib\site-packages\adodb\adodb.py", line 265, in > > _query > > raise sys.exc_info()[0] ,str(err)+': '+sql > > DatabaseError: ORA-00900: invalid SQL statement > > : metadata.sql > > > > What is in metadata.sql? If it is a PL/SQL query, then you should "SELECT > metadata()". If is a file containing sql (is the pl/sql you wish to execute > in this file?) then I'm not sure how to proceed. > > Is the PL/SQL you wish to run saved in Oracle? Can you show us what's in > the metadata.sql file? > > --greg > -- Thanks and Regards, Amit Saxena Senior QA Engineer Ketera Direct: +91 4199 5028 Mobile: +91 99001 18641 asaxena at ketera.com ? Visit us at http://www.ketera.com ? Watch the demo at http://www.ketera.com/resources/demos.html -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070730/d3a30f34/attachment-0001.html From amitsaxena69 at gmail.com Mon Jul 30 15:40:08 2007 From: amitsaxena69 at gmail.com (Amit Saxena) Date: Mon, 30 Jul 2007 19:10:08 +0530 Subject: [Tutor] How can I execute a PL/SQL Procedure directly through In-Reply-To: <82c58b390707300637q759b4198p75f44da61c5b78c5@mail.gmail.com> References: <82c58b390707300445k107698cck6168d0a043c5e598@mail.gmail.com> <82c58b390707300628j6a36ff94i77973beed5589ec@mail.gmail.com> <82c58b390707300637q759b4198p75f44da61c5b78c5@mail.gmail.com> Message-ID: <82c58b390707300640x15f6e2a8r20c9454ab488d832@mail.gmail.com> this is the file content of "metadata.sql" set serveroutput on CREATE OR REPLACE PROCEDURE Create_Process_Team (org_id IN VARCHAR2, org_desc IN VARCHAR2, org_team IN VARCHAR2, sessioner_id IN VARCHAR2) IS ptt_id KCM_PROCESS_TEAM_TEMPLATE.ID%TYPE; pt_id KCM_PROCESS_TEAM.ID%TYPE; BEGIN select HIBERNATE_SEQUENCE.NEXTVAL into ptt_id from dual; select HIBERNATE_SEQUENCE.NEXTVAL into pt_id from dual; --METADATA --Entry in Process Team Template Table insert into KCM_PROCESS_TEAM_TEMPLATE(ID,VERSION,DESCRIPTION,ORG_FK,NAME) values(ptt_id,0,org_desc,org_id,org_team); --Entry in Process Team Template Type Table insert into KCM_PROCESS_TEAM_TEMPLATE_TYPE(PROCESS_TEAM_TEMPLATE_FK, PROCESS_TYPE_FK) values(ptt_id, 3); --Entry in Process Team Role Table --Sessioner INSERT INTO KCM_PROCESS_TEAM_ROLE(ID, VERSION, ROLE_FK, ORG_TYPE_FK, IS_HIERARCHICAL, PROCESS_TEAM_TEMPLATE_FK, IS_OPTIONAL) values(HIBERNATE_SEQUENCE.NEXTVAL,0,29,2,1,ptt_id,0); --CREATING WORKFLOW TEAM --Entry in Process Team Table INSERT INTO KCM_PROCESS_TEAM (ID, VERSION, DESCRIPTION, NAME, CUSTOMER_RELATIONSHIP_FK, ISTEMPLATE,ORG_FK) VALUES(pt_id, 0, org_desc,org_team, NULL, 1, org_id); --Entry in Team User Table --Insert Sessioner insert into KCM_TEAM_USER(ID,VERSION,USER_FK,ROLE_FK,PROCESS_TEAM_FK) values(HIBERNATE_SEQUENCE.NEXTVAL,0,sessioner_id,'29',pt_id); --Entry in Team Type Table insert into KCM_PROCESS_TEAM_TYPE values(pt_id,4); END; / On 7/30/07, Amit Saxena wrote: > > It is a complete PL/SQL Procedure which is written in this "metadata.sql" > file > > On 7/30/07, Greg Lindstrom < gslindstrom at gmail.com> wrote: > > > > > > > > On 7/30/07, Amit Saxena wrote: > > > > > > > > > I m still not able to run a Procedure > > > > > > from cx_Oracle import makedsn > > > import adodb > > > > > > db = adodb.NewADOConnection('oci8') > > > connection_string = makedsn(" 10.200.91.27 ", 1521, "scorpio") #<== > > > your values here, of course > > > db.Connect(connection_string, "kcmdev", "devkcm") #<== and here, too > > > > > > #query = "SELECT * from USER_ROLE where ROLE_FK = 29" > > > results = db.Execute("metadata.sql") > > > print results > > > > > > > > > is giving an error saying > > > > > > Traceback (most recent call last): > > > File "D:/Python/sql.py", line 9, in > > > results = db.Execute("metadata.sql") > > > File "C:\Python25\Lib\site-packages\adodb\adodb.py", line 274, in > > > Execute > > > c = self._query(sql,params) > > > File "C:\Python25\Lib\site-packages\adodb\adodb.py", line 265, in > > > _query > > > raise sys.exc_info()[0] ,str(err)+': '+sql > > > DatabaseError: ORA-00900: invalid SQL statement > > > : metadata.sql > > > > > > > What is in metadata.sql? If it is a PL/SQL query, then you should > > "SELECT metadata()". If is a file containing sql (is the pl/sql you wish to > > execute in this file?) then I'm not sure how to proceed. > > > > Is the PL/SQL you wish to run saved in Oracle? Can you show us what's > > in the metadata.sql file? > > > > --greg > > > > > > -- > Thanks and Regards, > Amit Saxena > Senior QA Engineer > Ketera > Direct: +91 4199 5028 > Mobile: +91 99001 18641 > asaxena at ketera.com > > ? Visit us at http://www.ketera.com > ? Watch the demo at http://www.ketera.com/resources/demos.html > -- Thanks and Regards, Amit Saxena Senior QA Engineer Ketera Direct: +91 4199 5028 Mobile: +91 99001 18641 asaxena at ketera.com ? Visit us at http://www.ketera.com ? Watch the demo at http://www.ketera.com/resources/demos.html -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070730/693bd171/attachment.htm From gslindstrom at gmail.com Mon Jul 30 15:51:55 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Mon, 30 Jul 2007 08:51:55 -0500 Subject: [Tutor] How can I execute a PL/SQL Procedure directly through In-Reply-To: <82c58b390707300640x15f6e2a8r20c9454ab488d832@mail.gmail.com> References: <82c58b390707300445k107698cck6168d0a043c5e598@mail.gmail.com> <82c58b390707300628j6a36ff94i77973beed5589ec@mail.gmail.com> <82c58b390707300637q759b4198p75f44da61c5b78c5@mail.gmail.com> <82c58b390707300640x15f6e2a8r20c9454ab488d832@mail.gmail.com> Message-ID: I've never tried anything like that before; others may be of more help at this point. What I would try is reading the contents of the file into a local variable. my_data = file('metadata.sql').readlines() # read the file into a list query = ''.join(my_data) # append the list into a single string (including linefeeds) results = db.execute(query) That should -- though I haven't tried it -- run the script to create the stored procedure. You would then call it via a SELECT statement to capture the results of running the sproc. ado allows you to set "debug" to 1 and it will echo your queries back to you as you execute them. --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070730/76f85641/attachment.html From kent37 at tds.net Mon Jul 30 16:12:44 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 30 Jul 2007 10:12:44 -0400 Subject: [Tutor] How can I execute a PL/SQL Procedure directly through In-Reply-To: <82c58b390707300640x15f6e2a8r20c9454ab488d832@mail.gmail.com> References: <82c58b390707300445k107698cck6168d0a043c5e598@mail.gmail.com> <82c58b390707300628j6a36ff94i77973beed5589ec@mail.gmail.com> <82c58b390707300637q759b4198p75f44da61c5b78c5@mail.gmail.com> <82c58b390707300640x15f6e2a8r20c9454ab488d832@mail.gmail.com> Message-ID: <46ADF1DC.7040704@tds.net> Your original query asked how to execute an existing stored procedure. This is the SQL code to *create* a stored procedure. Are you trying to create it or execute it? Kent Amit Saxena wrote: > this is the file content of "metadata.sql" > > set serveroutput on > > CREATE OR REPLACE PROCEDURE Create_Process_Team (org_id IN VARCHAR2, > org_desc IN VARCHAR2, org_team IN VARCHAR2, sessioner_id IN VARCHAR2) IS > > ptt_id KCM_PROCESS_TEAM_TEMPLATE.ID%TYPE; > pt_id KCM_PROCESS_TEAM.ID%TYPE; > > BEGIN > > select HIBERNATE_SEQUENCE.NEXTVAL into ptt_id from dual; > select HIBERNATE_SEQUENCE.NEXTVAL into pt_id from dual; > > --METADATA > --Entry in Process Team Template Table > insert into > KCM_PROCESS_TEAM_TEMPLATE(ID,VERSION,DESCRIPTION,ORG_FK,NAME) > values(ptt_id,0,org_desc,org_id,org_team); > > --Entry in Process Team Template Type Table > insert into KCM_PROCESS_TEAM_TEMPLATE_TYPE(PROCESS_TEAM_TEMPLATE_FK, > PROCESS_TYPE_FK) values(ptt_id, 3); > > --Entry in Process Team Role Table > --Sessioner > INSERT INTO KCM_PROCESS_TEAM_ROLE(ID, VERSION, ROLE_FK, ORG_TYPE_FK, > IS_HIERARCHICAL, PROCESS_TEAM_TEMPLATE_FK, IS_OPTIONAL) > values(HIBERNATE_SEQUENCE.NEXTVAL,0,29,2,1,ptt_id,0); > > > --CREATING WORKFLOW TEAM > --Entry in Process Team Table > INSERT INTO KCM_PROCESS_TEAM (ID, VERSION, DESCRIPTION, NAME, > CUSTOMER_RELATIONSHIP_FK, ISTEMPLATE,ORG_FK) VALUES(pt_id, 0, > org_desc,org_team, NULL, 1, org_id); > > --Entry in Team User Table > --Insert Sessioner > insert into > KCM_TEAM_USER(ID,VERSION,USER_FK,ROLE_FK,PROCESS_TEAM_FK) > values(HIBERNATE_SEQUENCE.NEXTVAL,0,sessioner_id,'29',pt_id); > > --Entry in Team Type Table > insert into KCM_PROCESS_TEAM_TYPE values(pt_id,4); > > END; > / > > On 7/30/07, *Amit Saxena* > wrote: > > It is a complete PL/SQL Procedure which is written in this > "metadata.sql" file > > On 7/30/07, *Greg Lindstrom* < gslindstrom at gmail.com > > wrote: > > > > On 7/30/07, *Amit Saxena* > wrote: > > > I m still not able to run a Procedure > > from cx_Oracle import makedsn > import adodb > > db = adodb.NewADOConnection('oci8') > connection_string = makedsn(" 10.200.91.27 > ", 1521, "scorpio") #<== your values > here, of course > db.Connect(connection_string, "kcmdev", "devkcm") #<== and > here, too > > #query = "SELECT * from USER_ROLE where ROLE_FK = 29" > results = db.Execute("metadata.sql") > print results > > > is giving an error saying > > Traceback (most recent call last): > File "D:/Python/sql.py", line 9, in > results = db.Execute("metadata.sql") > File "C:\Python25\Lib\site-packages\adodb\adodb.py", line > 274, in Execute > c = self._query(sql,params) > File "C:\Python25\Lib\site-packages\adodb\adodb.py", line > 265, in _query > raise sys.exc_info()[0] ,str(err)+': '+sql > DatabaseError: ORA-00900: invalid SQL statement > : metadata.sql > > > What is in metadata.sql? If it is a PL/SQL query, then you > should "SELECT metadata()". If is a file containing sql (is the > pl/sql you wish to execute in this file?) then I'm not sure how > to proceed. > > Is the PL/SQL you wish to run saved in Oracle? Can you show us > what's in the metadata.sql file? > > --greg > > > > > -- > Thanks and Regards, > Amit Saxena > Senior QA Engineer > Ketera > Direct: +91 4199 5028 > Mobile: +91 99001 18641 > asaxena at ketera.com > > ? Visit us at http://www.ketera.com > ? Watch the demo at http://www.ketera.com/resources/demos.html > > > > > -- > Thanks and Regards, > Amit Saxena > Senior QA Engineer > Ketera > Direct: +91 4199 5028 > Mobile: +91 99001 18641 > asaxena at ketera.com > > ? Visit us at http://www.ketera.com > ? Watch the demo at http://www.ketera.com/resources/demos.html > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From amitsaxena69 at gmail.com Mon Jul 30 16:31:36 2007 From: amitsaxena69 at gmail.com (Amit Saxena) Date: Mon, 30 Jul 2007 20:01:36 +0530 Subject: [Tutor] How can I execute a PL/SQL Procedure directly through In-Reply-To: <46ADF1DC.7040704@tds.net> References: <82c58b390707300445k107698cck6168d0a043c5e598@mail.gmail.com> <82c58b390707300628j6a36ff94i77973beed5589ec@mail.gmail.com> <82c58b390707300637q759b4198p75f44da61c5b78c5@mail.gmail.com> <82c58b390707300640x15f6e2a8r20c9454ab488d832@mail.gmail.com> <46ADF1DC.7040704@tds.net> Message-ID: <82c58b390707300731j5c8920aeo95b9e5d906fab13b@mail.gmail.com> ya i m trying to execute the procedure,these were the contents of that SQL file which i m trying to execute On 7/30/07, Kent Johnson wrote: > > Your original query asked how to execute an existing stored procedure. > This is the SQL code to *create* a stored procedure. Are you trying to > create it or execute it? > > Kent > > Amit Saxena wrote: > > this is the file content of "metadata.sql" > > > > set serveroutput on > > > > CREATE OR REPLACE PROCEDURE Create_Process_Team (org_id IN VARCHAR2, > > org_desc IN VARCHAR2, org_team IN VARCHAR2, sessioner_id IN VARCHAR2) IS > > > > ptt_id KCM_PROCESS_TEAM_TEMPLATE.ID%TYPE; > > pt_id KCM_PROCESS_TEAM.ID%TYPE; > > > > BEGIN > > > > select HIBERNATE_SEQUENCE.NEXTVAL into ptt_id from dual; > > select HIBERNATE_SEQUENCE.NEXTVAL into pt_id from dual; > > > > --METADATA > > --Entry in Process Team Template Table > > insert into > > KCM_PROCESS_TEAM_TEMPLATE(ID,VERSION,DESCRIPTION,ORG_FK,NAME) > > values(ptt_id,0,org_desc,org_id,org_team); > > > > --Entry in Process Team Template Type Table > > insert into KCM_PROCESS_TEAM_TEMPLATE_TYPE(PROCESS_TEAM_TEMPLATE_FK, > > PROCESS_TYPE_FK) values(ptt_id, 3); > > > > --Entry in Process Team Role Table > > --Sessioner > > INSERT INTO KCM_PROCESS_TEAM_ROLE(ID, VERSION, ROLE_FK, ORG_TYPE_FK, > > IS_HIERARCHICAL, PROCESS_TEAM_TEMPLATE_FK, IS_OPTIONAL) > > values(HIBERNATE_SEQUENCE.NEXTVAL,0,29,2,1,ptt_id,0); > > > > > > --CREATING WORKFLOW TEAM > > --Entry in Process Team Table > > INSERT INTO KCM_PROCESS_TEAM (ID, VERSION, DESCRIPTION, NAME, > > CUSTOMER_RELATIONSHIP_FK, ISTEMPLATE,ORG_FK) VALUES(pt_id, 0, > > org_desc,org_team, NULL, 1, org_id); > > > > --Entry in Team User Table > > --Insert Sessioner > > insert into > > KCM_TEAM_USER(ID,VERSION,USER_FK,ROLE_FK,PROCESS_TEAM_FK) > > values(HIBERNATE_SEQUENCE.NEXTVAL,0,sessioner_id,'29',pt_id); > > > > --Entry in Team Type Table > > insert into KCM_PROCESS_TEAM_TYPE values(pt_id,4); > > > > END; > > / > > > > On 7/30/07, *Amit Saxena* > > wrote: > > > > It is a complete PL/SQL Procedure which is written in this > > "metadata.sql" file > > > > On 7/30/07, *Greg Lindstrom* < gslindstrom at gmail.com > > > wrote: > > > > > > > > On 7/30/07, *Amit Saxena* > > wrote: > > > > > > I m still not able to run a Procedure > > > > from cx_Oracle import makedsn > > import adodb > > > > db = adodb.NewADOConnection('oci8') > > connection_string = makedsn(" 10.200.91.27 > > ", 1521, "scorpio") #<== your values > > here, of course > > db.Connect(connection_string, "kcmdev", "devkcm") #<== and > > here, too > > > > #query = "SELECT * from USER_ROLE where ROLE_FK = 29" > > results = db.Execute("metadata.sql") > > print results > > > > > > is giving an error saying > > > > Traceback (most recent call last): > > File "D:/Python/sql.py", line 9, in > > results = db.Execute("metadata.sql") > > File "C:\Python25\Lib\site-packages\adodb\adodb.py", line > > 274, in Execute > > c = self._query(sql,params) > > File "C:\Python25\Lib\site-packages\adodb\adodb.py", line > > 265, in _query > > raise sys.exc_info()[0] ,str(err)+': '+sql > > DatabaseError: ORA-00900: invalid SQL statement > > : metadata.sql > > > > > > What is in metadata.sql? If it is a PL/SQL query, then you > > should "SELECT metadata()". If is a file containing sql (is the > > pl/sql you wish to execute in this file?) then I'm not sure how > > to proceed. > > > > Is the PL/SQL you wish to run saved in Oracle? Can you show us > > what's in the metadata.sql file? > > > > --greg > > > > > > > > > > -- > > Thanks and Regards, > > Amit Saxena > > Senior QA Engineer > > Ketera > > Direct: +91 4199 5028 > > Mobile: +91 99001 18641 > > asaxena at ketera.com > > > > ? Visit us at http://www.ketera.com > > ? Watch the demo at http://www.ketera.com/resources/demos.html > > > > > > > > > > -- > > Thanks and Regards, > > Amit Saxena > > Senior QA Engineer > > Ketera > > Direct: +91 4199 5028 > > Mobile: +91 99001 18641 > > asaxena at ketera.com > > > > ? Visit us at http://www.ketera.com > > ? Watch the demo at http://www.ketera.com/resources/demos.html > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- Thanks and Regards, Amit Saxena Senior QA Engineer Ketera Direct: +91 4199 5028 Mobile: +91 99001 18641 asaxena at ketera.com ? Visit us at http://www.ketera.com ? Watch the demo at http://www.ketera.com/resources/demos.html -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070730/bdc58bc0/attachment-0001.htm From kent37 at tds.net Mon Jul 30 16:43:54 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 30 Jul 2007 10:43:54 -0400 Subject: [Tutor] How can I execute a PL/SQL Procedure directly through In-Reply-To: <82c58b390707300731j5c8920aeo95b9e5d906fab13b@mail.gmail.com> References: <82c58b390707300445k107698cck6168d0a043c5e598@mail.gmail.com> <82c58b390707300628j6a36ff94i77973beed5589ec@mail.gmail.com> <82c58b390707300637q759b4198p75f44da61c5b78c5@mail.gmail.com> <82c58b390707300640x15f6e2a8r20c9454ab488d832@mail.gmail.com> <46ADF1DC.7040704@tds.net> <82c58b390707300731j5c8920aeo95b9e5d906fab13b@mail.gmail.com> Message-ID: <46ADF92A.3010102@tds.net> Amit Saxena wrote: > ya i m trying to execute the procedure,these were the contents of that > SQL file which i m trying to execute Then (paraphrasing Greg's earlier response) you need something like query = "SELECT Create_Process_Team(%(org_id)s, %(org_desc)s, %(org_team)s, %(sessioner_id)s)" results = db.execute(query, locals()) where org_id, org_desc, org_team and sessioner_id are existing local variables. Kent From keridee at jayco.net Mon Jul 30 23:46:00 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 30 Jul 2007 16:46:00 -0500 Subject: [Tutor] Sum of Scores References: <009401c7cfdc$3c3b4320$d6fce004@JSLAPTOP> <46A92D94.3090804@gmail.com> <002401c7cfee$9a191690$d6fce004@JSLAPTOP> <46A9606D.5070709@gmail.com> <001401c7d026$02865080$c3fce004@JSLAPTOP> <00c101c7d12e$d14be020$76fce004@JSLAPTOP> <46ABDBB2.70702@gmail.com> Message-ID: <00f501c7d2f3$08a0cbb0$29fde004@JSLAPTOP> > So normally, after the period is up, it would choose a new seed? or does > it repeat after the period whether or not the time has changed? It would repeat whether or not the time has changed, naturally. How would the algorithm know when the period has finished? The mersenne twister is based on functions that repeat naturally, and the way they are combined helps extend the period of the combined function. I seriously doubt that a new seed is chosen. Who bothers checking for repetition that is expected to occur a gazillion trillion billion and more years in the future? But because you can predict when it can repeat, you can predict what the outcome will be. That's why it's not used in cryptography for example. I thought I might look up just what occurs in the Mersenne twister. I have C code that performs this ~ yuck. Lots of bit shifts, ANDs, ORs, etc. I'll work through just what happens, but I know the theory. It's pattern repeats unhindered when it's period starts over. >> > as a side note - are you going to enter the September Pyweek? You >> should! >> >>> It's a lot of fun. >>> -Luke >>> >> >> Hmmm.... what's that? I'll google. >> > It's a whole lot of fun. And everyone's really nice. > SO even if you don't have time to finish a game, it's enjoyable and a > learning experience just to > hang out with everyone on IRC. Also, you should have time to learn pygame > for the competition if you don't know how to use it already. Of course > you could use pyglet or pyOpenGL or something instead, if you wanted. Oh man. As much as I would love to do something like that, I'm sure I would be highly Out of Place. I don't have the patience, nor the speed. I work slowly. I do a project slowly once a week making a huge design break-through so that it culminates into a working project. JS From sarliz73 at yahoo.com Mon Jul 30 23:13:50 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Mon, 30 Jul 2007 14:13:50 -0700 (PDT) Subject: [Tutor] attribute error - quick addition Message-ID: <302182.36892.qm@web35110.mail.mud.yahoo.com> Thanks Alan and Kent (for the sorting notes)! Alan...I guess I thought outfile2 had data. { i.e., outfile2=open('missmeas.dat','w') } My mistake. Thanks, Sara ----- Original Message ---- From: Alan Gauld To: tutor at python.org Sent: Sunday, July 29, 2007 7:00:12 PM Subject: Re: [Tutor] attribute error - quick addition "Sara Johnson" wrote > Sorry...I forgot a few more lines at the end of the code. Starts > with "outfile2write..." > I also added outfile2.sort() OK, at leasrt we see where the error occcurs. The problem emains that you are trying to sort a file which doesn't have a sort method. You need to sort the data before saving it. Alan G. ================ outfile2=open('missmeas.dat','w') for key in skeys: fracmiss=1.*numberMissing(z[key].values())/nsites outstring="%s has %4.1f%% missing" % (key,100*fracmiss) if fracmiss>0.: print outstring outfile2.write(outstring+'\n') #notice explicit newline \n outfile2.sort() outfile2.close() _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ____________________________________________________________________________________ Choose the right car based on your needs. Check out Yahoo! Autos new Car Finder tool. http://autos.yahoo.com/carfinder/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070730/bb69f11a/attachment.htm From kent37 at tds.net Mon Jul 30 23:27:04 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 30 Jul 2007 17:27:04 -0400 Subject: [Tutor] build a really simple "json" api from a db In-Reply-To: <825bef0c0707291236w27046440pe4d9a0ca536163c5@mail.gmail.com> References: <825bef0c0707281050n46aa8817q4ec55541080e3a0c@mail.gmail.com> <825bef0c0707291236w27046440pe4d9a0ca536163c5@mail.gmail.com> Message-ID: <46AE57A8.2040008@tds.net> Picio wrote: > The beginning idea was to build a json API myself. Since I need only > to generate json from a db, maybe Django is too much. I'm a Django > beginner. I don't know Turbogears. > I've not found anything like: "how to build a json api". > Maybe MySqldb+simplejson is the enough? I guess it depends on how you expect the site to grow. If your needs are modest and likely to remain so, maybe a Python CGI that reads data from MySQL and publishes it with simplejson is fine. You could do this with Django but for something really simple it's probably not worth the trouble. But if the site is going to grow, Django adds a lot, including an object model on top of the database, url dispatching and templated views. If that will be useful down the road then it might be worth starting with Django. Kent > Or > Is It more simple to learn how to use Django to create a json api? > > 2007/7/28, Alan Gauld : >> "Picio" wrote >> >>> Hello, I'd like to know the necessary steps to build a json api for >>> two table on my db. >> Since you seem to be using Django are you sure that isn't built in? >> >> I use Turbo Gears and JSON is a standard feature turned on by >> an option in a method. Django is quite similar to TG in most respects >> so I'll be surprised if it can't do JSON directly. >> >>> I've seen this snippet on the djangosnippet site. >>> http://www.djangosnippets.org/snippets/154/ >>> Is It the right way. >> If its on the Django web site and you are using Django then >> probably! :-) >> >> It certainly looks like a recommendation to me. >> >> -- >> 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 >> > > From picioslug at gmail.com Mon Jul 30 23:37:38 2007 From: picioslug at gmail.com (Picio) Date: Mon, 30 Jul 2007 23:37:38 +0200 Subject: [Tutor] build a really simple "json" api from a db In-Reply-To: <46AE57A8.2040008@tds.net> References: <825bef0c0707281050n46aa8817q4ec55541080e3a0c@mail.gmail.com> <825bef0c0707291236w27046440pe4d9a0ca536163c5@mail.gmail.com> <46AE57A8.2040008@tds.net> Message-ID: <825bef0c0707301437t1f5bb79ak80beeafbd045c96b@mail.gmail.com> Hi Kent, ok I've decided to go through Django. Now the clue is to find some simple guide to output json from my model and maybe I can benefit also for the url dispatcher to map in a clean way the request coming from my ajax app. This is what I'd like to do: ajax app-> URL -> urls.py -> view.py -> ORM -> db then view -> json -> ajax app The second path is something I really have to figure out! I hope It's right. Daniele 2007/7/30, Kent Johnson : > Picio wrote: > > The beginning idea was to build a json API myself. Since I need only > > to generate json from a db, maybe Django is too much. I'm a Django > > beginner. I don't know Turbogears. > > I've not found anything like: "how to build a json api". > > Maybe MySqldb+simplejson is the enough? > > I guess it depends on how you expect the site to grow. If your needs are > modest and likely to remain so, maybe a Python CGI that reads data from > MySQL and publishes it with simplejson is fine. You could do this with > Django but for something really simple it's probably not worth the trouble. > > But if the site is going to grow, Django adds a lot, including an object > model on top of the database, url dispatching and templated views. If > that will be useful down the road then it might be worth starting with > Django. > > Kent > > > Or > > Is It more simple to learn how to use Django to create a json api? > > > > 2007/7/28, Alan Gauld : > >> "Picio" wrote > >> > >>> Hello, I'd like to know the necessary steps to build a json api for > >>> two table on my db. > >> Since you seem to be using Django are you sure that isn't built in? > >> > >> I use Turbo Gears and JSON is a standard feature turned on by > >> an option in a method. Django is quite similar to TG in most respects > >> so I'll be surprised if it can't do JSON directly. > >> > >>> I've seen this snippet on the djangosnippet site. > >>> http://www.djangosnippets.org/snippets/154/ > >>> Is It the right way. > >> If its on the Django web site and you are using Django then > >> probably! :-) > >> > >> It certainly looks like a recommendation to me. > >> > >> -- > >> 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 > >> > > > > > > -- http://picio.gotdns.com ...Il mio blog su NSLU2 From brunson at brunson.com Mon Jul 30 23:39:00 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 30 Jul 2007 15:39:00 -0600 Subject: [Tutor] build a really simple "json" api from a db In-Reply-To: <825bef0c0707291236w27046440pe4d9a0ca536163c5@mail.gmail.com> References: <825bef0c0707281050n46aa8817q4ec55541080e3a0c@mail.gmail.com> <825bef0c0707291236w27046440pe4d9a0ca536163c5@mail.gmail.com> Message-ID: <46AE5A74.40805@brunson.com> Picio wrote: > The beginning idea was to build a json API myself. Since I need only > to generate json from a db, maybe Django is too much. I'm a Django > beginner. I don't know Turbogears. > I've not found anything like: "how to build a json api". > Maybe MySqldb+simplejson is the enough? > Or > Is It more simple to learn how to use Django to create a json api? > Picio, You seem to be in analysis paralysis. You don't understand the underlying technology, which is making the task seem daunting. Break it down into component parts and learn the ones you don't already understand. It seems the most important aspects of the project are getting info out of the database, converting it to JSON and publishing it via HTTP. Do you have a web server? Then write the simplest example of a CGI script to query a database and serve serve it up using simplejson. If you don't have a web server, then wrap it in a little CGIHTTPServer (http://docs.python.org/lib/module-CGIHTTPServer.html). I'm not trying to criticize on you or make you mad, but if you'd jumped in and tried it out instead of posting here all weekend, you'd probably have a working prototype by now. You'll probably go through 10 different iterations before you have a final product and you'll be able to reuse any of the code you come up with. Just do it and we'll help you with any questions you have along the way. Go, go, go. It's your birthday, you can do this. :-) e. > 2007/7/28, Alan Gauld : > >> "Picio" wrote >> >> >>> Hello, I'd like to know the necessary steps to build a json api for >>> two table on my db. >>> >> Since you seem to be using Django are you sure that isn't built in? >> >> I use Turbo Gears and JSON is a standard feature turned on by >> an option in a method. Django is quite similar to TG in most respects >> so I'll be surprised if it can't do JSON directly. >> >> >>> I've seen this snippet on the djangosnippet site. >>> http://www.djangosnippets.org/snippets/154/ >>> Is It the right way. >>> >> If its on the Django web site and you are using Django then >> probably! :-) >> >> It certainly looks like a recommendation to me. >> >> -- >> 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 >> >> > > > From keridee at jayco.net Tue Jul 31 00:42:47 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 30 Jul 2007 17:42:47 -0500 Subject: [Tutor] attribute error - quick addition References: <302182.36892.qm@web35110.mail.mud.yahoo.com> Message-ID: <001201c7d2fa$f74acd40$29fde004@JSLAPTOP> > Thanks Alan and Kent (for the sorting notes)! > > Alan...I guess I thought outfile2 had data. { i.e., > outfile2=open('missmeas.dat','w') } Argghh!!! No, no, no! Attribute Error! No matter how much data you have in the file, you will *never* be able to call sort on it, because file objects do not understand sort. They do not have the "attribute" called "sort". Lists have sort. If you want to sort them like you are trying, you will have to convert the file into a list (of lines). lst = list(outfile2) lst.sort() JS > My mistake. > > Thanks, > Sara From kent37 at tds.net Mon Jul 30 23:54:27 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 30 Jul 2007 17:54:27 -0400 Subject: [Tutor] build a really simple "json" api from a db In-Reply-To: <825bef0c0707301437t1f5bb79ak80beeafbd045c96b@mail.gmail.com> References: <825bef0c0707281050n46aa8817q4ec55541080e3a0c@mail.gmail.com> <825bef0c0707291236w27046440pe4d9a0ca536163c5@mail.gmail.com> <46AE57A8.2040008@tds.net> <825bef0c0707301437t1f5bb79ak80beeafbd045c96b@mail.gmail.com> Message-ID: <46AE5E13.1030405@tds.net> Picio wrote: > Hi Kent, ok I've decided to go through Django. Now the clue is to find > some simple guide to > output json from my model and maybe I can benefit also for the url > dispatcher to map in a clean way the request coming from my ajax app. > > This is what I'd like to do: > > ajax app-> URL -> urls.py -> view.py -> ORM -> db > > then > > view -> json -> ajax app > > The second path is something I really have to figure out! Here is the way I do it, with the real model name changed to xxx. Here is the view: def as_json(request, xxx_id): ''' Return a xxx in JSON format. Required this version of django/core/serializers/json.py: http://code.djangoproject.com/browser/django/trunk/django/core/serializers/json.py?rev=5302 ''' xxx = Xxx.objects.get(pk=int(xxx_id)) return HttpResponse(xxx.asJson(), mimetype='application/json') Here is the asJson() method from the xxx model, slightly edited to remove some extra hacks: def asJson(self): ''' Return a JSON representation of ourself. ''' from django.core import serializers # A note about encoding # xxx strings are encoded in UTF-8. That is the default encoding for # a JSON stream, so we just want to preserve the existing characters # which is what ensure_ascii=False does. # If ensure_ascii=True, the individual bytes of the UTF-8 text # will be encoded with \u escapes which is not at all correct data = serializers.serialize('json', [self], ensure_ascii=False) # Strip leading and trailing [] to make it a single xxx data = data[1:-1] return data Kent From sarliz73 at yahoo.com Mon Jul 30 23:56:32 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Mon, 30 Jul 2007 14:56:32 -0700 (PDT) Subject: [Tutor] attribute error - quick addition Message-ID: <287757.75261.qm@web35115.mail.mud.yahoo.com> Sorry... I'm still learning about lists, tuples, etc... Thanks, Sara ----- Original Message ---- From: Tiger12506 To: tutor at python.org Sent: Monday, July 30, 2007 5:42:47 PM Subject: Re: [Tutor] attribute error - quick addition > Thanks Alan and Kent (for the sorting notes)! > > Alan...I guess I thought outfile2 had data. { i.e., > outfile2=open('missmeas.dat','w') } Argghh!!! No, no, no! Attribute Error! No matter how much data you have in the file, you will *never* be able to call sort on it, because file objects do not understand sort. They do not have the "attribute" called "sort". Lists have sort. If you want to sort them like you are trying, you will have to convert the file into a list (of lines). lst = list(outfile2) lst.sort() JS > My mistake. > > Thanks, > Sara _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ____________________________________________________________________________________ Moody friends. Drama queens. Your life? Nope! - their life, your story. Play Sims Stories at Yahoo! Games. http://sims.yahoo.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070730/d73b9461/attachment.htm From keridee at jayco.net Tue Jul 31 01:09:21 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 30 Jul 2007 18:09:21 -0500 Subject: [Tutor] comparing lists, __lt__ and __gt__ References: <967982.72462.qm@web35110.mail.mud.yahoo.com> Message-ID: <014c01c7d2fe$ad5c9340$29fde004@JSLAPTOP> > That having been saisd their is another use for >> which is to append > output to a file, as in: > > print 'hello world' >> myfile > > sends the string to myfile instead of to stdout. (Although I couldn't > get this to > work when I tried it!) > > Alan G. >From Dive Into Python Section 10.2 print >> sys.stderr, 'entering function' Right idea, wrong order. :-) Cheers, JS From alan.gauld at btinternet.com Tue Jul 31 00:55:56 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 30 Jul 2007 23:55:56 +0100 Subject: [Tutor] attribute error - quick addition References: <287757.75261.qm@web35115.mail.mud.yahoo.com> Message-ID: "Sara Johnson" wrote > Sorry... I'm still learning about lists, tuples, etc... Sarah, You've been hanging around with this list for a few weeks now. If you just took one day out to go through the official tutorial then you should know enough to answer all of these questions. Seriously, invest the time to learn the language and you will cut the time messing around and solve your problem a lot sooner. Hacking away in the hope of stumbling on a solution and asking questions here if it doesn't work is one of the most inefficient ways to get your job done. (Both for you and us!) We are all here to help people learn Python and answer questions but you will make it easier on all of us if you work through a tutor to get the basics clearly fixed. Not only will your problem be easier to solve but the answers we give will make more sense too! Alan G. From maseriyer at yahoo.com Tue Jul 31 02:00:42 2007 From: maseriyer at yahoo.com (Iyer) Date: Mon, 30 Jul 2007 17:00:42 -0700 (PDT) Subject: [Tutor] os.path.exists(path) returns false when the path actually exists! In-Reply-To: <46AAF697.9030402@h-lab.net> Message-ID: <980854.34139.qm@web50710.mail.re2.yahoo.com> Just to check, try to do away with the backslashes. Windows will accept a path with forward slashes just as well: os.path.exists("c:/winnt/file_name") Nope, even, with the use of forward slashes in the path, it still returns false What am I doing wrong here ? This is driving me nuts! -iyer --------------------------------- Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070730/60f97e4f/attachment.htm From sarliz73 at yahoo.com Tue Jul 31 02:11:11 2007 From: sarliz73 at yahoo.com (Sara Johnson) Date: Mon, 30 Jul 2007 17:11:11 -0700 (PDT) Subject: [Tutor] attribute error - quick addition Message-ID: <718833.20807.qm@web35102.mail.mud.yahoo.com> No luck finding tutors. I don't make enough. It seems to be this script that's throwing me off. But I understand and I'll take what I've learned to date and something will work eventually. Thanks for your concern and support. Sara ----- Original Message ---- From: Alan Gauld To: tutor at python.org Sent: Monday, July 30, 2007 5:55:56 PM Subject: Re: [Tutor] attribute error - quick addition "Sara Johnson" wrote > Sorry... I'm still learning about lists, tuples, etc... Sarah, You've been hanging around with this list for a few weeks now. If you just took one day out to go through the official tutorial then you should know enough to answer all of these questions. Seriously, invest the time to learn the language and you will cut the time messing around and solve your problem a lot sooner. Hacking away in the hope of stumbling on a solution and asking questions here if it doesn't work is one of the most inefficient ways to get your job done. (Both for you and us!) We are all here to help people learn Python and answer questions but you will make it easier on all of us if you work through a tutor to get the basics clearly fixed. Not only will your problem be easier to solve but the answers we give will make more sense too! Alan G. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ____________________________________________________________________________________ Park yourself in front of a world of choices in alternative vehicles. Visit the Yahoo! Auto Green Center. http://autos.yahoo.com/green_center/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070730/4a5e9076/attachment.html From keridee at jayco.net Tue Jul 31 03:15:18 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 30 Jul 2007 20:15:18 -0500 Subject: [Tutor] os.path.exists(path) returns false when the pathactually exists! References: <980854.34139.qm@web50710.mail.re2.yahoo.com> Message-ID: <001401c7d310$45c84a00$13fde004@JSLAPTOP> > Just to check, try to do away with the backslashes. Windows will accept > a path with forward slashes just as well: > > os.path.exists("c:/winnt/file_name") > > Nope, even, with the use of forward slashes in the path, it still returns > false > > What am I doing wrong here ? > > This is driving me nuts! Not trying to insult you, but you do realize that Windows sometimes hides file extensions right? I would assume you know that if you are in this deep, but it's better to rule out all the possibilities before doing something drastic like taking an axe to your computer. ;-) For example. mine.txt os.path.exists("c:/winnt/mine") False os.path.exists("c:/winnt/mine.txt") True JS From john at fouhy.net Tue Jul 31 02:58:34 2007 From: john at fouhy.net (John Fouhy) Date: Tue, 31 Jul 2007 12:58:34 +1200 Subject: [Tutor] os.path.exists(path) returns false when the path actually exists! In-Reply-To: <980854.34139.qm@web50710.mail.re2.yahoo.com> References: <46AAF697.9030402@h-lab.net> <980854.34139.qm@web50710.mail.re2.yahoo.com> Message-ID: <5e58f2e40707301758j1cc35936r538756456f67e20f@mail.gmail.com> On 31/07/07, Iyer wrote: > os.path.exists("c:/winnt/file_name") > > Nope, even, with the use of forward slashes in the path, it still returns > false > > What am I doing wrong here ? Type 'os.listdir("c:/winnt")' and see what it gives you. I haven't looked at the code, but I presume 'os.path.exists(s)' is roughly equivalent to 'os.path.split(s)[1] in os.listdir(os.path.split(s)[0])'. -- John. From bgailer at alum.rpi.edu Tue Jul 31 03:45:13 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 30 Jul 2007 18:45:13 -0700 Subject: [Tutor] os.path.exists(path) returns false when the path actually exists! In-Reply-To: <980854.34139.qm@web50710.mail.re2.yahoo.com> References: <980854.34139.qm@web50710.mail.re2.yahoo.com> Message-ID: <46AE9429.2070708@alum.rpi.edu> Iyer wrote: > > > Just to check, try to do away with the backslashes. Windows will > accept > a path with forward slashes just as well: > > os.path.exists("c:/winnt/file_name") > > Nope, even, with the use of forward slashes in the path, it still > returns false > > What am I doing wrong here ? Is there any chance the file has an extension that Windows is hiding? Can you get True for other files in the folder? -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From brunson at brunson.com Tue Jul 31 04:48:55 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 30 Jul 2007 20:48:55 -0600 Subject: [Tutor] attribute error - quick addition In-Reply-To: <718833.20807.qm@web35102.mail.mud.yahoo.com> References: <718833.20807.qm@web35102.mail.mud.yahoo.com> Message-ID: <46AEA317.2060408@brunson.com> Sara Johnson wrote: > No luck finding tutors. I don't make enough. Sara, Alan didn't say to find a tutor, he suggested you read a tutorial. You seem to be having problems with very basic python concepts and his suggestion was to take an hour or two and *read* some gentle introductions that will lead you through concepts like tuples and lists. Without those basic understandings you're going to continue to struggle with simple tasks. We're here to help, but the approach you're taking isn't getting you where you need to go quickly. Here are a couple of starting points: http://docs.python.org/tut/ http://www.sthurlow.com/python/ http://www.diveintopython.org/toc/index.html http://en.wikibooks.org/wiki/Non-Programmer's_Tutorial_for_Python/Contents Glance through those and pick one that looks like you're style and speed. Skim though the sections you already understand and pay more attention to the bits you don't. A little time spent up front is going to save you immense time later. Let us know how it goes. Sincerely, e. > It seems to be this script that's throwing me off. But I understand > and I'll take what I've learned to date and something will work > eventually. > > Thanks for your concern and support. > > Sara From tpc247 at gmail.com Tue Jul 31 05:32:55 2007 From: tpc247 at gmail.com (tpc247 at gmail.com) Date: Mon, 30 Jul 2007 20:32:55 -0700 Subject: [Tutor] passing form data into a class Message-ID: dear fellow Python enthusiasts, let's say I have a dictionary of keys and values obtained from a form submitted by a user. For each submitted form I will create the Application and Candidate classes, and I want to be able to call Application(Candidate(**submitted_data)).display() to create an html representation of the user submitted data. Depending on the applicant's preferences and location, the number of fields on the form, and thus the size of this dictionary, is variable, and not all fields are required. I seem to recall a setargs function in Python that would take any argument passed into a class and set that argument as a member variable in a class. A Google search turned up no such construct, so here I am asking you, is there a way for me to create a class that accepts a dictionary of submitted data and uses each key ad value to create a corresponding member variable ? The current way I do this is with a very long argument list, and line by line: class Candidate(object): def __init__(self, full_name, address_line_1, city, postal_code, email, desired_program, telephone=None, disabled=None, can_receive_media=None, media_sent_to=None, ...): self.full_name = full_name self.address_line_1 = address_line_1 self.city = city self.postal_code = postal_code self.email = email self.desired_program = desired_program class Application(object): def __init__(self, candidate): self.candidate = candidate def display(self): pass -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070730/c0e3f183/attachment.html From john at fouhy.net Tue Jul 31 06:27:59 2007 From: john at fouhy.net (John Fouhy) Date: Tue, 31 Jul 2007 16:27:59 +1200 Subject: [Tutor] passing form data into a class In-Reply-To: References: Message-ID: <5e58f2e40707302127j29416a5cved2b9ade63708960@mail.gmail.com> On 31/07/07, tpc247 at gmail.com wrote: > is there a way for me to create a class that accepts a dictionary of > submitted data and uses each key ad value to create a corresponding member > variable ? The current way I do this is with a very long argument list, and > line by line: > > class Candidate(object): > def __init__(self, full_name, address_line_1, city, postal_code, email, > desired_program, telephone=None, disabled=None, can_receive_media=None, > media_sent_to=None, ...): > self.full_name = full_name > self.address_line_1 = address_line_1 > self.city = city > self.postal_code = postal_code > self.email = email > self.desired_program = desired_program The setattr() function is probably what you remember. You could write something like: for var in ['full_name', 'address_line_1', 'city'] # etc setattr(self, var, locals()[var]) You could even write: for var in locals(): setattr(self, var, locals()[var]) but what you gain in convienience you lose in clarity, and possibly safety if you aren't careful.. -- John. From kent37 at tds.net Tue Jul 31 13:44:47 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 31 Jul 2007 07:44:47 -0400 Subject: [Tutor] passing form data into a class In-Reply-To: References: Message-ID: <46AF20AF.7020902@tds.net> tpc247 at gmail.com wrote: > dear fellow Python enthusiasts, let's say I have a dictionary of keys > and values obtained from a form submitted by a user. For each submitted > form I will create the Application and Candidate classes, and I want to > be able to call Application(Candidate(**submitted_data)).display() to > create an html representation of the user submitted data. Depending on > the applicant's preferences and location, the number of fields on the > form, and thus the size of this dictionary, is variable, and not all > fields are required. I seem to recall a setargs function in Python that > would take any argument passed into a class and set that argument as a > member variable in a class. A Google search turned up no such > construct, so here I am asking you, is there a way for me to create a > class that accepts a dictionary of submitted data and uses each key ad > value to create a corresponding member variable ? I occasionally find this handy: class Bunch(object): ''' A container for data that supports attribute access. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 ''' def __init__(self, **kwds): self.__dict__.update(kwds) def __repr__(self): state = ["\n %s=%r" % (attribute, value) for (attribute, value) in sorted(self.__dict__.items())] return self.__class__.__name__ + ':' + ''.join(state) Kent From dkuhlman at rexx.com Tue Jul 31 18:09:46 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 31 Jul 2007 09:09:46 -0700 Subject: [Tutor] passing form data into a class In-Reply-To: References: Message-ID: <20070731160946.GA61994@cutter.rexx.com> On Mon, Jul 30, 2007 at 08:32:55PM -0700, tpc247 at gmail.com wrote: > dear fellow Python enthusiasts, let's say I have a dictionary of keys and > values obtained from a form submitted by a user. For each submitted form I > will create the Application and Candidate classes, and I want to be able to > call Application(Candidate(**submitted_data)).display() to create an html > representation of the user submitted data. Depending on the applicant's > preferences and location, the number of fields on the form, and thus the > size of this dictionary, is variable, and not all fields are required. I > seem to recall a setargs function in Python that would take any argument > passed into a class and set that argument as a member variable in a class. > A Google search turned up no such construct, so here I am asking you, is > there a way for me to create a class that accepts a dictionary of submitted > data and uses each key ad value to create a corresponding member variable ? > The current way I do this is with a very long argument list, and line by > line: You have already gotten one good solution from Kent. But, depending on your needs, you might also focus on the request side rather than on when the class or instance is created. That might enable you to add a bit of the security checking that Ken Fouey was concerned about. Here is an example of a class which looks a name up in a dictionary when the attribute is requested. It does not create attributes for the keys in the dictionary: class Bunch(object): def __init__(self, vardict=None): if vardict is None: self.vardict = vardict else: self.vardict = vardict def __getattr__(self, name): if name in self.vardict: return self.vardict[name] else: raise AttributeError, 'Bunch has no attribute: %s' % name def test(): d = {'aaa': 111, 'bbb': 222, } b = Bunch(d) print b.aaa print b.ccc test() Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From brunson at brunson.com Tue Jul 31 18:47:44 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 31 Jul 2007 10:47:44 -0600 Subject: [Tutor] passing form data into a class In-Reply-To: <20070731160946.GA61994@cutter.rexx.com> References: <20070731160946.GA61994@cutter.rexx.com> Message-ID: <46AF67B0.5060400@brunson.com> Dave Kuhlman wrote: > On Mon, Jul 30, 2007 at 08:32:55PM -0700, tpc247 at gmail.com wrote: > >> dear fellow Python enthusiasts, let's say I have a dictionary of keys and >> values obtained from a form submitted by a user. For each submitted form I >> will create the Application and Candidate classes, and I want to be able to >> call Application(Candidate(**submitted_data)).display() to create an html >> representation of the user submitted data. Depending on the applicant's >> preferences and location, the number of fields on the form, and thus the >> size of this dictionary, is variable, and not all fields are required. I >> seem to recall a setargs function in Python that would take any argument >> passed into a class and set that argument as a member variable in a class. >> A Google search turned up no such construct, so here I am asking you, is >> there a way for me to create a class that accepts a dictionary of submitted >> data and uses each key ad value to create a corresponding member variable ? >> The current way I do this is with a very long argument list, and line by >> line: >> > > You have already gotten one good solution from Kent. But, > depending on your needs, you might also focus on the request side > rather than on when the class or instance is created. That might > enable you to add a bit of the security checking that Ken Fouey was > concerned about. > > Here is an example of a class which looks a name up in a dictionary > when the attribute is requested. It does not create attributes for > the keys in the dictionary: > > class Bunch(object): > def __init__(self, vardict=None): > if vardict is None: > self.vardict = vardict > else: > self.vardict = vardict > def __getattr__(self, name): > if name in self.vardict: > return self.vardict[name] > else: > raise AttributeError, 'Bunch has no attribute: %s' % name > Since this is tutor, I'll add my $.02... Kent's version of Bunch is great, I use that sort of definition all the time in my code when I want to use "instance.thing = blah" to save typing and make my code more readable, but also want to use dict nomenclature for iteration over keys, etc, rather than "getattr( instance, key )," again, primarily for neatness of code. However, this version from Dave has the advantage of segregating your "special data" from the regular class attributes. If you wanted to, for example, keep a count of the number of form keys that were passed into the form, you couldn't store that in an instance attribute without it getting mixed up with all your form variables. I'm not saying either is better than the other overall, they each have their place and I use both, but in this *specific* case, I think you'd want to use Dave's version. Just my opinion, I could be wrong. :-) e. > def test(): > d = {'aaa': 111, 'bbb': 222, } > b = Bunch(d) > print b.aaa > print b.ccc > > test() > > Dave > > > From slewin at rogers.com Tue Jul 31 23:36:10 2007 From: slewin at rogers.com (scott) Date: Tue, 31 Jul 2007 17:36:10 -0400 Subject: [Tutor] Which GUI? In-Reply-To: <002001c7d0ad$034ac5a0$4cfce004@JSLAPTOP> References: <002001c7d0ad$034ac5a0$4cfce004@JSLAPTOP> Message-ID: <46AFAB4A.2020103@rogers.com> Hi, I have been doing some research on the GUI's and noticed it is a very difficult choice to make which one to write with. It seems to be even more difficult than choosing which programming language to use. If you don't mind I have a few questions to ask about selecting the right GUI to program with. 1: I know many people suggest learning more than one programming language when writing programs and use each programming language like a tool on a toolbox. Should one also learn more than one GUI and select the correct one for each individual program? 2: How have you come to select your favourite GUI(s)? 3: Is there a GUI that is better for developing for Linux? 4: I have read that WxPython is difficult to install on Linux from a couple different sources. I have personally never found that a problem. Is this true? Is WxPython a poor choice for a Linux developer? Thank you for any help you can give me :) -- Your friend, Scott Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn)