Re: [Tutor] Money matters
> Should I simply run the results of all calculations through something > like this: > > from __future__ import division > ... > ... > s=(int(round(s, 2)*100))/100 > > Or should I be using Decimal on all money calculations? Firstly - that does not magically fix the imprecisions in floating point numbers. If that would work, it would be hardcoded into the interpreter, no? I think that Decimal is the way to go here, but you do have another option. Whenever you put in a number, remove the decimal point and store it as an integer. Do all of you calculations with integers. Every time you have to display a total, convert it then (but don't overwrite the variable! Convert a temp) Obviously this is a tough way to go in an easy language like python. That is a solution I am considering using C. (I might just make it too..) That's why I encouraged Decimal. If you're interested in the integer representation of floats, like this particular efficiency & precision demon (me!), then you will have to work out ways to multiply and divide using pseudo floats... Not too difficult. Say you want to multiply an integer against say 5.5 %. Multiply the total by ten, 55, then divide by a 100. In that order. Of course you will still have problems. For example do it over and over and you will overflow your integer, but nevermind. Am I rambling? Ooops. HTH, tiger12506 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Here's what you need
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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Automating Windows (Maintenance)
> "Daniel McQuay" <[EMAIL PROTECTED]> 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. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how long?
> 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@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. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How can I escape a pound symbol in my script?
> 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. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with translating a c function to a python function
>> 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 = 0110i.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@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fastest way to iterate through a file
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@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] I/O error (?)
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about code reviews
>> >> > 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? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
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@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class question
> === > 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] interpreter restarts
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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class question
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class question
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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] curses
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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] interpreter restarts
> 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\{3184-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... {3184-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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] curses
> 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!!! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading random line from a file
Perhaps ~this~ is what you are worried about performance-wise? Image NameMem Usage - python.exe11,096 K That's not too bad considering ~this~ explorer.exe 14,356 K svchost.exe24,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 = 10 > while x > 0: >f.write("\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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tutor
> 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) ### ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading random line from a file
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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] interpreter restarts
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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] IDLE Usage - was Interpreter Restarts
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading random line from a file
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
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 <[EMAIL PROTECTED]> 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@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File parse
> 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? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File parse
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File parse
>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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading random line from a file
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) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading random line from a file
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Working with bash (subversion)
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Image library
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@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Image library
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] if and things
> man that looks totally pythonic. What you had is correct though. Good job. JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] if and things
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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading random line from a file
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] about importing a module
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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] about importing a module
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@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python: how do I create a list of definitions?
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] about importing a module
>> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] another question ( unrelated )
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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generators
> 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 2890035288 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generators
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python program design
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading random line from a file
> 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]) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python program design
>> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Text matching and replacing
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: Version: 3351 SpecId: Specification--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: Version: 3351 SpecId: Specification--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@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Logging module
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Text matching and replacing
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sum of Scores
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Livewires questions
> 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" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sum of Scores
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@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] function declaration problems perhaps?
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What exactly is [::-1]?
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sum of Scores
Hmmm... interesting tie to another post... >>> x = timeit.Timer('random.random()','import random') >>> x.timeit(300) 1.0161026052194018 >>> y = timeit.Timer('random()','from random import random') >>> y.timeit(460) 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 "NOOO" 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.
Re: [Tutor] Shelve del not reducing file size
> ...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. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Shelve del not reducing file size
>> 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 S simple. JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which GUI?
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.path.exists(path) returns false when the pathactually exists!
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] putting python to use
>> >> /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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sum of Scores
>> > 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sum of Scores
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
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@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] comparing lists, __lt__ and __gt__
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.path.exists(path) returns false when the pathactually exists!
> 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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] C program
Hello people of the world. This question is not a Python related question, but I thought I might just throw it in here and see if there are any C old-timers who could help out. I have a string with space and I would like to remove the space before comparing but I don't know how to go about doing it. Here is the code int result = strcmp("yes","yes ");//trailing space on the second yes this should give me '0' meaning they are both the same, but with the space, it gives me '-1' Please note: those arguments can be supplied by the user, and when they do, I want to strip off the trailing space. Any helps is highly appreciated. - I doubt if this is the best way, but you can do this. /*--*/ #include #include char s[20] = "yes"; char s2[20] = "yes "; void rstrip(char *c) { while (*c++!=0); c--; while (*--c==' ') *c = 0; } int main() { rstrip(s2); int result = strcmp(s, s2); printf("%d\n",result); system("pause"); } /*--*/ JS PS - This *is* a python list. Usually the tutors don't like people who post off-topic stuff. (And C is pretty off-topic) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.path.exists(path) returns false when the path actually exists!
> I have never understood Microsoft changing things from one release to > another. In the beginning extensions were IIRC always visible. > > Every time I configure a computer I have to spend a lot of time undoing > the initial settings so my users can get their work done! Even though I completely agree with you and detest Microsoft's decisions in these matters, here are the basic reasons: Computers are becoming more and more available for use amongst non-tech-savy individuals. Individuals who previously did not have to work with computers may now have to use them in their job for whatever reason. Microsoft would make less money if so called non-user-friendly attributes remained in their operating system. Consider: A potential computer user looks at the listing in a folder. Not quite understanding why things look the way they do, not quite understanding how these so called folders and files are supposed to look like the old paper file cabinet systems that they are used to. He sees these files with periods and strange letters. What do they mean? A file extension? What?! I don't get it, he says. You explain that the letters tell Windows which program is supposed to open the file. That doesn't make sense to him. He wonders why Windows can't just see that this is a spreadsheet, I mean look at it. It's obviously a spreadsheet! So to circumvent this confusion they hide the file extensions. Consider some other UI changes. The places bar, for example. Most programs save documents in My Documents. So where is it? Most people don't realize where they are. The file cabinets that they knew had folders yes, but never folders within folders. So Microsoft, in order to aid the new computer user provided a flattened view so that they could more easily find and understand where they are. Granted, all of these are just visual sugar and are completely worthless. But they have provided Microsoft with much money because more useless people can use computers. It is because these people do not wish to learn, do not have the capacity, or just plain would rather pay through their teeth. They would rather have Microsoft make obfuscate things, to make it "easier" for them, than to try to understand themselves. JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.path.exists(path) returns false when the path actually exists!
>> Granted, all of these are just visual sugar and are completely worthless. >> But they have provided Microsoft with much money because more useless >> people >> can use computers. It is because these people do not wish to learn, do >> not >> have the capacity, or just plain would rather pay through their teeth. >> They >> would rather have Microsoft make obfuscate things, to make it "easier" >> for >> them, than to try to understand themselves. >> >> JS > > Why are you making out people and Microsoft in such a negative way? > Also, how is it "harder" for them when things like file extensions are > obfuscated? They would rather have Microsoft obfuscate things, to make it "easier" for *the people* not Microsoft. Why am I being negative about it? Very simply: The necessary code and provisions it takes to implement UI devices like Hiding file extensions is a waste of space, time, resources, and too many other things to count. Windows Vista is the newest OS out from Microsoft. One look at the size of the installation should be enough to tell anyone that enough is enough. Another problem I have with Windows is the paradigm "There are only 500,000 ways to do it." For example, you can change network adapter configuration by going to Control Panel, by using the SysTray icon, by using the StartMenu shortcut, by navigating to the program itself, by using Device Manager, add especially dangerous - indirectly by using the network setup wizard, etc. All of these routes waste space, and only provide minimal advantage, but manage to provide serious breaches of understanding. I know I am not the only one who has tried to find why a network adapter doesn't work, only to find that an important setting was comprimised when running one of the handy "It does everything!" UIs. I don't know if you are one of those people that loves those all-in-one screwdrivers, but I find that pieces of them get lost, they are bulky, and when it comes right down to it, all I want to do is use the simple, light, and specialised screwdrivers. Why? Because they are faster, stronger, and more stable. Is that good enough? Why am I upset with people? Because they want "ease of use", I must buy bigger hard drives, and more ram. Because Microsoft has determined that media is more important to the mass population than performance, I have to fight to get my Windows installation to stop initiating the time-consuming Autoplay feature, or I have to jump through hoops to cut off the Windows Messenger just because I don't want to use it. Or I have to search through numerous wizards and settings to try to find where I can shut-up Windows Update. Yes, maybe I want it to update, but I don't want it to bother me! I have work to do. No I don't need "troubleshooting help". Give me a damn RFC. No, there is no big massive error, I just need to find where my program is using an invalid pointer. Why can't these changes be something useful? A great example. Such and such module is linked to missing export such and such. Okay. But you are preventing me from using the program! The Windows Loader provides API addresses at load time anyway, so why isn't there an option to redirect the API? It would take a hell of a lot less resource space than implementing some of the visual junk that makes "managing media" "so easy". I apologize for my bringing up these beliefs on this list. They are better placed in a blog somewhere, or more efficiently, in a zip file of ASCII text as small and as neat as possible. JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [OT] Re: os.path.exists(path) returns false when the path actually exists!
>> But they have provided Microsoft with much money because more useless >> people can use computers. > > That's a little harsh, isn't it? A person using a computer is not useless > by virtue of not wanting to program or understand technical details, but > rather just wanting to use it for its functional purpose. There are > people in my Finance department who know much more about finance than I > do, and more, I suspect, than you do. They are very useful to me and my > employer by virtue of that knowledge, and if some of them don't know > about Microsoft Windows file extension, well, quite frankly, who cares? > They know what's important. Very well. > I don't want to have to know the details of what makes my car run. All I > want to do is drive it from one location to another. And one day your car doesn't start. So you blindly take it to a car mechanic (or even the dealership~shudder) where they hook it up to a battery charger, send it back and charge you $300. Right. Not important to you. I wish I could throw away that kind of security. >> It is because these people do not wish to learn, do not have the >> capacity, > > Why should they have to learn? They just want to use the spreadsheet, for > example. Why should they have to learn that the magic sequence of ".XLS", > when appended to a file name, make the file work a certain way? In most > contexts, the name of a thing does not determine how it works. The name > is just a name. Why? Because it's a good idea. The name of the thing does not determine how it works. But it does determine how it works in Windows. I do not expect them to understand *why* the magic sequence of .xls causing this file to open in Excel. I expect them to overlook it. I expect them to accept them. I do not think it's appropriate that Microsoft should baby them by hiding the extensions by default. > I suppose I could have a television that would require me to know to tune > it to a frequency of about 69Mhz to watch a particular program; but it's > just so much more convenient to me to turn to channel 4. I see that > hiding of the technical details as an improvement, not a hindrance. Did I say I wanted people to know just what extension is what? Did I say that they have to parse the .xls file for Excel? No. I ask that they learn to accept it. Just like I would ask them to accept a slip of paper taped to the TV that lists all of the frequencies mapped to the channels. I would not ask them to use the table of frequencies to tune the TV. They may use the channels. But the table would be there, visible, not hidden away where potentially someone who needs it might not be able to find it. On the other hand, do you want a neural transmitter installed in you so that you can more easily change the channel? Hey ~ you wouldn't even have to know which channel you want to watch. All you would have to do is know *what* you want to watch. Wouldn't that be excellent? It's like looking all over the living room for the TV remote because you don't know how to change the channel using the TV. > Why should people adapt themselves to software instead of having the > software adapt to them? I'm cribbing a bit from George Bernard Shaw here, > who wrote something like, "The reasonable man adapts to the world; the > unreasonable man adapts the world to himself. Therefore, all progress > depends on the unreasonable man." Why should computer people have to adapt to user-friendly software? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which GUI?
I did that once for a very good fiction book I wanted to read. <$2. for transfer. It was worth it to me. Agreed. Definitely a good system. JS > On Thu, Aug 02, 2007 at 12:48:05PM -0400, scott wrote: >> >> We do have a inter-library exchange here as well, but I have never used >> it and don't know much about it. I'll take a trip to the library >> sometime to ask. >> > > For sure, even if you *don't* need the wxPython book, check into > the inter-library or inter-branch transfer program. And, also ask > about Internet access. Here in Sacramento, California, USA, when I > need a book, my first action is to go to http://saclibrary.org/ and > do a search. If the book is not at my local (small) branch library > but is in the Sacramento county library system, I click on request > and tell them which branch to deliver it to. I believe that they > have a truck that is constantly traveling between branches to > deliver the inter-branch transfers. It's a super system. > > I visited the libraries in Vancouver, B.C. and Victoria, B.C. > several years ago, and they were at least as advanced as ours here. > Be sure to check that out. Wherever you are in Canada, be sure to > check into it. > > By the way, my librarian tells me that they do this because it both > saves them money (by not having to have copies at all branches) and > enables them to afford to offer more titles. > > (Sorry for off-topic post. I'm a library "true believer".) > > Dave > >> -- >> Your friend, >> Scott >> >> Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) >> ___ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > > -- > Dave Kuhlman > http://www.rexx.com/~dkuhlman > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Editors .. which do you reccomend for a amateur?
It is found in python25\lib\site-packages\wx-2.6-msw-unicode\wx\py pyAlaMode.py I'm sure there are shortcuts, but that's where it is. JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Ingenious script (IMO)
Nice idea. Written style is average. Other tutors have discussed issues with performance, style, etc. I thought I would mention that whenever I am asked to give my opinion on a script, I compare it to something I have written/would write. In this case, I have already written. In my version, it not only tells how many of each denomination, but also how one would count back the change. It would be an interesting challenge to implement that, no? ;-) JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Ingenious script (IMO)
> The modern way seems to be to look at the change amount given by the > cash register and count that out starting with dollars... So true... tsk tsk. That's because the teenagers that give you the change do not know how to count it back. What a great idea to write a program that can show them how! Or perhaps the excuse is more the truth - it's faster to throw the change at you. I know that many old-timers would be very impressed to have their change counted back to them. (It's required sometimes-my father told stories of a blind man that knew how much money he had and where in his wallet it was by how the cashier counted it back). I imagine that however exactly it is phrased when you count back change is dialectual. Some people do it some way, some do it other ways. In my part of the US, the "proper" way is: $10.00 Say "5.77" "3 makes 80" "20 makes 6" "and four makes 10 dollars" "Have a nice day" While handing out the described amount at each line break. Sometimes, especially in important applications, like in a bank, they will count and hand the bills out to you individually - i.e. "and one, two, three, four makes 10 dollars" Of course, the "have a nice day" is optional, but it makes a nice touch ;-) Among the elders, it is considered very courteous to count back the change, but so often this is not the case that it is no longer considered rude to skip the counting... Anyway, the python part of this discussion is to point out that the method varies, so it would be even more of a challenge to provide options for how the change should be counted. JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] superscript with easydialogs
> It turns out, no, Unicode won't work, but using x\99 for the TM character > does, at least on my system (no idea if this will be universal): That's strange. Windows is Unicode based! All text operations done in Windows are first converted to unicode, calculated, and then back. That's even been mentioned on this list... ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Checking for custom error codes
> Traceback (most recent call last): > File "domainspotter.py", line 150, in >runMainParser() > File "domainspotter.py", line 147, in runMainParser >td.run() > File "domainspotter.py", line 71, in run >checkdomains.lookup() > File "domainspotter.py", line 108, in lookup >from rwhois import WhoisRecord, NoSuchDomain > ImportError: cannot import name NoSuchDomain > > Maybe I need to import something else to be able to throw it. > > I think if someone can explain a more general form of this I would be on > better footing: To use a custom error code (from a module) in a loop or > anywhere else, do I need to import the code itself? I had assumed that > once I imported the module that defined the error code, I could catch it > just like a core Python error code. The problem is evident. The name NoSuchDomain is not defined. It is not a variable. It is just a string. When you call an error like this raise 'NoSuchDomain', it's called something - don't know what (string exception?) - but as you found out, that method of raising errors is now frowned upon (deprecated). The way you are supposed to raise errors is to create a new class, subclassing Exception. Then you would be able to catch it by variable name as you are trying to do with the import. But you certainly can't import a constant string! It's like trying to import the contents of a string variable, instead of the variable itself. Again, the problem is deprecation, the rwhois will eventually have to be re-written so that it uses exception classes, instead of just raising string errors. JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Checking for custom error codes
> This is exactly what I needed, awesome! Looks like this is what you were > saying to do?: > http://docs.python.org/tut/node10.html#SECTION001050 Why ~ exactly! A link tells a thousand words. (Or maybe more.) So does that mean that a link is inherently more valuable than a picture? ;-) JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to sort a dictionary by values
> Just curious: Is there a reason to use __getitem__() over itemgetter (used > in the example in my reply)? __getitem__ is a method builtin to a dict object. itemgetter 1) has to be imported 2) is more generically used, therefore probably using a more generic/slower algorithm JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] WinPdb?
> Dick Moores wrote: >> (I posted this to the python-list 24 hours ago, and didn't get a >> single response. How about you guys?) > You mean this list? Cause if you mean this list, then you didn't post > it correctly. I don't believe he did. There are seperate python-lists, comp.lang.python, one actually called python-list I believe, and besides, since he specifically said "How about you guys?" as in let's try someone else - I think he didn't mean this list. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Losing the expressivenessofC'sfor-statement?/RESENDwith example
It seems this is a delightful exchange of rude threats and insults. ;-) My question is: If you love C syntax so much, why don't you program in C and leave us python people alone? And also: It is not the responsibility of the docs to ease the way for C programmers. That is what a specific tutorial is for. The docs are there for the sole purpose of teaching you how to program in python. That is - how you *think* in python. The reason for loops are not the same in python as they are in C is because they are not the same language. You are supposed to write things differently in python than in C (because they are different languages), and the fact that you don't seem capable of doing that tells me that *you* sir are inferior, not python's for. I certainly would not expect to go to Spain, tell them their language is inferior, and then ask them to make concessions for English speakers. JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Security [Was: Re: Decoding]
> foo = raw_input(...) > x = eval(foo) > > Is an exception, in almost[*] every scenario I can think of. (and is the > context eval was being used as far as I can see without reading the whole > thread) > > [*] One scenario that seems unlikely but possible is a scenario where a > machine has been put into a form of kiosk mode where the *only* > thing > they can do is type responses to the raw_input prompt. Given where > raw_input runs, this strikes me as highly unrealistic/unlikely. > > Why? Because if they can type on the keyboard of a machine that's running > raw_input they have the ability to do far more damage that way than any > other. (ability to use a real sledgehammer on the machine springs to mind > :-) Let your program run on your machine and I'll walk by, type in this string, and hit enter. We'll see how much of an exception it is when you can't boot your XP machine anymore. ;-) "file('boot.ini','w').close()" Of course, x would be set to None (the return value of the file method close()), but the damage is already done. btw - that *one scenario* happens a lot more often than you think. For example, you write a library. It doesn't have to be raw_input. You could get that string from anywhere. A text box, a username. A registry value!! If your program uses eval on a registry string, someone could set that key before hand to something similar to above. JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Security [Was: Re: Decoding]
> On Monday 13 August 2007 22:39, Tiger12506 wrote: >> > foo = raw_input(...) >> > x = eval(foo) >> > > ... >> Let your program run on your machine and I'll walk by, type in this >> string, >> and hit enter. We'll see how much of an exception it is when you can't >> boot >> your XP machine anymore. >> ;-) > > Who cares? I don't run XP :-D I'm sure the equivalent can be done on different operating systems. > Also, a broken XP machine is an opportunity anyway, not a problem. Agreed. > Seriously though, if typing: > >> "file('boot.ini','w').close()" > > Into an "eval prompt" worked then equally leaving a python interpreter > open > would be dumb, let alone a console. It does work. Try it with a simple file "temp.txt" for example. You can run any function call if the string is parsed with eval. Notice I did not say "type into an eval prompt type loop" I mean entirely if the string is parsed with eval. > Oddly my desktop machine often has a shell open, and often has a python > interpreter running as well. Indeed at present it has 11 shells open. The > non > graphical console is a root shell (accessible by alt-f1). My work machines > likewise have around a dozen shells open each. > > However, when I leave my machine alone the display locks itself, and its > normally behind a locked door (unless I'm with it). > > Quite frankly anyone getting worried about this: > >> > foo = raw_input(...) >> > x = eval(foo) > > Is pretty over anxious IMO. "Gosh, the person at the console might be able > to > get python do something which they can do anyway". Again. Anytime the function is parsed with eval, you can run *any* python function that is in the scope that the eval function is being executed from. Security risks are never simple. Of course they can do it with a python console window open. But if you are worried about security you don't allow them access to the python console. You ecapsulate it. But what if you use eval in a library function you write, which is used to parse some input? Peer to peer networks, http servers, even text files that you try to parse could be corrupted to cause your computer damage. The point is that eval is a security risk "greater than other implementations" that is-using int() is much more secure than eval(). > (This is rather distinct from taking random crap from someone not on the > local > console and just doing it (eg from a network connection/external > resource)) > > If the user wishes to trash their own machine, using an eval prompt is a > rather bizarre way to go about it. Sometimes it's not what they want to do. Kiosks centers are a good example. But if you parse a text file that you haven't reviewed... that's possible. Not likely. But possible. It's along the same lines as buffer overruns. It's possible. Not as likely. But possible. JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Security [Was: Re: Decoding]
The point is that even though eval(raw_input()) is not a security threat, Alan's suggestion of myscript.py < some.txt might be. And even though the script written will not be a security issue, the *coding practice* that it teaches will lead to times when he does encounter that "tiny set of scenarios" in which the input for the script is potentially untrustworthy. Even though the risk is perhaps minimal to you, it still needs to be made known. An analogy is the threat of mercury, in which breathing the vapors can cumulatively lead to brain damage. However, in most quantities that people are freaking out over are far too small to be a threat. Don't go overboard, and yet *know* what is out there. I'll give an example. The boss gives two employees the simple jobs: You~ write a function grapher And You~ write an input file that graphs the common mathematical functions so that it can be run in his~ function grapher. The first guy uses eval to parse the text file because of its power. All he has to do is graph, eval takes care of turning the lines from the text file into function objects. The second notices the first guy's approach and sees a chance to move up in the world. He writes his file to his advantage. The two put the final result together and show the boss. The computer destroys important data that the company has worked on (not protected by the OS) and the first guy is fired because *his* program deleted stuff. Ouch. Be aware of security risks, not infatuated by them. eval() is not a risk by itself, but getting used to using it could lead to problems. Subtle things will always bite you more than things of which you are completely aware. JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class Attribute "Overloading?"
> Sorry about that. I want something like: > > class foo: > >def __init__(self): > > self.attr1 = None > > >def get_attr1(self): > > if not self.attr1: > > attr1 = > > self.attr1 = attr1 > > return self.attr1 > > > such that: > > foo_instance = foo() > > then: > > foo_instance.get_attr1() > > and > > foo_instance.attr1 > > gets the same value. > > Such that you get to derive attr1 only as needed and just once, both > outside > and within foo class. > > Or is it a bad idea or just plain ugly to do something like that? If it > is, > kindly suggest better approach. > > Thanks. It's a little ugly but not too bad. What you are describing are properties. class Foo: def _get_attr1(self): if not self.attr1: attr1 = TheValue return attr1 def _set_attr1(self, value): self.attr1 = value ChangeDBFunction(value) attr1 = property(self._get_attr1,self._setattr1,None,None) I think that will work. The docs seem to suggest that you should subclass `object`. JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] open multiple files
> Hi everyone - > I'm beginning to learn how to program in python. I need to process > several text files simultaneously. The program needs to open several files > (like a corpus) and output the total number of words. I can do that with > just one file but not the whole directory. I tried glob but it didn't > work. Your ideas are greatly appreciated. Thanks, > Paulo What do you have so far? I don't just want to give you an answer. You say that glob didn't work... Probably because you are not realizing that glob returns a list of filenames, and you can't open a whole list at a time. You'll have to use a loop or something similar. JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] manipulating data
If you run this code # f = open('test1.mlc') for line in f: print f.split() # You will see that about halfway through the file there is an empty list. I assume that there was nothing on that line, in which case, there is no [0] value. In which case, you need to put in a try: except IndexError: block like this~ f = open('test1.mlc') fields={} for line in f: try: words = line.split() firstword = words[0] except IndexError: continue if firstword == 'Field': field = int(words[-1]) elif firstword == 'Leaf': fields[field] = words[-1] You will notice I made a few other changes. I changed it so line.split() is assigned to a variable. That means I don't have to make the split() call every time I want to check for a different word. The try except block just fixes the problem you encountered. Also, I took out the last block-the else block-because it is not necessary, and in fact will cause what you would consider an error in the program. Calling f.next() will increment the line, yes, but that is exactly for what the "for loop" is intended. The natural conclusion of the for block is "finish the elif test and its block, then execute code after it. Since there is no code after it indented to that level, it automatically increments 'line' (line = f.next()) HTH, JS - Original Message - From: "Bryan Fodness" <[EMAIL PROTECTED]> To: "Alan Gauld" <[EMAIL PROTECTED]> Cc: Sent: Monday, November 12, 2007 2:43 PM Subject: Re: [Tutor] manipulating data >I try this, > > f = open('TEST1.MLC') > > fields = {} > > for line in f: >if line.split()[0] == 'Field': >field = int(line.split()[-1]) >elif line.split()[0] == 'Leaf': >fields[field] = line.split()[-1] >else: >line = f.next() > > and get, > > Traceback (most recent call last): > File "", line 1, in >line.split()[0] > IndexError: list index out of range > > I have attached my data file. > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Memory consumption question
> OK, the analogy is cute, but I really don't know what it means in > Python. Can you give an example? What are the parts of an old-style > class that have to be 'ordered' separately? How do you 'order' them > concisely with a new-style class? > > Thanks, > Kent He is setting up the analogy so that python is the waiter (or waitress) taking the order. A "Reuben" in this case is a new-style class, whereas the whole list of sandwich components is also a reuben but expressed in old style class language. So, basically, he's saying that new style classes have more initial components but take up less room than old style classes because the waitress has less to write on her notepad. As for what has to be ordered seperately, he is treating the concept of a class abstractly as a sandwich. So he's saying that python has to "write less on the order pad" in order to create a new-style class because it's been restructured like that, whereas python writes all the stuff down, even for an empty class. Whether that's actually true or not, i do not know. I personally cannot imagine that a simple restructuring of classes can make that drastic a change. Here's the only way I can imagine it - in C++. C++ comes with virtual methods, i.e. methods of a base class that can function properly if the child does not provide that method in its definition. So I presume that he is thinking along the lines of old-style classes are C-structured based, whereas new-style classes are C++ based (even if they're not written in C++) with virtual methods - where you only need one copy of the methods in memory for all new-style classes. Maybe I'm way out in left field. I do not know. That is one explanation that I have provided myself so that I feel I have an understanding. Interpret it as you will. JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fw: Wrong version of Python being executed
I haven't seen anybody write down the full picture so that we are not misled. Windows chooses which python to use in this manner. 1) If you double click on a .py file in windows, it looks in the registry for the command string that pertains to "open". The .py extension has a default value that tells which type of file it is, this 'type' has it's own seperate command for "open" (So 'txtfile' will have a different open command than 'mp3file', for example.) If in the command interpreter (sometimes inaccurately called a dos box) you type the name of the .py file (WITHOUT typing python), then windows will open it with whatever value is in the registry, just as if you had double clicked it in explorer. 2) However, if you type python before the script name, then windows checks first a) in the directory that the prompt is at b) checks in each directory in the PATH environment variable for an executable named python.exe and uses that I have not found that the PYTHONPATH environment variable has any effect (which i doubt it would, as windows does not make a special case to check it before hand, and I doubt that python.exe will check that environ var and spawn the proper version before it runs the script) I am absolutely certain that the #! at the beginning of the python file does NOT work in windows, it is strictly a *nix thing. There are many solutions to this, my favorite being where one adds an extra entry to the sub menu of the .py file. Effectively what happens is that another key and value is added to the registry, providing an alternate command string for "open" If you go to control panel->folder options->file associations and choose py file and click advanced, there should be an option to add another "verb" i believe they call it. So add one and call it open w/23 or something to distinguish it from regular "open" and put in the command box the full path of the python exe, followed by "%1" with quotes, so that when you choose that menu option it will run that particular python and send the name of the file through %1 so it is passed in as the argument. Then, when you want to run it with your default python, you right-click->open. When you want to run it with the different version, right-click->open w/23 or whatever you called it. hope this helps JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List processing question - consolidating duplicateentries
> s=set() > [s.add(tuple(x)) for x in myEntries] > myEntries = [list(x) for x in list(s)] This could be written more concisely as... s = set(tuple(x) for x in myEntries) myEntries = [list(x) for x in list(s)] Generator expressions are really cool. Not what the OP asked for exactly. He wanted to eliminate duplicates by adding their last columns. He said the last column is a number of hours that pertain to the first four columns. When you apply your method, it will not get rid of duplicate projects, just circumstances where the number of hours is equivalent also, and of course, not add the hours like they should be. I like the dictionary approach for this personally... di = {} for x in myEntries: try: di[x[:3]]+=x[4] except KeyError: di[x[:3]] = x[4] This can be written even smaller and cleaner if you use the default value method... ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Variables and Functions
Sounds like an excuse for a global (aggh!) variable. Or more properly, wrap all of the relevant functions in a class and use a class variable for your puzzle - Original Message - From: "Devon MacIntyre" <[EMAIL PROTECTED]> To: Sent: Wednesday, November 28, 2007 4:00 PM Subject: [Tutor] Variables and Functions > Hi, > Just wondering, how would I get a variable out of one function and into > another? I'm trying to make a Sudoku puzzle for Python 2.5.1, and in one > function I have the finished puzzle (as a matrix) called 'puzzle'. Using > the > 'copy' module I made a deep copy called 'new_puzzle'. That function is > called to create the puzzle and its duplicate, because new_puzzle gets > changed so that 85% of the numbers in the matrix get replaced by an empty > string. Now, I have another function that allows you to choose the where > on > the grid to put in the number, but I also need to get new_puzzle in that > function to add numbers not only on the Turtle grid, but add them in > new_puzzle so I can compare it with the original 'puzzle' variable. > > PS: Both functions 'new_sudoku()' and 'play_game()' are called by a > function > called 'new_game()'. Also, I'm using a Mac, but I'm not sure if that > affects > the code or not. > > Thanks in advance. > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Variables and Functions
Okay. "Class" is not a module. It is a keyword that defines a new type. Similar to an integer, or a string. But in the case of a class, you define what happens when you add, subtract, open, close, etc. by defining "methods" of a class. A classic example is a car. class Car: running = 0 headlightson = 0 driving = 0 def start(self): self.running = 1 def drive(self): self.driving = 1 def opendoor(self): self.door = 1 def closedoor(self): self.door = 0 def turnonheadlights(self): self.headlightson = 1 In the case of your puzzle, it would roughly look like this-> class Sudoku: def creatpuzzle(self, which): self.puzzle = #whatever code it takes to make that list def emptypuzzle(self): #code that uses self.puzzle because it is accessible in all methods of the class Just a rough guideline of what we mean when we say you can put all of your functions in a class and use a class variable (in this case... self.puzzle) - Original Message - From: "Devon MacIntyre" <[EMAIL PROTECTED]> To: "Kent Johnson" <[EMAIL PROTECTED]> Cc: Sent: Wednesday, November 28, 2007 8:51 PM Subject: Re: [Tutor] Variables and Functions > Hi, > > I have two functions, 'new_sudoku' and 'play_game'. In new_sudoku, I have > a > pre-determined puzzle (I wasn't able to get a randomly generated puzzle > working), as a matrix in the variable 'puzzle'. I imported the 'copy' > module > and made a deep-copy of 'puzzle' to make 'new_puzzle', which randomly has > 85% of the digits replaced by an empty string. Now that 'new_puzzle' is > only > 15% filled with numbers, I use turtle to place the numbers on a grid that > I > made (also with turtle). After the grid and 'new_puzzle' are generated, I > ask the player if he/she wants to begin playing. If yes, then the function > 'play_game' is started. Here, I'm going to let the player choose spots to > input their own numbers to fill in the board. My problem is that I can't > get > the variables 'puzzle' and 'new_puzzle' into that function (to be > compared) > because they are not globally defined; only in 'new_sudoku' function. > Here's > some selected code from my program: > > def swap_row(puzzle,row1,row2): >temp = puzzle[row1] >puzzle[row1] = puzzle[row2] >puzzle[row2] = temp > > def new_sudoku(): >puzzle = [[1,2,3,4,5,6,7,8,9], \ > [4,5,6,7,8,9,1,2,3], \ > [7,8,9,1,2,3,4,5,6], \ > [2,3,4,5,6,7,8,9,1], \ > [5,6,7,8,9,1,2,3,4], \ > [8,9,1,2,3,4,5,6,7], \ > [3,4,5,6,7,8,9,1,2], \ > [6,7,8,9,1,2,3,4,5], \ > [9,1,2,3,4,5,6,7,8]] >num_of_swap = random.randint(10,20) >for i in range(num_of_swap): >row1 = random.randint(0,8) >row2 = random.randint(0,8) >if row1/3 == row2/3: >swap_row(puzzle,row1,row2) >new_puzzle = copy.deepcopy(puzzle) >sparseness = 0.85 >for i in range(9): >for j in range(9): >if random.uniform(0,1) < sparseness: >new_puzzle[i][j] = '' > > def play_game(): >''' >Here is where I need the variables 'puzzle' and 'new_puzzle' to be > brought. >''' > > I read about the 'class' module, but am not sure on it's execution. I > really > appreciate any time spent on my (simple) problem. > Thanks in advance. > > On Nov 28, 2007 4:18 PM, Kent Johnson <[EMAIL PROTECTED]> wrote: > >> Devon MacIntyre wrote: >> > Hi, >> > Just wondering, how would I get a variable out of one function and into >> > another? >> >> I don't understand your description of your situation, maybe you could >> show a little code as a simple example? >> >> The usual way to get a variable out of a function is to return a value >> from the function. The usual way to get a variable into a function is to >> pass a parameter. If you want tighter coupling than that maybe you >> should make the functions into methods of a class and make the variables >> into instance attributes. >> >> HTH, >> Kent >> > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lstrip removes '/' unexpectedly
>> ## > s = '/home/test/' > s1 = s.lstrip('/ehmo') > s1 >> 'test/' >> ## >> >> Take a closer look at the documentation of lstrip, and you should see >> that >> what it takes in isn't treated as a prefix: rather, it'll be treated as a >> set of characters. >> > > But then the real bug is why does it not strip the trailing '/' in > 'test/' or the 'e' that is in your set? Because lstrip strips the characters within that set, starting from the left, until it encounters a character not in that set. Then it stops. This code produces the same results, though surely more slowly. def lstrip(s, set): for x in s: if x in set: return lstrip(s[1:],set) return s JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [wxPython-users] passing file name from one script to theGUI class
I do not currently have wx installed, but I can see the errors... I think some information will help you more than answers in this instance. When you 'import clases_calling', what you are doing is creating a new namespace. Inside that namespace is the class 'funct'. In your code, you call the function 'clases_calling.func_call' which does not exist because it is hidden inside of the class 'funct'. To access this function you would have to 'clases_calling.funct.func_call(self)'. This is bad practice, and defeats the purpose of using a class. Which is understandable since the class 'funct' is not necessary here. All you need is a function that will return the new filename right? So, in the clases_calling module place a 'getnewfilename' function which will return the new filename (no class in clases_calling) and in your 'readfile.py' call it by 'clases_calling.getnewfilename()'. Also, when you try to call 'imagetobit' from your current 'func_call' function it will fail because in *this* module (clases_calling.py) you have it imported as 'MainWindow.imagetobit'. I would highly recommend *not* putting this code in this module anyway, intuitively it would belong in the 'OnRead' method right after the call to your new function 'getnewfilename'. More errors to be... sigh. Here we go. In your function 'imagetobit' in readfile.py you should get an error because 'self' is not defined. You have not put self in the argument list as you did in all the other methods of MainWindow. This also means that self.imageFile1 will not be defined either, and should give you an error when trying to define it. If you adjust the imagetobit function so that it is a method of the class, we see that the imagename parameter is no longer necessary, as we can set the self.imageFile variable directly from one of the other functions. Also, I see code that looks very similar in the __init__ method of MainWindow and the function imagetobit. I suggest that you change this so that in the __init__ method you actually call self.imagetobit. To summarize: 1) Change clases_calling.py to be a single function that return the new filename as a string. 2) Change MainWindow.OnRead so that it calls this new function first (I used clases_calling.getnewfilename()), then self.imagetobit(), and finally run the rest of the commented stuff you have there (Remembering that the Image redrawing has already been done in self.imagetobit() you can delete it here) 3) Change imagetobit so that it is a method of the class MainWindow, and remove the imagename parameter 4) Change all references of self.imageFile1 to just self.imageFile. You do not need the extra. 5) Change MainWindow.__init__ so that it calls self.imagetobit() immediately after you set the variable self.imageFile And... I think that's everything. IMHO the important concept inherently missed in these two modules is that the names of the functions and variable inside are hidden behind the names. i.e. import math is used as math.sqrt, instead of just sqrt. HTH, JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Button 1 Motion Event
>From your description, it sounds like the number of ovals placed depends only on when the B1-Motion even is sent to your Canvas object. If you want these a little more even, you might take the drawing code out of the function that's bound to the mouse event, so that whenever you process you a mouse event, for example, you append the appropriate information to a list, where it can be drawn all at once later. That will take the drawing time out of the equation, when it comes to how often the mouse event is called. At any rate, it is not likely to do you much good. Windows is allowed to process events such as WM_MOUSEMOVE whenever it's convenient for Windows. One way I can think of doing this (probably not the best way) is to start a timer on the mouse down message, and stop it on mouse up. Since the timer is sent messages rather evenly, you can poll the current mouse position in that function. - Original Message - From: "Johnston Jiaa" <[EMAIL PROTECTED]> To: Sent: Tuesday, December 04, 2007 7:30 PM Subject: [Tutor] Button 1 Motion Event > I'm creating a drawing program, like MS Paint in Tkinter. I bound > the event to my Canvas object. The function it's bound > to creates an oval at the event's x and y attributes. > > This works fine if the user is dragging slowly, but if he does a > sudden dragging motion, the ovals are very far apart. Is there any > way to fix this? > > Johnston Jiaa > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beat me over the head with it
Write a python script that prints out what 2+2 is NOW!!! And after you've done that, write one that does my chemistry homework, IMMEDIATELY! Bonk! ;-) JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Versions
The OP has not specified what his problems specifically are, but "earlylight publishing" described his problem before, and he was not understanding why the >>> prompt was expecting immediate keyboard input when he typed in raw_input(). So a noob cannot figure out why it is advantageous to have a raw_input function that immediately asks for input. He thinks, "why can't I put the input in directly?" That is why putting a program into an edit window is very advantageous. I believe it is very likely that raw_input() is the culprit of confusion here. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] what is the difference
> "johnf" <[EMAIL PROTECTED]> wrote > >> if self._inFlush: >> return >> self._inFlush = True >> >> >> AND >> >> if not self._inFlush: >> ... >> self._inFlush = True >> else: >> return >> >> I can not see the difference but the second one acts differently in >> my code. > > The first has no else clause so the second assignment always happens. > > Alan G. No it doesn't. The return statement does not allow the second assignment to occur in the first example. The second assignment only occurs if NOT (self._inFlush==True), as in the second example. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] user-given variable names for objects
I may sound like a know-it-all, but dictionaries *are* iterators. [a for a in eventData if eventData[a] < time.time()] This is more efficient. The keys method creates a list in memory first and then it iterates over it. Unnecessary. > > "Che M" <[EMAIL PROTECTED]> wrote > >> Although I was not familiar with what you can do with a list such >> as you did here: >> [a for a in eventData.keys() if eventData[a] < time.time()] > > This is known as a list comprehension (and is described in the > Functional > Programming topic of my tutorial - obligatory plug :-) > >> I guess .keys() is a built-in method for dictionaries to return a >> list of all their values, then? > > To be accurate it returns a list of the keys, the values are the > things you get when you access the dictionary using a key: > > value = dictionary[key] > > So you can do things like > > for key in dictionary.keys(): >print dictionary[key] > >> By the way, what was the purpose of the line with >> time.sleep(1) > > It pauses for 1 second. But i'm not sure why he wanted a pause! :-) > > Alan G. > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Versions
> Hey Tiger, > your system clock is set incorrectly and your e-mail was flagged as being > sent 12/12/2008, causing it to appear after an e-mail sent as a reply - > confusing. > Please remedy this situation ;P > -Luke Whoops!! I have to mess with my clock occasionally to test the integrity of date specific scripts that I write. Sorry. It has been fixed. Thank you. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Versions
My apologies for mistaking your gender. Because English does not have adequate neutral gender indication, I tend to use the male as such, as they do in Spanish, and perhaps many other languages. At any rate, that's how it's written in the Bible. I presumed that it was an issue with raw input because not many other things are truly different within the prompt. An extra line is necessary within the prompt after blocks of code such as classes and function declarations. (I guess this didn't bother me when I first started learning python because I got irritated when I hit enter and it didn't do anything, so I hit enter again, much more violently. ;-) My apologies also to you for assuming what was the issue. I have a knack for knowing just what goes wrong, but there are many occasions where I am wrong. :-) > I'm a "she" not a "he". :-) But actually I don't believe I was a member > of this group when I was working with the book "A Byte Of Python" I don't > believe I ever described a problem with raw_input here. That concept > seems pretty clear to me but as you say the OP hasn't described a specific > problem. As I said before, it was the fact that the author was describing > features that I was not seeing in the shell that prompted me to try to > figure out the "new window" feature.As soon as I solved the shell > problem I had no further difficulties understanding the concepts in the > book. I just thought I'd share what worked for me. :-) > > The OP has not specified what his problems specifically are, but > "earlylight > publishing" described his problem before, and he was not understanding > why > the >>> prompt was expecting immediate keyboard input when he typed in > raw_input(). So a noob cannot figure out why it is advantageous to have > a > raw_input function that immediately asks for input. He thinks, "why > can't I > put the input in directly?" That is why putting a program into an edit > window is very advantageous. > > I believe it is very likely that raw_input() is the culprit of > confusion > here. > > > > - > Never miss a thing. Make Yahoo your homepage. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Versions
> Despite what your english teacher might have tried to make you > believe, they were wrong about the lack of a neutral in english. Just > like ending sentences with prepositions has always been done and > always will be done, the use of "they" to refer to someone of > indeterminate gender has been well and alive for hundreds of years. > > The fact you think it isn't okay is because some english teacher sold > you a line of crap about prescriptive grammar rules that don't > actually hold true in actual writing. Many grammar books try to make > the language into what it is not, rather than describing it as it is. No. I form my own opinions and do not believe individuals such as my english "teachers" unless I truly believe that each one is correct. Each of my english teachers will not tell you to use "they" or even the masculine, instead prefering the "proper" way to be "his/her", and equivalent forms. I personally believe this to be a waste of time, and efficiency is one of my primary motivators. Therefore, for space and time I use "he" for an unknown. Proper english (as it is from my viewpoint) would be to restructure the sentence so that it uses "one" in that instance. (My english teachers would gasp at this) This makes the most logical sense. For more than one person of unknown gender, English uses "everyone". So for one person of unknown gender, English uses "one". "They" does not match plurality. Using "they" as you describe it would mean that we should be forming sentences such as "They works" "They bakes" "They codes in python". Clearly this does not sound correct because the word "they" is meant to be used as a plural pronoun only. No, I do not believe in english teachers, and I believe that just because people have used "they" for centuries should not indicate that it is the correct way to speak. I feel that the only correct language is the one which closely follows the rules of mathematics. A few examples. English: "In no way should I stop working". Math: (-) * (-) = (+) English: "This and that"Math: (this) + (that) = both English: "This, but not that" Math: (both) - (that) = this Spanish: "Estos dos árboles verdes son bonitos" Math: 2(a+b) = 2a+2b That is why I like to program so much. Computer languages are very closely mapped to mathematical theory. No, I do not listen to my english teachers because they do not understand what it is to be a musician, mathematician, scientist, and philospher simultaneously. > Leave the sexist, antediluvian notions of your grammar texts behind > and write like people always have. Don't make a mistake about that > next person, no matter what *their* gender may be. I shall not make the same mistake, but I shall not write like people "always" have. If I were more capable, I would write exceptionally better. This is a python list and this discussion has continued for enough time. I would much rather hear your opinions on a piece of python code rather than your criticism of an action for which I have already apologized. Jacob Schmidt PS - "Always" is such a strong word; in math it translates to the limit as time approaches infinity in both directions. So powerful that even the mathematical language has difficulties expressing it. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] user-given variable names for objects
> Mmm, to nit-pick a little, dictionaries are iterables, not iterators. They > don't have a next() method. I'm a little fuzzy on the details of that, I will have to look over some reference material again. >> [a for a in eventData if eventData[a] < time.time()] >> >> This is more efficient. The keys method creates a list in memory first >> and then it iterates over it. > > I've never tested it but I suspect that when you need keys and values, it > is more efficient to use itervalues(): > > [ k for k, v in eventData.itervalues() if v < time.time() ] Oh! This is new to me! When did they put in itervalues? See what happens when you leave the python community so you can learn C and assembly~ > and of course if you care about efficiency you should hoist the call to > time.time() out of the loop! Oh, I thought it was necessary for the time to change within the loop which might or might not be necessary, depending on just what exactly is supposed to happen. I would guess that in an unordered data structure like that, it wouldn't be of any use to update the time within the loop. Ask me if you are curious and can't follow my reasoning. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor