[Tutor] code review request
Hoping to get some of you guru types to look over the start of a tool I am working on in python. A working version of the script is at https://mikaru.homeunix.org/py-bin/memberlist.py The site only allows https because I got sick of all the hacked windoze boxes trying to execute crap that I didn't have, so port 80(http) is blocked on my firewall. This lets you add users, divisions (groups) and put the users in divisions(groups). and list the users out by group. I haven't figure out yet how to authenticate the users from the database (postgresql) so any pointers there would be helpful. When a user is added, the password is encrypted in the database using postgresql's encrypt() function so that it would be possible to use another application to access the data. Any pointers or advise on where improvments could be made would be welcome. #!/usr/bin/python print 'Content-type: text/html\n' import psycopg import cgitb import cgi import sys cgitb.enable() def quote(string): if string: return string.replace("'", "\\'") else: return string form = cgi.FieldStorage() conn = psycopg.connect('dbname=XXX user=xxx password=x') curs = conn.cursor() div_name = quote(form.getvalue('div_name')) div_director = quote(form.getvalue('div_director')) div_email = quote(form.getvalue('div_email')) if not (div_name and div_director and div_email): print 'ALL FIELDS MUST BE COMPLETED' sys.exit() query = """INSERT INTO divisions(div_name, div_director, div_email) VALUES ('%s', '%s', '%s')""" % (div_name, div_director, div_email) curs.execute(query) conn.commit() conn.close() print """ Division added Division created successfully Back to the main page """ #!/usr/bin/python print 'Content-type: text/html\n' import psycopg import cgitb import cgi import sys cgitb.enable() def quote(string): if string: return string.replace("'", "\\'") else: return string form = cgi.FieldStorage() conn = psycopg.connect('dbname= user=x password=x') curs = conn.cursor() name = quote(form.getvalue('name')) address = quote(form.getvalue('address')) email = quote(form.getvalue('email')) password = quote(form.getvalue('password')) username = quote(form.getvalue('username')) div_id = quote(form.getvalue('division')) if not (name and username and password): print 'Please supply name, username, and password' sys.exit() query = """INSERT INTO members(name, address, email, password, username, div_id) VALUES ('%s', '%s', '%s', encrypt('%s', \'f00zball\', \'aes\'), '%s', '%i')""" % (name, address, email, password, username, int(div_id)) curs.execute(query) conn.commit() conn.close() print """ User added User created successfully Back to the main page """ #!/usr/bin/python from mod_python import apache import cgitb; cgitb.enable() import psycopg conn = psycopg.connect('dbname= user= password=x') curs = conn.cursor() print 'Content-type: text/html\n' print """ Member Management User List """ curs.execute('SELECT * FROM divisions') rows = curs.dictfetchall() toplevel = [] children = {} for row in rows: division = row['div_id'] print '%(div_name)s' % row def format(row): print '%(div_name)s' % row try: kids = children[row['div_id']] except KeyError: pass else: print '' for kid in kids: format(kid) print '' print '' for row in toplevel: format(row) print """ Create User | Add Division """ #!/usr/bin/python from mod_python import apache import cgitb; cgitb.enable() import psycopg conn = psycopg.connect('dbname=x user= password=x') curs = conn.cursor() print 'Content-type: text/html\n' print """ Member Management User List """ curs.execute('SELECT * FROM members') rows = curs.dictfetchall() toplevel = [] children = {} for row in rows: parent_id = row['div_id'] if parent_id is None: toplevel.append(row) else: children.setdefault(parent_id,[]).append(row) def format(row): print '%(name)s' % row try: kids = children[row['mem_id']] except KeyError: pass else: print '' for kid in kids: format(kid) print '' print '' for row in toplevel: format(row) print """ Create User | Add Division | List Divisions """ #!/usr/bin/python print 'Content-type: text/html\n' import cgitb; cgitb.enable() import psycopg conn = psycopg.connect('dbname=xx user= password=x') curs = conn.cursor() import cgi, sys form = cgi.FieldStorage() #name = form.getvalue('name') print """ Division Add Division """ print """ Division Name: Director: Division E-Mail List: Back to the main page' """ #!/usr/bin/python print 'Content-type: text/html\n' import cgitb; cgitb.enable()
Re: [Tutor] glibc error while Python script runs
Rest assured, Kent, that I fully understand your point. My experience is quite a lot more limited than yours, and yes I experience this frustrating mess that you talk about and I'm aware that I'm not doing myself any favor with such a design. Sorting this is high on my TODO list. but not on top I'm affraid for now :-) The next project will start off better, I hope :-) Cheers Bernard On 1/4/06, Kent Johnson <[EMAIL PROTECTED]> wrote: > Bernard Lebel wrote: > > Here is the script (1550 lines, I know - just wants to get to > > functional code before improving the design), if it can help. > > Hmm, a common attitude but a bad plan and false economy IMO. In my > experience if I keep the code and the design clean as I go, development > moves faster because - surprise! - I am always working with clean code > whose design fits the current needs. At the end I have clean, > well-designed maintainable code. If I ignore design and expect to clean > up at the end, I end up with a frustrating mess that I would rather not > look at and anyway it's too tangled to fix. > > And sorry, I don't have a clue what is causing your glibc error... > > 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] glibc error while Python script runs
Bernard Lebel wrote: > Here is the script (1550 lines, I know - just wants to get to > functional code before improving the design), if it can help. Hmm, a common attitude but a bad plan and false economy IMO. In my experience if I keep the code and the design clean as I go, development moves faster because - surprise! - I am always working with clean code whose design fits the current needs. At the end I have clean, well-designed maintainable code. If I ignore design and expect to clean up at the end, I end up with a frustrating mess that I would rather not look at and anyway it's too tangled to fix. And sorry, I don't have a clue what is causing your glibc error... Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] XOR, bytes and strings
congratulations, you are good in explaining something easily and in a simple english, too! i was able to get it work, thank you, tobi p.s.: sorry for this wrong 'from' field in the other message >10101010 (0xaa) > > and xor it against: > >01010101 (0x55) > > We know what to expect: (0xff), but let's try it: > > ## > >>> 0xaa ^ 0x55 > 255 > ## __ Verschicken Sie romantische, coole und witzige Bilder per SMS! Jetzt bei WEB.DE FreeMail: http://f.web.de/?mc=021193 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Design questions?
Hi Richard, The first thiong is forget the GUI for now it will be much easier to get a command line version working then add a GUI (or web page) later. > (Input Clients name) input text box > age= spinner > Male or Female= radio buttons > Tobacco User yes or no > Health Here I was thinking about 4-5 options > Diabetic yes or no? > > Amount of Coverage input text box Just make all of these raw_input lines initially, you can do some validation for good data after you've captured it. > So those would be the input parameters, Here is how it would work (at > least in my limited knowledge) The program is going to look at age first > then Male or female then, Tobacco, and health after it accumulates all the > information then it will have 5- 6 companies to find the rates from.( This > will be based on the health too, because as an example if health= poor > then there is only one company to look at. This is true if the person is > diabetic, only one company. Try doing it with one company fdirst, then once you get the right rate its easy enough to adapt it to repeat the check for seveal companies. > I can use a prefered rate too but then I would have to put in a weight > chart. (sigh) I'd leave this bit till you get the basic one working with several companies. > So when the program looks at these companies. Let me back up a minute > here. To calculate rates is as follows > > Rate= (Unit cost X amount) + policy fee X modal factor (modal factor is > different for monthly,quarterly and semi annual. Get the calcuilations going first, then worry about repeating them per company and storiung results > So then program looks to find the best rate and return the value into 3 > box...Monthly Quarterly and Semi Just get it to print the result to screen initially. > Also now I bet your saying this guy is getting picky, I want to be able to > write the quote to a file for future use. Yep, you can do that too. > So I have allot of the rates in excel now, do I need to build tables with > each company? You can actually read them from Excel but for now I'd save the Excel data in a CSV file and use the csv module to read them in. But first get it working witrh static data from one company. > I know this is a big project so I was told by someone. But I am just look > for a starting point and then I will go from there. Its actually a very good project because its possible to break it into a lot of small bite size bits. Have fun, ask questions as you go. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] XOR, bytes and strings
On Wed, 4 Jan 2006, to bifu wrote: > thanks for the help, but my problem is how to use that for a string, Hi To, A character can be translated into an ordinal number by using the ord() function. For example: ## >>> ord('a') 97 ## > and those hexadecimals are confusing me, too. Let's talk about this a bit. Do you understand that hexadecimal is a compact way of writing out numbers or bit patterns? For example: ## >>> 0xff 255 ## shows us that the bit pattern consisting of eight 1's: 1 1 1 1 1 1 1 1 can be seen as the number 255. (2**7 + 2**6 + ... + 2**1 + 2**0). The reason that 0xff corresponds to that particular bit pattern of all-ones is because of this relationship between bits and hex digits: bits hex --- 0 00011 00102 00113 01004 01015 01106 01117 10008 10019 1010A 1011B 1100C 1101D 1110E F > if it are only bits, it's easy to understand, but how to use XOR for bytes? XOR works for bytes too. Let's define a byte to be a number between 0 and 255, inclusive. Let's play with the pattern: 10101010 (0xaa) and xor it against: 01010101 (0x55) We know what to expect: (0xff), but let's try it: ## >>> 0xaa ^ 0x55 255 ## We know that 255 corresponds to the bit pattern , so things appear to be working. If this is the first time you've seen stuff like this, this might seem really weird. Please feel free to ask more questions about this. By the way, another thread this week is doing similar stuff with bitwise arithmetic; you may want to look at it: http://mail.python.org/pipermail/tutor/2006-January/044244.html Good luck! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Printing in Windows (was: Further help needed!
On Wed, 4 Jan 2006, John Corry wrote: > I am using the following code to send a text file to the printer:- > This code works on windows XP + Windows 2000. However it does not work on > windows 98SE. Here's another alternative, which might be even simpler, if it works for you, invoking the good old-fashioned DOS "print" command: import os filename = "testprint.txt" commandline = "print " + filename os.popen(commandline) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Further help needed!
John, On Win 9X try 1) copying the text file to PRN: using os.system() 2) use the DIS PRINT command using os.system() 3) Try opening the file LPT1: and copying your text to that. All of the above should work. But I no onger have a Win9X box to check... HTH, Alan G. - Original Message - From: "John Corry" <[EMAIL PROTECTED]> To: Sent: Wednesday, January 04, 2006 9:01 PM Subject: [Tutor] Further help needed! >I am using the following code to send a text file to the printer:- > > import win32api > filename = "testprint.txt" > fileobj=open (filename, "w") > fileobj.write ("This is a test") > fileobj.close() > win32api.ShellExecute ( > 0, > "print", > filename, > None, > ".", > 0 > ) > > This code works on windows XP + Windows 2000. However it does not work on > windows 98SE. I have tried this code on 3 seperate machines with windows > 98SE. They all come up with the same error: > > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript >exec codeObject in __main__.__dict__ > File "C:\test\Script1.py", line 12, in ? >0 > error: (31, 'ShellExecute', 'A device attached to the system is not > functioning.') > > Is there another way to print out a text file on windows 98SE? Do I have > to > do something different on the windows 98SE machine? Any help would be > greatly appreciated. > > Thanks, > > John. > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] glibc error while Python script runs
Hi Danny, See [Bernard] below... On 1/4/06, Danny Yoo <[EMAIL PROTECTED]> wrote: > > > rn200.bbfxa.com Wed Jan 4 16:23:36 2006 [jobid: 9]: Get status of all > > local jobs for this job... > > > > *** glibc detected *** double free or corruption: 0x09484d58 *** > > Aborted > > > Hi Bernard, > > Ugh. I hate memory allocation bugs. > > Is it reproducable? Can you run this through a debugger like GDB to find > out where we are when this happens? A stack trace will be invaluable > because we need to know who to blame. [Bernard] I am quite unfamiliar with Linux in general and a lot more with these tools. Where can I find information about GDB? > *grin* We need to know if it's > Python that's doing this, or if it's MySQLdb, or if it's something else > entirely... > > Just checking up on this: what version of MySQLdb do you have on those > systems? I do remember some ugly memory-leaking bugs that haunted ancient > versions of MySQLdb, so I want to make sure we're not hitting those. [Bernard] I am using 1.2.0, with Python 2.3.4. > > Analyzing this might goes out of Tutor's scope, so you may want to bring > this up on a more general forum like comp.lang.python instead. [Bernard] Okay thanks a lot. I'll check it out, but if you have any idea... :-) Bernard ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] query regarding mysql database backup?? please Help
> > os.system("mysqldump --add-drop-table -c -u root -pmysql > > max_everest_2006 > "+target_dir+"/table.bak.sql") > > root is my user name,mysql is my password You shouldn't use root to adnin a database, it leaves you open to all sorts of security holes. And you shouldn't post your root password on a public list, I hope it wasn't really your password or that you changed it immediately! > but it tolds me that does not recognise mysqldump as an internal > or external command I suspect the path needs to be set or more likely you provide the full path of the mysqldump command to os.system... HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] XOR, bytes and strings
> now i have the problem that i should encrypt a string (the password) by > XOR with this bytes: f3, 26, 81, c4, 39, 86, db, 92, 71, a3, b9, e6, 53, > 7a, 95, 7c. > > but although i have searched in the documentation for about an hour, Look for bitwise operators, there is a bitwise xor operator. Its amazing how often the same topic arises in different threads at the same time on this list! You can get a brief into to bitwise operators in my OS topic - look for the sidebar. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] HD/DVD/CD
>> >>> i = long(-1972144115) & 0x > > Ah, thanks. I've never had a need to to bit manipulation in Python (or in For anyone interested, my new OS topic has a section on bitwise operations in Python - they are needed for checking stat flags... (see the sig for the link) Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Printing in Windows (was: Further help needed!
I've edited the subject line to be a little more clear. On Wed, 4 Jan 2006, John Corry wrote: > I am using the following code to send a text file to the printer:- [ snip ] > This code works on windows XP + Windows 2000. However it does not work on > windows 98SE. Well, at least that narrows it down. This continues to befuddle me. I don't know enough about Windows to know the differences that might be here for this purpose. Question: do you need to use the Windows print function, or can you live with printing it yourself (as below)? For example, if you use the ShellExecute approach, it actually causes an application to be invoked for you, which does the printing, just as if you right-clicked on the file and selected "print." ON my system, for example, that will invoke Notepad, which prints it with a heading and a page number at the bottom. But, if you don't care about that, assuming your file is straight text, try the win32print approach from http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html . Here's an attempt that seems to work for me: --- import win32print lines_to_print = open("testprint.txt","r").readlines() print_data = '' for line in lines_to_print: print_data=''.join([print_data,line,"\r"]) printer_name = win32print.GetDefaultPrinter() printer = win32print.OpenPrinter(printer_name) print_job = win32print.StartDocPrinter(printer, 1, ("Printer test", None, "RAW")) win32print.WritePrinter(printer, print_data) win32print.EndDocPrinter(printer) win32print.ClosePrinter(printer) --- The for-loop is a kludge; my first attempt was something like print_data=open("testprint.txt","r").read() but it turns out my printer needs a carriage return on each line. I suspect that printer handling is more likely to be inconsistent between Win98 and Win/XP than the ShellExecute you were already using, and so this may not work; but it's worth looking into. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] glibc error while Python script runs
> rn200.bbfxa.com Wed Jan 4 16:23:36 2006 [jobid: 9]: Get status of all > local jobs for this job... > > *** glibc detected *** double free or corruption: 0x09484d58 *** > Aborted Hi Bernard, Ugh. I hate memory allocation bugs. Is it reproducable? Can you run this through a debugger like GDB to find out where we are when this happens? A stack trace will be invaluable because we need to know who to blame. *grin* We need to know if it's Python that's doing this, or if it's MySQLdb, or if it's something else entirely... Just checking up on this: what version of MySQLdb do you have on those systems? I do remember some ugly memory-leaking bugs that haunted ancient versions of MySQLdb, so I want to make sure we're not hitting those. Analyzing this might goes out of Tutor's scope, so you may want to bring this up on a more general forum like comp.lang.python instead. Best of wishes! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Further help needed!
[resending 'cause I forgot to address to tutor..] On 05/01/06, John Corry <[EMAIL PROTECTED]> wrote: > This code works on windows XP + Windows 2000. However it does not work on > windows 98SE. I have tried this code on 3 seperate machines with windows > 98SE. They all come up with the same error: > > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\test\Script1.py", line 12, in ? > 0 > error: (31, 'ShellExecute', 'A device attached to the system is not > functioning.') Have you verified that the printer on your Win98 machine does work? For example, create a text file on that computer. In Windows Explorer, right-click on the text file and select 'print' from the context menu. What happens? -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Design questions?
Hi all! First I want to thank everyone for the help in regards to learning python book and gui's!! Happy New year!! I am just learning Python, and I do have a project in mind but I am not sure where to start on it. I am in the Insurance business so the project is a rate calculator. I have a ton of questions. So bear with me please. The picture I have in my mind and what I have written down too. (Input Clients name) input text box age= spinner Male or Female= radio buttons Tobacco User yes or no Health Here I was thinking about 4-5 options Diabetic yes or no? Amount of Coverage input text box So those would be the input parameters, Here is how it would work (at least in my limited knowledge) The program is going to look at age first then Male or female then, Tobacco, and health after it accumulates all the information then it will have 5- 6 companies to find the rates from.( This will be based on the health too, because as an example if health= poor then there is only one company to look at. This is true if the person is diabetic, only one company. I can use a prefered rate too but then I would have to put in a weight chart. (sigh) So when the program looks at these companies. Let me back up a minute here. To calculate rates is as follows Rate= (Unit cost X amount) + policy fee X modal factor (modal factor is different for monthly,quarterly and semi annual. So then program looks to find the best rate and return the value into 3 box...Monthly Quarterly and Semi Also now I bet your saying this guy is getting picky, I want to be able to write the quote to a file for future use. So I have allot of the rates in excel now, do I need to build tables with each company? I know this is a big project so I was told by someone. But I am just look for a starting point and then I will go from there. Thanks In Advance for all of your help. Richard ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] glibc error while Python script runs
Hello, I'm not sure if it's the appropriate place for this question, but since it happens because of a Python script So I have this Python script that runs on render farm nodes. All seem to work well, but at one point I get this crash: rn200.bbfxa.com Wed Jan 4 16:23:36 2006 [jobid: 9]: Get status of all local jobs for this job... *** glibc detected *** double free or corruption: 0x09484d58 *** Aborted So what happens at that particular moment is the script sends a SELECT query to a MySQL database. It collects all the values of a field called Status in a certain table. I just have no idea what to do with this error. Here is the script (1550 lines, I know - just wants to get to functional code before improving the design), if it can help. http://www.bernardlebel.com/scripts/nonxsi/farmclient_2.0_beta04.txt Thanks Bernard ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Further help needed!
I am using the following code to send a text file to the printer:- import win32api filename = "testprint.txt" fileobj=open (filename, "w") fileobj.write ("This is a test") fileobj.close() win32api.ShellExecute ( 0, "print", filename, None, ".", 0 ) This code works on windows XP + Windows 2000. However it does not work on windows 98SE. I have tried this code on 3 seperate machines with windows 98SE. They all come up with the same error: File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\test\Script1.py", line 12, in ? 0 error: (31, 'ShellExecute', 'A device attached to the system is not functioning.') Is there another way to print out a text file on windows 98SE? Do I have to do something different on the windows 98SE machine? Any help would be greatly appreciated. Thanks, John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fw: query regarding mysql database backup?? please Help
- Original Message - From: deepak.gupta To: tutor@python.org Sent: Wednesday, January 04, 2006 5:27 PM Subject: query regarding mysql database backup?? please Help Hi, I did my script like this for backing my max_everest_2006 mysql database >>import os > > target_dir = "./backup"> > os.system("mysqldump --add-drop-table -c -u root -pmysql max_everest_2006 > "+target_dir+"table.bak.sql") root is my user name,mysql is my password,max_everest_2006 is my database name. reply me as soon as possible but it tolds me that does not recognise mysqldump as an internal or external command Please help Thanks deepak gupta ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] query regarding mysql database backup?? please Help
Hi, I did my script like this for backing my max_everest_2006 mysql database >>import os > > target_dir = "./backup"> > os.system("mysqldump --add-drop-table -c -u root -pmysql max_everest_2006 > "+target_dir+"/table.bak.sql") root is my user name,mysql is my password,max_everest_2006 is my database name. reply me as soon as possible but it tolds me that does not recognise mysqldump as an internal or external command Please help Thanks deepak gupta ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] XOR, bytes and strings
> i'm a totally newbie to python, but i can't resist to try to communicyte > with an ICQ-server via my own tool. > > now i have the problem that i should encrypt a string (the password) by > XOR with this bytes: f3, 26, 81, c4, 39, 86, db, 92, 71, a3, b9, e6, 53, > 7a, 95, 7c. Hello Tobi, According to: http://www.python.org/doc/ref/bitwise.html I think you're looking for the exclusive or (XOR) bitwise operator '^'. For example: ## >>> bits = [0, 1] >>> for x in bits: ... for y in bits: ... print x, y, x ^ y ... 0 0 0 0 1 1 1 0 1 1 1 0 ## Is this where you're getting stuck, or is it somewhere else? Good luck to you. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] XOR, bytes and strings
i'm a totally newbie to python, but i can't resist to try to communicyte with an ICQ-server via my own tool. now i have the problem that i should encrypt a string (the password) by XOR with this bytes: f3, 26, 81, c4, 39, 86, db, 92, 71, a3, b9, e6, 53, 7a, 95, 7c. but although i have searched in the documentation for about an hour, i wasn't able to find out how to manage it. i hope you can help me, tobi. __ Verschicken Sie romantische, coole und witzige Bilder per SMS! Jetzt bei WEB.DE FreeMail: http://f.web.de/?mc=021193 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] HD/DVD/CD
On Wed, 4 Jan 2006, Kent Johnson wrote: > To get the desired representation, you have to find a way to make Python > interpret the number as an unsigned integer. One way to do this is to > convert it to a long integer, then mask off the sign bits: > >>> i = long(-1972144115) & 0x Ah, thanks. I've never had a need to to bit manipulation in Python (or in anything since IBM S/390 assembler, for that matter), so this is terra incognito to me. That feels much cleaner to me than using an arithmetic addition; and is has the advantages of being shorter and addressing both positive and negative numbers with the same operation, rather than using the if. So, changing my previous code, I now like the short and sweet: >>> import win32api >>> CD_Info = win32api.GetVolumeInformation("D:/") >>> serno = "%X" % (long(CD_Info[1]) & 0x) >>> serno '8A73780D' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] HD/DVD/CD
Terry Carroll wrote: > I'm assuming you want the same serial # that shows up when you do a > DIR on the CD, e.g.: > > >dir d: >Volume in drive D is 050512_1752 >Volume Serial Number is 8A73-780D > > Here's some code: > > import win32api CD_Info = win32api.GetVolumeInformation("D:/") serno = CD_Info[1] serno > > -1972144115 > "%X" % serno > > '-758C87F3' > "%X" % -serno > > '758C87F3' > > This is as far as I can get. the hex string, in this case 758C87F3 is the > two's complement of the serial number that shows up when I do a "dir d:": > > >dir d: >Volume in drive D is 050512_1752 >Volume Serial Number is 8A73-780D > > Note that: > 758C 87F3 > + 8A73 780D > = > 1 > > Put another way, if you flip every bit in the 758C87F3 string and add one, > you'll get the 8A73780D serial no. > > I hope someone more artful than I can show a quick and easy way to convert > either '758C87F3' or -1972144115 to the '8A73780D' that is your goal. What is happening here is that Python is treating the bit pattern '8A73780D' as a signed integer. A common way to represent signed integers is with two's complement notation, so Python interprets '8A73780D' as the number -1972144115. When you convert this to hex using %x formatting, the sign is preserved and you see the representation '-758C87F3'. To get the desired representation, you have to find a way to make Python interpret the number as an unsigned integer. One way to do this is to convert it to a long integer, then mask off the sign bits: >>> i = long(-1972144115) & 0x >>> i 2322823181L >>> '%x' % i '8a73780d' As you noted, John Fouhy's number doesn't have the high bit set. So it is interpreted as a positive number. Masking the sign bits has no effect because they are already zeros: >>> i=0x49BC31DB >>> i 1237070299 >>> i = long(i) & 0x >>> i 1237070299L >>> '%x' % i '49bc31db' More about two's complement notation here: http://en.wikipedia.org/wiki/Two%27s_complement Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to make to exit the loop, while typing Enter
Hi John, The code is looking better, some minor points below: > import sys > maxmark = [] > counter = 0 > > while 1: >try: >mark = int(raw_input("Enter the Values for the Array: ")) >maxmark.append(mark) >print maxmark >except ValueError: >#print "From Here to Where " While what you have written will work, its not usually a good idea to use a try/except block to control program flow like that. In pseudo code terms what you want is: while more marks read and store marks process marks So the processing should really be outside the loop. The idiomatic way to break out of a loop in Python is to use the 'break' keyword (it has a cousin 'continue' too) while: try: loop code here if loop should end break except E: handle any exceptions either break or continue post loop processing here Hopefully that makes sense, it just makes the shape (ie the layout) of your code follow the logical structure of your design. And it doesn't confuse the error handling in the except block with the normal 'happy path' process. >counter = 0 You already did this up above so its not needed here... >length = len(maxmark) >max = maxmark[counter] >for counter in range(length): >if maxmark[counter] > max: >max = maxmark[counter] Because you only use counter to access the array you can do this more cleanly by using the for syntax directly: for mark in maxmark: if mark > max: max = mark No need for the counter, the length, or the call to range. I suspect you may have some experience in a language like C or Basic or Pascal which doesn't havce a 'foreach' kind of operation, often it can be hard to break out of the idea of using indexing to access items in a container. But the for loop is designed specifically for that purpose, using range() is just a trick to simulate conventional for loops on the rare occasions when we really do want the index.(and the new enumerate() method is reducing those occasions even more). >print "At last the Maximum Marks U got is ", max >sys.exit() Because we used break to exit the loop we no longer need the sys.exit() call here, nor by implication, the import statement at the top. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 23, Issue 7
Wouw, this is realy good!! Thanks for all, I can go on now with my DB. you were realy helpful, all. > > >>> import win32api > >>> CD_Info = win32api.GetVolumeInformation("D:/") > >>> serno = CD_Info[1] > >>> if serno < 0: >...serno_str = "%X" % (0x1+serno) >... else: >...serno_str = "%X" % serno >... > >>> serno_str >'8A73780D' > >>> > > Thanks Gr Ron Speerstra _ Een audiogesprek? Pak Messenger, niet de telefoon http://www1.imagine-msn.com/Messenger/Video.aspx ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python code pretty-print?
On Tue, 3 Jan 2006, Lance E Sloan wrote: > A colleague of mine often develops Python code under Mac OS X. He would > like to be able to print the code in an easily readable format. He's > found that kwrite on Linux does a very nice job, but it's inconvenient > to copy his code to a Linux box just to print it out. > > We've found mention (mostly in manpages) of a program called > "pyhtmlizer", but couldn't find source or binary for it. Hi Did you try subethaedit ( http://www.codingmonkeys.de/subethaedit/ )? Despite of the strange name IMHO the best editor for OS X. Excellent syntax highlighting included. Cheers Christian ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor