Re: Receing a form variable as a list instead of as a string
On Tue, 11 Jun 2013 18:29:05 -0700, nagia.retsina wrote: if page or form.getvalue('show') == 'log': # it is a python script page = page.replace( '/home/nikos/public_html/cgi-bin', '' ) elif page or form.getvalue('show') == 'stats': page = page.replace( '/home/nikos/public_html/cgi-bin', '' ) in the first if option page works a string and replace happens , while in the second it behaves liek a list and the error i mentioned is being produced. It doesn't *behave* like a list. It **IS** a list. I know that people have already pointed you to the documentation, where getvalue is documented to return either a string or a list, depending on how many values there are in the form. So, yet again, here is the documentation: http://docs.python.org/3/library/cgi.html READ IT. Here is an extract: [quote] In the previous section, you learned to write following code anytime you expected a user to post more than one value under one name: item = form.getvalue(item) if isinstance(item, list): # The user is requesting more than one item. else: # The user is requesting only one item. [end quote] Read the rest of the docs. Don't ask any more questions until you have read them. Then, if anything is still unclear, you can point to a section of the docs and say I don't understand this. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On Jun 12, 3:44 pm, Tim Roberts t...@probo.com wrote: It seems silly to fire up a regular expression compiler to look for a single character. if name.find('=') 0 and month.find('=') 0 and year.find('=') 0: If truthiness is the only concern, I prefer using `in`: if '=' in name and '=' in month ... -- http://mail.python.org/mailman/listinfo/python-list
Re: Split a list into two parts based on a filter?
On 12 Jun 2013 01:36, Roy Smith r...@panix.com wrote: In article mailman.3023.1370964449.3114.python-l...@python.org, Serhiy Storchaka storch...@gmail.com wrote: 11.06.13 07:11, Roy Smith написав(ла): In article mailman.2992.1370904643.3114.python-l...@python.org, Roel Schroeven r...@roelschroeven.net wrote: new_songs, old_songs = [], [] [(new_songs if s.is_new() else old_songs).append(s) for s in songs] Thanks kind of neat, thanks. I'm trying to figure out what list gets created and discarded. I think it's [None] * len(songs). It is the same as your klunky code, but consumes more memory. Well, continuing down this somewhat bizarre path: new_songs, old_songs = [], [] itertools.takewhile( lambda x: True, (new_songs if s.is_new() else old_songs).append(s) for s in songs) ) I'm not sure I got the syntax exactly right, but the idea is anything that will iterate over a generator expression. That at least gets rid of the memory requirement to hold the throw-away list :-) You could equivalently pass the generator to deque() with maxlen=0 - this consumes the iterator with constant memory usage. We are of course firmly in the twilight zone at this point (although this can be a useful technique in general). Cheers, Phil -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: e-mail reply to old/archived message
On 12 Jun 2013 02:20, nagia.rets...@gmail.com wrote: How can i be able to answer you guys posts by my mail client? Don't delete mails that you might want to reply to. If you do anything else, you're just making it difficult for yourself. Cheers, Phil -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: e-mail reply to old/archived message
Τη Τετάρτη, 12 Ιουνίου 2013 9:36:41 π.μ. UTC+3, ο χρήστης Phil Connell έγραψε: On 12 Jun 2013 02:20, nagia@gmail.com wrote: How can i be able to answer you guys posts by my mail client? Don't delete mails that you might want to reply to. If you do anything else, you're just making it difficult for yourself. Cheers, Phil -- http://mail.python.org/mailman/listinfo/python-list i installed pan for windows just now, lets hpe it will be a workign alternative. -- http://mail.python.org/mailman/listinfo/python-list
Modify code with AST
Hello, I am trying to write a script which will parse a code segment (with ast.parse()), locate the correct function/method node (by name) in the resulting tree and replace this function (node) with another function (node), e.g.: MyMod1.py: class FooBar(): def Foo(self): #I want to replace this and only this return 1 def Bar(self): return 2 Here is the parser-class: class FindAndTransform(NodeTransformer): Visit the function and check name def visit_FunctionDef(self, node): if node.name == 'Foo': #Only replace if name is Foo #Create a new function and assign it to node node = parse(''' def add(n, m): return n + m ''') return node When I run the parser on MyMod1.py and generate code (with codegen), the output is: class FooBar(): def add(n, m): return n + m i.e. both methods are replaced. It seems like node in the parser contains all method bodies of class FooBar, not only Foo. When ran through a debugger, it iterates both methods. What I really wanted to do, was to replace only one method (Foo) and leave the other untouched. I hope this was understandable conveyed. Answers are highly appreciated. Regards, Ronny Mandal -- http://mail.python.org/mailman/listinfo/python-list
Re: ValueError: I/O operation on closed file. with python3
Adam Mercer wrote: Hi I'm trying to update one of my scripts so that it runs under python2 and python3, but I'm running into an issue that the following example illustrates: $ cat test.py try: # python-2.x from urllib2 import urlopen from ConfigParser import ConfigParser except ImportError: # python-3.x from urllib.request import urlopen from configparser import ConfigParser server='http://www.lsc-group.phys.uwm.edu/~ram/files' fp = urlopen('%s/latest.ini' % server).fp cp = ConfigParser() cp.readfp(fp) print(cp.get('version', '10.8')) $ This works as expected when using python2: $ python2.7 test.py 5.2.10 $ but when using python3 I receive the following error: $ python3.3 test.py Traceback (most recent call last): File test.py, line 14, in module cp.readfp(fp) File /opt/local/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/configparser.py, line 753, in readfp self.read_file(fp, source=filename) File /opt/local/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/configparser.py, line 708, in read_file self._read(f, source) File /opt/local/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/configparser.py, line 1010, in _read for lineno, line in enumerate(fp, start=1): ValueError: I/O operation on closed file. $ Is there a way to get this working in both python2 and python3? This is a small script and I'm starting to have some users wanting to use python3 and others sticking to python2 so I'd like to accommodate them both if possible. Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 30 2012, 14:49:00) [GCC 4.6.1] on linux Type help, copyright, credits or license for more information. from urllib.request import urlopen url = http://www.lsc-group.phys.uwm.edu/~ram/files/latest.ini; fp = urlopen(url).fp fp.read() Traceback (most recent call last): File stdin, line 1, in module ValueError: read of closed file resp = urlopen(url) resp.fp.read() b'[version]\n10.5 = 5.2.4\n10.6 = 5.2.10\n10.7 = 5.2.10\n10.8 = 5.2.10\n' I don't know whether this behaviour is intentional or accidental (I assume the latter). I then ran into another problem: from configparser import ConfigParser p = ConfigParser() resp = urlopen(url) p.readfp(resp.fp) Traceback (most recent call last): File stdin, line 1, in module File /usr/local/lib/python3.3/configparser.py, line 754, in readfp self.read_file(fp, source=filename) File /usr/local/lib/python3.3/configparser.py, line 709, in read_file self._read(f, source) File /usr/local/lib/python3.3/configparser.py, line 1011, in _read if line.strip().startswith(prefix): TypeError: startswith first arg must be bytes or a tuple of bytes, not str So ConfigParser.readfp() (which has been deprecated in favour of read_file(), btw.) expects a text file: from io import TextIOWrapper resp = urlopen(url) p.readfp(TextIOWrapper(resp.fp)) p.get(version, 10.8) '5.2.10' Applying these findings to your script: from contextlib import contextmanager try: # python-2.x from urllib2 import urlopen from ConfigParser import ConfigParser @contextmanager def my_urlopen(url): yield urlopen(url).fp except ImportError: # python-3.x from urllib.request import urlopen from configparser import ConfigParser import io @contextmanager def my_urlopen(url): resp = urlopen(url) yield io.TextIOWrapper(resp.fp) server='http://www.lsc-group.phys.uwm.edu/~ram/files' cp = ConfigParser() with my_urlopen('%s/latest.ini' % server) as fp: cp.readfp(fp) print(cp.get('version', '10.8')) I've run it with 2.6, 2.7, 3.2, and 3.3. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyGame tutorial?
On 06/11/2013 08:47 AM, Eam onn wrote: Is there a PyGame tutorial out there? I've seen TheNewBoston's tuts, but he didn't finish his. MetalX100 did a VERY good tutorial. I've been having trouble with some player movement because he isn't moving smoothly, he jumps. If I add 5 pixels to his X position if I press a button, jumps to the next 5 pixels instead of smoothly moving. If I just add 5 pixels normally, he moves smooth. Thanks! Any help is appreciated! I posted this link before, but here it is again... http://inventwithpython.com/pygame/ for the book Making Games with Python Pygame You can buy the dead-tree version, Or you can read it on-line for free, Or download the pdf or ebook versions for free. -=- Larry -=- -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On Tue, 11 Jun 2013 22:49:05 -0600, Michael Torrie wrote: What do each of these functions return? When you print out re.search('=', name) what happens? First of all i have changed the code to the following because using a regex to detect a single char was an overkill. if '=' not in name and '=' not in month and '=' not in year: cur.execute( '''SELECT * FROM works WHERE clientsID = (SELECT id FROM clients WHERE name = %s) and MONTH(lastvisit) = %s and YEAR (lastvisit) = %s ORDER BY lastvisit ASC''', (name, month, year) ) elif '=' not in month and '=' not in year: cur.execute( '''SELECT * FROM works WHERE MONTH(lastvisit) = %s and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (month, year) ) elif '=' not in year: cur.execute( '''SELECT * FROM works WHERE YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', year ) else: print( 'h2font color=redΠώς να γίνει αναζήτηση αφού δεν επέλεξες ούτε πελάτη ούτε μήνα ή τουλάχιστον το έτος?' ) print( 'meta http-equiv=REFRESH content=5;/cgi-bin/ pelatologio.py' ) sys.exit(0) Here is the definements of those varibles. as you can see are all tuples # populate names, months, years names.add( '==' ) months = ( '==', 'Ιανουάριος', 'Φεβρουάριος', 'Μάρτιος', 'Απρίλιος', 'Μάϊος', 'Ιούνιος', 'Ιούλιος', 'Αύγουστος', 'Σεπτέμβριος', 'Οκτώβριος', 'Νοέμβριος', 'Δεκέμβριος' ) years = ( '==', 2010, 2011, 2012, 2013 ) i used print( name, month, year ) and noticed that all values returned as expected when selected fro drop-down menus and submitted. But when it comes to select '==' form month instead of '==' to be submitted a zero gets submitted and i think the problem is the way i'm filling up months into the drop down menu which is: for i, month in enumerate(months): print('option value=%s %s /option' % (i, month) ) the if case does not execute because of the way it checks for None entry which is: elif '=' not in year: but if enumerate yields 0 instead of '==' then elif '=' not in year of course fails. So, i must tell: for i, month in enumerate(months): print('option value=%s %s /option' % (i, month) ) to somehow return '==' instead of 0 but dont know how. -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On Wed, Jun 12, 2013 at 5:45 PM, Νικόλαος Κούρας supp...@superhost.gr wrote: First of all i have changed the code to the following because using a regex to detect a single char was an overkill. if '=' not in name and '=' not in month and '=' not in year: It'd be courteous to acknowledge those who made that suggestion, most notably alex23 who posted it in almost that exact form. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Turnign greek-iso filenames = utf-8 iso
# # Collect directory and its filenames as bytes path = b'/home/nikos/public_html/data/apps/' files = os.listdir( path ) for filename in files: # Compute 'path/to/filename' filepath_bytes = path + filename for encoding in ('utf-8', 'iso-8859-7', 'latin-1'): try: filepath = filepath_bytes.decode( encoding ) except UnicodeDecodeError: continue # Rename to something valid in UTF-8 if encoding != 'utf-8': os.rename( filepath_bytes, filepath.encode('utf-8') ) assert os.path.exists( filepath.encode('utf-8') ) break else: # This only runs if we never reached the break raise ValueError( 'unable to clean filename %r' % filepath_bytes ) # Collect filenames of the path dir as strings filenames = os.listdir( '/home/nikos/public_html/data/apps/' ) # Build a set of 'path/to/filename' based on the objects of path dir filepaths = set() for filename in filenames: filepaths.add( filename ) == # Load'em for filename in filenames: try: # Check the presence of a file against the database and insert if it doesn't exist cur.execute('''SELECT url FROM files WHERE url = %s''', filename ) data = cur.fetchone() [Wed Jun 12 10:56:56 2013] [error] [client 79.103.41.173] Traceback (most recent call last):, referer: http://superhost.gr/ [Wed Jun 12 10:56:56 2013] [error] [client 79.103.41.173] File /home/ nikos/public_html/cgi-bin/files.py, line 102, in module, referer: http://superhost.gr/ [Wed Jun 12 10:56:56 2013] [error] [client 79.103.41.173] print ( filename ), referer: http://superhost.gr/ [Wed Jun 12 10:56:56 2013] [error] [client 79.103.41.173] File /usr/ local/lib/python3.3/codecs.py, line 355, in write, referer: http:// superhost.gr/ [Wed Jun 12 10:56:56 2013] [error] [client 79.103.41.173] data, consumed = self.encode(object, self.errors), referer: http://superhost.gr/ [Wed Jun 12 10:56:56 2013] [error] [client 79.103.41.173] UnicodeEncodeError: 'utf-8' codec can't encode character '\\udcce' in position 0: surrogates not allowed, referer: http://superhost.gr/ = i tried to insert print( filename ) sys.exit(0) just before the execute and the output is just Pacman.exe as seen in http://superhost.gr/?page=files.py Seens the encoding precedure successfully turned all the filenames from greek-iso to utf-8 without failing, why woul it still be encoding issues when it comes to execute? -- http://mail.python.org/mailman/listinfo/python-list
Re: Encoding questions (continuation)
On 06/11/2013 01:09 PM, Νικόλαος Κούρας wrote: Τη Τρίτη, 11 Ιουνίου 2013 10:52:02 π.μ. UTC+3, ο χρήστης Larry Hudson έγραψε: On 06/10/2013 06:56 AM, Νικόλαος Κούρας wrote: i think your suggestions works only if you have a mail handy in TB and you hit follow-up what if you dont have the mail handy? Followup or Reply brings up the Compose window (with the message you're replying to already quoted). Now you can either type your reply directly, OR if you have it already available you can copy/paste it. THEN you click on Send. If it's a Followup it will be posted to the list, if it is a Reply it sends it as e-mail. BTW, you can *AND SHOULD* edit the quoted text to remove all the unnecessary irrelevant crap, so you are quoting ONLY what you are actually replying to. All the rest is junk and annoying. But definitely keep the parts you are replying to give context to your reply message. -- http://mail.python.org/mailman/listinfo/python-list
Re: Turnign greek-iso filenames = utf-8 iso
On Wed, 12 Jun 2013 08:02:24 +, Νικόλαος Κούρας wrote: i tried to insert print( filename ) sys.exit(0) That's not very useful. That will just print ONE file name, then stop. You have how many files in there? Two? Twenty? What if the problem does not lie with the first one? just before the execute and the output is just Pacman.exe as seen in http://superhost.gr/?page=files.py Wrong. The output is: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. ... Seens the encoding precedure successfully turned all the filenames from greek-iso to utf-8 without failing, why woul it still be encoding issues when it comes to execute? Because the problems are unrelated. Just because you fix one bug, doesn't mean all the other bugs magically disappear. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On Tue, 11 Jun 2013 13:20:52 -0700, Νικόλαος Κούρας wrote: The above if structure works correctly *only* if the user sumbits by form: name, month, year or month, year If, he just enter a year in the form and sumbit then, i get no error, but no results displayed back. Any ideas as to why this might happen? Yes, I know exactly why this is happening. It is for one of two reasons. You may determine which one using the following secret code which I stole from the illuminati in 1836: import random reason = { 1: Input data is not as expected by coder, 2: Flow control logic not performing as coder expects, 3: Badger Badger Badger Badger Badger Badger Badger Badger Mushroom, 4: Please try again, 5: Snake, 6: Grumpy cat says fix your own damn code, 7: I'll be back } print reason[ random.choice( reason.keys() ) ] Note - this only has a small chance of actually doing what you want (ie giving a possibly accurate answer), but it sounds as if that's a level of precision you're used to working with anyway. On a slightly more serious note, if you can't apply yourself to debugging a case of the program logic isn't doing what I expect for some value of program logic that you coded, that may be a hint that: a) you don't actually understand what the program logic is doing b) you shouldn't be writing logic so complex that you can't see how to debug it c) your logic is overly convoluted and complex d) all of the above So perhaps you need to scrub the logic altogether, and start again taking smaller steps. You could also perhaps do with a lesson in De Morgan's theorem: not a and not b and not c = not ( a or b or c ) not a or not b or not c = not ( a and b and c ) and sometimes the alternative form is easier to understand Now, looking at your code here are two important questions: (1) What is the initial values of name, month and year? (2) Which block is actually being executed? Bear in mind that if a branch other than one you expect to be executed is executing, the fail condition might not be what you think it is. Specifically, is it possible that the code is executing the wrong branch and tripping up when it tries to generate or perhaps execute the sql statement empty strings, or just not getting any result from the sql because of the empty strings? Hint - take the code from the current file, apply a liberal smattering of print statements, and test it for various values of month, year and name. def test(name, month, year): print name, month, year ::, name, month, year if not re.search( '=', name ) and not re.search( '=', month ) and not re.search( '=', year ): print branch 1 elif not re.search( '=', month ) and not re.search( '=', year ): print branch 2 elif not re.search( '=', year ): print branch 3 else: print branch 4 # testing logic for 8 possible input conditions test(=, =, =) test(=, =, x) test(=, x, =) test(=, x, x) test(x, =, =) test(x, =, x) test(x, x, =) test(x, x, x) -- Denis McMahon, denismfmcma...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Encoding questions (continuation)
On 06/12/2013 01:20 AM, Larry Hudson wrote: On 06/11/2013 01:09 PM, Νικόλαος Κούρας wrote: Τη Τρίτη, 11 Ιουνίου 2013 10:52:02 π.μ. UTC+3, ο χρήστης Larry Hudson έγραψε: On 06/10/2013 06:56 AM, Νικόλαος Κούρας wrote: I forgot to specify I'm talking about using Thunderbird Newsgroups, not the E-mail part. If you're not using the Thunderbird Newsgroups, try it. It makes things much MUCH easier. (And it eliminates the annoying double-spacing from Google Groups!) -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems with serial port interface
I've done some tests: i've simulated a serial transmission with 1. Terminal.exe https://sites.google.com/site/terminalbpp/ 2. Com0com I've made a script that transmit a char every 5ms. The test system is Terminal---Com0Com---Terminal so i haven't used my program. After 3-4minutes the terminal program crashes, so i think that i have an OS problem: what do you think?I'm using Windows7/64bit... Any suggestion? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On 12/6/2013 11:27 πμ, Denis McMahon wrote: On Tue, 11 Jun 2013 13:20:52 -0700, Νικόλαος Κούρας wrote: The above if structure works correctly *only* if the user sumbits by form: name, month, year or month, year If, he just enter a year in the form and sumbit then, i get no error, but no results displayed back. Any ideas as to why this might happen? Yes, I know exactly why this is happening. It is for one of two reasons. You may determine which one using the following secret code which I stole from the illuminati in 1836: import random reason = { 1: Input data is not as expected by coder, 2: Flow control logic not performing as coder expects, 3: Badger Badger Badger Badger Badger Badger Badger Badger Mushroom, 4: Please try again, 5: Snake, 6: Grumpy cat says fix your own damn code, 7: I'll be back } print reason[ random.choice( reason.keys() ) ] Note - this only has a small chance of actually doing what you want (ie giving a possibly accurate answer), but it sounds as if that's a level of precision you're used to working with anyway. On a slightly more serious note, if you can't apply yourself to debugging a case of the program logic isn't doing what I expect for some value of program logic that you coded, that may be a hint that: a) you don't actually understand what the program logic is doing b) you shouldn't be writing logic so complex that you can't see how to debug it c) your logic is overly convoluted and complex d) all of the above So perhaps you need to scrub the logic altogether, and start again taking smaller steps. You could also perhaps do with a lesson in De Morgan's theorem: not a and not b and not c = not ( a or b or c ) not a or not b or not c = not ( a and b and c ) and sometimes the alternative form is easier to understand Now, looking at your code here are two important questions: (1) What is the initial values of name, month and year? (2) Which block is actually being executed? Bear in mind that if a branch other than one you expect to be executed is executing, the fail condition might not be what you think it is. Specifically, is it possible that the code is executing the wrong branch and tripping up when it tries to generate or perhaps execute the sql statement empty strings, or just not getting any result from the sql because of the empty strings? Hint - take the code from the current file, apply a liberal smattering of print statements, and test it for various values of month, year and name. def test(name, month, year): print name, month, year ::, name, month, year if not re.search( '=', name ) and not re.search( '=', month ) and not re.search( '=', year ): print branch 1 elif not re.search( '=', month ) and not re.search( '=', year ): print branch 2 elif not re.search( '=', year ): print branch 3 else: print branch 4 # testing logic for 8 possible input conditions test(=, =, =) test(=, =, x) test(=, x, =) test(=, x, x) test(x, =, =) test(x, =, x) test(x, x, =) test(x, x, x) Thank you but i already foudn out what the problem was, i just don't known how to fix it. Here is is again: Here is the defines of those variables. as you can see are all tuples # populate names, months, years names.add( '==' ) months = ( '==', 'Ιανουάριος', 'Φεβρουάριος', 'Μάρτιος', 'Απρίλιος', 'Μάϊος', 'Ιούνιος', 'Ιούλιος', 'Αύγουστος', 'Σεπτέμβριος', 'Οκτώβριος', 'Νοέμβριος', 'Δεκέμβριος' ) years = ( '==', 2010, 2011, 2012, 2013 ) i used print( name, month, year ) and noticed that all values returned as expected when selected fro drop-down menus and submitted. But when it comes to select '==' from month instead of '==' to be submitted a zero gets submitted and i think the problem is the way i'm filling up months into the drop down menu which is: for i, month in enumerate(months): print('option value=%s %s /option' % (i, month) ) the if case does not execute because of the way it checks for None entry which is: elif '=' not in year: but if enumerate yields 0 instead of '==' then elif '=' not in year of course fails. So, i must tell: for i, month in enumerate(months): print('option value=%s %s /option' % (i, month) ) to somehow return '==' instead of 0 but don't know how. -- http://mail.python.org/mailman/listinfo/python-list
Re: Modify code with AST
Ronny Mandal wrote: Hello, I am trying to write a script which will parse a code segment (with ast.parse()), locate the correct function/method node (by name) in the resulting tree and replace this function (node) with another function (node), e.g.: MyMod1.py: class FooBar(): def Foo(self): #I want to replace this and only this return 1 def Bar(self): return 2 Here is the parser-class: class FindAndTransform(NodeTransformer): Visit the function and check name def visit_FunctionDef(self, node): if node.name == 'Foo': #Only replace if name is Foo #Create a new function and assign it to node node = parse(''' def add(n, m): return n + m ''') return node When I run the parser on MyMod1.py and generate code (with codegen), the output is: class FooBar(): def add(n, m): return n + m i.e. both methods are replaced. It seems like node in the parser contains all method bodies of class FooBar, not only Foo. When ran through a debugger, it iterates both methods. What I really wanted to do, was to replace only one method (Foo) and leave the other untouched. I hope this was understandable conveyed. I think the main problem is that you have to return the unchanged node (you return None which might be an indentation accident). I also had to take the add() FunctionDef out of the enclosing Module. So (I don't have codegen or is it part of the stdlib?): import ast class FindAndTransform(ast.NodeTransformer): def visit_FunctionDef(self, node): if node.name == 'Foo': node = ast.parse(''' def add(n, m): return n + m ''').body[0] return node if __name__ == __main__: orig = class FooBar(): def Foo(self): #I want to replace this and only this return 1 def Bar(self): return 2 p = ast.parse(orig) q = FindAndTransform().visit(p) qq = compile(q, nofile, exec) exec(qq) assert {n for n in dir(FooBar) if not n.startswith(_)} == {Bar, add} -- http://mail.python.org/mailman/listinfo/python-list
Re: Turnign greek-iso filenames = utf-8 iso
On 12/6/2013 11:31 πμ, Steven D'Aprano wrote: On Wed, 12 Jun 2013 08:02:24 +, Νικόλαος Κούρας wrote: i tried to insert print( filename ) sys.exit(0) That's not very useful. That will just print ONE file name, then stop. You have how many files in there? Two? Twenty? What if the problem does not lie with the first one? just before the execute and the output is just Pacman.exe as seen in http://superhost.gr/?page=files.py Wrong. The output is: Internal Server Error print( filenames ) sys.exit(0) No it dosnt not, it loads properly and if you visit it again you will see all the files being displayed since now i: print( filenames ) sys.exit(0) Thne grek ones ar displayed as '\udcce\udc95\udccf\udc85\udccf\udc87\udcce\udcae \udccf\udc84\udcce\udcbf\udccf\udc85 \udcce\udc99\udcce\udcb7\udccf\udc83\udcce\udcbf\udccf\udc8d.mp3' in Chrome dont know why since the above procedure supposed to turned them into utf-8 ls -l apps though via putty display all filesnames correctly. === # Collect filenames of the path dir as strings filenames = os.listdir( '/home/nikos/public_html/data/apps/' ) # Build a set of 'path/to/filename' based on the objects of path dir filepaths = set() for filename in filenames: filepaths.add( filename ) # Load'em for filename in filenames: try: # Check the presence of a file against the database and insert if it doesn't exist print( filenames ) sys.exit(0) cur.execute('''SELECT url FROM files WHERE url = %s''', filename ) data = cur.fetchone() === Into the database only 2 english have been inserted pacman.exe and one other english filenames before filename breaks into the execute statemnt. -- http://mail.python.org/mailman/listinfo/python-list
Re: Turnign greek-iso filenames = utf-8 iso
root@nikos [/home/nikos/www/data/apps]# ls -l total 412788 drwxr-xr-x 2 nikos nikos 4096 Jun 12 12:03 ./ drwxr-xr-x 6 nikos nikos 4096 May 26 21:13 ../ -rwxr-xr-x 1 nikos nikos 13157283 Mar 17 12:57 100\ Mythoi\ tou\ Aiswpou.pdf* -rwxr-xr-x 1 nikos nikos 29524686 Mar 11 18:17 Anekdotologio.exe* -rw-r--r-- 1 nikos nikos 42413964 Jun 2 20:29 Battleship.exe -rw-r--r-- 1 nikos nikos 51819750 Jun 2 20:04 Luxor\ Evolved.exe -rw-r--r-- 1 nikos nikos 60571648 Jun 2 14:59 Monopoly.exe -rwxr-xr-x 1 nikos nikos 1788164 Mar 14 11:31 Online\ Movie\ Player.zip* -rw-r--r-- 1 nikos nikos 5277287 Jun 1 18:35 O\ Nomos\ tou\ Merfy\ v1-2-3.zip -rwxr-xr-x 1 nikos nikos 16383001 Jun 22 2010 Orthodoxo\ Imerologio.exe* -rw-r--r-- 1 nikos nikos 6084806 Jun 1 18:22 Pac-Man.exe -rw-r--r-- 1 nikos nikos 45297713 Jun 10 12:38 Raptor\ Chess.exe -rw-r--r-- 1 nikos nikos 25476584 Jun 2 19:50 Scrabble.exe -rwxr-xr-x 1 nikos nikos 49141166 Mar 17 12:48 To\ 1o\ mou\ vivlio\ gia\ to\ skaki.pdf* -rwxr-xr-x 1 nikos nikos 3298310 Mar 17 12:45 Vivlos\ gia\ Atheofovous.pdf* -rw-r--r-- 1 nikos nikos 1764864 May 29 21:50 V-Radio\ v2.4.msi -rw-r--r-- 1 nikos nikos 3511233 Jun 4 14:11 Ευχή\ του\ Ιησού.mp3 -rwxr-xr-x 1 nikos nikos 66896732 Mar 17 13:13 Κοσμάς\ Αιτωλός\ -\ Προφητείες.pdf* -rw-r--r-- 1 nikos nikos 236032 Jun 4 14:10 Σκέψου\ έναν\ αριθμό.exe root@nikos [/home/nikos/www/data/apps]# -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On Wed, Jun 12, 2013 at 9:54 AM, Νικόλαος Κούρας supp...@superhost.gr wrote: but if enumerate yields 0 instead of '==' then elif '=' not in year of course fails. So, i must tell: for i, month in enumerate(months): print('option value=%s %s /option' % (i, month) ) to somehow return '==' instead of 0 but don't know how. -- http://mail.python.org/mailman/listinfo/python-list Well, you could try this: for i, month in enumerate(months): if i == 0: month = ('=' * 10) print('option value=%s %s /option' % (i, month) ) No? -- Fábio Santos -- http://mail.python.org/mailman/listinfo/python-list
Re: A few questiosn about encoding
(*) infact UTF8 also indicates the end of each character Up to a point. The initial byte encodes the length and the top few bits, but the subsequent octets aren’t distinguishable as final in isolation. 0x80-0xBF can all be either medial or final. So, the first high-bits are a directive that UTF-8 uses to know how many bytes each character is being represented as. 0-127 codepoints(characters) use 1 bit to signify they need 1 bit for storage and the rest 7 bits to actually store the character ? while 128-256 codepoints(characters) use 2 bit to signify they need 2 bits for storage and the rest 14 bits to actually store the character ? Isn't 14 bits way to many to store a character ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Turnign greek-iso filenames = utf-8 iso
On Wed, 12 Jun 2013 08:02:24 +, Νικόλαος Κούρας wrote: # Collect directory and its filenames as bytes path = b'/home/nikos/public_html/data/apps/' files = os.listdir( path ) [snip code] I realised that the version I gave you earlier, or rather the modified version you came up with, was subject to a race condition. If somebody uploaded a file while the script was running, and that file name was not UTF-8 clean, the script would fail. This version may be more robust and should be resistant to race conditions when files are uploaded. (However, do not *delete* files while this script is running.) As before, I have not tested this. I recommend that you test it thoroughly before deploying it live. def guess_encoding(bytestring): for encoding in ('utf-8', 'iso-8859-7', 'latin-1'): try: bytestring.decode(encoding) except UnicodeDecodeError: # Decoding failed. Try the next one. pass else: # Decoding succeeded. This is our guess. return encoding # If we get here, none of the encodings worked. We cannot guess. return None path = b'/home/nikos/public_html/data/apps/' files = os.listdir( path ) clean_files = [] for filename in files: # Compute 'path/to/filename' filepath_bytes = path + filename encoding = guess_encoding(filepath_bytes) if encoding == 'utf-8': # File name is valid UTF-8, so we can skip to the next file. clean_files.append(filepath_bytes) continue if encoding is None: # No idea what the encoding is. Hit it with a hammer until it # stops moving. filename = filepath_bytes.decode('utf-8', 'xmlcharrefreplace') else: filename = filepath_bytes.decode(encoding) # Rename the file to something which ought to be UTF-8 clean. newname_bytes = filename.encode('utf-8') os.rename(filepath_bytes, newname_bytes) clean_files.append(newname_bytes) # Once we get here, the file ought to be UTF-8 clean, # and the Unicode name ought to exist: assert os.path.exists(newname_bytes.decode('utf-8')) # Dump the old list of file names, it is no longer valid. del files # DO NOT CALL listdir again. Somebody might have uploaded a # new file, with a broken file name. That will be fixed next # time this script runs, but for now, we ignore the dirty file # name and just use the list of clean file names we built above. clean_files = set(clean_files) for name_as_bytes in sorted(clean_files): filename = name_as_bytes.decode('utf-8') # Check the presence of a file against the database # and insert if it doesn't exist cur.execute('SELECT url FROM files WHERE url = %s', filename) data = cur.fetchone() -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Turnign greek-iso filenames = utf-8 iso
On Wed, 12 Jun 2013 12:00:38 +0300, Νικόλαος Κούρας wrote: On 12/6/2013 11:31 πμ, Steven D'Aprano wrote: On Wed, 12 Jun 2013 08:02:24 +, Νικόλαος Κούρας wrote: and the output is just Pacman.exe as seen in http://superhost.gr/?page=files.py Wrong. The output is: Internal Server Error print( filenames ) sys.exit(0) No it dosnt not, it loads properly and if you visit it again you will see all the files being displayed since now i: Wrong again. It still gives Internal Error. I have just revisited the page three times now, and every time it still fails. I am not lying, I am not making this up. Here is the text: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator, supp...@superhost.gr and inform them of the time the error occurred, and anything you might have done that may have caused the error. More information about this error may be available in the server error log. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. Apache/2.2.24 (Unix) mod_ssl/2.2.24 OpenSSL/1.0.0-fips mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635 Server at superhost.gr Port 80 -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On 12/6/2013 12:07 μμ, F�bio Santos wrote: On Wed, Jun 12, 2013 at 9:54 AM, Νικόλαος Κούρας supp...@superhost.gr wrote: but if enumerate yields 0 instead of '==' then elif '=' not in year of course fails. So, i must tell: for i, month in enumerate(months): print('option value=%s %s /option' % (i, month) ) to somehow return '==' instead of 0 but don't know how. -- http://mail.python.org/mailman/listinfo/python-list Well, you could try this: for i, month in enumerate(months): if i == 0: month = ('=' * 10) print('option value=%s %s /option' % (i, month) ) No? I'am afraid not Fabio, i just tried byt sumbitting only the year, not name not month after printign the valeus to see what went wrong, the values look like: == 0 2010 instead of: == == 2010 == is the value of the month when its not selected by the user, but even with your suggestions it reurns t0 intead of the equal signs. -- http://mail.python.org/mailman/listinfo/python-list
Re: Turnign greek-iso filenames = utf-8 iso
On 12/6/2013 12:17 μμ, Steven D'Aprano wrote: On Wed, 12 Jun 2013 12:00:38 +0300, Νικόλαος Κούρας wrote: On 12/6/2013 11:31 πμ, Steven D'Aprano wrote: On Wed, 12 Jun 2013 08:02:24 +, Νικόλαος Κούρας wrote: and the output is just Pacman.exe as seen in http://superhost.gr/?page=files.py Wrong. The output is: Internal Server Error print( filenames ) sys.exit(0) No it dosnt not, it loads properly and if you visit it again you will see all the files being displayed since now i: Wrong again. It still gives Internal Error. I have just revisited the page three times now, and every time it still fails. I am not lying, I am not making this up. Here is the text: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator, supp...@superhost.gr and inform them of the time the error occurred, and anything you might have done that may have caused the error. More information about this error may be available in the server error log. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. Apache/2.2.24 (Unix) mod_ssl/2.2.24 OpenSSL/1.0.0-fips mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635 Server at superhost.gr Port 80 I know that you do not lie and also i think i know why *you* specifically can load my webiste. i think your ip address does not have a PTR entry (reverse DNS entry) and when you try to laod superhost.gr this lines fail for you and hece it errs out an internal server error. host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0] i just switched the above line to to avoid missing PTRs host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0] or 'UnResolved' Try now please. -- http://mail.python.org/mailman/listinfo/python-list
Re: A few questiosn about encoding
On Wed, 12 Jun 2013 09:09:05 +, Νικόλαος Κούρας wrote: Isn't 14 bits way to many to store a character ? No. There are 1114111 possible characters in Unicode. (And in Japan, they sometimes use TRON instead of Unicode, which has even more.) If you list out all the combinations of 14 bits: 00 01 10 11 [...] 10 11 you will see that there are only 32767 (2**15-1) such values. You can't fit 1114111 characters with just 32767 values. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Turnign greek-iso filenames = utf-8 iso
On Wed, 12 Jun 2013 12:24:24 +0300, Νικόλαος Κούρας wrote: On 12/6/2013 12:17 μμ, Steven D'Aprano wrote: On Wed, 12 Jun 2013 12:00:38 +0300, Νικόλαος Κούρας wrote: On 12/6/2013 11:31 πμ, Steven D'Aprano wrote: On Wed, 12 Jun 2013 08:02:24 +, Νικόλαος Κούρας wrote: and the output is just Pacman.exe as seen in http://superhost.gr/?page=files.py Νικόλαος, look at the URL you have given me. It still fails. I have tested it repeatedly.[1] Now look at this URL: http://superhost.gr/data/apps/ Notice that it is a different URL? That one works and shows the file listing. Also, you need to include an encoding line in the page, otherwise people viewing it will see mojibake. You need a line like: meta charset=UTF-8 / in the generated HTML. [1] Correction. While I was typing this, it came good, for about 20 seconds, and displayed a hideously ugly background pattern and a cute smiling face waving, and then broke again. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On 12 Jun 2013 10:29, Νικόλαος Κούρας supp...@superhost.gr wrote: On 12/6/2013 12:07 μμ, F�bio Santos wrote: On Wed, Jun 12, 2013 at 9:54 AM, Νικόλαος Κούρας supp...@superhost.gr wrote: but if enumerate yields 0 instead of '==' then elif '=' not in year of course fails. So, i must tell: for i, month in enumerate(months): print('option value=%s %s /option' % (i, month) ) to somehow return '==' instead of 0 but don't know how. -- http://mail.python.org/mailman/listinfo/python-list Well, you could try this: for i, month in enumerate(months): if i == 0: month = ('=' * 10) print('option value=%s %s /option' % (i, month) ) No? I'am afraid not Fabio, i just tried byt sumbitting only the year, not name not month after printign the valeus to see what went wrong, the values look like: == 0 2010 instead of: == == 2010 == is the value of the month when its not selected by the user, but even with your suggestions it reurns t0 intead of the equal signs. -- http://mail.python.org/mailman/listinfo/python-list Have you tried i = month = '=' * 10 I had assumed you just wanted those equal signs for the user display. -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
[Please trim your replies to the relevant parts.] On 12.06.2013 10:54, Νικόλαος Κούρας wrote: But when it comes to select '==' from month instead of '==' to be submitted a zero gets submitted and i think the problem is the way i'm filling up months into the drop down menu which is: for i, month in enumerate(months): print('option value=%s %s /option' % (i, month) ) the if case does not execute because of the way it checks for None entry which is: elif '=' not in year: but if enumerate yields 0 instead of '==' then elif '=' not in year of course fails. How often do we need to tell you that you should reread your posts before sending them? You start with telling us you have problems with month and then show us code regarding year So, i must tell: for i, month in enumerate(months): print('option value=%s %s /option' % (i, month) ) to somehow return '==' instead of 0 but don't know how. As with most of your problems you are barking up the wrong tree. Why not use the actual value you get from the form to check whether you have a valid month? Do you understand why 0 is submitted instead of ==? Bye, Andreas -- http://mail.python.org/mailman/listinfo/python-list
Re: Questions on import and datetime
On Monday, June 10, 2013 7:01:30 PM UTC+2, Zachary Ware wrote: On Mon, Jun 10, 2013 at 10:37 AM, Yunfei Dai yunfei.dai.si...@gmail.com wrote: Hi all, Hi Yunfei, I have some questions on import: 1.from datetime import datetime works well. But I am confused why import datetime.datetime leads to importerror. from xlrd import open_workbook could be replaced by from xlrd.open_workbook without any problem. I assume you mean import xlrd.open_workbook here, as from xlrd.open_workbook would be a SyntaxError :) The only difference here is that if from xlrd import open_workbook is used we do not have to write xlrd.open_workbook in the following code but just open_workbook. So my understanding of the difference is from...import... shortens the code (just like using namespace std in C++) but maybe leads to name clash. from ... import ... imports an object from a module and assigns it to a local name that is the same as the name in the other module. In other words, the following two examples do the same thing: from foo import bar import foo;bar = foo.bar If foo.bar happens to be a module (module 'bar' in package 'foo'), you could also do this: import foo.bar as bar ...and that restriction is where your problem lies. But what is the problem of datetime? I'm not familiar with xlrd, but I believe the difference between xlrd.open_workbook and datetime.datetime would be that xlrd.open_workbook is a module in a package, while datetime.datetime is a class in a module. 'from ... import ...' can import any object from the target module/package, and assign it to a local name. 'import ...' on the other hand can only import a module (you'll notice the ImportError you get when you try 'import datetime.datetime' is 'No module named datetime'. This particular example is a bit confusing due to there being a class in a module of the same name, but try 'import datetime.date' for a clearer message. 2.I am also comfused that datetime.datetime is a function but whithin datetime.datetime there are lots of other functions. So what is the type of datetime.datetime on earth? is it a function, or a class or a folder(library) here? datetime.datetime is actually a type of type 'type' (as can be seen with 'import datetime;type(datetime.datetime)'). In Python 2, this means it is a new-style class (meaning it is a subclass of 'object'). In Python 3, it's just a class (since there are no longer old-style classes). Thanks very much in advance! Very looking forward to your answers. Best, Yunfei I hope I have actually answered your question and not just muddied things further for you. You can of course ask again if I've made things worse :) -- Zach Hi Zach, Thanks so much for your quick, long and detailed reply and sorry for replying you late. It is really helpful for me understanding import. Yunfei -- http://mail.python.org/mailman/listinfo/python-list
Re: Modify code with AST
I think the main problem is that you have to return the unchanged node (you return None which might be an indentation accident). I also had to take the add() FunctionDef out of the enclosing Module. So (I don't have codegen or is it part of the stdlib?): Thank you, my problem is now solved. It was the indentation of the return statement which was the culprit. I forgot that visit() (in this context) is called once for each FunctionDef-node. I moved the return-statement one click to the left, then it worked. codegen is not a part of the stdlib. It is written by Armin Ronacher (the same person who wrote ast) and it uses ast to generate python code from the AST. Thanks! Regards, Ronny Mandal import ast class FindAndTransform(ast.NodeTransformer): def visit_FunctionDef(self, node): if node.name == 'Foo': node = ast.parse(''' def add(n, m): return n + m ''').body[0] return node if __name__ == __main__: orig = class FooBar(): def Foo(self): #I want to replace this and only this return 1 def Bar(self): return 2 p = ast.parse(orig) q = FindAndTransform().visit(p) qq = compile(q, nofile, exec) exec(qq) assert {n for n in dir(FooBar) if not n.startswith(_)} == {Bar, add} -- http://mail.python.org/mailman/listinfo/python-list
Re: Turnign greek-iso filenames = utf-8 iso
Thanks Steven , i made some alternations to the variables names and at the end of the way that i check a database filename against and hdd filename. Here is the code: # = # Convert wrongly encoded filenames to utf-8 # = path = b'/home/nikos/public_html/data/apps/' filenames = os.listdir( path ) utf8_filenames = [] for filename in filenames: # Compute 'path/to/filename' filename_bytes = path + filename encoding = guess_encoding( filename_bytes ) if encoding == 'utf-8': # File name is valid UTF-8, so we can skip to the next file. utf8_filenames.append( filename_bytes ) continue elif encoding is None: # No idea what the encoding is. Hit it with a hammer until it stops moving. filename = filename_bytes.decode( 'utf-8', 'xmlcharrefreplace' ) else: filename = filename_bytes.decode( encoding ) # Rename the file to something which ought to be UTF-8 clean. newname_bytes = filename.encode('utf-8') os.rename( filename_bytes, newname_bytes ) utf8_filenames.append( newname_bytes ) # Once we get here, the file ought to be UTF-8 clean and the Unicode name ought to exist: assert os.path.exists( newname_bytes.decode('utf-8') ) # Switch filenames from utf8 bytestrings = unicode strings filenames = [] for utf8_filename in utf8_filenames: filenames.append( utf8_filename.decode('utf-8') ) # Check the presence of a database file against the dir files and delete record if it doesn't exist cur.execute('''SELECT url FROM files''') data = cur.fetchall() for url in data: if url not in filenames: # Delete spurious cur.execute('''DELETE FROM files WHERE url = %s''', url ) = Now 'http://superhost.gr/?page=files.py' is not erring out at all but also it doesn't display the big filename table for users to download. Here is how i try to print the filenames with button for the users: = #Display ALL files, each with its own download button# = print('''body background='/data/images/star.jpg' centerimg src='/data/images/download.gif'brbr table border=5 cellpadding=5 bgcolor=green ''') try: cur.execute( '''SELECT * FROM files ORDER BY lastvisit DESC''' ) data = cur.fetchall() for row in data: (filename, hits, host, lastvisit) = row lastvisit = lastvisit.strftime('%A %e %b, %H:%M') print(''' form method=get action=/cgi-bin/files.py tr td center input type=submit name=filename value=%s /td td center font color=yellow size=5 %s /td td center font color=orange size=4 %s /td td center font color=silver size=4 %s /td /tr /form ''' % (filename, hits, host, lastvisit) ) print( '''/tablebrbr''' ) except pymysql.ProgrammingError as e: print( repr(e) ) -- http://mail.python.org/mailman/listinfo/python-list
Re: Questions on import and datetime
On Monday, June 10, 2013 9:10:16 PM UTC+2, Dave Angel wrote: On 06/10/2013 01:01 PM, Zachary Ware wrote: On Mon, Jun 10, 2013 at 10:37 AM, Yunfei Dai yunfei.dai.si...@gmail.com wrote: Hi all, Hi Yunfei, I have some questions on import: 1.from datetime import datetime works well. But I am confused why import datetime.datetime leads to importerror. from xlrd import open_workbook could be replaced by from xlrd.open_workbook without any problem. It's a historical flaw in datetime that the class has the same name as the module it's in. It should have been called class Datetime (according to pep 10, class names should be capitalized). If that were the case, it'd be clear that datetime.Datetime is a class. It would also be clearer that from datetime import Datetime creates an alias in the present global namespace for the datetime.Datetime class, as simply Datetime. This class has attributes that you can access, like Datetime.hour, and it has static methods like Datetime.fromTimeStamp(). And like all classes, it's callable, meaning that you can create an instance by pretending it's a function: obj = Datetime(2013, 12, 1) But since it's not a module inside a package, you can't use the form: import datetime.Datetime Now, just interpret all the above with a lowercase D and the confusion becomes clearer. The compiler/interpreter doesn't care either way. SNIP from ... import ... imports an object from a module and assigns it to a local name that is the same as the name in the other module. In other words, the following two examples do the same thing: from foo import bar import foo;bar = foo.bar If foo.bar happens to be a module (module 'bar' in package 'foo'), you could also do this: import foo.bar as bar ...and that restriction is where your problem lies. In other words, since datetime.datetime is a class, not a module, you can't just import it. SNIP 2.I am also comfused that datetime.datetime is a function but whithin datetime.datetime there are lots of other functions. So what is the type of datetime.datetime on earth? is it a function, or a class or a folder(library) here? As I said before, datetime.datetime is a class, and the functions within it are called methods. You can see it all for yourself very easily. Use the __file__ attribute to locate the source for datetime module on your system. Here's what it looks like on mine: import datetime datetime.__file__ '/usr/local/lib/python3.3/datetime.py' Then you can go look at that file. For my copy, the datetime class begins at 1301. But you can just search for the following line: class datetime(date): HTH -- DaveA Thank you Dave for your reply! It is very helpful. -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On 11Jun2013 18:25, Nikos nagia.rets...@gmail.com wrote: | What are the values of 'name', 'month' and 'year' in each of the cases? | | Printing out ascii(name), ascii(month) and ascii(year), will be helpful. | | Then try stepping through those lines in your head. | | i hav epribted all values of those variables and they are all correct. | i just dont see why ti fails to enter the specific if case. Gah! _Show_ us the values! And _specify_ which part of the if-statement should run. -- Cameron Simpson c...@zip.com.au It's a vague science. - Rory Tate, circle researcher. -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
Original Message Subject: Re: A certainl part of an if() structure never gets executed. Date: Wed, 12 Jun 2013 10:07:39 +0100 From: Fábio Santos fabiosantos...@gmail.com To: Νικόλαος Κούρας supp...@superhost.gr CC: python-list@python.org python-list@python.org Newsgroups: comp.lang.python References: 2bc90d3b-09c2-4315-9357-ff7f03946...@googlegroups.com kp9bcq$o1i$2...@dont-email.me kp9d02$1jfb$1...@news.ntua.gr On Wed, Jun 12, 2013 at 9:54 AM, Νικόλαος Κούρας supp...@superhost.gr wrote: but if enumerate yields 0 instead of '==' then elif '=' not in year of course fails. So, i must tell: for i, month in enumerate(months): print('option value=%s %s /option' % (i, month) ) to somehow return '==' instead of 0 but don't know how. -- http://mail.python.org/mailman/listinfo/python-list Well, you could try this: for i, month in enumerate(months): if i == 0: month = ('=' * 10) print('option value=%s %s /option' % (i, month) ) No? You can see if for yourself if you go to: http://superhost.gr/?page=pelatologio.py bottom down where the form drop down menus are: search will work but f the suer just gives out the year it will never make it to the specific if() branch. -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On 12/6/2013 1:07 μμ, Andreas Perstinger wrote: So, i must tell: for i, month in enumerate(months): print('option value=%s %s /option' % (i, month) ) to somehow return '==' instead of 0 but don't know how. As with most of your problems you are barking up the wrong tree. Why not use the actual value you get from the form to check whether you have a valid month? Do you understand why 0 is submitted instead of ==? No, this is exactly what i do not understand. months = ( '==', 'Ιανουάριος', 'Φεβρουάριος', 'Μάρτιος', 'Απρίλιος', 'Μάϊος', 'Ιούνιος', 'Ιούλιος', 'Αύγουστος', 'Σεπτέμβριος', 'Οκτώβριος', 'Νοέμβριος', 'Δεκέμβριος' ) This is a tuple containign months. Then we have this: for i, month in enumerate(months): print('option value=%s %s /option' % (i, month) ) i is assiciated to month in similar fashion as a dic's key to it's value i = the increasing counter after each iteration in the loop month = just the displayed month. when iteration happens we get this: value 0 for month '==' value 1 for month 'Ιανουάριος' . . value 12 for month 'Δεκέμβριος' So when '==' is being selected as month from the user value 0 is beign returned, but what i need is the string '==' itself, not the value. the year var have no prblem, is the month that always fails the if() condition branch. -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
Oh my God! i just need to do this: for i, month in enumerate( months ): print('option value=%s %s /option' % (month, month) ) -- http://mail.python.org/mailman/listinfo/python-list
Re: PYTHONPATH: dev and prod
this idea seemed perfect but it turned out that you have to execute the module as a package (python -m scripts.myscript) otherwise I get an error on the relative import. Unfortunately I am working in a team and I do not have control on how the module is launched. On Tuesday, June 11, 2013 6:14:43 PM UTC+1, rusi wrote: On Jun 11, 9:28 pm, jacopo jacopo.pe...@gmail.com wrote: I am developing my code in the path: /py/myscripts /py/mylib In order to import mylib, I need to add /py/mylib to PYTHONPATH. Now I want to save a snapshot of the current code in the production directory, I will copy all in: /prod/myscripts /prod/mylib The problem now is that when I execute /prod/myscripts/any_script.py, every import will look at PYTHONPATH and therefore it will load the modules from /py/mylib. On the contrary I want to load it from /prod/mylib. Is there an elegant way to cope with this? thanks, Jacopo I-think Use explicit (dot-based) relative imports http://docs.python.org/release/2.5/whatsnew/pep-328.html Avoid using PYTHONPATH /I-think -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
Am Mittwoch, 12. Juni 2013 12:07:54 UTC+2 schrieb Andreas Perstinger: [Please trim your replies to the relevant parts.] On 12.06.2013 10:54, Νικόλαος Κούρας wrote: But when it comes to select '==' from month instead of '==' to be submitted a zero gets submitted and i think the problem is the way i'm filling up months into the drop down menu which is: for i, month in enumerate(months): print('option value=%s %s /option' % (i, month) ) the if case does not execute because of the way it checks for None entry which is: elif '=' not in year: but if enumerate yields 0 instead of '==' then elif '=' not in year of course fails. How often do we need to tell you that you should reread your posts before sending them? You start with telling us you have problems with month and then show us code regarding year So, i must tell: for i, month in enumerate(months): print('option value=%s %s /option' % (i, month) ) to somehow return '==' instead of 0 but don't know how. As with most of your problems you are barking up the wrong tree. Why not use the actual value you get from the form to check whether you have a valid month? Do you understand why 0 is submitted instead of ==? To Nikos: My I elaborate that for you: Your form contains: option value=0 == /option If you still don't know why you get 0 read: http://www.w3schools.com/tags/att_option_value.asp (or something in greek about html forms) (Sorry, I know, you do not read doks, because they describe what the software DOES and not what you WANT it to DO) So this is no python problem, it is a html-problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: PYTHONPATH: dev and prod
this idea seemed perfect but it turned out that you have to execute the module as a package (python -m py.myscripts.any_script) otherwise I get an error on the relative import. Unfortunately I am working in a team and I do not have control on how the module is launched. On Tuesday, June 11, 2013 6:14:43 PM UTC+1, rusi wrote: On Jun 11, 9:28 pm, jacopo jacopo.pe...@gmail.com wrote: I am developing my code in the path: /py/myscripts /py/mylib In order to import mylib, I need to add /py/mylib to PYTHONPATH. Now I want to save a snapshot of the current code in the production directory, I will copy all in: /prod/myscripts /prod/mylib The problem now is that when I execute /prod/myscripts/any_script.py, every import will look at PYTHONPATH and therefore it will load the modules from /py/mylib. On the contrary I want to load it from /prod/mylib. Is there an elegant way to cope with this? thanks, Jacopo I-think Use explicit (dot-based) relative imports http://docs.python.org/release/2.5/whatsnew/pep-328.html Avoid using PYTHONPATH /I-think -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
As with most of your problems you are barking up the wrong tree. Why not use the actual value you get from the form to check whether you have a valid month? Do you understand why 0 is submitted instead of ==? Bye, Andreas I have corrected the enumerate loop but it seems thet now the year works and the selected name nad month fail: if '=' not in ( name and month and year ): cur.execute( '''SELECT * FROM works WHERE clientsID = (SELECT id FROM clients WHERE name = %s) and MONTH(lastvisit) = %s and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (name, month, year) ) elif '=' not in ( month and year ): cur.execute( '''SELECT * FROM works WHERE MONTH(lastvisit) = %s and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (month, year) ) elif '=' not in year: cur.execute( '''SELECT * FROM works WHERE YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', year ) else: print( 'h2font color=redΠώς να γίνει αναζήτηση αφού δεν επέλεξες ούτε πελάτη ούτε μήνα ή τουλάχιστον το έτος?' ) print( 'meta http-equiv=REFRESH content=5;/cgi-bin/pelatologio.py' ) sys.exit(0) i tried in , not in and all possible combinations. but somehow it confuses me. doesn't that mean? if '=' not in ( name and month and year ): if '=' does not exists as a char inside the name and month and year variables? i think it does, but why it fails then? -- http://mail.python.org/mailman/listinfo/python-list
Re: A few questiosn about encoding
On 12/6/2013 12:24 μμ, Steven D'Aprano wrote: On Wed, 12 Jun 2013 09:09:05 +, Νικόλαος Κούρας wrote: Isn't 14 bits way to many to store a character ? No. There are 1114111 possible characters in Unicode. (And in Japan, they sometimes use TRON instead of Unicode, which has even more.) If you list out all the combinations of 14 bits: 00 01 10 11 [...] 10 11 you will see that there are only 32767 (2**15-1) such values. You can't fit 1114111 characters with just 32767 values. Thanks Steven, So, how many bytes does UTF-8 stored for codepoints 127 ? example for codepoint 256, 1345, 16474 ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Turnign greek-iso filenames = utf-8 iso
On 12/6/2013 12:37 μμ, Steven D'Aprano wrote: On Wed, 12 Jun 2013 12:24:24 +0300, Νικόλαος Κούρας wrote: [1] Correction. While I was typing this, it came good, for about 20 seconds, and displayed a hideously ugly background pattern and a cute smiling face waving, and then broke again. Ah sorry Steven i made the change of: host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0] or 'UnResolved' to metrites.py isntead of files.py now i have made both chnages. you can see the webpage now, eys the one with the cure smile face. behidn that we should beeen seeing all the files in a table like format for uses to downlaod, instead not a single file is being displayed. here is the print process., actually here is what i have up until now after modifications for you to take an overall look. # = # Convert wrongly encoded filenames to utf-8 # = path = b'/home/nikos/public_html/data/apps/' filenames = os.listdir( path ) utf8_filenames = [] for filename in filenames: # Compute 'path/to/filename' filename_bytes = path + filename encoding = guess_encoding( filename_bytes ) if encoding == 'utf-8': # File name is valid UTF-8, so we can skip to the next file. utf8_filenames.append( filename_bytes ) continue elif encoding is None: # No idea what the encoding is. Hit it with a hammer until it stops moving. filename = filename_bytes.decode( 'utf-8', 'xmlcharrefreplace' ) else: filename = filename_bytes.decode( encoding ) # Rename the file to something which ought to be UTF-8 clean. newname_bytes = filename.encode('utf-8') os.rename( filename_bytes, newname_bytes ) utf8_filenames.append( newname_bytes ) # Once we get here, the file ought to be UTF-8 clean and the Unicode name ought to exist: assert os.path.exists( newname_bytes.decode('utf-8') ) # Switch filenames from utf8 bytestrings = unicode strings filenames = [] for utf8_filename in utf8_filenames: filenames.append( utf8_filename.decode('utf-8') ) # Check the presence of a database file against the dir files and delete record if it doesn't exist cur.execute('''SELECT url FROM files''') data = cur.fetchall() for url in data: if url not in filenames: # Delete spurious cur.execute('''DELETE FROM files WHERE url = %s''', url ) # = # Display ALL files, each with its own download button # = print('''body background='/data/images/star.jpg' centerimg src='/data/images/download.gif'brbr table border=5 cellpadding=5 bgcolor=green ''') try: cur.execute( '''SELECT * FROM files ORDER BY lastvisit DESC''' ) data = cur.fetchall() for row in data: (filename, hits, host, lastvisit) = row lastvisit = lastvisit.strftime('%A %e %b, %H:%M') print(''' form method=get action=/cgi-bin/files.py tr td center input type=submit name=filename value=%s /td td center font color=yellow size=5 %s /td td center font color=orange size=4 %s /td td center font color=silver size=4 %s /td /tr /form ''' % (filename, hits, host, lastvisit) ) print( '''/tablebrbr''' ) except pymysql.ProgrammingError as e: print( repr(e) ) sys.exit(0) == ima happy that at elaST IT DOES NOT ERRIGN OUT! -- http://mail.python.org/mailman/listinfo/python-list
Re: Split a list into two parts based on a filter?
In article mailman.3050.1371018754.3114.python-l...@python.org, Phil Connell pconn...@gmail.com wrote: Well, continuing down this somewhat bizarre path: new_songs, old_songs = [], [] itertools.takewhile( lambda x: True, (new_songs if s.is_new() else old_songs).append(s) for s in songs) ) I'm not sure I got the syntax exactly right, but the idea is anything that will iterate over a generator expression. That at least gets rid of the memory requirement to hold the throw-away list :-) You could equivalently pass the generator to deque() with maxlen=0 - this consumes the iterator with constant memory usage. We are of course firmly in the twilight zone at this point (although this can be a useful technique in general). We've been in the twilight zone for a while. That's when the fun starts. But, somewhat more seriously, I wonder what, exactly, it is that freaks people out about: [(new_songs if s.is_new() else old_songs).append(s) for s in songs] Clearly, it's not the fact that it build and immediately discards a list, because that concern is addressed with the generator hack, and I think everybody (myself included) agrees that's just horrible. Or, is it the use of the conditional to create the target for append()? Would people be as horrified if I wrote: for s in songs: (new_songs if s.is_new() else old_songs).append(s) or even: for s in songs: the_right_list = new_songs if s.is_new() else old_songs the_right_list.append(s) -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On 12 Jun 2013 12:08, Νικόλαος Κούρας supp...@superhost.gr wrote: Oh my God! i just need to do this: for i, month in enumerate( months ): print('option value=%s %s /option' % (month, month) ) Usually what goes in option value=... is an ID of something. You should keep using (i, month) and then do months[id] to get the month string. Also, tuples aren't traditionally used for this. Normally you'd use a list. -- http://mail.python.org/mailman/listinfo/python-list
Re: Split a list into two parts based on a filter?
On 12 Jun 2013 12:43, Roy Smith r...@panix.com wrote: In article mailman.3050.1371018754.3114.python-l...@python.org, Phil Connell pconn...@gmail.com wrote: Well, continuing down this somewhat bizarre path: new_songs, old_songs = [], [] itertools.takewhile( lambda x: True, (new_songs if s.is_new() else old_songs).append(s) for s in songs) ) I'm not sure I got the syntax exactly right, but the idea is anything that will iterate over a generator expression. That at least gets rid of the memory requirement to hold the throw-away list :-) You could equivalently pass the generator to deque() with maxlen=0 - this consumes the iterator with constant memory usage. We are of course firmly in the twilight zone at this point (although this can be a useful technique in general). We've been in the twilight zone for a while. That's when the fun starts. But, somewhat more seriously, I wonder what, exactly, it is that freaks people out about: [(new_songs if s.is_new() else old_songs).append(s) for s in songs] Clearly, it's not the fact that it build and immediately discards a list, because that concern is addressed with the generator hack, and I think everybody (myself included) agrees that's just horrible. I think someone has already said that the problem is that you're creating the list comprehension just for the side effects. Or, is it the use of the conditional to create the target for append()? I particularly liked that part. -- http://mail.python.org/mailman/listinfo/python-list
Re: PYTHONPATH: dev and prod
On Jun 12, 4:10 pm, jacopo jacopo.pe...@gmail.com wrote: this idea seemed perfect but it turned out that you have to execute the module as a package (python -m py.myscripts.any_script) otherwise I get an error on the relative import. Unfortunately I am working in a team and I do not have control on how the module is launched. You need to give more data: 1. How you run -- 'launch' -- the code -- from py and from prod 2. What error you get 3. Did you try bundling your modules into a package? What problem happened? If PYTHONPATH does not work for you you can look at path-configuration- files (.pth) files http://docs.python.org/2/library/site.html [Ive not used them myself] -- http://mail.python.org/mailman/listinfo/python-list
Re: Split a list into two parts based on a filter?
Roy Smith writes: We've been in the twilight zone for a while. That's when the fun starts. But, somewhat more seriously, I wonder what, exactly, it is that freaks people out about: [(new_songs if s.is_new() else old_songs).append(s) for s in songs] Clearly, it's not the fact that it build and immediately discards a list, because that concern is addressed with the generator hack, and I think everybody (myself included) agrees that's just horrible. I expect e(s) in [e(s) for s in songs] to be an expression that is evaluated for its value and not for an effect. The comprehension should stand for a list of those values. The one above violates this expectation. Or, is it the use of the conditional to create the target for append()? Would people be as horrified if I wrote: for s in songs: (new_songs if s.is_new() else old_songs).append(s) or even: for s in songs: the_right_list = new_songs if s.is_new() else old_songs the_right_list.append(s) These are fine. -- http://mail.python.org/mailman/listinfo/python-list
Re: ValueError: I/O operation on closed file. with python3
On Wed, Jun 12, 2013 at 2:26 AM, Peter Otten __pete...@web.de wrote: Applying these findings to your script: from contextlib import contextmanager try: # python-2.x from urllib2 import urlopen from ConfigParser import ConfigParser @contextmanager def my_urlopen(url): yield urlopen(url).fp except ImportError: # python-3.x from urllib.request import urlopen from configparser import ConfigParser import io @contextmanager def my_urlopen(url): resp = urlopen(url) yield io.TextIOWrapper(resp.fp) server='http://www.lsc-group.phys.uwm.edu/~ram/files' cp = ConfigParser() with my_urlopen('%s/latest.ini' % server) as fp: cp.readfp(fp) print(cp.get('version', '10.8')) I've run it with 2.6, 2.7, 3.2, and 3.3. Thanks that's very helpful, I hadn't realised that .readfp() had been deprecated. Cheers Adam -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Magazine
On Sun, May 26, 2013 at 1:30 AM, Roy Smith r...@panix.com wrote: In article 51a0caac$0$30002$c3e8da3$54964...@news.astraweb.com, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: On Sat, 25 May 2013 16:41:58 +1000, Chris Angelico wrote: On Sat, May 25, 2013 at 4:38 PM, zoom z...@yahoo.com wrote: But why would anyone want to use IPv6? I hope you're not serious :) He's planning to drop off the Internet once the IP address run out. We already have run out. People have gotten so used to being behind NAT gateways they don't even understand how evil it is. From my phone, I can call any other phone anywhere in the world. But I can't talk directly to the file server in my neighbor's house across the street? Of course, the shift from IPv4 and NAT to IPv6 and direct addressing does shift the firewalling burden somewhat. Instead of I'll forward whatever ports I choose, it becomes alright let's think about this whole firewall thang. I'm not 100% confident that home-grade routers will have proper firewall facilities in them; I suspect that moving home users onto IPv6 may result in a spate of attacks. On the flip side, it becomes less useful to simply port-scan across huge IP blocks - bulk-attacking an IPv4 /24 block is easy, but spamming even a single IPv6 /64 is practically impossible. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Debugging parallel nose tests?
- Original Message - In article mailman.2027.1369333910.3114.python-l...@python.org, Dave Angel da...@davea.name wrote: On 05/23/2013 09:09 AM, Roy Smith wrote: SNIP nosetests --process-timeout=60 --processes=40 test_api.py Do you have a 40-processor system? No, but many of the tests are I/O bound. Sorry to hijack your thread but what do you mean by that ? I have a lot of tests myself that spend most of their time writing and reading files. Should I try to multiprocess them ? JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple algorithm question - how to reorder a sequence economically
On 05/25/2013 09:49 PM, Roy Smith wrote: In article 15a1bb3a-514c-454e-a966-243c84123...@googlegroups.com, John Ladasky john_lada...@sbcglobal.net wrote: Because someone's got to say it... The generation of random numbers is too important to be left to chance. ‹ Robert R. Coveyou Absolutely. I know just enough about random number generation to understand that I don't really know anything about it :-) That being said, people who really care about random numbers, tend to rely on some sort of physical process instead of computer algorithms. A classic example would be /dev/random. A somewhat more fun example is http://www.youtube.com/watch?v=7n8LNxGbZbs. Something radioactive and a geiger counter are a good source of randomness (time intervals between decay events). That's good unless you're a cat, and you belong to Schroedinger... -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple algorithm question - how to reorder a sequence economically
On Fri, May 24, 2013 at 11:23 PM, Peter Brooks peter.h.m.bro...@gmail.com wrote: Actually, thinking about it, there is probably a source of non-algorithmically-derived 'random' numbers somewhere on the net that would do the job nicely. True entropy is usually provided by a source such as /dev/random (on Unix systems). It's sometimes referred to as cryptographic randomness, due to its necessity in secure encryption work. There are various ways to get this in a cross-platform way. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Survey of Python-in-browser technologies
On 05/24/2013 08:38 PM, Carlos Nepomuceno wrote: Date: Fri, 24 May 2013 17:11:18 -0700 Subject: Re: Survey of Python-in-browser technologies From: drsali...@gmail.com To: carlosnepomuc...@outlook.com CC: python-list@python.org Security is an important topic... but I'm not sure how I could gather info about the security of these implementations. Still, it's an idea worth at least keeping in the back of my mind. Security specialists opinions and facts about known vulnerabilities would be a start, although it may be time consuming to gather all data. Just a thought! ;) Thank you for putting your response after the part you're quoting. And for trimming out the irrelevant parts. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
RE: Python Magazine
I don't think IPv6 will change anything about NAPT usage. In fact, I guess, it will probably will make NAPT usage even more important and needed. -- http://mail.python.org/mailman/listinfo/python-list
RE: Simple algorithm question - how to reorder a sequence economically
Date: Fri, 24 May 2013 17:28:07 -0700 Subject: Re: Simple algorithm question - how to reorder a sequence economically From: peter.h.m.bro...@gmail.com To: python-list@python.org [...] If the scenario could be modelled mathematically, then there'd be no point in writing the simulation. I don't know what you mean. A computer simulation is an instance of a mathematical model. -- http://mail.python.org/mailman/listinfo/python-list
Re: Harmonic distortion of a input signal
On 20 May 2013 00:36, killybear...@gmail.com wrote: One more question. Function np.argmax returns max of non-complex numbers ? Because FFT array of my signal is complex. Use abs() like in my example. This will give the absolute value of the complex numbers: z = 1+1j z (1+1j) abs(z) 1.4142135623730951 Oscar -- http://mail.python.org/mailman/listinfo/python-list
Re: Cutting a deck of cards
On Sun, May 26, 2013 at 12:16 PM, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: list(range(13 * 4 * decks)) == range(13 * 4 * decks) Not in Python 3. -- http://mail.python.org/mailman/listinfo/python-list
RE: Python Magazine
Date: Sun, 26 May 2013 15:17:11 +1000 Subject: Re: Python Magazine From: ros...@gmail.com [...] Blocking a whole network (/65) is totally undesirable and may even become illegal. Blocking a /64 is exactly the same as blocking a /32 with NAT behind it. And how could it be illegal? I provide service to those I choose to provide to. I'm not a lawyer, so what I say about the IP blocking legal matter is just an opinion. I'm not responsible for any damages it may cause to anyone!!! lol It just looks like those damn software disclaimers, doesn't it? ;) Depending on the jurisdiction things maybe very different. I've been told that in California it is really illegal to block IP addresses without a court order. Any Californians available to confirm that? The sender of information over the Internet is the owner of both the information and the IP address attached to the information. The practice of IP address blocking records the IP address and destroys the information in the message without the intent or permission of the owner of the information, and usurp[s] the normal operation of the . . computer network. Software designed to record IP addresses and use them to block messages is thus a computer contaminant according to the above definition. Source: http://im-from-missouri.blogspot.com.br/2007/05/ip-address-blocking-is-illegal-in.html Also check California Penal Code Section 502, Unauthorized Access To Computers, Computer Systems and Computer Data: http://www.leginfo.ca.gov/cgi-bin/displaycode?section=pengroup=1-01000file=484-502.9 The problem is serious and there are many cases, such as: http://www.theregister.co.uk/2011/10/13/dutch_isp_accuses_spamhaus/ Currently it may not only happen at the target of the DDoS attack, but be spread all over the internet where block lists are enforced. I don't expect that to happen and if it happens I'm surely in favor of protection against this type of 'solution' because it will block not only malicious clients but potentially many other legitimate clients. Banning a wide netblock is of course going to lock out legit clients. But IP rotation means that can happen anyway. You block a single IPv4 address that right now represents an abusive user; that user disconnects and reconnects, gets a new IP, and someone else gets the other one. Can happen all too easily. That's why IP-banning is at best a temporary solution anyway. IP blocking isn't a perfect solution as you have confirmed. That's why using it is so problematic. It may hurt legitimate clients and other unrelated ones, while the abusive user as you said gets out unharmed. -- http://mail.python.org/mailman/listinfo/python-list
Re: Cutting a deck of cards
On Sun, May 26, 2013 at 12:17 PM, RVic rvinc...@gmail.com wrote: Ah, brilliant -- yes, this is so much more elegant in Python: #now cut the cards x = random.randrange(2,range(13 * 4 * decks)) cards = cards[x:]+cards[:x] Or if for some reason you want to do it in place: cards[x:], cards[:x] = cards[:x], cards[x:] But note that the order of assignments is subtly important there, so unless you have a good reason for doing that, it's probably better just to create a new list for clarity. -- http://mail.python.org/mailman/listinfo/python-list
RE: Cutting a deck of cards
From: usenetm...@solar-empire.de Subject: Re: Cutting a deck of cards Date: Sun, 26 May 2013 22:13:55 +0200 To: python-list@python.org Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: From: usenetm...@solar-empire.de [...] Not in Python3.x decks = 6 list(range(13 * 4 * decks)) == range(13 * 4 * decks) False What does list(range(13 * 4 * decks)) returns in Python 3? A list of course. But Py3 range is very similar to Py2 xrange, it returns a range object. Adiaŭ Marc What list? '[[0,1,2,...]]' or '[0,1,2,...]'? If it's the later then it's no different than what range() returns in Python 2.7.5! -- http://mail.python.org/mailman/listinfo/python-list
RE: Cutting a deck of cards
To: python-list@python.org From: breamore...@yahoo.co.uk [...] See this http://docs.python.org/3/whatsnew/3.3.html#pep-397-python-launcher-for-windows -- If you're using GoogleCrap™ please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence Piece of cake! So, is there any risk of breaking anything if I install a new package after having both Puthon 2 and 3 installed? How do I choose which one will run the package? Will the package handle the settings accordingly or will I need to setup manually? -- http://mail.python.org/mailman/listinfo/python-list
Re: Cutting a deck of cards
On Mon, May 27, 2013 at 4:16 AM, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: list(range(13 * 4 * decks)) == range(13 * 4 * decks) ;) Not in Python 3. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
RE: Encodign issue in Python 3.3.1 (once again)
Date: Tue, 28 May 2013 08:18:06 +1000 Subject: Re: Encodign issue in Python 3.3.1 (once again) From: ros...@gmail.com To: python-list@python.org [...] This is something that's utterly trivial, yet a window to your mind. It's like boarding an airliner and finding coffee stains on the flip-down trays - the plane flies just fine with those stains, yet the impression they give is that the crew don't care about engine maintenance either. ChrisA Stain Is Too Damn High!!! lol That's my party man!!! :) -- http://mail.python.org/mailman/listinfo/python-list
RE: How to: Setuptools
Date: Mon, 27 May 2013 21:26:21 -0700 Subject: Re: How to: Setuptools From: rustompm...@gmail.com To: python-list@python.org On May 28, 9:09 am, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: Date: Mon, 27 May 2013 20:54:53 -0700 Subject: Re: How to: Setuptools From: rustompm...@gmail.com [...] Oooff! Talk of using sledgehammers to crack nuts... All that is needed is to visithttp://peak.telecommunity.com/dist/ez_setup.py with the browser and to save the file!! Can you show me how to do that from a batch file? Please... What in the OP's question translates into a need for a batch-file? And you are proposing that he downloads curl just to write that batch- file?!?! How come that proposal is not subject to the same requirement, viz. I dont see in your recipe any: Here-is-a-batchfile-to-download-curl-without-curl? -- http://mail.python.org/mailman/listinfo/python-list So, you don't know how to download from a batch file? -- http://mail.python.org/mailman/listinfo/python-list
RE: Total Beginner - Extracting Data from a Database Online (Screenshot)
Date: Tue, 28 May 2013 07:40:07 +0100 Subject: RE: Total Beginner - Extracting Data from a Database Online (Screenshot) From: pconn...@gmail.com [...] c11 = [tables[0][r][10] for r in range(len(tables[0]))] Or rather: c11 = [row[10] for row in tables[0]] In most cases, range(len(x)) is a sign that you're doing it wrong :) Indeed! Much better that way! \o -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Magazine
On 31 May 2013, at 13:11, DRJ Reddy wrote: Hello all, Was busy with work. Finally finished the job of registering the domain name. Will be live soon. The url is http://pythonmagazine.org. Hope we will be live soon. I was surprised when I saw it is running on ASP.NET, can this be ? Server: Microsoft-IIS/7.0 Vary: Accept-Encoding X-Pingback: http://pythonmagazine.org/xmlrpc.php X-Powered-By: ASP.NET -- http://mail.python.org/mailman/listinfo/python-list
Re: Encodign issue in Python 3.3.1 (once again)
don't ya have something intelligent to say motherfucker? 2013/5/28 rusi rustompm...@gmail.com On May 28, 10:55 am, Νίκος Γκρ33κ nikos.gr...@gmail.com wrote: Ôç Ôñßôç, 28 ÌáÀïõ 2013 1:18:06 ð.ì. UTC+3, ï ÷ñÞóôçò Chris Angelico Ýãñáøå: You're effectively asking people to put in a few minutes' work, sometimes quite a few minutes, to help you. Is it too much to hope that you'll spend one more minute on your posts? No it is not, you are right, i should be more careful when typing and spend some time to correct before i send my responses. I promise i will not overlook this as well as the blank line google imposes. As fo my initial question any comments-remarks? You say you should be more careful to correct your typing and 'promise' to not overlook this. Your next line has a 'fo' instead of a 'for' -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: Changing filenames from Greeklish = Greek (subprocess complain)
To: python-list@python.org From: breamore...@yahoo.co.uk Subject: Re: Changing filenames from Greeklish = Greek (subprocess complain) Date: Sun, 2 Jun 2013 15:51:31 +0100 [...] Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green. Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence -- http://mail.python.org/mailman/listinfo/python-list le+666l -- http://mail.python.org/mailman/listinfo/python-list
[ANN] pypiserver 1.1.1 - minimal private pypi server
Hi, I've just uploaded pypiserver 1.1.1 to the python package index. pypiserver is a minimal PyPI compatible server. It can be used to serve a set of packages and eggs to easy_install or pip. pypiserver is easy to install (i.e. just 'pip install pypiserver'). It doesn't have any external dependencies. https://pypi.python.org/pypi/pypiserver/ should contain enough information to easily get you started running your own PyPI server in a few minutes. The code is available on github: https://github.com/schmir/pypiserver Changes in this version --- - add 'overwrite' option to allow overwriting existing package files (default: false) - show names with hyphens instead of underscores on the /simple listing - make the standalone version work with jython 2.5.3 - upgrade waitress to 0.8.5 in the standalone version - workaround broken xmlrpc api on pypi.python.org by using HTTPS -- Cheers Ralf -- http://mail.python.org/mailman/listinfo/python-list
RE: Python #ifdef
Date: Mon, 3 Jun 2013 12:05:49 +1000 Subject: Re: Python #ifdef From: ros...@gmail.com To: python-list@python.org [...] Ah. I actually wasn't aware of m4's use with sendmail. I first met it as the aforementioned PHP preprocessor, simply by Googling for something along the lines of generic preprocessor. First hit solved my problems. ChrisA Why didn't you use something like EZT[1]? [1] https://code.google.com/p/ezt/ -- http://mail.python.org/mailman/listinfo/python-list
Re: User Input
On 05/30/2013 10:03 AM, Eternaltheft wrote: do you think ti would be better if i call drawBoard? Better is meaningless without context. Are you being charged per keystroke? -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: PyWart: The problem with print
On 4 June 2013 14:35, Mark Lawrence breamore...@yahoo.co.uk wrote: On 04/06/2013 14:29, rusi wrote: The Clash of the Titans Lé jmf chârgeth with mightƴ might And le Mond underneath trembleth Now RR mounts his sturdy steed And the windmill yonder turneth +1 funniest poem of the week :) Week? Do we do this every Tuesday? I vote all-time best post for python-list@python.org. -- http://mail.python.org/mailman/listinfo/python-list
Re: Short-circuit Logic
On 30 May 2013 22:03, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: Here's another way, mathematically equivalent (although not necessarily equivalent using floating point computations!) which avoids the divide-by- zero problem: abs(a - b) epsilon*a That's wrong! If abs(a) abs(a-b)/epsilon you will break the commutative law. There is no commutative law for relative tolerance floating point comparisons. If you want to compare with a relative tolerance then you you should choose carefully what your tolerance is to be relative to (and how big your relative tolerance should be). In some applications it's obvious which of a or b you should use to scale the tolerance but in others it is not or you should compare with something more complex. For an example where it is obvious, when testing numerical code I might write something like: eps = 1e-7 true_answer = 123.4567879 estimate = myfunc(5) assert abs(estimate - true_answer) eps * abs(true_answer) Oscar -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't rebind built-in names* - it confuses readers
list = [] Reading further, one sees that the function works with two lists, a list of file names, unfortunately called 'list', That is very good advice in general: never choose a variable name that is a keyword. -- MarkJ Tacoma, Washington -- http://mail.python.org/mailman/listinfo/python-list
RE: Short-circuit Logic
From: oscar.j.benja...@gmail.com Date: Thu, 30 May 2013 23:57:28 +0100 Subject: Re: Short-circuit Logic To: carlosnepomuc...@outlook.com CC: python-list@python.org On 30 May 2013 22:03, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: Here's another way, mathematically equivalent (although not necessarily equivalent using floating point computations!) which avoids the divide-by- zero problem: abs(a - b) epsilon*a That's wrong! If abs(a) abs(a-b)/epsilon you will break the commutative law. There is no commutative law for relative tolerance floating point comparisons. If you want to compare with a relative tolerance then you you should choose carefully what your tolerance is to be relative to (and how big your relative tolerance should be). Off course there is! It might not suite your specific needs though. I'll just quote Knuth because it's pretty damn good: A. An axiomatic approach. Although the associative law is not valid, the commutative law u (+) v == v (+) u (2) does hold, and this law can be a valuable conceptual asset in programming and in the analysis of programs. This example suggests that we should look for important laws that are satified by (+), (-), (*), and (/); it is not unreasonable to say that floating point routines should be designed to preserve as many of the ordinary mathematical laws as possible. If more axioms are valid, it becomes easier to write good programs, and programs also become more portable from machine to machine. TAOCP, Vol .2, p. 214 In some applications it's obvious which of a or b you should use to scale the tolerance but in others it is not or you should compare with something more complex. For an example where it is obvious, when testing numerical code I might write something like: eps = 1e-7 true_answer = 123.4567879 estimate = myfunc(5) assert abs(estimate - true_answer) eps * abs(true_answer) Oscar -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't rebind built-in names* - it confuses readers
On Tue, Jun 11, 2013 at 1:30 PM, rusi rustompm...@gmail.com wrote: Or by example: def foo(x)... def bar(x,y)... there is no reason to confuse the two xes. Whereas x = ... def foo(x)... Now there is! The first should be encouraged, the second discouraged. Again, there can be good reason for it, such as snapshotting globals: qwer=123 def asdf(qwer=qwer): print(qwer,qwer) asdf() qwer=234 asdf() Done for performance (avoiding lookups), could also be done for stability (as depicted here) though I've never seen it needed for that. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing filenames from Greeklish = Greek (subprocess complain)
On Sunday 02 June 2013 13:10:30 Chris Angelico did opine: On Mon, Jun 3, 2013 at 2:21 AM, حéêüëلïٍ تïٌلٍ nikos.gr...@gmail.com wrote: Paying for someone to just remove a dash to get the script working is too much to ask for One dash: 1c Knowing where to remove it: $99.99 Total bill: $100.00 Knowing that it ought really to be utf8mb4 and giving hints that the docs should be read rather than just taking this simple example and plugging it in: Priceless. ChrisA Chuckle. Chris, I do believe you have topped yourself. Love it. Cheers, Gene -- There are four boxes to be used in defense of liberty: soap, ballot, jury, and ammo. Please use in that order. -Ed Howdershelt (Author) My web page: http://coyoteden.dyndns-free.com:85/gene is up! My views http://www.armchairpatriot.com/What%20Has%20America%20Become.shtml Unnamed Law: If it happens, it must be possible. A pen in the hand of this president is far more dangerous than 200 million guns in the hands of law-abiding citizens. -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
On Tue, Jun 4, 2013 at 9:53 PM, Carlos Nepomuceno carlosnepomuc...@outlook.com wrote: Are there any benefits from using dict() instead of {}? Not for what you're doing, but you can use dict() with an iterable. Most of the time, use the literal. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
RE: Changing filenames from Greeklish = Greek (subprocess complain)
' Server: ApacheBooster/1.6' isn't a signature of httpd. I think you are really running something different. From: nob...@nowhere.com Subject: Re: Changing filenames from Greeklish = Greek (subprocess complain) Date: Tue, 4 Jun 2013 14:01:48 +0100 To: python-list@python.org On Tue, 04 Jun 2013 00:58:42 -0700, Νικόλαος Κούρας wrote: Τη Τρίτη, 4 Ιουνίου 2013 10:39:08 π.μ. UTC+3, ο χρήστης Nobody έγραψε: Chrome didn't choose ISO-8859-1, the server did; the HTTP response says: Content-Type: text/html;charset=ISO-8859-1 From where do you see this $ wget -S -O - http://superhost.gr/data/apps/ --2013-06-04 14:00:10-- http://superhost.gr/data/apps/ Resolving superhost.gr... 82.211.30.133 Connecting to superhost.gr|82.211.30.133|:80... connected. HTTP request sent, awaiting response... HTTP/1.1 200 OK Server: ApacheBooster/1.6 Date: Tue, 04 Jun 2013 13:00:19 GMT Content-Type: text/html;charset=ISO-8859-1 Transfer-Encoding: chunked Connection: keep-alive Vary: Accept-Encoding X-Cacheable: YES X-Varnish: 2000177813 Via: 1.1 varnish age: 0 X-Cache: MISS -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Apache and suexec issue that wont let me run my python script
On Tue, Jun 4, 2013 at 1:12 PM, Νικόλαος Κούρας nikos.gr...@gmail.comwrote: Τη Τρίτη, 4 Ιουνίου 2013 8:09:18 μ.μ. UTC+3, ο χρήστης Chris Angelico έγραψε: On Wed, Jun 5, 2013 at 3:02 AM, Νικόλαος Κούρας nikos.gr...@gmail.com wrote: I'm willing to let someone with full root access to my webhost to see thigns from the inside. Does someone want to take o allok or at elast tell me what else i need to try, that hasn't been tried out yet? You need to read up on what happens when you enter Dummy Mode and give someone full root access to your web host. You really REALLY need to understand what that means before you offer random strangers that kind of access to someone else's data. I've half a mind to take you up on your offer, then go look for personal and private info from your clients, and email it to them (along with a link to this thread) to point out what's going on. ChrisA I know what full root access mean. I also trust you. I'm hopeless man, its 1 week now dealing with this. -- http://mail.python.org/mailman/listinfo/python-list I trust you too Chris! -- Joel Goldstick http://joelgoldstick.com -- http://mail.python.org/mailman/listinfo/python-list
Re: A few questiosn about encoding
On 06/12/2013 05:24 AM, Steven D'Aprano wrote: On Wed, 12 Jun 2013 09:09:05 +, Νικόλαος Κούρας wrote: Isn't 14 bits way to many to store a character ? No. There are 1114111 possible characters in Unicode. (And in Japan, they sometimes use TRON instead of Unicode, which has even more.) If you list out all the combinations of 14 bits: 00 01 10 11 [...] 10 11 you will see that there are only 32767 (2**15-1) such values. You can't fit 1114111 characters with just 32767 values. Actually, it's worse. There are 16536 such values (2**14), assuming you include null, which you did in your list. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get an integer from a sequence of bytes
On Tue, Jun 4, 2013 at 3:49 PM, Chris Angelico ros...@gmail.com wrote: So... can we cite http://xkcd.com/859/ in two threads at once, or does that create twice as much tension? No, you just look at one of them upside-down, and then they cancel each other out. -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On 2013-06-12, Chris Angelico ros...@gmail.com wrote: On Wed, Jun 12, 2013 at 5:45 PM, ?? supp...@superhost.gr wrote: First of all i have changed the code to the following because using a regex to detect a single char was an overkill. if '=' not in name and '=' not in month and '=' not in year: It'd be courteous to acknowledge those who made that suggestion, most notably alex23 who posted it in almost that exact form. Also, I wish he would stop fudging his From info. I've got something like 8 entries for this ass in my killfile, and it seems I need a new one every day. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Pywart: The problem with Rick Johnson
Is Rick Johnson the alter ego of Xah Lee, or is he the result of a cross breeding experiement with a troll by Saruman at Isengard?-- http://mail.python.org/mailman/listinfo/python-list
Re: A few questiosn about encoding
Am 12.06.2013 13:23, schrieb Νικόλαος Κούρας: So, how many bytes does UTF-8 stored for codepoints 127 ? What has your research turned up? I personally consider it lazy and respectless to get lots of pointers that you could use for further research and ask for more info before you even followed these links. example for codepoint 256, 1345, 16474 ? Yes, examples exist. Gee, if there only was an information network that you could access and where you could locate information on various programming-related topics somehow. Seriously, someone should invent this thing! But still, even without it, you have all the tools (i.e. Python) in your hand to generate these examples yourself! Check out ord, bin, encode, decode for a start. Uli -- http://mail.python.org/mailman/listinfo/python-list
Re: Apache and suexec issue that wont let me run my python script
Op 05-06-13 11:06, Νικόλαος Κούρας schreef: Τη Τετάρτη, 5 Ιουνίου 2013 11:59:28 π.μ. UTC+3, ο χρήστης alex23 έγραψε: On Jun 5, 6:41 pm, Chris Angelico ros...@gmail.com wrote: This matter is far more serious than you seem to be giving it consideration for. You complain that I violated your trust; you violated the trust of people who are paying you money. I think the term I'm looking for here is: EPIC WIN :D I didnt violate anything. Chris violated my treust. There would have been no violation if he just look into en encoding issue and not meddled with my customers mail and data. Yes you violated peoples trust. People trust you to act in a way to keep their data safe. Mailing your root password to someone you only know from a mailinglist/newsgroup is acting irresponsibly. That Chris has violated your trust, doesn't make your own irresponsible behaviour dissappear. Not only that, you made it public you would continue to act the same way in the future. If I had trusted you with my data, I would have felt my trust to be violated. Your actions are similar to someone who keeps a credit card for an organisation, gives the security code to a stranger and then complains the stranger moved a lot of money from one bank account to another (although all owned by you). Sure the stranger had no business doing that, but you sure were violating the trust of the organisation by acting so irresponsibly. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Re-using copyrighted code
At least partially, my confusion seems to be caused by the dichotomy of the concepts of copyright and license. How do these relate to each other? A license emerges out of the commercial domain is purely about commercial protections. I should clarify, that commercial protections here means *money*, not other potentially legal assets. As soon as money is exchange you entangle yourself with their domain. Otherwise, as long as you give credit, you're really quite safe, from a Constitutional perspective. -- MarkJ Tacoma, Washington -- http://mail.python.org/mailman/listinfo/python-list
Re: .mat files processing in Python
On Mon, 27 May 2013 13:43:36 -0700 (PDT) Romila Anamaria romila.anama...@yahoo.com wrote: I am beginner in Python programming Are you a beginner in using the Internet too? You just sent a 2.69MB message to a mailing list. You shouldn't send huge files like that in email at all but especially not to a mailing list that gets archived. Please don't ever do that again. -- D'Arcy J.M. Cain da...@druid.net | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 788 2246 (DoD#0082)(eNTP) | what's for dinner. IM: da...@vex.net, VOIP: sip:da...@vex.net -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get an integer from a sequence of bytes
On 5 Jun 2013 06:23, Tim Roberts t...@probo.com wrote: A single machine word was 60 bits, so a single register read got you 10 characters. 10 characters! Now that sounds like it's enough to actually store a word. However long words can inadverten be cropped. -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On 12/6/2013 2:49 μμ, F�bio Santos wrote: On 12 Jun 2013 12:08, �� supp...@superhost.gr mailto:supp...@superhost.gr wrote: Oh my God! i just need to do this: for i, month in enumerate( months ): � � � � print('option value=%s %s /option' % (month, month) ) Usually what goes in option value=... is an ID of something. You should keep using (i, month) and then do months[id] to get the month string. Also, tuples aren't traditionally used for this. Normally you'd use a list. You were right, i counter needed to signify the value: I just made it work as i wanted to! print('/selectselect name=month') for i, month in enumerate( months ): print('option value=%s %s /option' % (i, month) ) if month == '0': month = '==' # = # find display requested info based on name/month/year criteria # = if( seek ): try: if '=' not in ( name or month or year ): cur.execute( '''SELECT * FROM works WHERE clientsID = (SELECT id FROM clients WHERE name = %s) and MONTH(lastvisit) = %s and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (name, month, year) ) elif '=' not in ( month or year ): cur.execute( '''SELECT * FROM works WHERE MONTH(lastvisit) = %s and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (month, year) ) elif '=' not in year: cur.execute( '''SELECT * FROM works WHERE YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', year ) -- http://mail.python.org/mailman/listinfo/python-list
Re: Turnign greek-iso filenames = utf-8 iso
On 12/6/2013 2:32 μμ, Νικόλαος Κούρας wrote: On 12/6/2013 12:37 μμ, Steven D'Aprano wrote: On Wed, 12 Jun 2013 12:24:24 +0300, Νικόλαος Κούρας wrote: [1] Correction. While I was typing this, it came good, for about 20 seconds, and displayed a hideously ugly background pattern and a cute smiling face waving, and then broke again. Ah sorry Steven i made the change of: host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0] or 'UnResolved' to metrites.py isntead of files.py now i have made both chnages. you can see the webpage now, eys the one with the cure smile face. behidn that we should beeen seeing all the files in a table like format for uses to downlaod, instead not a single file is being displayed. here is the print process., actually here is what i have up until now after modifications for you to take an overall look. # = # Convert wrongly encoded filenames to utf-8 # = path = b'/home/nikos/public_html/data/apps/' filenames = os.listdir( path ) utf8_filenames = [] for filename in filenames: # Compute 'path/to/filename' filename_bytes = path + filename encoding = guess_encoding( filename_bytes ) if encoding == 'utf-8': # File name is valid UTF-8, so we can skip to the next file. utf8_filenames.append( filename_bytes ) continue elif encoding is None: # No idea what the encoding is. Hit it with a hammer until it stops moving. filename = filename_bytes.decode( 'utf-8', 'xmlcharrefreplace' ) else: filename = filename_bytes.decode( encoding ) # Rename the file to something which ought to be UTF-8 clean. newname_bytes = filename.encode('utf-8') os.rename( filename_bytes, newname_bytes ) utf8_filenames.append( newname_bytes ) # Once we get here, the file ought to be UTF-8 clean and the Unicode name ought to exist: assert os.path.exists( newname_bytes.decode('utf-8') ) # Switch filenames from utf8 bytestrings = unicode strings filenames = [] for utf8_filename in utf8_filenames: filenames.append( utf8_filename.decode('utf-8') ) # Check the presence of a database file against the dir files and delete record if it doesn't exist cur.execute('''SELECT url FROM files''') data = cur.fetchall() for url in data: if url not in filenames: # Delete spurious cur.execute('''DELETE FROM files WHERE url = %s''', url ) # = # Display ALL files, each with its own download button # = print('''body background='/data/images/star.jpg' centerimg src='/data/images/download.gif'brbr table border=5 cellpadding=5 bgcolor=green ''') try: cur.execute( '''SELECT * FROM files ORDER BY lastvisit DESC''' ) data = cur.fetchall() for row in data: (filename, hits, host, lastvisit) = row lastvisit = lastvisit.strftime('%A %e %b, %H:%M') print(''' form method=get action=/cgi-bin/files.py tr td center input type=submit name=filename value=%s /td td center font color=yellow size=5 %s /td td center font color=orange size=4 %s /td td center font color=silver size=4 %s /td /tr /form ''' % (filename, hits, host, lastvisit) ) print( '''/tablebrbr''' ) except pymysql.ProgrammingError as e: print( repr(e) ) sys.exit(0) == ima happy that at elaST IT DOES NOT ERRIGN OUT! Can you shed some ligth please as to what might the problem be and its not displayign the filenames sicn ethey are utf8 encoded correctly? Something you want me to try? -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple algorithm question - how to reorder a sequence economically
On 2013-05-24 14:43, Chris Angelico wrote: On Fri, May 24, 2013 at 11:23 PM, Peter Brooks peter.h.m.bro...@gmail.com wrote: Actually, thinking about it, there is probably a source of non-algorithmically-derived 'random' numbers somewhere on the net that would do the job nicely. True entropy is usually provided by a source such as /dev/random (on Unix systems). It's sometimes referred to as cryptographic randomness, due to its necessity in secure encryption work. There are various ways to get this in a cross-platform way. os.random() and os.urandom(), particularly. -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: PYTHONPATH: dev and prod
1. How you run -- 'launch' -- the code -- from py and from prod when I have to test I use python any_script.py but in production there is a c++ program that is able to wrap and run python code (the technical details are a bit beyond my knowledge) 2. What error you get when I run as python any_script.py I get ValueError: Attempted relative import in non-package I have found this explanation: http://stackoverflow.com/questions/11536764/attempted-relative-import-in-non-package-even-with-init-py So I have added at the top of my module: if __name__==__main__ and __package__ is None: __package__=myscripts from ..mylib import MyClass and I get the error: SystemError: Parent module 'mylib' not loaded, canno perform relative import 3. Did you try bundling your modules into a package? What problem happened? What does it mean? what does build mean in this contest? I am not compiling, I just write the .py files. -- http://mail.python.org/mailman/listinfo/python-list
Re: py_compile vs. built-in compile, with __future__
On 2013-06-11, dhyams dhy...@gmail.com wrote: You would use StringIO instead of writing a temp file. I don't think that would work...py_compile takes a filename as input, not a file object. Dang. Sorry for the misinfo. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On 12/06/2013 14:05, Neil Cerutti wrote: Also, I wish he would stop fudging his From info. I've got something like 8 entries for this ass in my killfile, and it seems I need a new one every day. An ass eh, when did he get promoted to that position? -- Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green. Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't rebind built-in names* - it confuses readers
On 2013-06-11, Mark Janssen dreamingforw...@gmail.com wrote: list = [] Reading further, one sees that the function works with two lists, a list of file names, unfortunately called 'list', That is very good advice in general: never choose a variable name that is a keyword. You can't choose a vriable name that is a keyword: the compiler won't allow it. list isn't a keyword. -- Grant Edwards grant.b.edwardsYow! Maybe I should have at asked for my Neutron Bomb gmail.comin PAISLEY -- -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get an integer from a sequence of bytes
On 2013-06-12, F?bio Santos fabiosantos...@gmail.com wrote: On 5 Jun 2013 06:23, Tim Roberts t...@probo.com wrote: A single machine word was 60 bits, so a single register read got you 10 characters. 10 characters! Now that sounds like it's enough to actually store a word. However long words can inadverten be cropped. Only the first 10 characters in variable names were significant when you wrote Pascal programs (I don't remember if that was true for FORTRAN, but I bet it was). -- Grant Edwards grant.b.edwardsYow! I'm gliding over a at NUCLEAR WASTE DUMP near gmail.comATLANTA, Georgia!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Turnign greek-iso filenames = utf-8 iso
On 12/06/2013 13:42, Νικόλαος Κούρας wrote: Something you want me to try? I'd suggest suicide but that would no doubt start another stream of questions along the lines of How do I do it?. -- Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green. Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence -- http://mail.python.org/mailman/listinfo/python-list