Re: Confusing Algorithm
RBotha r...@ymond.co.za wrote: I'm facing the following problem: In a city of towerblocks, Spiderman can cover all the towers by connecting the first tower with a spider-thread to the top of a later tower and then to a next tower and then to yet another tower until he reaches the end of the city. ... -Example: List of towers: 1 5 3 7 2 5 2 Output: 4 I'm not sure how a 'towerblock' could be defined. How square does a shape have to be to qualify as a towerblock? Any help on solving this problem? Here's your city; [ ] [ ] [ ][ ][ ] [ ][ ][ ] [ ][ ][ ][ ] [ ][ ][ ][ ][ ][ ] [ ][ ][ ][ ][ ][ ][ ] -- A B C D E F G Once you see the picture, you can see that you'd thread from B to D without involving C. I think you'll go A to B to D to F to G -- 4 threads. -- Tim Roberts, t...@probo.com Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
QTableWidget updating columns in a single row
I have written a GUI that gets data sent to it in real time and this data is displayed in a table. Every time data is sent in it is displayed in the table in a new row. My problem is that I would like to have the data just replace the old in the first row. The table has 6 columns (A, B, C, D, E, F) I want the new data to continue replacing the old data in the same row unless the data that goes under column A changes, at which point a new row would be added. Does anyone have tips on how to approach this? I can post a portion of my code to get a better idea of what I have done. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get JSON values and how to trace sessions??
webmas...@terradon.nl wrote: But now i am wondering how to trace sessions? it is needed for a multiplayer game, connected to a webserver. How do i trace a PHP-session? I suppose i have to save a cookie with the sessionID from the webserver? Yes. The server will send a Set-Cookie: header with your first response. You just need to return that in a Cookie: header with every request you make after that. Are their other ways to keep control over which players sends the gamedata? Not sure what you mean. If the web site requires cookies, this is what you have to do. -- Tim Roberts, t...@probo.com Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Fixing escaped characters python-xbee
I am using a XBee to receive data from an arduino network. But they have AP=2 which means escaped characters are used when a 11 or 13 appears (and some more...) When this occurs, XBee sends 7D and inmediatly XOR operation with char and 0x20. I am trying to recover the original character in python but I don't know ho to do it. I tried something like this: read = ser.read(4) #Read 4 chars from serial port for x in range (0,4): if(toHex(read[x]) != '7d'): #toHex converts it to hexadecimal just for checking purposes if(x 3): read[x] = logical_xor(read[x+1], 20) #XOR for y in range (x+1,3): read[y] = read[y+1] read[3] = ser.read() else: read[x] = logical_xor(ser.read(), 20) #XOR data = struct.unpack('f', read)[0] logical_xor is: def logical_xor(str1, str2): return bool(str1) ^ bool(str2) I check if 7D character is in the first 3 chars read, I use the next char to convert it, if it is the 4th, I read another one. But I read in python strings are inmutables and I can't change their value once they have one. What would you do in this case? I started some days ago with python and I don't know how to solve this kind of things... -- http://mail.python.org/mailman/listinfo/python-list
Re: QTableWidget updating columns in a single row
On Wed, Apr 24, 2013 at 8:22 AM, Sara Lochtie sara.loch...@gmail.com wrote: I have written a GUI that gets data sent to it in real time and this data is displayed in a table. Every time data is sent in it is displayed in the table in a new row. My problem is that I would like to have the data just replace the old in the first row. The table has 6 columns (A, B, C, D, E, F) I want the new data to continue replacing the old data in the same row unless the data that goes under column A changes, at which point a new row would be added. Does anyone have tips on how to approach this? I can post a portion of my code to get a better idea of what I have done. -- http://mail.python.org/mailman/listinfo/python-list My suggestion: compare the new data’s column A with the existing data (store a copy of the old data somewhere?). If it differs, add a new row; if it doesn’t, change an existing one. If you need help with the exact implementation, show the *entire* code. -- Kwpolska http://kwpolska.tk | GPG KEY: 5EAAEA16 stop html mail| always bottom-post http://asciiribbon.org| http://caliburn.nl/topposting.html -- http://mail.python.org/mailman/listinfo/python-list
Re: List Count
On 24/04/2013 02:59, Steven D'Aprano wrote: On Tue, 23 Apr 2013 17:57:17 +0100, Blind Anagram wrote: [snip] In my opinion, it is more important to be efficient for large sieves, not small. As they say, for small N, everything is fast. Nobody is going to care about the difference between small-N taking 1ms or 10ms, but they will care about the difference between big-N taking 1 minute or 1 hour. So, as a general rule, optimize the expensive cases, and if the cheap cases are a little less cheap than they otherwise would have been, nobody will care or notice. I agree in general but it is often the case that more sophisticated algorithms only gain traction over simpler ones at much higher points than might be expected from a simple analysis. In my experience a naive sieve is an efficient solution for a general purpose sieve class primarily intended for situations where the sieve length can be large but not huge. As I think you have pointed out, memory is cheap and the memory operations needed to do copying and counting operations are fast. So using up memory is not normally an issue. I have just found a situation where a copy can have a serious impact on performance in an admittedly limiting, minority use case. It the fact that this copy is not, in principle, necessary, that I find disappointing. [snip] In this case, I would say that adding a limit argument to list.count is *absolutely not* worthwhile, because it is insufficiently general. To be general enough to be worthwhile, you would have to add three arguments: list.count(value, start=0, end=None, step=1) But even there I don't think it's general enough to cover the costs. I believe that a better solution would be to create list views to offer a subset of the list without actually copying. I don't know a great deal about Python internals but I suspect that these solutions would offer more but also cost more. So where the balance of advantages would lie is unclear. But I am not pushing for a particular (or, indeed, any) solution. -- http://mail.python.org/mailman/listinfo/python-list
Using SciPy in application
Hi all, I want to use spline interpolation function from SciPy in an application and at the same time, I don't want the end user to have to install SciPy separately. Is there a way around this problem? Thanks in advance for your help -- http://mail.python.org/mailman/listinfo/python-list
examples of pyraknet
do anyone has examples of pyraknet??? I've being seen these ones (http://nullege.com/codes/search/pyraknet) but I still don't understand lot of things about it and I can't find anything else. http://www.uci.cu -- http://mail.python.org/mailman/listinfo/python-list
Re: Fixing escaped characters python-xbee
On 24/04/2013 08:33, pablobl...@gmail.com wrote: I am using a XBee to receive data from an arduino network. But they have AP=2 which means escaped characters are used when a 11 or 13 appears (and some more...) When this occurs, XBee sends 7D and inmediatly XOR operation with char and 0x20. I am trying to recover the original character in python but I don't know ho to do it. I tried something like this: read = ser.read(4) #Read 4 chars from serial port for x in range (0,4): if(toHex(read[x]) != '7d'): #toHex converts it to hexadecimal just for checking purposes if(x 3): read[x] = logical_xor(read[x+1], 20) #XOR for y in range (x+1,3): read[y] = read[y+1] read[3] = ser.read() else: read[x] = logical_xor(ser.read(), 20) #XOR data = struct.unpack('f', read)[0] logical_xor is: def logical_xor(str1, str2): return bool(str1) ^ bool(str2) I check if 7D character is in the first 3 chars read, I use the next char to convert it, if it is the 4th, I read another one. But I read in python strings are inmutables and I can't change their value once they have one. What would you do in this case? I started some days ago with python and I don't know how to solve this kind of things... You could try converting to a list, which is mutable. # Python 3 read = list(ser.read(4)) pos = 0 try: while True: pos = read.index(0x7D, pos) del read[pos] read.extend(ser.read()) read[pos] ^= 0x20 except ValueError: # There are no (more) 0x7D in the data. pass data = struct.unpack('f', bytes(read))[0] # Python 2 read = [ord(c) for c in ser.read(4)] pos = 0 try: while True: pos = read.index(0x7D, pos) del read[pos] read.append(ord(ser.read())) read[pos] ^= 0x20 except ValueError: # There are no (more) 0x7D in the data. pass data = struct.unpack('f', b.join(chr(c) for c in read))[0] -- http://mail.python.org/mailman/listinfo/python-list
Re: Using SciPy in application
On 24 April 2013 10:13, Roozbeh roozbe...@gmail.com wrote: I want to use spline interpolation function from SciPy in an application and at the same time, I don't want the end user to have to install SciPy separately. Is there a way around this problem? They cannot use the function from scipy if scipy is not installed. There are three ways round this problem: 1) Rewrite the interpolation function you need in your own code. 2) Require the user to install scipy. 3) Require the user to install some other package that has interpolation functions. Rewriting the interpolation function is probably not that difficult depending on the type of interpolation you're using. Oscar -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the reason for defining classes within classes in Python?
On Wednesday, April 24, 2013 6:20:36 AM UTC+5:30, alex23 wrote: On Apr 24, 9:13 am, vasudevram vasudev...@gmail.com wrote: On Wednesday, April 24, 2013 3:52:57 AM UTC+5:30, Ian wrote: On Tue, Apr 23, 2013 at 3:50 PM, vasudevram wrote: I saw an example of defining a class within another class In what way is this useful? In that particular case they're just using it as a namespace. Not clear. An example or more explanation might help, if you can. Thanks. Namespaces are used to allow for the same label to be applied to different concepts without the labels conflicting with each other. If I was writing a program that dealt with the mathematics of morality, I might want to use the sine function and refer to it in the standard way as 'sin', and I might also want to store a value representing your lack of goodness as 'sin'. As you can't use the same label in the same scope to refer to two different objects, one way of dealing with this that lets you still use what you feel are the most appropriate names is to put them into a namespace. So you could express this as: class Math(object): sin = function() class Morality(object): sin = True Then in your code you can clearly distinguish between the two by using Math.sin and Morality.sin. Modules packages are also namespaces, so in this example we'd replace the Math class with `import math`, which has a sin function defined within it. A nested class definition will be defined as an attribute of the class its defined within: class Outer(object): ... foo = 'FOO' ... class Inner(object): ... bar = 'BAR' ... Outer.Inner class '__main__.Inner' Outer.Inner.bar 'BAR' With peewee, the Model class looks for a Meta attribute and uses attributes on it to perform some tasks, like where to retrieve/store the model data. This allows for a way of distinguishing between attributes used to define fields, and attributes needed for those tasks. It also means your Models can use field names that the class would otherwise reserve for its own internal purposes: class DatabaseDetails(Model): # these attributes are fields database = CharField() owner = CharField() # ...but the Meta attribute isn't class Meta: # these attributes are used by the Model class database = db Here, database as a field is a text string that could contain a database name, while DatabaseDetails.Meta.database contains a reference to an actual database where the DatabaseDetails record would be stored. Actually, I did know what namespaces are in general. What I didn't get was how the inner class Meta in the peewee example was being used as a namespace. Your explanation makes things very clear. Thank you. Just one other doubt: Outer.Inner class '__main__.Inner' In the above output, I would have thought Python would print __main__.Outer.Inner or Outer.Inner instead of __main__.Inner, since Inner is an attribute of Outer? -- http://mail.python.org/mailman/listinfo/python-list
Re: Using SciPy in application
On 2013-04-24 16:34, Oscar Benjamin wrote: On 24 April 2013 10:13, Roozbeh roozbe...@gmail.com wrote: I want to use spline interpolation function from SciPy in an application and at the same time, I don't want the end user to have to install SciPy separately. Is there a way around this problem? They cannot use the function from scipy if scipy is not installed. There are three ways round this problem: 1) Rewrite the interpolation function you need in your own code. Variant: 1.a) Copy the interpolation code from scipy into your own code. -- 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: Using SciPy in application
On Wednesday, April 24, 2013 11:13:45 AM UTC+2, Roozbeh wrote: Hi all, I want to use spline interpolation function from SciPy in an application and at the same time, I don't want the end user to have to install SciPy separately. Is there a way around this problem? Thanks in advance for your help -- http://mail.python.org/mailman/listinfo/python-list
Re: Using SciPy in application
On Wednesday, April 24, 2013 11:13:45 AM UTC+2, Roozbeh wrote: Hi all, I want to use spline interpolation function from SciPy in an application and at the same time, I don't want the end user to have to install SciPy separately. Is there a way around this problem? Thanks in advance for your help The thing is that the SciPy code for spline interpolation imports NumPy which also I don't want to use. So, I think I will have to write the code myself I guess. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using SciPy in application
On Wednesday, April 24, 2013 11:13:45 AM UTC+2, Roozbeh wrote: Hi all, I want to use spline interpolation function from SciPy in an application and at the same time, I don't want the end user to have to install SciPy separately. Is there a way around this problem? Thanks in advance for your help Any idea where can I find the recipe for the spline interpolation that does not rely on NumPy and/or SciPy and is written pure Python (no C code)? -- http://mail.python.org/mailman/listinfo/python-list
Re: Using SciPy in application
On 2013-04-24 17:04, Roozbeh wrote: On Wednesday, April 24, 2013 11:13:45 AM UTC+2, Roozbeh wrote: Hi all, I want to use spline interpolation function from SciPy in an application and at the same time, I don't want the end user to have to install SciPy separately. Is there a way around this problem? Thanks in advance for your help Any idea where can I find the recipe for the spline interpolation that does not rely on NumPy and/or SciPy and is written pure Python (no C code)? If Google can't find it, it probably doesn't exist. Very few people would do this without numpy. -- 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: Fixing escaped characters python-xbee
pablobl...@gmail.com wrote: I am using a XBee to receive data from an arduino network. But they have AP=2 which means escaped characters are used when a 11 or 13 appears (and some more...) When this occurs, XBee sends 7D and inmediatly XOR operation with char and 0x20. I am trying to recover the original character in python but I don't know ho to do it. I tried something like this: read = ser.read(4) #Read 4 chars from serial port for x in range (0,4): if(toHex(read[x]) != '7d'): #toHex converts it to hexadecimal just for checking purposes if(x 3): read[x] = logical_xor(read[x+1], 20) #XOR for y in range (x+1,3): read[y] = read[y+1] read[3] = ser.read() else: read[x] = logical_xor(ser.read(), 20) #XOR data = struct.unpack('f', read)[0] logical_xor is: def logical_xor(str1, str2): return bool(str1) ^ bool(str2) I check if 7D character is in the first 3 chars read, I use the next char to convert it, if it is the 4th, I read another one. But I read in python strings are inmutables and I can't change their value once they have one. What would you do in this case? I started some days ago with python and I don't know how to solve this kind of things... As you cannot change the old string you have to compose a new one. I think the simplest approach is to always read one byte, and if it's the escape marker read another one and decode it. The decoded bytes/chars are then stored in a list and finally joined: # Python 2 # untested def read_nbytes(ser, n): accu = [] for i in xrange(n): b = ser.read(1) if b == \x7d: b = chr(ord(ser.read(1)) ^ 0x20) accu.append(b) return .join(accu) b = read_nbytes(ser, 4) data = struct.unpack('f', b)[0] -- http://mail.python.org/mailman/listinfo/python-list
Re: Using SciPy in application
On Wed, 24 Apr 2013 04:34:44 -0700, Roozbeh wrote: The scipy interpolation routines (splev, splrep, etc.) are on netlib: http://www.netlib.org/dierckx/ This gives you FORTRAN source codes which you will have to compile yourself to either a DLL or an SO. Call them from python using ctypes. I have done that for a number of the dierckx routines. No problems at all. Hope this helps, Alex van der Spek On Wednesday, April 24, 2013 11:13:45 AM UTC+2, Roozbeh wrote: Hi all, I want to use spline interpolation function from SciPy in an application and at the same time, I don't want the end user to have to install SciPy separately. Is there a way around this problem? Thanks in advance for your help Any idea where can I find the recipe for the spline interpolation that does not rely on NumPy and/or SciPy and is written pure Python (no C code)? -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the reason for defining classes within classes in Python?
vasudevram wrote: On Wednesday, April 24, 2013 6:20:36 AM UTC+5:30, alex23 wrote: A nested class definition will be defined as an attribute of the class its defined within: class Outer(object): ... foo = 'FOO' ... class Inner(object): ... bar = 'BAR' ... Outer.Inner Just one other doubt: Outer.Inner class '__main__.Inner' In the above output, I would have thought Python would print __main__.Outer.Inner or Outer.Inner instead of __main__.Inner, since Inner is an attribute of Outer? The Python developers seem to agree with you and have made the compiler smart enough to accomodate your expectations in Python 3.3: $ cat tmp.py class Outer: class Inner: pass print(Outer.Inner) $ python3.2 tmp.py class '__main__.Inner' $ python3.3 tmp.py class '__main__.Outer.Inner' -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the reason for defining classes within classes in Python?
Interesting. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
ALL function arguments in a common dictionary
Hi everybody, what is the recommended way of stuffing *all* function arguments (not just the ones passed by **kwargs) into a common dictionary? The following sort of works when used as the first block in a function: try: kwargs.update(locals()) except NameError: kwargs = locals().copy() except that it's nesting pre-existing kwargs. Thanks for your help, Wolfgang -- http://mail.python.org/mailman/listinfo/python-list
Re: ALL function arguments in a common dictionary
A quick hack: from inspect import getargspec def func(a, b, c=3, **kwargs): ... out_dict = {} ... args, _, keywords, _ = getargspec(func) ... for argname in args: ... out_dict[argname] = locals()[argname] ... if keywords: ... out_dict.update(locals()[keywords]) ... return out_dict ... func(1,2, gah=123) {'a': 1, 'c': 3, 'b': 2, 'gah': 123} On Wed, Apr 24, 2013 at 2:36 PM, Wolfgang Maier wolfgang.ma...@biologie.uni-freiburg.de wrote: Hi everybody, what is the recommended way of stuffing *all* function arguments (not just the ones passed by **kwargs) into a common dictionary? The following sort of works when used as the first block in a function: try: kwargs.update(locals()) except NameError: kwargs = locals().copy() except that it's nesting pre-existing kwargs. Thanks for your help, Wolfgang -- http://mail.python.org/mailman/listinfo/python-list -- Fábio Santos -- http://mail.python.org/mailman/listinfo/python-list
Re: Using SciPy in application
I want to use spline interpolation function from SciPy in an application and at the same time, I don't want the end user to have to install SciPy separately. You can pack you application with py2exe, pyinstaller ... and then they won't even need to install Python. Another option (which is not always possible) is to make you application a web site and then only you need to install SciPy on the server. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using SciPy in application
On Wednesday, April 24, 2013 3:52:50 PM UTC+2, Miki Tebeka wrote: I want to use spline interpolation function from SciPy in an application and at the same time, I don't want the end user to have to install SciPy separately. You can pack you application with py2exe, pyinstaller ... and then they won't even need to install Python. Another option (which is not always possible) is to make you application a web site and then only you need to install SciPy on the server. I thought about the py2exe option but the problem is, this application is a plug-in written for Abaqus CAE and hence it will use the python version that comes with Abaqus CAE distribution and Abaqus must be able to compile the Python codes every time on the start-up otherwise it won't recognize the plug-in and thats why SciPy and NumPy are also not an option. I guess as Alex said, I will have to use DLLs or write it myself. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using SciPy in application
On Wednesday, April 24, 2013 1:40:14 PM UTC+2, Robert Kern wrote: On 2013-04-24 17:04, Roozbeh wrote: On Wednesday, April 24, 2013 11:13:45 AM UTC+2, Roozbeh wrote: Hi all, I want to use spline interpolation function from SciPy in an application and at the same time, I don't want the end user to have to install SciPy separately. Is there a way around this problem? Thanks in advance for your help Any idea where can I find the recipe for the spline interpolation that does not rely on NumPy and/or SciPy and is written pure Python (no C code)? If Google can't find it, it probably doesn't exist. Very few people would do this without numpy. A trivial 'pure python spline' google search yields this: http://urchin.earth.li/~twic/splines.py (Warning: old code, python 2.2 era). Maarten -- http://mail.python.org/mailman/listinfo/python-list
improvements sought re. logging across modules
Hi all I have a small suite of python modules, say A.py B.py C.py which can be invoked in a variety of ways. eg. 1) A.py is invoked directly; this imports and uses B.py and C.py 2) B.py is invoked; this imports and uses A.py and C.py I use the logging module in all of these python modules, and I want to be able to use a single logger across the entire suite of whichever set of scripts is running. The way I do this at the moment is to have a separate module mylogger.py: == mylogger.py == import logging class MyLogger: #using python 2.4 ;-o def __init__(self): self.log = logging.getLogger(MY_APP_NAME) def setupLogging(self): self.log.setlevel(logging.DEBUG) # ... # our singleton logging object mylogger = Mylogger() # EOF and then in my other modules A.py, B.py etc. I have something like: == A.py == import mylogger gLog = mylogger.mylogger if __name__ == __main__: gLog.setupLogging() gLog.info(Module A running as main) main() #EOF == B.py == import mylogger gLog = mylogger.mylogger if __name__ == __main__: gLog.setupLogging() gLog.info(Module B running as main) main() # EOF This works, but I can't help thinking I'm missing a trick here. Any suggestions? Thanks j^n -- http://mail.python.org/mailman/listinfo/python-list
My gui
Today, being the last day of lectures at school, my instructor ran briefly through Tkninter and GUIs. I'd been looking forward to this particular lesson all semester, but when I got home and copied a sample program from my textbook verbatim, IDLE does nothing. No error, no nothing. Any ideas? Here is the code from my program. I'm not sure if this is appropriate, but suggestions are helpful. import tkinter import tkinter.messagebox class MyGui: def _init_(self): self.main_window = tkinter.Tk() self.top_frame = tkinter.Frame(self.main_window) self.bottom_frame = tkinter.Frame(self.main_window) self.prompt_label = tkinter.Label(self.top_frame, text = 'Enter a distance in Kilometers: ') self.kilo_entry = tkinter.Entry(self.top_frame, width = 10) self.prompt_label.pack(side = 'left') self.kilo_entry.pack(side = 'left') self.calc_button = tkinter.Button(self.bottom_frame, text = 'Convert', command = self.convert) self.quit_button = tkinter.Button(self.bottom_frame, text = 'Quit', command = self.main_window.destroy) self.calc_button.pack(side = 'left') self.quit_button.pack(side = 'left') self.top_frame.pack() self.bottom_frame.pack() tkinter.mainloop() def convert(self): kilo = float(self.kilo_entry.get()) miles = kilo * 0.6214 tkinter.messagebox.showinfo('Result', str(kilo) + ' kilometers is equal to ' + str(miles) + 'miles.') poop = MyGui() -- http://mail.python.org/mailman/listinfo/python-list
Re: QTableWidget updating columns in a single row
On Tuesday, April 23, 2013 11:22:29 PM UTC-7, Sara Lochtie wrote: I have written a GUI that gets data sent to it in real time and this data is displayed in a table. Every time data is sent in it is displayed in the table in a new row. My problem is that I would like to have the data just replace the old in the first row. The table has 6 columns (A, B, C, D, E, F) I want the new data to continue replacing the old data in the same row unless the data that goes under column A changes, at which point a new row would be added. Does anyone have tips on how to approach this? I can post a portion of my code to get a better idea of what I have done. So that is where I am stuck. I don't how to compare them and I am trying to avoiding saving the data to a file. This is the code that I have: if msg.arg2() != ERROR: entry = (A, B, C, D, E, F) self.data.append(entry) data = self.data # Display how many runs occurred self.statusBar().showMessage('Data read. %s Run(s) Occurred.' % self.runCount) # Populates table by adding only new entries to the end of the table lastRow = self.table.rowCount() self.table.setRowCount(len(data)) for entryPos in range(lastRow, len(data)): for fieldPos in range(6): item = QtGui.QTableWidgetItem(str(data[entryPos][fieldPos])) self.table.setItem(entryPos, fieldPos, item) self.table.resizeColumnsToContents() self.table.horizontalHeader().setStretchLastSection(True) self.currentRunLabel.setText('Current Run: ' + str(self.runCount)) self.currentLineLabel.setText('Number of lines: ' + str(len(self.data))) print('End of %s. run:%s. entries found' % (self.runCount, len(self.data))) -- http://mail.python.org/mailman/listinfo/python-list
Re: using pandoc instead of rst to document python
On Wed, Apr 24, 2013 at 12:14 AM, Peng Yu pengyu...@gmail.com wrote: I currently use sphinx to generate the doc (in rst). How to figure it to support pandoc's markdown? If I understand the desired workflow, it's just 1) write in markdown; 2) then run pandoc to convert to rst; 3) then run Sphinx to render html or whatever you want. You could even script this in python ;-) Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: improvements sought re. logging across modules
Maybe import mylogger.mylogger as gLog? I don't know what you mean by missing a trick. Your example seems pretty pythonic to me, except for the fact that you use a singleton where you could have a couple of functions and use the module as the namespace. On 24 Apr 2013 17:58, The Night Tripper jkn...@nicorp.co.uk wrote: Hi all I have a small suite of python modules, say A.py B.py C.py which can be invoked in a variety of ways. eg. 1) A.py is invoked directly; this imports and uses B.py and C.py 2) B.py is invoked; this imports and uses A.py and C.py I use the logging module in all of these python modules, and I want to be able to use a single logger across the entire suite of whichever set of scripts is running. The way I do this at the moment is to have a separate module mylogger.py: == mylogger.py == import logging class MyLogger: #using python 2.4 ;-o def __init__(self): self.log = logging.getLogger(MY_APP_NAME) def setupLogging(self): self.log.setlevel(logging.DEBUG) # ... # our singleton logging object mylogger = Mylogger() # EOF and then in my other modules A.py, B.py etc. I have something like: == A.py == import mylogger gLog = mylogger.mylogger if __name__ == __main__: gLog.setupLogging() gLog.info(Module A running as main) main() #EOF == B.py == import mylogger gLog = mylogger.mylogger if __name__ == __main__: gLog.setupLogging() gLog.info(Module B running as main) main() # EOF This works, but I can't help thinking I'm missing a trick here. Any suggestions? Thanks j^n -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: improvements sought re. logging across modules
On Wed, Apr 24, 2013 at 6:54 PM, The Night Tripper jkn...@nicorp.co.uk wrote: Hi all I have a small suite of python modules, say A.py B.py C.py which can be invoked in a variety of ways. eg. 1) A.py is invoked directly; this imports and uses B.py and C.py 2) B.py is invoked; this imports and uses A.py and C.py I use the logging module in all of these python modules, and I want to be able to use a single logger across the entire suite of whichever set of scripts is running. The way I do this at the moment is to have a separate module mylogger.py: == mylogger.py == import logging class MyLogger: #using python 2.4 ;-o def __init__(self): self.log = logging.getLogger(MY_APP_NAME) def setupLogging(self): self.log.setlevel(logging.DEBUG) # ... # our singleton logging object mylogger = Mylogger() # EOF and then in my other modules A.py, B.py etc. I have something like: == A.py == import mylogger gLog = mylogger.mylogger if __name__ == __main__: gLog.setupLogging() gLog.info(Module A running as main) main() #EOF == B.py == import mylogger gLog = mylogger.mylogger if __name__ == __main__: gLog.setupLogging() gLog.info(Module B running as main) main() # EOF This works, but I can't help thinking I'm missing a trick here. Any suggestions? Thanks j^n -- http://mail.python.org/mailman/listinfo/python-list No need to do such magic. Just set logging up as you would normally. The first logging instance should pick up logs from everywhere. For example: === aurqt/aqds.py === class AQDS: logging.basicConfig(format='%(asctime)-15s [%(levelname)-7s] ' ':%(name)-10s: %(message)s', filename=os.path.join(confdir, 'aurqt.log'), level=logging.DEBUG) log = logging.getLogger('aurqt') console = logging.StreamHandler() console.setLevel(logging.INFO) console.setFormatter(logging.Formatter('[%(levelname)-7s] ' ':%(name)-10s: %(message)s')) logging.getLogger('').addHandler(console) log.info('*** aurqt v' + __version__) === pkgbuilder/pbds.py === class PBDS: logging.basicConfig(format='%(asctime)-15s [%(levelname)-7s] ' ':%(name)-10s: %(message)s', filename=os.path.join(confdir, 'pkgbuilder.log'), level=logging.DEBUG) log = logging.getLogger('pkgbuilder') log.info('*** PKGBUILDer v' + __version__) === aurqt/__init__.py === from .aqds import AQDS DS = AQDS() import pkgbuilder # ← also imports pkgbuilder.DS = pkgbuilder.pbds.PBDS() === bin/aurqt output === [INFO ] :aurqt : *** aurqt v0.1.0 [INFO ] :requests.packages.urllib3.connectionpool: Starting new HTTPS connection (1): aur.archlinux.org [WARNING] :pkgbuilder: tty-clock version is a date, ignored for downgrade. === {confdir}/aurqt.log === 2013-04-24 19:34:21,079 [INFO ] :aurqt : *** aurqt v0.1.0 2013-04-24 19:35:19,096 [WARNING] :requests.packages.urllib3.connectionpool: Starting new HTTPS connection (1): aur.archlinux.org 2013-04-24 19:35:21,004 [WARNING] :pkgbuilder: tty-clock version is a date, ignored for downgrade. -- Kwpolska http://kwpolska.tk | GPG KEY: 5EAAEA16 stop html mail| always bottom-post http://asciiribbon.org| http://caliburn.nl/topposting.html -- http://mail.python.org/mailman/listinfo/python-list
A Healthy Alternative to Takeaway Regret
A Healthy Alternative to Takeaway Regret http://natigtas7ab.blogspot.com/2013/03/a-healthy-alternative-to-takeaway-regret.html -- http://mail.python.org/mailman/listinfo/python-list
Re: My gui
On 04/24/2013 01:08 PM, Daniel Kersgaard wrote: Today, being the last day of lectures at school, my instructor ran briefly through Tkninter and GUIs. I'd been looking forward to this particular lesson all semester, but when I got home and copied a sample program from my textbook verbatim, IDLE does nothing. No error, no nothing. Any ideas? Here is the code from my program. I'm not sure if this is appropriate, but suggestions are helpful. import tkinter import tkinter.messagebox class MyGui: def _init_(self): self.main_window = tkinter.Tk() self.top_frame = tkinter.Frame(self.main_window) self.bottom_frame = tkinter.Frame(self.main_window) self.prompt_label = tkinter.Label(self.top_frame, text = 'Enter a distance in Kilometers: ') self.kilo_entry = tkinter.Entry(self.top_frame, width = 10) self.prompt_label.pack(side = 'left') self.kilo_entry.pack(side = 'left') self.calc_button = tkinter.Button(self.bottom_frame, text = 'Convert', command = self.convert) self.quit_button = tkinter.Button(self.bottom_frame, text = 'Quit', command = self.main_window.destroy) self.calc_button.pack(side = 'left') self.quit_button.pack(side = 'left') self.top_frame.pack() self.bottom_frame.pack() tkinter.mainloop() def convert(self): kilo = float(self.kilo_entry.get()) miles = kilo * 0.6214 tkinter.messagebox.showinfo('Result', str(kilo) + ' kilometers is equal to ' + str(miles) + 'miles.') poop = MyGui() I'm not an IDLE user, but I wouldn't be surprised if IDLE interferes with some GUI apps. I'd run your code from the bash prompt. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: improvements sought re. logging across modules
On 04/24/2013 12:54 PM, The Night Tripper wrote: Hi all I have a small suite of python modules, say A.py B.py C.py which can be invoked in a variety of ways. eg. 1) A.py is invoked directly; this imports and uses B.py and C.py 2) B.py is invoked; this imports and uses A.py and C.py Right there you have a potential problem. Unless you make those imports conditional, you have an import loop, which can be a minor problem, or a big one. Whenever you find loops in the import call tree, please break them. The best way is to move the interdependencies into yet another module, and let both A and B import that one. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: My gui
On Wed, Apr 24, 2013 at 7:08 PM, Daniel Kersgaard danielkersga...@gmail.com wrote: Today, being the last day of lectures at school, my instructor ran briefly through Tkninter and GUIs. I'd been looking forward to this particular lesson all semester, but when I got home and copied a sample program from my textbook verbatim, IDLE does nothing. No error, no nothing. Any ideas? Here is the code from my program. I'm not sure if this is appropriate, but suggestions are helpful. import tkinter import tkinter.messagebox class MyGui: def _init_(self): self.main_window = tkinter.Tk() self.top_frame = tkinter.Frame(self.main_window) self.bottom_frame = tkinter.Frame(self.main_window) self.prompt_label = tkinter.Label(self.top_frame, text = 'Enter a distance in Kilometers: ') self.kilo_entry = tkinter.Entry(self.top_frame, width = 10) self.prompt_label.pack(side = 'left') self.kilo_entry.pack(side = 'left') self.calc_button = tkinter.Button(self.bottom_frame, text = 'Convert', command = self.convert) self.quit_button = tkinter.Button(self.bottom_frame, text = 'Quit', command = self.main_window.destroy) self.calc_button.pack(side = 'left') self.quit_button.pack(side = 'left') self.top_frame.pack() self.bottom_frame.pack() tkinter.mainloop() def convert(self): kilo = float(self.kilo_entry.get()) miles = kilo * 0.6214 tkinter.messagebox.showinfo('Result', str(kilo) + ' kilometers is equal to ' + str(miles) + 'miles.') poop = MyGui() -- http://mail.python.org/mailman/listinfo/python-list poop? Seriously? You aren’t serious about that copying, right? Your code seems to be missing a lot of important stuff. You don’t inherit from tkinter.Frame. Compare your program to the sample “Hello world!” program: http://docs.python.org/2/library/tkinter.html#a-simple-hello-world-program — unfortunately, I am not a fan and I am not knowledgeable about tkinter, but I can see a lot of stuff is missing. Please try fixing it and running it _outside of IDLE_, which is also built in Tk. This may cause problems (but don’t worry, the code you pasted doesn’t work anyways.) -- Kwpolska http://kwpolska.tk | GPG KEY: 5EAAEA16 stop html mail| always bottom-post http://asciiribbon.org| http://caliburn.nl/topposting.html -- http://mail.python.org/mailman/listinfo/python-list
Re: QTableWidget updating columns in a single row
On Wed, Apr 24, 2013 at 7:12 PM, Sara Lochtie sara.loch...@gmail.com wrote: So that is where I am stuck. I don't how to compare them and I am trying to avoiding saving the data to a file. To a file? Just store it in a class attribute and you will be fine. You have it in self.data already. Unless that structure doesn’t work, then “mirror” your table in a Python array. (alternatively, you could query QTableWidgetItem.text() for every existing item, but that’s crazy.) -- Kwpolska http://kwpolska.tk | GPG KEY: 5EAAEA16 stop html mail| always bottom-post http://asciiribbon.org| http://caliburn.nl/topposting.html -- http://mail.python.org/mailman/listinfo/python-list
Re: My gui
On 4/24/2013 1:08 PM, Daniel Kersgaard wrote: Today, being the last day of lectures at school, my instructor ran briefly through Tkninter and GUIs. I'd been looking forward to this particular lesson all semester, but when I got home and copied a sample program from my textbook verbatim, IDLE does nothing. No error, no nothing. Any ideas? Here is the code from my program. I'm not sure if this is appropriate, but suggestions are helpful. import tkinter import tkinter.messagebox class MyGui: def_init_(self): You need to define __init__, not _init_. Python special methods are named with double underscore leading and trailing, and __x__ is pronounced dunder-x. --Ned. -- http://mail.python.org/mailman/listinfo/python-list
Re: QTableWidget updating columns in a single row
Le 24/04/2013 19:12, Sara Lochtie a écrit : On Tuesday, April 23, 2013 11:22:29 PM UTC-7, Sara Lochtie wrote: I have written a GUI that gets data sent to it in real time and this data is displayed in a table. Every time data is sent in it is displayed in the table in a new row. My problem is that I would like to have the data just replace the old in the first row. The table has 6 columns (A, B, C, D, E, F) I want the new data to continue replacing the old data in the same row unless the data that goes under column A changes, at which point a new row would be added. Does anyone have tips on how to approach this? I can post a portion of my code to get a better idea of what I have done. So that is where I am stuck. I don't how to compare them and I am trying to avoiding saving the data to a file. This is the code that I have: if msg.arg2() != ERROR: entry = (A, B, C, D, E, F) self.data.append(entry) data = self.data # Display how many runs occurred self.statusBar().showMessage('Data read. %s Run(s) Occurred.' % self.runCount) # Populates table by adding only new entries to the end of the table lastRow = self.table.rowCount() self.table.setRowCount(len(data)) for entryPos in range(lastRow, len(data)): for fieldPos in range(6): item = QtGui.QTableWidgetItem(str(data[entryPos][fieldPos])) self.table.setItem(entryPos, fieldPos, item) self.table.resizeColumnsToContents() self.table.horizontalHeader().setStretchLastSection(True) self.currentRunLabel.setText('Current Run: ' + str(self.runCount)) self.currentLineLabel.setText('Number of lines: ' + str(len(self.data))) print('End of %s. run:%s. entries found' % (self.runCount, len(self.data))) As sayed by Chris Kwpolska, you can compare the new data with the data of the first row. Something like that: # Get the content of row 0, column A first = str(self.table.item(0, 0).text()) for entryPos in range(lastRow, len(data)): if str(data[entryPos][0]) == first: self.update_first_row(data[entryPos]) else: self.add_new_row(data[entryPos]) -- Vincent V.V. Oqapy https://launchpad.net/oqapy . Qarte https://launchpad.net/qarte . PaQager https://launchpad.net/paqager -- http://mail.python.org/mailman/listinfo/python-list
Re: Weird python behavior
On 2013-04-24, Forafo San ppv.g...@gmail.com wrote: Hello All, I'm running Python version 2.7.3_6 on a FreeBSD system. The following session in a Python interpreter throws a mysterious TypeError: -- [ppvora@snowfall ~/xbrl]$ python Python 2.7.3 (default, Apr 22 2013, 18:42:18) [GCC 4.2.1 20070719 [FreeBSD]] on freebsd8 Type help, copyright, credits or license for more information. import glob Traceback (most recent call last): File stdin, line 1, in module File glob.py, line 14, in module myl = glob.glob('data/*.xml') TypeError: 'module' object is not callable -- The file glob.py that the error refers to was run under another screen session. It's a mystery why even that program threw an error. Regardless, why should that session throw an import error in this session? Weird. Any help is appreciated. Thanks, 'Cause Python's import statement looks in the current directory first for files to import. So you're importing your own error-riddled and mortal glob.py, rather than Python's pristine and Olympian glob.py. -- Neil Cerutti This room is an illusion and is a trap devisut by Satan. Go ahead and dauntlessly! Make rapid progres! --Ghosts 'n Goblins -- http://mail.python.org/mailman/listinfo/python-list
Weird python behavior
Hello All, I'm running Python version 2.7.3_6 on a FreeBSD system. The following session in a Python interpreter throws a mysterious TypeError: -- [ppvora@snowfall ~/xbrl]$ python Python 2.7.3 (default, Apr 22 2013, 18:42:18) [GCC 4.2.1 20070719 [FreeBSD]] on freebsd8 Type help, copyright, credits or license for more information. import glob Traceback (most recent call last): File stdin, line 1, in module File glob.py, line 14, in module myl = glob.glob('data/*.xml') TypeError: 'module' object is not callable -- The file glob.py that the error refers to was run under another screen session. It's a mystery why even that program threw an error. Regardless, why should that session throw an import error in this session? Weird. Any help is appreciated. Thanks, -Premal -- http://mail.python.org/mailman/listinfo/python-list
Re: Using SciPy in application
On 2013-04-24, Roozbeh roozbe...@gmail.com wrote: I want to use spline interpolation function from SciPy in an application and at the same time, I don't want the end user to have to install SciPy separately. Is there a way around this problem? You could bundle you app along with python and SciPy and whatever other libraries are required using py2exe, py2app, cx_Freeze, Freeze, etc. -- Grant Edwards grant.b.edwardsYow! JAPAN is a WONDERFUL at planet -- I wonder if we'll gmail.comever reach their level of COMPARATIVE SHOPPING ... -- http://mail.python.org/mailman/listinfo/python-list
Re: Weird python behavior
On Wednesday, April 24, 2013 3:08:27 PM UTC-4, Neil Cerutti wrote: On 2013-04-24, Forafo San ppv.g...@gmail.com wrote: Hello All, I'm running Python version 2.7.3_6 on a FreeBSD system. The following session in a Python interpreter throws a mysterious TypeError: -- [ppvora@snowfall ~/xbrl]$ python Python 2.7.3 (default, Apr 22 2013, 18:42:18) [GCC 4.2.1 20070719 [FreeBSD]] on freebsd8 Type help, copyright, credits or license for more information. import glob Traceback (most recent call last): File stdin, line 1, in module File glob.py, line 14, in module myl = glob.glob('data/*.xml') TypeError: 'module' object is not callable -- The file glob.py that the error refers to was run under another screen session. It's a mystery why even that program threw an error. Regardless, why should that session throw an import error in this session? Weird. Any help is appreciated. Thanks, 'Cause Python's import statement looks in the current directory first for files to import. So you're importing your own error-riddled and mortal glob.py, rather than Python's pristine and Olympian glob.py. -- Neil Cerutti This room is an illusion and is a trap devisut by Satan. Go ahead and dauntlessly! Make rapid progres! --Ghosts 'n Goblins OK, lesson learned: Take care not to have module names that conflict with python's built ins. Sorry for being so obtuse. -- http://mail.python.org/mailman/listinfo/python-list
Re: My gui
On 24 April 2013 18:53, Chris “Kwpolska” Warrick kwpol...@gmail.com wrote: On Wed, Apr 24, 2013 at 7:08 PM, Daniel Kersgaard danielkersga...@gmail.com wrote: Today, being the last day of lectures at school, my instructor ran briefly through Tkninter and GUIs. I'd been looking forward to this particular lesson all semester, but when I got home and copied a sample program from my textbook verbatim, IDLE does nothing. No error, no nothing. Any ideas? Here is the code from my program. I'm not sure if this is appropriate, but suggestions are helpful. import tkinter import tkinter.messagebox class MyGui: def _init_(self): self.main_window = tkinter.Tk() self.top_frame = tkinter.Frame(self.main_window) self.bottom_frame = tkinter.Frame(self.main_window) self.prompt_label = tkinter.Label(self.top_frame, text = 'Enter a distance in Kilometers: ') self.kilo_entry = tkinter.Entry(self.top_frame, width = 10) self.prompt_label.pack(side = 'left') self.kilo_entry.pack(side = 'left') self.calc_button = tkinter.Button(self.bottom_frame, text = 'Convert', command = self.convert) self.quit_button = tkinter.Button(self.bottom_frame, text = 'Quit', command = self.main_window.destroy) self.calc_button.pack(side = 'left') self.quit_button.pack(side = 'left') self.top_frame.pack() self.bottom_frame.pack() tkinter.mainloop() def convert(self): kilo = float(self.kilo_entry.get()) miles = kilo * 0.6214 tkinter.messagebox.showinfo('Result', str(kilo) + ' kilometers is equal to ' + str(miles) + 'miles.') poop = MyGui() -- http://mail.python.org/mailman/listinfo/python-list poop? Seriously? You aren’t serious about that copying, right? Your code seems to be missing a lot of important stuff. You don’t inherit from tkinter.Frame. Compare your program to the sample “Hello world!” program: His class is not a frame, it's just a container for the tkinter code. It's a bit unusual but it looks correct to me (apart from the single underscores in __init__() as spotted by Ned Batchelder). -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Finding the source of an exception in a python multiprocessing program
I run a bit of python code that monitors my connection to the greater Internet. It checks connectivity to the requested target IP addresses, logging both successes and failures, once every 15 seconds. I see failures quite regularly, predictably on Sunday nights after midnight when various networks are undergoing maintenance. I'm trying to use python's multiprocessing library to run multiple copies in parallel to check connectivity to different parts of the country (they in no way interact with each other). On rare occasions (maybe once every couple of months) I get the following exception and traceback: Traceback (most recent call last): File ./CM_Harness.py, line 12, in module Foo = pool.map(monitor, targets)# and hands off two targets File /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py, line 227, in map return self.map_async(func, iterable, chunksize).get() File /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py, line 528, in get raise self._value IndexError: list index out of range The code where the traceback occurs is: #!/usr/bin/env python Harness to call multiple parallel copies of the basic monitor program from multiprocessing import Pool from Connection_Monitor import monitor targets = [8.8.8.8, www.ncsa.edu] pool = Pool(processes=2)# start 2 worker processes Foo = pool.map(monitor, targets)# and hands off two targets Line 12, in my code is simply the line that launches the underlying monitor code. I'm assuming that the real error is occurring in the monitor program that is being launched, but I'm at a loss as to what to do to get a better handle on what's going wrong. Since, as I said, I see failures quite regularly, typically on Sunday nights after midnight when various networks are undergoing maintenance, I don't _think_ the exception is being triggered by that sort of failure. When I look at the pool module, the error is occurring in get(self, timeout=None) on the line after the final else: def get(self, timeout=None): self.wait(timeout) if not self._ready: raise TimeoutError if self._success: return self._value else: raise self._value Python v 2.7.3, from Python.org, running on Mac OS-X 10.8.3 Thanks for any suggestions, Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: My gui
On 2013-04-24, Arnaud Delobelle arno...@gmail.com wrote: His class is not a frame, it's just a container for the tkinter code. It's a bit unusual but it looks correct to me (apart from the single underscores in __init__() as spotted by Ned Batchelder). I dunno if it makes any difference, but it's usual to call mainloop of the root window, rather than tkinter.mainloop. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding the source of an exception in a python multiprocessing program
On 2013-04-24, William Ray Wing w...@mac.com wrote: When I look at the pool module, the error is occurring in get(self, timeout=None) on the line after the final else: def get(self, timeout=None): self.wait(timeout) if not self._ready: raise TimeoutError if self._success: return self._value else: raise self._value The code that's failing is in self.wait. Somewhere in there you must be masking an exception and storing it in self._value instead of letting it propogate and crash your program. This is hiding the actual context. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
how to: multiplayer game connecting to central server effectively?
hi, I struggle for some days about a model for a multiplayer game application. I read so much from my enemy Google, i got lost by all that info and dont know which path i should chose. a multiplayer game application, sending/receiving instantly every change in the game to a central webserver, http://www.x.com, probably via socket connection? which system/module should i use for this contineous connection and where can i find a good tutorial, which a beginner like me can understand a bit? (i have read too many too complicated/technical artickles, but no nice tutorials). i have tried and accompished an urllib connection, with get and post variabels, but that will be polling, with all the http-overhead for every poll. I think this is also to slow and no real updating of the game status. Thanks in advance for any hint/tutorial i get:) -- http://mail.python.org/mailman/listinfo/python-list
Re: how to: multiplayer game connecting to central server effectively?
In c6c26882-ec2e-41f9-a4c3-d403976c7...@googlegroups.com webmas...@terradon.nl writes: i have tried and accompished an urllib connection, with get and post variabels, but that will be polling, with all the http-overhead for every poll. I think this is also to slow and no real updating of the game status. Http can still work, depending on what kind of game it is. For example a game where only the current player can make decisions and the other players just sit and watch (like Risk), or a game where each player submits a move and the server applies the game rules to resolve the outcome (like Rock-Scissors-Paper). But a truly interactive game would probably require something more, like an active socket connection. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, The Gashlycrumb Tinies -- http://mail.python.org/mailman/listinfo/python-list
Re: how to: multiplayer game connecting to central server effectively?
This series of articles is flash-based, and the examples apparently don't run, but it is a great read on all the problems you face when coding several kinds of multiplayer games, and the variety of things you can do to fix it: http://playerio.com/documentation/tutorials/building-flash-multiplayer-games-tutorial/ Did you know that Age of Empires was actually internally turn-based, in order to avoid syncing problems? On Wed, Apr 24, 2013 at 10:48 PM, John Gordon gor...@panix.com wrote: In c6c26882-ec2e-41f9-a4c3-d403976c7...@googlegroups.com webmas...@terradon.nl writes: i have tried and accompished an urllib connection, with get and post variabels, but that will be polling, with all the http-overhead for every poll. I think this is also to slow and no real updating of the game status. Http can still work, depending on what kind of game it is. For example a game where only the current player can make decisions and the other players just sit and watch (like Risk), or a game where each player submits a move and the server applies the game rules to resolve the outcome (like Rock-Scissors-Paper). But a truly interactive game would probably require something more, like an active socket connection. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, The Gashlycrumb Tinies -- http://mail.python.org/mailman/listinfo/python-list -- Fábio Santos -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding the source of an exception in a python multiprocessing program
On Apr 24, 2013, at 4:31 PM, Neil Cerutti ne...@norwich.edu wrote: On 2013-04-24, William Ray Wing w...@mac.com wrote: When I look at the pool module, the error is occurring in get(self, timeout=None) on the line after the final else: def get(self, timeout=None): self.wait(timeout) if not self._ready: raise TimeoutError if self._success: return self._value else: raise self._value The code that's failing is in self.wait. Somewhere in there you must be masking an exception and storing it in self._value instead of letting it propogate and crash your program. This is hiding the actual context. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list I'm sorry, I'm not following you. The get routine (and thus self.wait) is part of the pool module in the Python multiprocessing library. None of my code has a class or function named get. -Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding the source of an exception in a python multiprocessing program
On 24 April 2013 20:25, William Ray Wing w...@mac.com wrote: I run a bit of python code that monitors my connection to the greater Internet. It checks connectivity to the requested target IP addresses, logging both successes and failures, once every 15 seconds. I see failures quite regularly, predictably on Sunday nights after midnight when various networks are undergoing maintenance. I'm trying to use python's multiprocessing library to run multiple copies in parallel to check connectivity to different parts of the country (they in no way interact with each other). On rare occasions (maybe once every couple of months) I get the following exception and traceback: Traceback (most recent call last): File ./CM_Harness.py, line 12, in module Foo = pool.map(monitor, targets)# and hands off two targets File /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py, line 227, in map return self.map_async(func, iterable, chunksize).get() File /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py, line 528, in get raise self._value IndexError: list index out of range The code where the traceback occurs is: #!/usr/bin/env python Harness to call multiple parallel copies of the basic monitor program from multiprocessing import Pool from Connection_Monitor import monitor targets = [8.8.8.8, www.ncsa.edu] pool = Pool(processes=2)# start 2 worker processes Foo = pool.map(monitor, targets)# and hands off two targets Line 12, in my code is simply the line that launches the underlying monitor code. I'm assuming that the real error is occurring in the monitor program that is being launched, but I'm at a loss as to what to do to get a better handle on what's going wrong. Since, as I said, I see failures quite regularly, typically on Sunday nights after midnight when various networks are undergoing maintenance, I don't _think_ the exception is being triggered by that sort of failure. When I look at the pool module, the error is occurring in get(self, timeout=None) on the line after the final else: def get(self, timeout=None): self.wait(timeout) if not self._ready: raise TimeoutError if self._success: return self._value else: raise self._value Python v 2.7.3, from Python.org, running on Mac OS-X 10.8.3 This looks to me like a bug in multiprocessing but I'm not very experienced with it. Perhaps it would be good to open an issue on the tracker. It might not be solvable without an easier way of reproducing it though. Oscar -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding the source of an exception in a python multiprocessing program
On 24/04/2013 20:25, William Ray Wing wrote: I run a bit of python code that monitors my connection to the greater Internet. It checks connectivity to the requested target IP addresses, logging both successes and failures, once every 15 seconds. I see failures quite regularly, predictably on Sunday nights after midnight when various networks are undergoing maintenance. I'm trying to use python's multiprocessing library to run multiple copies in parallel to check connectivity to different parts of the country (they in no way interact with each other). On rare occasions (maybe once every couple of months) I get the following exception and traceback: Traceback (most recent call last): File ./CM_Harness.py, line 12, in module Foo = pool.map(monitor, targets)# and hands off two targets File /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py, line 227, in map return self.map_async(func, iterable, chunksize).get() File /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py, line 528, in get raise self._value IndexError: list index out of range The code where the traceback occurs is: #!/usr/bin/env python Harness to call multiple parallel copies of the basic monitor program from multiprocessing import Pool from Connection_Monitor import monitor targets = [8.8.8.8, www.ncsa.edu] pool = Pool(processes=2)# start 2 worker processes Foo = pool.map(monitor, targets)# and hands off two targets Line 12, in my code is simply the line that launches the underlying monitor code. I'm assuming that the real error is occurring in the monitor program that is being launched, but I'm at a loss as to what to do to get a better handle on what's going wrong. Since, as I said, I see failures quite regularly, typically on Sunday nights after midnight when various networks are undergoing maintenance, I don't _think_ the exception is being triggered by that sort of failure. [snip] If the exception is being raised by 'monitor', you could try catching the exception within that (or write a simple wrapper function which calls it), write the traceback to a logfile, and then re-raise. -- http://mail.python.org/mailman/listinfo/python-list
Scan CSV file and saving it into an array
Hello! I have this script that scans a csv file and if the value in the first column == 200 it saves that row into an array. The problem is, I need to save that row and the next 10 rows in that same array. What can I add to the script so it does that? I tried to do for row in len(10): but I get an error. p = csv.reader(open('file.csv'), delimiter=';') a=[0]*2881 a = numpy.array(a, dtype=dict) for row in p: if row[0]==200: a=row break print a -- http://mail.python.org/mailman/listinfo/python-list
Re: Scan CSV file and saving it into an array
On Thu, 25 Apr 2013 00:01:01 +0100, Ana Dionísio anadionisio...@gmail.com wrote: I tried to do for row in len(10): but I get an error. Please remember to tell us what error, with the traceback, so that we can make fun of you for not reading it :-) In this case it's pretty obvious; Python will complain that you can't call len() on an integer (because it's not a container type, so the whole idea of length is meaningless). You probably meant to use range(10) instead of len(10), but then row would be the integers from 0 to 9 inclusive, which isn't what you want either. What you actually want to do is row = p.next() (in Python 2.x) or row = next(p) (in Python 3.x) to get the next row from the CSV file, add it to the array and repeat until you have ten more lines. Another for-loop will make this less tedious to write. Odd that this subject should have come up so many times in various guises in the last week or two. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding the source of an exception in a python multiprocessing program
On 04/24/2013 05:09 PM, William Ray Wing wrote: On Apr 24, 2013, at 4:31 PM, Neil Cerutti ne...@norwich.edu wrote: On 2013-04-24, William Ray Wing w...@mac.com wrote: When I look at the pool module, the error is occurring in get(self, timeout=None) on the line after the final else: def get(self, timeout=None): self.wait(timeout) if not self._ready: raise TimeoutError if self._success: return self._value else: raise self._value The code that's failing is in self.wait. Somewhere in there you must be masking an exception and storing it in self._value instead of letting it propogate and crash your program. This is hiding the actual context. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list I'm sorry, I'm not following you. The get routine (and thus self.wait) is part of the pool module in the Python multiprocessing library. None of my code has a class or function named get. -Bill My question is why bother with multithreading? Why not just do these as separate processes? You said they in no way interact with each other and that's a clear clue that separate processes would be cleaner. Without knowing anything about those libraries, I'd guess that somewhere they do store state in a global attribute or equivalent, and when that is accessed by both threads, it can crash. Separate processes will find it much more difficult to interact, which is a good thing most of the time. Further, they seem to be scheduled more efficiently because of the GIL, though that may not make that much difference when you're time-limited by network data. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Scan CSV file and saving it into an array
On 04/24/2013 07:21 PM, Rhodri James wrote: On Thu, 25 Apr 2013 00:01:01 +0100, Ana Dionísio anadionisio...@gmail.com wrote: SNIP Odd that this subject should have come up so many times in various guises in the last week or two. Not that odd. In a larger classroom I'd expect several of the students to have enough internet savvy to find a forum like this. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
epiphany
I discovered something really neat today. We've got a system with a bunch of rules. Each rule is a method which returns True or False. At some point, we need to know if all the rules are True. Complicating things, not all the rules are implemented. Those that are not implemented raise NotImplementedError. We used to have some ugly logic which kept track of which rules were active and only evaluated those. So, here's the neat thing. It turns out that bool(NotImplemented) returns True. By changing the unimplemented rules from raising NotImplementedError to returning NotImplemented, the whole thing becomes: return all(r() for r in rules) -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding the source of an exception in a python multiprocessing program
On 25 April 2013 00:26, Dave Angel da...@davea.name wrote: On 04/24/2013 05:09 PM, William Ray Wing wrote: On Apr 24, 2013, at 4:31 PM, Neil Cerutti ne...@norwich.edu wrote: On 2013-04-24, William Ray Wing w...@mac.com wrote: When I look at the pool module, the error is occurring in get(self, timeout=None) on the line after the final else: def get(self, timeout=None): self.wait(timeout) if not self._ready: raise TimeoutError if self._success: return self._value else: raise self._value The code that's failing is in self.wait. Somewhere in there you must be masking an exception and storing it in self._value instead of letting it propogate and crash your program. This is hiding the actual context. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list I'm sorry, I'm not following you. The get routine (and thus self.wait) is part of the pool module in the Python multiprocessing library. None of my code has a class or function named get. -Bill My question is why bother with multithreading? Why not just do these as separate processes? You said they in no way interact with each other and that's a clear clue that separate processes would be cleaner. It's using multiprocessing rather than threads: they are separate processes. Without knowing anything about those libraries, I'd guess that somewhere they do store state in a global attribute or equivalent, and when that is accessed by both threads, it can crash. It's state that is passed to it by the subprocess and should only be accessed by the top-level process after the subprocess completes (I think!). Separate processes will find it much more difficult to interact, which is a good thing most of the time. Further, they seem to be scheduled more efficiently because of the GIL, though that may not make that much difference when you're time-limited by network data. They are separate processes and do not share the GIL (unless I'm very much mistaken). Also I think the underlying program is limited by the call to sleep for 15 seconds. Oscar -- http://mail.python.org/mailman/listinfo/python-list
Re: Scan CSV file and saving it into an array
On 04/24/2013 07:01 PM, Ana Dionísio wrote: Hello! I have this script that scans a csv file and if the value in the first column == 200 it saves that row into an array. No it doesn't. It creates a list, then overwrites it with a numpy array, then overwrites that with a list of strings representing one row. If you want to really use a Python array, then read here: http://docs.python.org/2/library/array.html It'd probably be best to start with a precise problem statement, presumably copied from your textbook or assignment sheet. What python version is this for? And what OS? (that affects whether you need a file mode) Exactly what data structure are you trying to build? What type of a csv file are you trying to use? Is there a standard header line? How big might the file be? What behavior do you want if there's no line that begins with the field 200? Or if there's more than one such line? Or if there are less than 10 lines following it in the file? What about a field of 0200? The problem is, I need to save that row and the next 10 rows in that same array. What can I add to the script so it does that? I tried to do for row in len(10): but I get an error. When you say get an error it could be one of many things. In this case, it's obvious, since len() doesn't make sense with an integer parameter. But in general you want to say either: 1) it gave me the wrong result. I expected and got 2) it did nothing at all. 3) it gave an exception, and here's the full traceback. p = csv.reader(open('file.csv'), delimiter=';') a=[0]*2881 a = numpy.array(a, dtype=dict) These two lines do nothing useful, and they confuse the reader of the code, since they imply that the list will end up of size 2881, and/or as a numpy array. for row in p: if row[0]==200: a=row break missing else clause. How do you detect that there was no match? print a -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding the source of an exception in a python multiprocessing program
On 04/24/2013 08:00 PM, Oscar Benjamin wrote: On 25 April 2013 00:26, Dave Angel da...@davea.name wrote: On 04/24/2013 05:09 PM, William Ray Wing wrote: SNIP My question is why bother with multithreading? Why not just do these as separate processes? You said they in no way interact with each other and that's a clear clue that separate processes would be cleaner. It's using multiprocessing rather than threads: they are separate processes. You're right; I was completely off base. brain-freeze. SNIP It's state that is passed to it by the subprocess and should only be accessed by the top-level process after the subprocess completes (I think!). Separate processes will find it much more difficult to interact, which is a good thing most of the time. Further, they seem to be scheduled more efficiently because of the GIL, though that may not make that much difference when you're time-limited by network data. They are separate processes and do not share the GIL (unless I'm very much mistaken). No, you're not mistaken. Somehow I interpreted the original as saying multi-thread, and everything else was wrong as a result. Now it sounds like a bug in, or misuse of, the Pool class. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Scan CSV file and saving it into an array
On 25 April 2013 00:01, Ana Dionísio anadionisio...@gmail.com wrote: Hello! I have this script that scans a csv file and if the value in the first column == 200 it saves that row into an array. The problem is, I need to save that row and the next 10 rows in that same array. What can I add to the script so it does that? I tried to do for row in len(10): but I get an error. p = csv.reader(open('file.csv'), delimiter=';') a=[0]*2881 a = numpy.array(a, dtype=dict) You shouldn't be using a numpy array for this; use a list instead. I suggest that you have a go at the Python tutorial and avoid using numpy until you are more confident with the basics of Python itself. The tutorial (for Python 2) is here: http://docs.python.org/2/tutorial/ Oscar -- http://mail.python.org/mailman/listinfo/python-list
Re: epiphany
On Wed, 24 Apr 2013 19:50:33 -0400, Roy Smith wrote: I discovered something really neat today. We've got a system with a bunch of rules. Each rule is a method which returns True or False. At some point, we need to know if all the rules are True. Complicating things, not all the rules are implemented. Those that are not implemented raise NotImplementedError. NotImplementedError is intended to be raised by abstract base classes to indicate a method that must be overridden. I also use it as a place- holder for functions or methods I haven't actually written yet. I'm not sure what semantics you're giving NotImplementedError in your code, but I wonder whether a neater solution might be to just use rule = None for unimplemented rules, rather than: def unimplemented(): raise NotImplementedError rule = unimplemented Then your logic for seeing if all rules return true would become: all(r() for r in rules if r is not None) and for seeing if all rules return true or are unimplemented: all(r is None or r() for r in rules) We used to have some ugly logic which kept track of which rules were active and only evaluated those. I don't see why you would need anything like that. Reading further on, I see that you are counting unimplemented rules as true, for some reason which I don't understand. (Knowing nothing of your use-case, I would have expected intuitively that unimplemented rules count as not true.) A simple helper function will do the job: def eval(rule): try: return rule() except NotImplementedError: return True everything_is_true = all(eval(r) for r in rules) No need for complicated ugly logic keeping track of what rules are implemented. But if you're worried about the cost of catching those exceptions (you've profiled your code, right?) then that's easy with a decorator: def not_implemented(func): @functools.wraps(func) def inner(*args, **kw): raise NotImplementedError inner.ni = True return inner # Decorate only the rules you want to be unimplemented. @not_implemented def my_rule(): pass everything_is_true = all(r() for r in rules if not hasattr(r, 'ni')) Note that if you could reverse the logic so that unimplemented rules count as not true, this will also work: try: everything_is_true = all(r() for r in rules) except NotImplementedError: everything_is_true = False So, here's the neat thing. It turns out that bool(NotImplemented) returns True. By changing the unimplemented rules from raising NotImplementedError to returning NotImplemented, the whole thing becomes: return all(r() for r in rules) Objects are supposed to return NotImplemented from special dunder methods like __add__, __lt__, etc. to say I don't know how to implement this method for the given argument. Python will then try calling the other object's special method. If both objects return NotImplemented, Python falls back on whatever default behaviour is appropriate. So, knowing nothing of your application, I fear that this is an abuse of NotImplemented's semantics. If a rule returns NotImplemented, I would expect your application to fall back on a different rule. If that's not the case, you're using it in a non-standard way that will cause confusion for those with expectations of what NotImplemented means. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: epiphany
In article 5178884b$0$29977$c3e8da3$54964...@news.astraweb.com, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: I don't see why you would need anything like that. Reading further on, I see that you are counting unimplemented rules as true, for some reason which I don't understand. The top-level logic we need to enforce is this configuration doesn't violate any rules. -- http://mail.python.org/mailman/listinfo/python-list
Re: epiphany
On Thu, Apr 25, 2013 at 11:41 AM, Roy Smith r...@panix.com wrote: In article 5178884b$0$29977$c3e8da3$54964...@news.astraweb.com, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: I don't see why you would need anything like that. Reading further on, I see that you are counting unimplemented rules as true, for some reason which I don't understand. The top-level logic we need to enforce is this configuration doesn't violate any rules. Then have your unimplemented rules simply return True. Easy! ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: epiphany
In article mailman.1044.1366856455.3114.python-l...@python.org, Chris Angelico ros...@gmail.com wrote: On Thu, Apr 25, 2013 at 11:41 AM, Roy Smith r...@panix.com wrote: In article 5178884b$0$29977$c3e8da3$54964...@news.astraweb.com, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: I don't see why you would need anything like that. Reading further on, I see that you are counting unimplemented rules as true, for some reason which I don't understand. The top-level logic we need to enforce is this configuration doesn't violate any rules. Then have your unimplemented rules simply return True. Easy! ChrisA It's nice to have tri-state logic: * This rule passes * This rule fails * This rule was not evaluated What I've got now expresses that perfectly. -- http://mail.python.org/mailman/listinfo/python-list
Re: epiphany
On 04/24/2013 06:35 PM, Steven D'Aprano wrote: Objects are supposed to return NotImplemented from special dunder methods like __add__, __lt__, etc. to say I don't know how to implement this method for the given argument. Python will then try calling the other object's special method. If both objects return NotImplemented, Python falls back on whatever default behaviour is appropriate. So, knowing nothing of your application, I fear that this is an abuse of NotImplemented's semantics. If a rule returns NotImplemented, I would expect your application to fall back on a different rule. If that's not the case, you're using it in a non-standard way that will cause confusion for those with expectations of what NotImplemented means. Why would you assume some random application is going to deal with NotImplemented the same way the python interpreter does? And even the interpreter isn't consistent -- sometimes it will return false (__eq__) and sometimes it will raise an Exception (__add__). I hardly think it an abuse of NotImplemented to signal something is not implemented when NotImplemented means, um, not implemented. possibly-not-implemented-ly yours, -- ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: My gui
On 4/24/2013 1:53 PM, Chris “Kwpolska” Warrick wrote: Please try fixing it and running it _outside of IDLE_, which is also built in Tk The default mode of Idle runs user code in a separate process. Editing tkinter code with Idle and running it (in the separate process) should be no problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: epiphany
On 04/24/2013 07:20 PM, Chris Angelico wrote: On Thu, Apr 25, 2013 at 11:41 AM, Roy Smith r...@panix.com wrote: In article 5178884b$0$29977$c3e8da3$54964...@news.astraweb.com, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: I don't see why you would need anything like that. Reading further on, I see that you are counting unimplemented rules as true, for some reason which I don't understand. The top-level logic we need to enforce is this configuration doesn't violate any rules. Then have your unimplemented rules simply return True. Easy! And less clear. -- ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: how to: multiplayer game connecting to central server effectively?
On Thu, Apr 25, 2013 at 6:59 AM, webmas...@terradon.nl wrote: hi, I struggle for some days about a model for a multiplayer game application. I read so much from my enemy Google, i got lost by all that info and dont know which path i should chose. a multiplayer game application, sending/receiving instantly every change in the game to a central webserver, http://www.x.com, probably via socket connection? which system/module should i use for this contineous connection and where can i find a good tutorial, which a beginner like me can understand a bit? (i have read too many too complicated/technical artickles, but no nice tutorials). i have tried and accompished an urllib connection, with get and post variabels, but that will be polling, with all the http-overhead for every poll. I think this is also to slow and no real updating of the game status. Thanks in advance for any hint/tutorial i get:) The easiest way to start would be a MUD or chat server. Establish a TCP socket, then whenever anything happens, report the change to all connected sockets. In its simplest form: * Accept connection * Wait for login (or, for a simple test, just Enter your name: would do) * Add connection to pool * Whenever a line of text is received, prepend the name and send it to every connection in the pool. That's a basic chat server. A MUD adds only a small bit of complication: you need some form of command parser, and not everything will announce to all connected clients. I can walk you through a lot of this, but I haven't done most of it in Python; there's another language, very similar in semantics, which is better suited to MUD building: Pike. But it's all similar enough that you'll be able to do it in either. The project you're looking at sounds to me like it'd be well implemented as a MUD-style connection with a fancy client in front of it. Debug your system using the MUD connection, and make sure you don't have any security holes that can be exploited by someone switching out your client for a custom one; because, believe you me, someone will figure out how to do it. (If you're concerned about privacy, you can easily switch in SSL/TLS, while not fundamentally changing any of your code.) Start with something as simple as you possibly can, and then add complication only as you find you need it. Here's the module you'll be wanting: http://docs.python.org/3.3/library/socket.html (By the way, you won't be connecting to a *web* server. Your central server will be quite separate from that system. It might happen to be the same computer, but there's no real connection.) ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: My gui
On Thu, Apr 25, 2013 at 3:08 AM, Daniel Kersgaard danielkersga...@gmail.com wrote: import tkinter import tkinter.messagebox class MyGui: def _init_(self): ... all code here poop = MyGui() As already mentioned, changing that to __init__ makes everything work (I just tested in Python 3.3 on Windows). But since Python is not Java, there's no reason to bury all this code in a class; just move all that code flush left and abandon the explicit instantiation. The constructor doesn't return until the window's been closed, so there's really no point in returning an object. (Maybe if you remove the mainloop() call, you could possibly make use of two of these sorts of windows, but YAGNI - don't bother with the complexity required to handle multiple simultaneous windows until you have a use-case.) So here's a direct translation to top-level code: import tkinter import tkinter.messagebox def convert(): kilo = float(kilo_entry.get()) miles = kilo * 0.6214 tkinter.messagebox.showinfo('Result', str(kilo) + ' kilometers is equal to ' + str(miles) + 'miles.') main_window = tkinter.Tk() top_frame = tkinter.Frame(main_window) bottom_frame = tkinter.Frame(main_window) prompt_label = tkinter.Label(top_frame, text = 'Enter a distance in Kilometers: ') kilo_entry = tkinter.Entry(top_frame, width = 10) prompt_label.pack(side = 'left') kilo_entry.pack(side = 'left') calc_button = tkinter.Button(bottom_frame, text = 'Convert', command = convert) quit_button = tkinter.Button(bottom_frame, text = 'Quit', command = main_window.destroy) calc_button.pack(side = 'left') quit_button.pack(side = 'left') top_frame.pack() bottom_frame.pack() tkinter.mainloop() -- cut -- (You may want to bury the code inside a main(), but that's optional too.) And here's a slightly modified version: import tkinter import tkinter.messagebox main_window = tkinter.Tk() top_frame = tkinter.Frame(main_window) bottom_frame = tkinter.Frame(main_window) tkinter.Label(top_frame, text = 'Enter a distance in Kilometers: ').pack(side = 'left') km_entry = tkinter.Entry(top_frame, width = 10); km_entry.pack(side = 'left') def convert(): km = float(km_entry.get()) miles = km * 0.6214 tkinter.messagebox.showinfo('Result', '%.2f kilometers is equal to %.2f miles.' % (km, miles) ) tkinter.Button(bottom_frame, text = 'Convert', command = convert).pack(side = 'left') tkinter.Button(bottom_frame, text = 'Quit', command = main_window.destroy).pack(side = 'left') top_frame.pack() bottom_frame.pack() tkinter.mainloop() -- cut -- I've removed some redundant variables (you don't need to hang onto references to your labels,just pack 'em in and be done), and reordered the code a bit to put the Convert button's function right near where the Convert button is created (take your pick - do you prefer that, or to have all the other functions up top? Both are viable); I also changed your message box to use percent-formatting with fixed decimals rather than str(), to tidy up the display a bit. Oh, and renamed kilo to km, because to me kilo means kilogram. :) This version of the code isn't necessarily better in every way, but it's different. Like the Oracle in The Matrix, I want you to make up your own mind as to what you ought to do; maybe you'll like some of my changes, maybe you won't, but either way you're making an intelligent decision about code style :) ChrisA -- http://mail.python.org/mailman/listinfo/python-list
IPython in Emacs
Hi, Please excuse the slightly off-topic query. I'm learning Python, using the IPython (0.13) shell, and wanted to run it from Emacs 24. AFAICT, python.el is the most actively developed library, and is included in Emacs. How do experienced Python programmers set up their python.el to make the best of it? I've done it following the recommendations given in the library¹: (setq python-shell-interpreter ipython python-shell-interpreter-args python-shell-prompt-regexp In \\[[0-9]+\\]: python-shell-prompt-output-regexp Out\\[[0-9]+\\]: python-shell-completion-setup-code from IPython.core.completerlib import module_completion python-shell-completion-module-string-code ';'.join(module_completion('''%s'''))\n python-shell-completion-string-code ';'.join(get_ipython().Completer.all_completions('''%s'''))\n) but this may be a little outdated as it refers to IPython 0.11. Thanks, Seb +--- Footnotes ---+ ¹ Ignored recommended setting for `python-shell-interpreter-args' -- http://mail.python.org/mailman/listinfo/python-list
Re: epiphany
On Wed, 24 Apr 2013 19:25:37 -0700, Ethan Furman wrote: On 04/24/2013 06:35 PM, Steven D'Aprano wrote: Objects are supposed to return NotImplemented from special dunder methods like __add__, __lt__, etc. to say I don't know how to implement this method for the given argument. Python will then try calling the other object's special method. If both objects return NotImplemented, Python falls back on whatever default behaviour is appropriate. So, knowing nothing of your application, I fear that this is an abuse of NotImplemented's semantics. If a rule returns NotImplemented, I would expect your application to fall back on a different rule. If that's not the case, you're using it in a non-standard way that will cause confusion for those with expectations of what NotImplemented means. Why would you assume some random application is going to deal with NotImplemented the same way the python interpreter does? Why would you assume that some random application is going to treat x==y the same way the Python interpreter does? Just because you can design your objects to do anything you want doesn't mean you should. Breaking conventions carries costs by the mere fact that you're breaking conventions. There are established semantics that an experienced Python developer will expect for NotImplemented, and doing something else risks causing confusion and mistakes. Or worse, bugs. If there is any chance that a rule might be called in a context where the Python interpreter gets to interpret the return result before you see it, then returning NotImplemented could lead to difficult to debug problems. And even the interpreter isn't consistent -- sometimes it will return false (__eq__) and sometimes it will raise an Exception (__add__). As I said: If both objects return NotImplemented, Python falls back on whatever default behaviour is appropriate. If neither object knows how to compare the other for equality, the appropriate behaviour is to treat them as unequal. If neither object knows how to add itself to the other, the appropriate behaviour is to raise an exception. I hardly think it an abuse of NotImplemented to signal something is not implemented when NotImplemented means, um, not implemented. It doesn't just mean not implemented in general, it has a specific meaning: I don't know what to do here, let the other object handle it. As I have repeatedly said, I don't know the context of the application, but from what little has been described, this part of it doesn't feel to me like a good, clean design. I might be wrong, but from the outside it feels like the API should be that rules return a three-state logic instance: True, False, Unknown where Unknown can be trivially created with Unknown = object() The semantics of NotImplementedError is that it is an *error*, and that doesn't sound appropriate given the example shown. Why would a rule that raises an *error* exception be treated as if it had passed? That's just wrong. The semantics of NotImplemented is that it is a signal for one object to say I don't know how to do this, let somebody else try. That also doesn't seem appropriate. There's no sign that Roy's application does the equivalent to this: result = rule() if result is NotImplemented: result = another_rule() if result is NotImplemented: result = some_default Since rules apparently take no arguments, either: 1) they rely on global state, which is a nasty design; or 2) rules actually have a fixed return result, in which case why make them functions in the first place? Since both possibilities seem stupid, and I do not believe that Roy actually is stupid, I suspect that his example over-simplifies the situation. But I can't comment on the infinite number of things that his code might do, I can only comment on the examples as actually given, and as given, I don't think that either NotImplementedError or NotImplemented is a clean solution to the problem. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: IPython in Emacs
On Apr 25, 8:35 am, Seb splu...@gmail.com wrote: Hi, Please excuse the slightly off-topic query. I'm learning Python, using the IPython (0.13) shell, and wanted to run it from Emacs 24. AFAICT, python.el is the most actively developed library, and is included in Emacs. How do experienced Python programmers set up their python.el to make the best of it? I've done it following the recommendations given in the library¹: (setq python-shell-interpreter ipython python-shell-interpreter-args python-shell-prompt-regexp In \\[[0-9]+\\]: python-shell-prompt-output-regexp Out\\[[0-9]+\\]: python-shell-completion-setup-code from IPython.core.completerlib import module_completion python-shell-completion-module-string-code ';'.join(module_completion('''%s'''))\n python-shell-completion-string-code ';'.join(get_ipython().Completer.all_completions('''%s'''))\n) but this may be a little outdated as it refers to IPython 0.11. Thanks, Seb +--- Footnotes ---+ ¹ Ignored recommended setting for `python-shell-interpreter-args' There were some ipython+emacs+windows bugs: https://bugs.launchpad.net/ipython/+bug/290228 Last I tried nearly 2 years, they were still there http://groups.google.com/group/comp.lang.python/browse_thread/thread/36e757567f28368e [Since you did not say whether you are on windows or *nix, just saying] -- http://mail.python.org/mailman/listinfo/python-list
Pythonic way to count sequences
I have to count the number of various two-digit sequences in a list such as this: mylist = [(2,4), (2,4), (3,4), (4,5), (2,1)] # (Here the (2,4) sequence appears 2 times.) and tally up the results, assigning each to a variable. The inelegant first pass at this was something like... # Create names and set them all to 0 alpha = 0 beta = 0 delta = 0 gamma = 0 # etc... # loop over all the tuple sequences and increment appropriately for sequence_tuple in list_of_tuples: if sequence_tuple == (1,2): alpha += 1 if sequence_tuple == (2,4): beta += 1 if sequence_tuple == (2,5): delta +=1 # etc... But I actually have more than 10 sequence types. # Finally, I need a list created like this: result_list = [alpha, beta, delta, gamma] #etc...in that order I can sense there is very likely an elegant/Pythonic way to do this, and probably with a dict, or possibly with some Python structure I don't typically use. Suggestions sought. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonic way to count sequences
On Thu, Apr 25, 2013 at 3:05 PM, CM cmpyt...@gmail.com wrote: I have to count the number of various two-digit sequences in a list such as this: mylist = [(2,4), (2,4), (3,4), (4,5), (2,1)] # (Here the (2,4) sequence appears 2 times.) and tally up the results, assigning each to a variable. You can use a tuple as a dictionary key, just like you would a string. So you can count them up directly with a dictionary: count = {} for sequence_tuple in list_of_tuples: count[sequence_tuple] = count.get(sequence_tuple,0) + 1 Also, since this is such a common thing to do, there's a standard library way of doing it: import collections count = collections.Counter(list_of_tuples) This doesn't depend on knowing ahead of time what your elements will be. At the end of it, you can simply iterate over 'count' and get all your counts: for sequence,number in count.items(): print(%d of %r % (number,sequence)) ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Comparison Style
Given that s = some static value i = a value incremented during a loop I'm used to comparing them as if i == s: # some code But for some unknown reason I did a switch if s == i: # same code It didn't seem to make any difference at first glance, so I just got to wondering -- Is there a standard for comparison order? Is there any kind of performance difference? Is there even a tradition for one or the other? Are there any gotchas? Do I need to get a hobby? -- http://mail.python.org/mailman/listinfo/python-list
[issue9849] Argparse needs better error handling for nargs
paul j3 added the comment: This patch adds a value test for nargs during add_argument. The core of the new test is in ArgumentParser._check_argument. add_argument() now calls ArgumentParser._check_argument(), which calls _format_args(). If it gets a TypeError, it raises a metavar ValueError as before. But if it gets an ValueError, it raises an ArgumentError. An argument group gets the _check_argument method from its container. This way, check_argument() works for both parsers and groups. HelpFormater _format_args() now raises a ValueError if the nargs is not an integer (or one of the recognized strings). What kind of error should we produce when there is a problem with nargs? An ArgumentError has the advantage that it includes the action name. But the metavar tuple test was coded to raise ValueError. Plus the test_argparse.py TestInvalidArgumentConstructors class tests all check for TypeError or ValueError. I have kept the metavar tuple case as ValueError. That way, test_argparse.py runs without a change. I still need to add tests for invalid string nargs values. And I think the case could be made for returning ArgumentValue errors. -- keywords: +patch Added file: http://bugs.python.org/file29998/nargswarn.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9849 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9849] Argparse needs better error handling for nargs
paul j3 added the comment: The attached test_nargswarn.py file tests the argparse.py patch. It tries out various nargs values, both for parsers, groups, and mutually exclusive groups. I intend to recast these to work in test_argparse.py -- Added file: http://bugs.python.org/file2/test_nargswarn.py ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9849 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue17532] IDLE: Always include Options menu on MacOSX
Guilherme Simões added the comment: Since extensions are probably going to be included into IDLE soon I'm attaching a version of the patch that also changes PyShell.py. -- Added file: http://bugs.python.org/file3/17532MenuOptions-2.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue17532 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue15301] os.chown: OverflowError: Python int too large to convert to C long
Serhiy Storchaka added the comment: Yes, it is what I had in mean. Sorry for indistinctness. As far as you change _fd_converter() it will be good to add also a test for float/decimal/fractional fd. Otherwise the patch LGTM. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue15301 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue17825] Indentation.offset and SyntaxError.offset mismatch
New submission from Florent Xicluna: I noticed a difference between computation of column offset for SyntaxError and IndentationError (a subclass of SyntaxError). It is slightly confusing. def report(exc): print('lineno %s, offset %s' % (exc.lineno, exc.offset)) raise try: exec('except IOError:') except Exception as e: report(e) try: exec('open(filepath)') except Exception as e: report(e) ** OUTPUT ** lineno 1, offset 6 Traceback (most recent call last): File stdin, line 4, in module File stdin, line 2, in module File string, line 1 except IOError: ^ SyntaxError: invalid syntax lineno 1, offset 4 Traceback (most recent call last): File stdin, line 4, in module File stdin, line 2, in module File string, line 1 open(filepath) ^ IndentationError: unexpected indent ** Analysis ** Case (1): offset is 6, and caret is below column 5 for SyntaxError Case (2): offset is 4, and caret is below column 4 for IndentationError -- messages: 187690 nosy: flox priority: normal severity: normal status: open title: Indentation.offset and SyntaxError.offset mismatch type: behavior versions: Python 2.7, Python 3.3 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue17825 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue12634] Random Remarks in class documentation
Yongzhi Pan added the comment: It may be worth to noting that when creating property attribute using the property decorator, we may tend to name the method using nouns, like here: http://docs.python.org/2/library/functions.html#property This is when I once overided data attribute with method. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue12634 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue17826] Setting a side_effect on mock from create_autospec doesn't work
New submission from Michael Foord: from unittest.mock import create_autospec def f(): pass ... m = create_autospec(f) m.side_effect = [1, 2] m() Traceback (most recent call last): File stdin, line 1, in module File string, line 3, in f File /compile/py3k-cpython/Lib/unittest/mock.py, line 872, in __call__ return _mock_self._mock_call(*args, **kwargs) File /compile/py3k-cpython/Lib/unittest/mock.py, line 931, in _mock_call result = next(effect) TypeError: 'list' object is not an iterator -- assignee: michael.foord components: Library (Lib) messages: 187692 nosy: michael.foord priority: normal severity: normal stage: needs patch status: open title: Setting a side_effect on mock from create_autospec doesn't work type: behavior versions: Python 3.3, Python 3.4 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue17826 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue17547] checking whether gcc supports ParseTuple __format__... erroneously returns yes with gcc 4.8
Alex Leach added the comment: I don't think I can tell you anything you don't know already, but ... On Tue, 23 Apr 2013 19:38:18 +0100, Dave Malcolm rep...@bugs.python.org wrote: BTW, is that GCC format checking code available anywhere? Is this what you mean? http://gcc.gnu.org/viewcvs/gcc/trunk/gcc/c-family/c-format.c?annotate=193304pathrev=193304 I got taken straight there from the link you sent, above... Am I right in thinking that it was an out-of-tree patch to GCC, from the pre-plugin days? No idea.. GCC plugins have been around for several years now, though and the patch was only introduced in November. If this patch was applied to any past GCC distributions, I'm sure someone else would have been overwhelmed with warnings and would have mentioned something before now. Either way, it looks like the patch is going to stay. In case you hadn't seen it already, the invoke.texi source file probably has the most descriptive changes:- http://gcc.gnu.org/viewcvs/gcc/trunk/gcc/doc/invoke.texi?r1=193304r2=193303pathrev=193304 KR, Alex -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue17547 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue17813] lzma and bz2 decompress methods lack max_size parameter
Changes by Ezio Melotti ezio.melo...@gmail.com: -- stage: - committed/rejected status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue17813 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10951] gcc 4.6 warnings
Martin v. Löwis added the comment: I don't mind them being backported, in the spirit of supporting newer tools well in 2.7. OTOH, I don't see it as necessary, either. 2.7 will eventually be phased out, and then it doesn't matter how much warnings it produces. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10951 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue16499] CLI option for isolated mode
Changes by yaccz yac@gmail.com: -- nosy: +yaccz ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue16499 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue12238] Readline module loading in interactive mode
Changes by yaccz yac@gmail.com: -- nosy: +yaccz ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue12238 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue7475] codecs missing: base64 bz2 hex zlib hex_codec ...
Martin v. Löwis added the comment: I don't see any point in merely bringing the codecs back, without any convenience API to use them. If I need to do import codecs result = codecs.getencoder(base64).encode(data) I don't think people would actually prefer this over import base64 result = base64.encodebytes(data) I't (IMO) only the convenience method (.encode) that made people love these codecs. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue7475 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue7475] codecs missing: base64 bz2 hex zlib hex_codec ...
Ezio Melotti added the comment: IMHO it's also a documentation problem. Once people figure out that they can't use encode/decode anymore, it's not immediately clear what they should do instead. By reading the codecs docs[0] it's not obvious that it can be done with codecs.getencoder(...).encode/decode, so people waste time finding a solution, get annoyed, and blame Python 3 because it removed a simple way to use these codecs without making clear what should be used instead. FWIW I don't care about having to do an extra import, but indeed something simpler than codecs.getencoder(...).encode/decode would be nice. [0]: http://docs.python.org/3/library/codecs.html -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue7475 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue15392] Create a unittest framework for IDLE
Tomoki Imai added the comment: I have already posted idle_dev mailing list (and, no one replied :P). I think, Ezio's suggestion is good if we will work for Python2. Using unittest.mock and mock to support Python2 and Python3. My proposal for GSoC is here. Making very initial version for Python2 and Python3 and, complete Python3 version and, backport it in the end. I'll set backporting for Python2 as optional work. My main goal is to make unittest for Python3. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue15392 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue17226] libintl should also check for libiconv
Alan Hourihane added the comment: Bumping. How does Jeffrey's patch look folks ? -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue17226 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue17827] Document codecs.encode and codecs.decode
New submission from Nick Coghlan: The codecs module has long offered encode() and decode() convenience functions (since 2004: http://hg.python.org/cpython-fullhistory/rev/8ea2cb1ec598), but they're not documented (except through docstrings). We should fix that. From the docstrings: == encode(obj, [encoding[,errors]]) - object Encodes obj using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a ValueError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle ValueErrors. == decode(obj, [encoding[,errors]]) - object Decodes obj using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a ValueError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that is able to handle ValueErrors. == Note that the difference between the convenience functions in the codecs module and the methods on str, bytes and bytearray is that the latter have additional type checks to limit their usage to text encodings. str.encode expects a str-bytes conversion, while bytes.decode and bytearray.decode both expect the codec to produce a str object. codecs.encode and codecs.decode are both arbitrary object-object conversions, limited only by whatever the chosen codec supports. -- assignee: docs@python components: Documentation messages: 187700 nosy: docs@python, ncoghlan priority: normal severity: normal status: open title: Document codecs.encode and codecs.decode versions: Python 2.7, Python 3.3, Python 3.4 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue17827 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue7475] codecs missing: base64 bz2 hex zlib hex_codec ...
Nick Coghlan added the comment: It turns out MAL added the convenience API I'm looking for back in 2004, it just didn't get documented, and is hidden behind the from _codecs import * call in the codecs.py source code: http://hg.python.org/cpython-fullhistory/rev/8ea2cb1ec598 So, all the way from 2.4 to 2.7 you can write: from codecs import encode result = encode(data, base64) It works in 3.x as well, you just need to add the _codec to the end to account for the missing aliases: encode(bexample, base64_codec) b'ZXhhbXBsZQ==\n' decode(bZXhhbXBsZQ==\n, base64_codec) b'example' Note that the convenience functions omit the extra checks that are part of the methods (although I admit the specific error here is rather quirky): bZXhhbXBsZQ==\n.decode(base64_codec) Traceback (most recent call last): File stdin, line 1, in module File /usr/lib64/python3.2/encodings/base64_codec.py, line 20, in base64_decode return (base64.decodebytes(input), len(input)) File /usr/lib64/python3.2/base64.py, line 359, in decodebytes raise TypeError(expected bytes, not %s % s.__class__.__name__) TypeError: expected bytes, not memoryview I'me going to create some additional issues, so this one can return to just being about restoring the missing aliases. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue7475 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue7475] codecs missing: base64 bz2 hex zlib hex_codec ...
Marc-Andre Lemburg added the comment: Just copying some details here about codecs.encode() and codec.decode() from python-dev: Just as reminder: we have the general purpose encode()/decode() functions in the codecs module: import codecs r13 = codecs.encode('hello world', 'rot-13') These interface directly to the codec interfaces, without enforcing type restrictions. The codec defines the supported input and output types. As Nick found, these aren't documented, which is a documentation bug (I probably forgot to add documentation back then). They have been in Python since 2004: http://hg.python.org/cpython-fullhistory/rev/8ea2cb1ec598 These API are nice for general purpose codec work and that's why I added them back in 2004. For the codecs in question, it would still be nice to have a more direct way to access them via methods on the types that you typically use them with. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue7475 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue17827] Document codecs.encode and codecs.decode
Changes by Ezio Melotti ezio.melo...@gmail.com: -- keywords: +easy nosy: +ezio.melotti stage: - needs patch type: - enhancement ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue17827 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue7475] codecs missing: base64 bz2 hex zlib hex_codec ...
Ezio Melotti added the comment: It works in 3.x as well, you just need to add the _codec to the end to account for the missing aliases: FTR this is because of ff1261a14573 (see #10807). -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue7475 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue17825] Indentation.offset and SyntaxError.offset mismatch
R. David Murray added the comment: Well, that would be because the invalid indent is detected when the 'o' is encountered, whereas the invalid syntax is detected when the 't' completes the keyword 'except'. I don't think there is a bug here. -- nosy: +r.david.murray ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue17825 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue17828] More informative error handling when encoding and decoding
New submission from Nick Coghlan: Passing the wrong types to codecs can currently lead to rather confusing exceptions, like: bZXhhbXBsZQ==\n.decode(base64_codec) Traceback (most recent call last): File stdin, line 1, in module File /usr/lib64/python3.2/encodings/base64_codec.py, line 20, in base64_decode return (base64.decodebytes(input), len(input)) File /usr/lib64/python3.2/base64.py, line 359, in decodebytes raise TypeError(expected bytes, not %s % s.__class__.__name__) TypeError: expected bytes, not memoryview codecs.decode(example, utf8) Traceback (most recent call last): File stdin, line 1, in module File /usr/lib64/python3.2/encodings/utf_8.py, line 16, in decode return codecs.utf_8_decode(input, errors, True) TypeError: 'str' does not support the buffer interface This situation could be improved by having the affected APIs use the exception chaining system to wrap these errors in a more informative exception that also display information on the codec involved. Note that UnicodeEncodeError and UnicodeDecodeError are not appropriate, as those are specific to text encoding operations, while these new wrappers will apply to arbitrary codecs, regardless of whether or not they use the unicode error handlers. Furthermore, for backwards compatibility with existing exception handling, it is probably necessary to limit ourselves to specific exception types and ensure that the wrapper exceptions are subclasses of those types. These new wrappers would have __cause__ set to the exception raised by the codec, but emit a message more along the lines of the following: == codecs.DecodeTypeError: encoding='utf8', details=TypeError: 'str' does not support the buffer interface == Wrapping TypeError and ValueError should cover most cases, which would mean four new exception types in the codecs module: Raised by codecs.decode, bytes.decode and bytearray.decode: * codecs.DecodeTypeError * codecs.DecodeValueError Raised by codecs.encode, str.encode: * codecs.EncodeTypeError * codecs.EncodeValueError Instances of UnicodeError wouldn't be wrapped, since they already contain codec information. -- components: Library (Lib) messages: 187704 nosy: ncoghlan priority: normal severity: normal status: open title: More informative error handling when encoding and decoding versions: Python 3.4 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue17828 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue7475] codecs missing: base64 bz2 hex zlib hex_codec ...
Nick Coghlan added the comment: Issue 17827 covers adding documentation for codecs.encode and codecs.decode Issue 17828 covers adding exception handling improvements for all encoding and decoding operations -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue7475 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com