content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Compile Python 2.5.5 on OS X 10.6 I would like to install Python 2.5.5 to use with Google apps but have been having a very hard time tracking down instructions on how to do so. I am thinking the following might work but was wondering if anyone had successfully built it? ./configure --prefix=/usr/local/python2.5.5 MACOSX_DEPLOYMENT_TARGET=10.6 --enable-framework --with-universal-archs="64-bit" CFLAGS="-arch x86_64" LDFLAGS="-arch x86_64" ~: make -j6 ~: sudo make install Any help is appreciated! A: You should install it via MacPorts, which makes this a piece of cake. After you have it installed... $ sudo port install python25 A: You should install it via Fink, which makes this a piece of cake. After you have it installed... $ fink install python25 Fink has more packages than MacPorts. A: Assuming that you are running OS 10.6, At the terminal if you type % python<tab> The terminal should show you all the python* items on your PATH. As suggested by @philipp, Python 2.5 and Python 2.6 are installed by default. You can see listed as: python2.5 python2.6 You will also see an entry which is just python. This is the one that is going to used by default when you invoke the command python at the command line. To see the version of this default version either start it by typing python at the command line and note the text printed out at startup, or do a which python to see the absolute path for that executable. The executables in the PATH on OS X are managed by links, so to see the actual location ls -lha `which python` ls -lha `which python2.5` ls -lha `which python2.6` Note the backtics will cause the which command to run and insert the result into the ls command. Lastly, you can choose the version of Python which is the default by using the python_select command. I don't have a lot of experience with this, as I usually manage my access to Python via my own soft links or shell aliases. That all being said, if you are going to be installing a lot of packages for development purposes give the advice of @Dave Pirotte a try. By using MacPorts, or fink, you will get a new installation of Python (and whatever further packages you need) outside of the system Python installation. This can be handy if you need to make a lot of modifications and if you're going to hard on the health of your Python installation it is easier to whipe the slate clean and start over if you don't mess with the default system Python. A: Python 2.5 does not build correctly out of the box on Mac OS X 10.6. (It does build OK as is on 10.5 or 10.4, though.) There is at least one configure fix that needs to be backported from later Pythons. And you need to use gcc-4.0, not -4.2. Once you have extracted the source: cd ./Python-2.5.5/ cat >patch-configure-for-10-6.patch <<EOF --- configure.O 2008-12-13 06:13:52.000000000 -0800 +++ configure 2010-09-29 10:16:05.000000000 -0700 @@ -2039,7 +2039,11 @@ # disables platform specific features beyond repair. # On Mac OS X 10.3, defining _POSIX_C_SOURCE or _XOPEN_SOURCE # has no effect, don't bother defining them - FreeBSD/4.* | Darwin/[6789].*) + FreeBSD/4.*) + define_xopen_source=no;; + Darwin/[6789].*) + define_xopen_source=no;; + Darwin/1[0-9].*) define_xopen_source=no;; # On AIX 4 and 5.1, mbstate_t is defined only when _XOPEN_SOURCE == 500 but # used in wcsnrtombs() and mbsnrtowcs() even if _XOPEN_SOURCE is not defined EOF patch < patch-configure-for-10-6.patch export CC=/usr/bin/gcc-4.0 ./configure --prefix=/usr/local --enable-framework MACOSX_DEPLOYMENT_TARGET=10.6 make sudo make install Then there are various less obvious build issues like third-party libraries that are needed for all of the standard library modules to build and work as expected - GNU readline and bsddb come to mind - so there is no guarantee that you won't run into other problems. $ python2.5 Python 2.5.5 (r255:77872, Sep 29 2010, 10:23:54) [GCC 4.0.1 (Apple Inc. build 5494)] on darwin Type "help", "copyright", "credits" or "license" for more information. Module readline not available. >>> You could try using the installer build script in the source tree (in Mac/BuildScript/) but it will likely need to be patched to work correctly on 10.6. Even though there is no official python.org installer for 2.5.5 (which just has security fixes), there is an OS X installer for 2.5.4 which works fine on 10.6. Or use the Apple-supplied 2.5.4. Or try MacPorts. It will be nice when GAE is supported on current Python versions.
Compile Python 2.5.5 on OS X 10.6
I would like to install Python 2.5.5 to use with Google apps but have been having a very hard time tracking down instructions on how to do so. I am thinking the following might work but was wondering if anyone had successfully built it? ./configure --prefix=/usr/local/python2.5.5 MACOSX_DEPLOYMENT_TARGET=10.6 --enable-framework --with-universal-archs="64-bit" CFLAGS="-arch x86_64" LDFLAGS="-arch x86_64" ~: make -j6 ~: sudo make install Any help is appreciated!
[ "You should install it via MacPorts, which makes this a piece of cake. After you have it installed...\n$ sudo port install python25\n\n", "You should install it via Fink, which makes this a piece of cake. After you have it installed...\n$ fink install python25\n\nFink has more packages than MacPorts.\n", "Ass...
[ 1, 1, 0, 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0003821957_macos_python.txt
Q: How do I store a list (or dict) of key terms from a regular expression? -Python I am quite new at python and regex so please bear with me. I am trying to read in a file, match a particular name using a regex while ignoring the case, and store each time I find it. For example, if the file is composed of Bill bill biLl biLL, I need to store each variation in a dictionary or list. Current code: import re import sys import fileinput if __name__ == '__main__': print "flag" pattern = re.compile("""([b][i][l][l])""") for line in fileinput.input(): variation=set(pattern.search(line, re.I)) print variation.groupdict() print "flag2" When ran, the code will return an error: 'NoneType' cannot be iterated (or something along those lines). So how do I store each variation? Thanks in advance! A: I'd use findall: re.findall(r'bill', open(filename).read(), re.I) Easy as pie: >>> s = 'fooBiLL bill BILL bIlL foo bar' >>> import re >>> re.findall(r'bill', s, re.I) ['BiLL', 'bill', 'BILL', 'bIlL'] A: I think that you want re.findall. This is of course available on the compiled regular expression as well. The particular error code that you are getting though, would seem to indicate that you are not matching your pattern. try pattern = re.compile("bill", re.IGNORE_CASE)
How do I store a list (or dict) of key terms from a regular expression? -Python
I am quite new at python and regex so please bear with me. I am trying to read in a file, match a particular name using a regex while ignoring the case, and store each time I find it. For example, if the file is composed of Bill bill biLl biLL, I need to store each variation in a dictionary or list. Current code: import re import sys import fileinput if __name__ == '__main__': print "flag" pattern = re.compile("""([b][i][l][l])""") for line in fileinput.input(): variation=set(pattern.search(line, re.I)) print variation.groupdict() print "flag2" When ran, the code will return an error: 'NoneType' cannot be iterated (or something along those lines). So how do I store each variation? Thanks in advance!
[ "I'd use findall:\nre.findall(r'bill', open(filename).read(), re.I)\n\nEasy as pie:\n>>> s = 'fooBiLL bill BILL bIlL foo bar'\n>>> import re\n>>> re.findall(r'bill', s, re.I)\n['BiLL', 'bill', 'BILL', 'bIlL']\n\n", "I think that you want re.findall. This is of course available on the compiled regular expression a...
[ 2, 1 ]
[]
[]
[ "dictionary", "python", "regex" ]
stackoverflow_0003824373_dictionary_python_regex.txt
Q: Multiple versions of django admin page for the same model In my django admin section, I'd like to show different versions of the admin page depending on what kind of user is currently logged in. I can think of a couple ways this might work, but haven't figured out how to do any of them. Perhaps I could put logic into the admin.ModelAdmin to look at the current user and change the 'exclude' field dynamically. Does that work? Or maybe run different custom templates based on who's logged in, and have the templates include / exclude the fields as appropriate. I could register two versions of the admin.ModelAdmin class, one for each type of user, and maybe restrict access through permissions? But the permissions system seems to believe fairly deeply in one set of permissions per model class so I'm not sure how to change that. I could grab a couple of the widgets that are used in rendering the admin page templates, and include them in my own page that does the one specific job I need powerful users to be able to do. I could set up multiple AdminSites and restrict access to them through the url / view system. But then I'm not sure how to register different admin.ModelAdmin classes with the different AdminSites. Any advice on this would be appreciated. Answer Thanks for the hint. Here's how I did it... def get_form(self, request, obj=None, **kwargs): """This dynamically inserts the "owners" field into the exclude list if the current user is not superuser. """ if not request.user.is_superuser: if self.exclude: self.exclude.append('owners') else: self.exclude = ['owners'] else: # Necessary since Admin objects outlive requests try: self.exclude.remove('owners') except: pass return super(OwnersModelAdmin,self).get_form(request, obj=None, **kwargs) A: There are quite a few hooks provided in the ModelAdmin class for this sort of thing. One possibility would be to override the get_form method. This takes the request, as well as the object being edited, so you could get the current user from there, and return different ModelForms dependent on the user. It's worth looking at the source for ModelAdmin - it's in django.contrib.admin.options - to see if overriding this or any other other methods might meet your needs.
Multiple versions of django admin page for the same model
In my django admin section, I'd like to show different versions of the admin page depending on what kind of user is currently logged in. I can think of a couple ways this might work, but haven't figured out how to do any of them. Perhaps I could put logic into the admin.ModelAdmin to look at the current user and change the 'exclude' field dynamically. Does that work? Or maybe run different custom templates based on who's logged in, and have the templates include / exclude the fields as appropriate. I could register two versions of the admin.ModelAdmin class, one for each type of user, and maybe restrict access through permissions? But the permissions system seems to believe fairly deeply in one set of permissions per model class so I'm not sure how to change that. I could grab a couple of the widgets that are used in rendering the admin page templates, and include them in my own page that does the one specific job I need powerful users to be able to do. I could set up multiple AdminSites and restrict access to them through the url / view system. But then I'm not sure how to register different admin.ModelAdmin classes with the different AdminSites. Any advice on this would be appreciated. Answer Thanks for the hint. Here's how I did it... def get_form(self, request, obj=None, **kwargs): """This dynamically inserts the "owners" field into the exclude list if the current user is not superuser. """ if not request.user.is_superuser: if self.exclude: self.exclude.append('owners') else: self.exclude = ['owners'] else: # Necessary since Admin objects outlive requests try: self.exclude.remove('owners') except: pass return super(OwnersModelAdmin,self).get_form(request, obj=None, **kwargs)
[ "There are quite a few hooks provided in the ModelAdmin class for this sort of thing.\nOne possibility would be to override the get_form method. This takes the request, as well as the object being edited, so you could get the current user from there, and return different ModelForms dependent on the user.\nIt's wort...
[ 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0003824468_django_django_admin_python.txt
Q: What are good specs/libraries for closed network communication in python? The situation is that I have a small datacenter, with each server running python instances. It's not your usual distributed worker setup, as each server has a specific role with an appropriate long-running process. I'm looking for good ways to implement the the cross-server communication. REST seems like overkill. XML-RPC seems nice, but I haven't played with it yet. What other libraries should I be looking at to get this done? Requirements: Computation servers crunch numbers in the background. Other servers would like to occasionally ask them for values, based upon their calculation sets. I know this seems pretty well aligned with a REST mentality, but I'm curious about other options. A: Twisted's Perspective Broker is an extremely easy to use and robust mechanism for cross-server communication. It's definitely worth a look. A: It wasn't obvious from your question but if getting answers back synchronously doesn't matter to you (i.e., you are just asking for work to be performed) you might want to consider just using a job queue. It's generally the easiest way to communicate between hosts. If you don't mind depending on AWS using SQS is super simple. If you can't depend on AWS then you might want to try something like RabbitMQ. Many times problems that we think need to be communicated synchronously are really just queues in disguise.
What are good specs/libraries for closed network communication in python?
The situation is that I have a small datacenter, with each server running python instances. It's not your usual distributed worker setup, as each server has a specific role with an appropriate long-running process. I'm looking for good ways to implement the the cross-server communication. REST seems like overkill. XML-RPC seems nice, but I haven't played with it yet. What other libraries should I be looking at to get this done? Requirements: Computation servers crunch numbers in the background. Other servers would like to occasionally ask them for values, based upon their calculation sets. I know this seems pretty well aligned with a REST mentality, but I'm curious about other options.
[ "Twisted's Perspective Broker is an extremely easy to use and robust mechanism for cross-server communication. It's definitely worth a look.\n", "It wasn't obvious from your question but if getting answers back synchronously doesn't matter to you (i.e., you are just asking for work to be performed) you might want...
[ 2, 1 ]
[]
[]
[ "network_protocols", "python" ]
stackoverflow_0003823420_network_protocols_python.txt
Q: Python structure always stuck at 0 no matter what value you assign to it? I was writing a module to compact bits to be passed to C program, but keep getting errors. After some tests, I found out that the field a of class Blah is stuck at 0 no matter what. Does anyone know if this is a bug or if I'm doing something wrong here? Sorry, I forgot to mention I'm using python 3.1.2 from http://www.python.org/download/releases/3.1.2/ >>> import ctypes >>> class Blah(ctypes.Structure): ... _fields_ = [("a", ctypes.c_uint64, 64), ... ("b", ctypes.c_uint16, 16), ... ("c", ctypes.c_uint8, 8), ... ("d", ctypes.c_uint8, 8)] ... >>> x = Blah(0xDEAD,0xBEEF,0x44,0x12) >>> print (hex(x.a) ) 0x0 >>> print (hex(x.b )) 0xbeef >>> print (hex(x.c )) 0x44 >>> print (hex(x.d )) 0x12 >>> >>> g = Blah(0x2BAD,0xBEEF,0x55,0x12) >>> print (hex(g.a )) 0x0 >>> print (hex(g.b )) 0xbeef >>> print (hex(g.c )) 0x55 >>> print (hex(g.d )) 0x12 >>> swapping first two fields' position gives same result >>> import ctypes >>> class Blah(ctypes.Structure): ... _fields_ = [("a", ctypes.c_uint16, 16), ... ("b", ctypes.c_uint64, 64), ... ("c", ctypes.c_uint8, 8), ... ("d", ctypes.c_uint8, 8)] ... >>> x = Blah(0xDEAD,0xBEEF,0x44,0x12) >>> print (hex(x.a) ) 0xdead >>> print (hex(x.b )) 0x0 >>> print (hex(x.c )) 0x44 >>> print (hex(x.d )) 0x12 >>> >>> g = Blah(0x2BAD,0xBEEF,0x55,0x12) >>> print (hex(g.a )) 0x2bad >>> print (hex(g.b )) 0x0 >>> print (hex(g.c )) 0x55 >>> print (hex(g.d )) 0x12 >>> varying field's size and I observe some weird cutoff of the input >>> import ctypes >>> class Blah(ctypes.Structure): ... _fields_ = [("a", ctypes.c_uint64, 40), ... ("b", ctypes.c_uint64, 40), ... ("c", ctypes.c_uint8, 8), ... ("d", ctypes.c_uint8, 8)] ... >>> x = Blah(0xDEAD,0xBEEF,0x44,0x12) >>> print (hex(x.a) ) 0xad >>> print (hex(x.b )) 0xef >>> print (hex(x.c )) 0x44 >>> print (hex(x.d )) 0x12 >>> >>> g = Blah(0x2BAD,0xBEEF,0x55,0x12) >>> print (hex(g.a )) 0xad >>> print (hex(g.b )) 0xef >>> print (hex(g.c )) 0x55 >>> print (hex(g.d )) 0x12 >>> Does anyone know why is this happening? A: You could omit the 3rd field as a workaround. >>> import ctypes >>> class Blah(ctypes.Structure): ... _fields_ = [("a", ctypes.c_uint64), ('b', ctypes.c_uint16), ('c', ctypes.c_uint8), ('d', ctypes.c_uint8)] ... >>> x = Blah(0xDEAD,0xBEEF,0x44,0x12) >>> hex(x.a) '0xdead' >>> hex(x.b) '0xbeef' I guess the rest is a bug.
Python structure always stuck at 0 no matter what value you assign to it?
I was writing a module to compact bits to be passed to C program, but keep getting errors. After some tests, I found out that the field a of class Blah is stuck at 0 no matter what. Does anyone know if this is a bug or if I'm doing something wrong here? Sorry, I forgot to mention I'm using python 3.1.2 from http://www.python.org/download/releases/3.1.2/ >>> import ctypes >>> class Blah(ctypes.Structure): ... _fields_ = [("a", ctypes.c_uint64, 64), ... ("b", ctypes.c_uint16, 16), ... ("c", ctypes.c_uint8, 8), ... ("d", ctypes.c_uint8, 8)] ... >>> x = Blah(0xDEAD,0xBEEF,0x44,0x12) >>> print (hex(x.a) ) 0x0 >>> print (hex(x.b )) 0xbeef >>> print (hex(x.c )) 0x44 >>> print (hex(x.d )) 0x12 >>> >>> g = Blah(0x2BAD,0xBEEF,0x55,0x12) >>> print (hex(g.a )) 0x0 >>> print (hex(g.b )) 0xbeef >>> print (hex(g.c )) 0x55 >>> print (hex(g.d )) 0x12 >>> swapping first two fields' position gives same result >>> import ctypes >>> class Blah(ctypes.Structure): ... _fields_ = [("a", ctypes.c_uint16, 16), ... ("b", ctypes.c_uint64, 64), ... ("c", ctypes.c_uint8, 8), ... ("d", ctypes.c_uint8, 8)] ... >>> x = Blah(0xDEAD,0xBEEF,0x44,0x12) >>> print (hex(x.a) ) 0xdead >>> print (hex(x.b )) 0x0 >>> print (hex(x.c )) 0x44 >>> print (hex(x.d )) 0x12 >>> >>> g = Blah(0x2BAD,0xBEEF,0x55,0x12) >>> print (hex(g.a )) 0x2bad >>> print (hex(g.b )) 0x0 >>> print (hex(g.c )) 0x55 >>> print (hex(g.d )) 0x12 >>> varying field's size and I observe some weird cutoff of the input >>> import ctypes >>> class Blah(ctypes.Structure): ... _fields_ = [("a", ctypes.c_uint64, 40), ... ("b", ctypes.c_uint64, 40), ... ("c", ctypes.c_uint8, 8), ... ("d", ctypes.c_uint8, 8)] ... >>> x = Blah(0xDEAD,0xBEEF,0x44,0x12) >>> print (hex(x.a) ) 0xad >>> print (hex(x.b )) 0xef >>> print (hex(x.c )) 0x44 >>> print (hex(x.d )) 0x12 >>> >>> g = Blah(0x2BAD,0xBEEF,0x55,0x12) >>> print (hex(g.a )) 0xad >>> print (hex(g.b )) 0xef >>> print (hex(g.c )) 0x55 >>> print (hex(g.d )) 0x12 >>> Does anyone know why is this happening?
[ "You could omit the 3rd field as a workaround.\n>>> import ctypes\n>>> class Blah(ctypes.Structure):\n... _fields_ = [(\"a\", ctypes.c_uint64), ('b', ctypes.c_uint16), ('c', ctypes.c_uint8), ('d', ctypes.c_uint8)]\n... \n>>> x = Blah(0xDEAD,0xBEEF,0x44,0x12)\n>>> hex(x.a)\n'0xdead'\n>>> hex(x.b)\n'0xbeef'\n\nI gu...
[ 1 ]
[]
[]
[ "python", "structure" ]
stackoverflow_0003824617_python_structure.txt
Q: Python datetime TypeError, integer expected I'm pretty new to Python, so hopefully the problem I'm having has a simple solution. At work we always us either Shell (ksh) or Perl for all of our scripting work. Since python has been shipped with Solaris for some time now, it has (finally) been given the green light as a scripting platform. I've started prototyping some improvements to our scripts using Python. What I'm trying to accomplish is taking a time stamp and a string representing a time stamp and creating a datetime object for some date arithmetic. My example code follows: #!/bin/python import datetime fileTime="201009211100" format = "YYYYmmdd" yIdxS = format.find('Y') yIdxE = format.rfind('Y') if not fileTime[yIdxS:yIdxE+1].isdigit(): print "ERROR: Year in wrong format" exit else: print "Year [" + fileTime[yIdxS:yIdxE+1] + "]" mIdxS = format.find('m') mIdxE = format.rfind('m') if not fileTime[mIdxS:mIdxE+1].isdigit(): print "ERROR: Month in wrong format" exit else: print "Month [" + fileTime[mIdxS:mIdxE+1] + "]" dIdxS = format.find('d') dIdxE = format.rfind('d') if not fileTime[dIdxS:dIdxE+1].isdigit(): print "ERROR: Day in wrong format" exit else: print "Day [" + fileTime[dIdxS:dIdxE+1] + "]" old = datetime.date( fileTime[yIdxS:yIdxE+1], \ fileTime[mIdxS:mIdxE+1], \ fileTime[dIdxS:dIdxE+1] ); I'm getting the following output/error: Year [2010] Month [09] Day [21] Traceback (most recent call last): File "./example.py", line 37, in <module> fileTime[dIdxS:dIdxE+1] ); TypeError: an integer is required I don't understand why I'm getting this TypeError exception. My understanding of Python's dynamic typing is that I shouldn't need to convert a string to an integer if the string is all digits. So the problem would seem to be I'm either missing something that I need, or my understanding of the language is flawed. Any help would be greatly appreciated. Thanks. A: Strongly consider using datetime.datetime.strptime: import datetime tests=["201009211100","201009211199"] for fileTime in tests: try: date=datetime.datetime.strptime(fileTime,'%Y%m%d%H%M') print(date) except ValueError as err: print(fileTime,err) # 2010-09-21 11:00:00 # ('201009211199', ValueError('unconverted data remains: 9',)) Or, if you install the third-party module, dateutil, you could parse it like this: In [106]: import dateutil.parser as dparser In [107]: dparser.parse('201009211100') Out[107]: datetime.datetime(2010, 9, 21, 11, 0) Notice that dateutil tries to parse the string without you explicitly declaring the format. This has to be used carefully (with testing and control over admissible input strings) since otherwise there are ambiguous dates which dateutil may parse incorrectly. A: datetime.date wants integers. Change the last line of your code like this to get your desired results: old = datetime.date( int(fileTime[yIdxS:yIdxE+1]), \ int(fileTime[mIdxS:mIdxE+1]), \ int(fileTime[dIdxS:dIdxE+1]) ); However, there's an easier and maybe more pythonic way too: old = datetime.datetime.strptime(fileTime, '%Y%m%d%H%M') Doing this at the top of your script, you get the ease of extracting the various pieces like so: print 'Month: %d' % old.month A: Python is more strongly typed; it does not make automatic conversions from strings to integer. The global function int is needed to do the conversion.
Python datetime TypeError, integer expected
I'm pretty new to Python, so hopefully the problem I'm having has a simple solution. At work we always us either Shell (ksh) or Perl for all of our scripting work. Since python has been shipped with Solaris for some time now, it has (finally) been given the green light as a scripting platform. I've started prototyping some improvements to our scripts using Python. What I'm trying to accomplish is taking a time stamp and a string representing a time stamp and creating a datetime object for some date arithmetic. My example code follows: #!/bin/python import datetime fileTime="201009211100" format = "YYYYmmdd" yIdxS = format.find('Y') yIdxE = format.rfind('Y') if not fileTime[yIdxS:yIdxE+1].isdigit(): print "ERROR: Year in wrong format" exit else: print "Year [" + fileTime[yIdxS:yIdxE+1] + "]" mIdxS = format.find('m') mIdxE = format.rfind('m') if not fileTime[mIdxS:mIdxE+1].isdigit(): print "ERROR: Month in wrong format" exit else: print "Month [" + fileTime[mIdxS:mIdxE+1] + "]" dIdxS = format.find('d') dIdxE = format.rfind('d') if not fileTime[dIdxS:dIdxE+1].isdigit(): print "ERROR: Day in wrong format" exit else: print "Day [" + fileTime[dIdxS:dIdxE+1] + "]" old = datetime.date( fileTime[yIdxS:yIdxE+1], \ fileTime[mIdxS:mIdxE+1], \ fileTime[dIdxS:dIdxE+1] ); I'm getting the following output/error: Year [2010] Month [09] Day [21] Traceback (most recent call last): File "./example.py", line 37, in <module> fileTime[dIdxS:dIdxE+1] ); TypeError: an integer is required I don't understand why I'm getting this TypeError exception. My understanding of Python's dynamic typing is that I shouldn't need to convert a string to an integer if the string is all digits. So the problem would seem to be I'm either missing something that I need, or my understanding of the language is flawed. Any help would be greatly appreciated. Thanks.
[ "Strongly consider using datetime.datetime.strptime:\nimport datetime\n\ntests=[\"201009211100\",\"201009211199\"]\nfor fileTime in tests:\n try:\n date=datetime.datetime.strptime(fileTime,'%Y%m%d%H%M')\n print(date)\n except ValueError as err:\n print(fileTime,err)\n\n# 2010-09-21 11:00:...
[ 5, 1, 0 ]
[]
[]
[ "python", "scripting" ]
stackoverflow_0003825056_python_scripting.txt
Q: How do I write to the apache log files when using mod_wsgi I have a Django project where I have been logging to a file using the standard library logging module. For a variety of reasons I would like to change it so that it writes to the Apache log files. I've seen quite a bit of discussion of how to do this with mod_python, but not mod_wsgi. How do I do this for a project running under mod_wsgi? A: Mostly, we use logging and write to sys.stderr. That seems to write to the Apache error_log.
How do I write to the apache log files when using mod_wsgi
I have a Django project where I have been logging to a file using the standard library logging module. For a variety of reasons I would like to change it so that it writes to the Apache log files. I've seen quite a bit of discussion of how to do this with mod_python, but not mod_wsgi. How do I do this for a project running under mod_wsgi?
[ "Mostly, we use logging and write to sys.stderr. That seems to write to the Apache error_log.\n" ]
[ 13 ]
[]
[]
[ "apache", "logging", "mod_wsgi", "python" ]
stackoverflow_0003824923_apache_logging_mod_wsgi_python.txt
Q: How to apply a function to every element in a list using Linq in C# like the method reduce() in python? How to apply a function to every element in a list using Linq in C# like the method reduce() in python? A: Assuming you're talking about this reduce function, the equivalent in C# and LINQ is Enumerable.Aggregate. Quick example: var list = Enumerable.Range(5, 3); // [5, 6, 7] Console.WriteLine("Aggregation: {0}", list.Aggregate((a, b) => (a + b))); // Result is "Aggregation: 18" A: Enumerable.Aggregate is your answer. reduce(function, list, seed) ==> list.Aggregate(seed, function). In addition, there are many predefined "aggregates", like Sum, Min, Max, Average, etc. You should use Aggregate only when the aggregator is not built-in.
How to apply a function to every element in a list using Linq in C# like the method reduce() in python?
How to apply a function to every element in a list using Linq in C# like the method reduce() in python?
[ "Assuming you're talking about this reduce function, the equivalent in C# and LINQ is Enumerable.Aggregate.\nQuick example:\nvar list = Enumerable.Range(5, 3); // [5, 6, 7]\nConsole.WriteLine(\"Aggregation: {0}\", list.Aggregate((a, b) => (a + b)));\n// Result is \"Aggregation: 18\"\n\n", "Enumerable.Aggregate is...
[ 11, 2 ]
[]
[]
[ "c#", "linq", "python" ]
stackoverflow_0003825200_c#_linq_python.txt
Q: Selenium and Python: remove \n from returned selenium.get_text() When I call selenium.get_text("foo") on a certain element it returns back a different value depending on what browser I am working in due to the way each browser handles newlines. Example: An elements string is "hello[newline]how are you today?[newline]Very well, thank you." When selenium gets this back from IE it gets the string "hello\nhow are you today?\nVery well, thank you." When selenium gets this back from Firefox it gets the string "hello\n how are you today?\n Very well, thank you." (Notice that IE changes [newline] into '\n' and Firefox changes it into '\n ') Is there anyway using selenium/python that I can easily strip out this discrepancy? I thought about using .replace("\n ", "\n"), but that would cause issues if there was an intended space after a newline (for whatever reason). Any ideas? A: I ended up just doing a check of what browser I was running and then returning the string with the '\n ' replaced with '\n' if the browser was firefox.
Selenium and Python: remove \n from returned selenium.get_text()
When I call selenium.get_text("foo") on a certain element it returns back a different value depending on what browser I am working in due to the way each browser handles newlines. Example: An elements string is "hello[newline]how are you today?[newline]Very well, thank you." When selenium gets this back from IE it gets the string "hello\nhow are you today?\nVery well, thank you." When selenium gets this back from Firefox it gets the string "hello\n how are you today?\n Very well, thank you." (Notice that IE changes [newline] into '\n' and Firefox changes it into '\n ') Is there anyway using selenium/python that I can easily strip out this discrepancy? I thought about using .replace("\n ", "\n"), but that would cause issues if there was an intended space after a newline (for whatever reason). Any ideas?
[ "I ended up just doing a check of what browser I was running and then returning the string with the '\\n ' replaced with '\\n' if the browser was firefox.\n" ]
[ 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0003824734_python_selenium.txt
Q: Computing number of sub-queries in Google AppEngine How can I determine how many sub-queries are required for a single top-level query on app engine (python)? I am playing around with the IN operator, and I am curious if there is any way to be notified if I over-step my 30 sub-query limit. A: If you try to execute a query which would spawn too many sub-queries then you would get this error: BadArgumentError: Cannot satisfy query -- too many subqueries (max: 30, got 31). Probable cause: too many IN/!= filters in query. If you wanted to check before trying to execute the query, you could check the length of the list which you are passing query - as long as it has 30 or fewer elements the query will be okay (as long as you aren't using the != operator in the query too; if you are, then each != query will double the number of sub-queries that you would otherwise have).
Computing number of sub-queries in Google AppEngine
How can I determine how many sub-queries are required for a single top-level query on app engine (python)? I am playing around with the IN operator, and I am curious if there is any way to be notified if I over-step my 30 sub-query limit.
[ "If you try to execute a query which would spawn too many sub-queries then you would get this error:\nBadArgumentError: Cannot satisfy query -- too many subqueries (max: 30, got 31). Probable cause: too many IN/!= filters in query.\n\nIf you wanted to check before trying to execute the query, you could check the le...
[ 4 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003825845_google_app_engine_google_cloud_datastore_python.txt
Q: Regular Expressions: How would I extract a given word using a regular expression? How would I extract the word 'wrestle' from the following: type=weaksubj len=1 word1=wrestle pos1=verb stemmed1=y priorpolarity=negative using a regular expression? A: The question is not very clear, but I guess this is what you are looking for: word1=(\w+) Your match will be in the 1st group. Here's some sample Python code: import re yourstring = 'type=weaksubj len=1 word1=wrestle pos1=verb stemmed1=y priorpolarity=negative' m = re.search(r'word1=(\w+)', yourstring) print m.group(1) As seen on codepad. A more generalized solution: import re def get_attr(str, attr): m = re.search(attr + r'=(\w+)', str) return None if not m else m.group(1) str = 'type=weaksubj len=1 word1=wrestle pos1=verb stemmed1=y priorpolarity=negative' print get_attr(str, 'word1') # wrestle print get_attr(str, 'type') # weaksubj print get_attr(str, 'foo') # None Also available on codepad A: Given the following regex... /word1=(\w+)/ ...$1 or whatever your first match is in your language will be wrestle. A: You regex would be something like this /.*word1=(\w+)/ A: Use: /word1=(\w+)/ A: Assuming it is always separated by spaces word1=([^ ]+) Then you can get the value by the first group match. A: Maybe re is unnecessary when str.split looks like it will suffice: >>> s = "type=weaksubj len=1 word1=wrestle pos1=verb stemmed1=y priorpolarity=negative" >>> dd = dict(ss.split('=',1) for ss in s.split()) >>> dd['word1'] 'wrestle'
Regular Expressions: How would I extract a given word using a regular expression?
How would I extract the word 'wrestle' from the following: type=weaksubj len=1 word1=wrestle pos1=verb stemmed1=y priorpolarity=negative using a regular expression?
[ "The question is not very clear, but I guess this is what you are looking for:\nword1=(\\w+)\n\nYour match will be in the 1st group. Here's some sample Python code:\nimport re\nyourstring = 'type=weaksubj len=1 word1=wrestle pos1=verb stemmed1=y priorpolarity=negative'\n\nm = re.search(r'word1=(\\w+)', yourstring)\...
[ 6, 2, 0, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003823599_python_regex.txt
Q: INVALID SYNTAX ERROR for 'else' statement in python I am trying to write a quicksort program in python, however I'm getting an invalid syntax error at else statement in the second last line below: import random n=int(raw_input("Enter the size of the list: ")) # size of the list intlist = [0]*n for num in range(n): intlist[num]=random.randint(0,10*n) pivot=random.choice(intlist) list_1=[] # list of elements smaller than pivot list_2=[] # list of elements greater than pivot for num in range(n): if num<=pivot: list_1.append(num) else list_2.append(num) This is not a complete program as I am still writing. A: add a colon after the else so that it looks like else:. and pick up a good tutorial ;) A: Looks like you need a ':' after "else".
INVALID SYNTAX ERROR for 'else' statement in python
I am trying to write a quicksort program in python, however I'm getting an invalid syntax error at else statement in the second last line below: import random n=int(raw_input("Enter the size of the list: ")) # size of the list intlist = [0]*n for num in range(n): intlist[num]=random.randint(0,10*n) pivot=random.choice(intlist) list_1=[] # list of elements smaller than pivot list_2=[] # list of elements greater than pivot for num in range(n): if num<=pivot: list_1.append(num) else list_2.append(num) This is not a complete program as I am still writing.
[ "add a colon after the else so that it looks like else:. and pick up a good tutorial ;)\n", "Looks like you need a ':' after \"else\".\n" ]
[ 5, 2 ]
[]
[]
[ "if_statement", "python", "syntax_error" ]
stackoverflow_0003826236_if_statement_python_syntax_error.txt
Q: Key bindings or workflow suggestions for managing breakpoints with pydbgr in Emacs 23.2 I have pydbgr working well now in Emacs 23.2 with virtualenv. But I am confused why breakpoints are not established from the source code buffer after running M-x pydbgr - as they would be e.g. when using pdb. I tried invoking C-cC-b but this does not toggle breakpoints on the selected line as one would hope/expect. Neither does C-xSPC work as it would in pdb. When in the pydbgr shell window I can set breakpoints according to the first keyboard short-cut above, but it is naturally far more convenient to not have to move windows in order to do this. Also, the left buffer margin intended for setting breakpoints via the mouse does not appear by default, and the MOUSE button binding for toggling normal and temporary breakpoints do not appear to work out-of-the-box, at least with my .emacs configuration. I am using the latest pydbgr and dbgr.el code at the time of this posting. Can anybody with experience of using pdbgr for debugging Python application please comment on the best approaches they have adopted in this regard. Perhaps some elisp configuration code to establish key-bindings that work from the source code windows. I noticed that pydbgr does not appear to invoke a minor/major-mode within the source buffer window, so I don't know where to start implementing this myself as I have no mode-hooks to hang elisp code off. A: A recent change in emacs-dbgr on http://github.com/rocky/emacs-dbgr adds this. There are a number of other issues regarding breakpoint synchronization. emacs-dbgr is a work in progress, not a finished product.
Key bindings or workflow suggestions for managing breakpoints with pydbgr in Emacs 23.2
I have pydbgr working well now in Emacs 23.2 with virtualenv. But I am confused why breakpoints are not established from the source code buffer after running M-x pydbgr - as they would be e.g. when using pdb. I tried invoking C-cC-b but this does not toggle breakpoints on the selected line as one would hope/expect. Neither does C-xSPC work as it would in pdb. When in the pydbgr shell window I can set breakpoints according to the first keyboard short-cut above, but it is naturally far more convenient to not have to move windows in order to do this. Also, the left buffer margin intended for setting breakpoints via the mouse does not appear by default, and the MOUSE button binding for toggling normal and temporary breakpoints do not appear to work out-of-the-box, at least with my .emacs configuration. I am using the latest pydbgr and dbgr.el code at the time of this posting. Can anybody with experience of using pdbgr for debugging Python application please comment on the best approaches they have adopted in this regard. Perhaps some elisp configuration code to establish key-bindings that work from the source code windows. I noticed that pydbgr does not appear to invoke a minor/major-mode within the source buffer window, so I don't know where to start implementing this myself as I have no mode-hooks to hang elisp code off.
[ "A recent change in emacs-dbgr on http://github.com/rocky/emacs-dbgr adds this. There are a number of other issues regarding breakpoint synchronization. emacs-dbgr is a work in progress, not a finished product. \n" ]
[ 0 ]
[]
[]
[ "configuration", "debugging", "emacs", "python" ]
stackoverflow_0003821639_configuration_debugging_emacs_python.txt
Q: Pythons M2Crypto raises exception in ssl_ctx_load_verify_locations when loading certificates M2Crypto raises a TypeError when loading SSL CA certificates. I'm getting the path of an SSL certificate from an instance of a Django model. My code worked perfectly because I was pulling the path of the certificate from a Django model My code: from M2Crypto import SSL from django.db import models class MyModel(models.Model): ca_file = models.FilePathField(path='/path/to/my/certificates/') m = MyModel(ca_file='/path/to/my/certificates/certificate.cer') m.save() ctx = SSL.Context() ctx.load_verify_locations(m.ca_file) Raises: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/django/lib/datalivelib/utils/https.py", line 51, in do_https if ctx.load_verify_locations(ca_file) != 1: File "/usr/lib/pymodules/python2.6/M2Crypto/SSL/Context.py", line 131, in load_verify_locations return m2.ssl_ctx_load_verify_locations(self.ctx, cafile, capath) TypeError: in method 'ssl_ctx_load_verify_locations', argument 2 of type 'char const *' However this code works fine from M2Crypto import SSL ctx = SSL.Context() ctx.load_verify_locations('/path/to/my/certificates/certificate.cer') A: Just worked it out! The load_verify_locations() function is expecting a string object, not a unicode object. Django uses unicode by default, so the certificate path needs to be converted to a string before passed into load_verify_locations(). So: ctx.load_verify_locations(str(m.ca_file))
Pythons M2Crypto raises exception in ssl_ctx_load_verify_locations when loading certificates
M2Crypto raises a TypeError when loading SSL CA certificates. I'm getting the path of an SSL certificate from an instance of a Django model. My code worked perfectly because I was pulling the path of the certificate from a Django model My code: from M2Crypto import SSL from django.db import models class MyModel(models.Model): ca_file = models.FilePathField(path='/path/to/my/certificates/') m = MyModel(ca_file='/path/to/my/certificates/certificate.cer') m.save() ctx = SSL.Context() ctx.load_verify_locations(m.ca_file) Raises: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/django/lib/datalivelib/utils/https.py", line 51, in do_https if ctx.load_verify_locations(ca_file) != 1: File "/usr/lib/pymodules/python2.6/M2Crypto/SSL/Context.py", line 131, in load_verify_locations return m2.ssl_ctx_load_verify_locations(self.ctx, cafile, capath) TypeError: in method 'ssl_ctx_load_verify_locations', argument 2 of type 'char const *' However this code works fine from M2Crypto import SSL ctx = SSL.Context() ctx.load_verify_locations('/path/to/my/certificates/certificate.cer')
[ "Just worked it out!\nThe load_verify_locations() function is expecting a string object, not a unicode object.\nDjango uses unicode by default, so the certificate path needs to be converted to a string before passed into load_verify_locations(). So:\nctx.load_verify_locations(str(m.ca_file))\n\n" ]
[ 2 ]
[]
[]
[ "django", "m2crypto", "python", "ssl_certificate" ]
stackoverflow_0003826694_django_m2crypto_python_ssl_certificate.txt
Q: Pythonic way of copying an iterable object For a small project I'm working on I need to cycle through a list. For each element of this cycle I have to start another cycle through the same list, with the former element as first element of the new cycle. For example I'd like to be able to produce something like this: 1, 2, 3, 4, 1, 2, 3, 4, 1, ... 2, 3, 4, 1, 2, 3, 4, 1, 2, ... 3, 4, 1, 2, 3, 4, 1, 2, 3, ... 4, 1, 2, 3, 4, 1, 2, 3, 4, ... 1, 2, 3, 4, 1, 2, 3, 4, 1, ... ... I thought that copying a itertools.cycle after each .next() would conserve the current state, so that I can begin the new cycle with the element from the "outer" cycle. Or even "reset the cycle pointer" to an older position. I tried the following: >>> import itertools, copy >>> a = itertools.cycle([1, 2, 3, 4]) >>> b = copy.copy(a) but got this error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/copy.py", line 95, in copy return _reconstruct(x, rv, 0) File "/usr/lib/python2.6/copy.py", line 323, in _reconstruct y = callable(*args) File "/usr/lib/python2.6/copy_reg.py", line 93, in __newobj__ return cls.__new__(cls, *args) TypeError: cycle expected 1 arguments, got 0 I know there are many different ways to achieve what I want but I'm looking for some short, clear and pythonic code. Maybe someone has another idea or even a snippet? The fact that it's not possible to copy iterator objects woke my interest. Is there a best-practice in situations where one wants a copy of an iterable? Or is copying iterables silly and useless in general? A: Is there a best-practice in situations where one wants a copy of an iterable? itertools.tee gives you two iterators that each yield the same items as the original, but it takes the original and memorizes everything it yields, so you can't use the original anymore. It wouldn't help here though, because it would keep on memorizing these cycled values until you get a MemoryError. Or is copying iterables silly and useless in general? iterators are just defined to have a current state and yield a item. You can't tell if they will yield the same items in the future or which items they yielded in the past. A real copy would have to do both, so it's impossible! In your case it's so trivial to make a new cycle that I'd rather do that than try to copy an existing. For example: def new_cycle( seq, last=None): if last is None: return cycle(seq) else: it = cycle(seq) while next(it) != last: pass return it
Pythonic way of copying an iterable object
For a small project I'm working on I need to cycle through a list. For each element of this cycle I have to start another cycle through the same list, with the former element as first element of the new cycle. For example I'd like to be able to produce something like this: 1, 2, 3, 4, 1, 2, 3, 4, 1, ... 2, 3, 4, 1, 2, 3, 4, 1, 2, ... 3, 4, 1, 2, 3, 4, 1, 2, 3, ... 4, 1, 2, 3, 4, 1, 2, 3, 4, ... 1, 2, 3, 4, 1, 2, 3, 4, 1, ... ... I thought that copying a itertools.cycle after each .next() would conserve the current state, so that I can begin the new cycle with the element from the "outer" cycle. Or even "reset the cycle pointer" to an older position. I tried the following: >>> import itertools, copy >>> a = itertools.cycle([1, 2, 3, 4]) >>> b = copy.copy(a) but got this error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/copy.py", line 95, in copy return _reconstruct(x, rv, 0) File "/usr/lib/python2.6/copy.py", line 323, in _reconstruct y = callable(*args) File "/usr/lib/python2.6/copy_reg.py", line 93, in __newobj__ return cls.__new__(cls, *args) TypeError: cycle expected 1 arguments, got 0 I know there are many different ways to achieve what I want but I'm looking for some short, clear and pythonic code. Maybe someone has another idea or even a snippet? The fact that it's not possible to copy iterator objects woke my interest. Is there a best-practice in situations where one wants a copy of an iterable? Or is copying iterables silly and useless in general?
[ "\nIs there a best-practice in situations\n where one wants a copy of an iterable?\n\nitertools.tee gives you two iterators that each yield the same items as the original, but it takes the original and memorizes everything it yields, so you can't use the original anymore. It wouldn't help here though, because it w...
[ 7 ]
[]
[]
[ "copy", "cycle", "python", "python_itertools" ]
stackoverflow_0003826746_copy_cycle_python_python_itertools.txt
Q: match two strings with letters in random order in python if I have 2 strings like: a = "hello" b = "olhel" I want to use a regular expression (or something else?) to see if the two strings contain the same letters. In my example a would = b because they have the same letters. How can this be achieved? A: a = "hello" b = "olhel" print sorted(a) == sorted(b) A: An O(n) algorithm is to create a dictionary of counts of each letter and then compare the dictionaries. In Python 2.7 or newer this can be done using collections.Counter: >>> from collections import Counter >>> Counter('hello') == Counter('olhel') True
match two strings with letters in random order in python
if I have 2 strings like: a = "hello" b = "olhel" I want to use a regular expression (or something else?) to see if the two strings contain the same letters. In my example a would = b because they have the same letters. How can this be achieved?
[ "a = \"hello\"\nb = \"olhel\"\nprint sorted(a) == sorted(b)\n\n", "An O(n) algorithm is to create a dictionary of counts of each letter and then compare the dictionaries.\nIn Python 2.7 or newer this can be done using collections.Counter:\n>>> from collections import Counter\n>>> Counter('hello') == Counter('olhe...
[ 10, 4 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003826867_python_regex.txt
Q: python-couchdb pager hitting recursion depth limit I am creating a pager that returns documents from an Apache CouchDB map function from python-couchdb. This generator expression is working well, until it hits the max recursion depth. How can it be improved to move to iteration, rather than recursion? def page(db, view_name, limit, include_docs=True, **opts): """ `page` goes returns all documents of CouchDB map functions. It accepts all options that `couchdb.Database.view` does, however `include_docs` should be omitted, because this will interfere with things. >>> import couchdb >>> db = couchdb.Server()['database'] >>> for doc in page(db, '_all_docs', 100): >>> doc #etc etc >>> del db['database'] Notes on implementation: - `last_doc` is assigned on every loop, because there doesn't seem to be an easy way to know if something is the last item in the iteration. """ last_doc = None for row in db.view(view_name, limit=limit+1, include_docs=include_docs, **opts): last_doc = row.key, row.id yield row.doc if last_doc: for doc in page(db, view_name, limit, inc_docs=inc_docs, startkey=last_doc[0], startkey_docid=last_doc[1]): yield doc A: Here's something to get you started. You didn't specify what *opts might be; if you only need startkey and startkey_docid to start the recursion, and not some other fields, then you can get rid of the extra function. Obviously, untested. def page_key(db, view_name, limit, startkey, startkey_docid, inc_docs=True): queue = [(startkey, startkey_docid)] while queue: key = queue.pop() last_doc = None for row in db.view(view_name, limit=limit+1, include_docs=inc_docs, startkey=key[0], startkey_docid=key[1]): last_doc = row.key, row.id yield row.doc if last_doc: queue.append(last_doc) def page(db, view_name, limit, inc_docs=True, **opts): last_doc = None for row in db.view(view_name, limit=limit+1, include_docs=inc_docs, **opts): last_doc = row.key, row.id yield row.doc if last_doc: for doc in page_key(db, view_name, limit, last_doc[0], last_doc[1], inc_docs): yield doc A: This is an alternative approach that I've tested (manually) on a database with >800k docs. Seems to work. def page2(db, view_name, limit, inc_docs=True, **opts): def get_batch(db=db, view_name=view_name, limit=limit, inc_docs=inc_docs, **opts): for row in db.view(view_name, limit=limit+1, include_docs=inc_docs, **opts): yield row last_doc = None total_rows = db.view(view_name, limit=1).total_rows batches = (total_rows / limit) + 1 for i in xrange(batches): if not last_doc: for row in get_batch(): last_doc = row.key, row.id yield row.doc or row # if include_docs is False, # row.doc will be None else: for row in get_batch(startkey=last_doc[0], startkey_docid=last_doc[1]): last_doc = row.key, row.id yield row.doc or row A: I don't use CouchDB so I had a little trouble understanding the sample code. Here's a stripped down version, which I believe works the way you want: all_docs = range(0, 100) def view(limit, offset): print "view: returning", limit, "rows starting at", offset return all_docs[offset:offset+limit] def generate_by_pages(page_size): offset = 0 while True: rowcount = 0 for row in generate_page(page_size, offset): rowcount += 1 yield row if rowcount == 0: break else: offset += rowcount def generate_page(page_size, offset): for row in view(page_size, offset): yield row for r in generate_by_pages(10): print r The key thing is replacing recursion with iteration. There are lots of ways to do this (I like trampolining in Python) but the above is straightforward.
python-couchdb pager hitting recursion depth limit
I am creating a pager that returns documents from an Apache CouchDB map function from python-couchdb. This generator expression is working well, until it hits the max recursion depth. How can it be improved to move to iteration, rather than recursion? def page(db, view_name, limit, include_docs=True, **opts): """ `page` goes returns all documents of CouchDB map functions. It accepts all options that `couchdb.Database.view` does, however `include_docs` should be omitted, because this will interfere with things. >>> import couchdb >>> db = couchdb.Server()['database'] >>> for doc in page(db, '_all_docs', 100): >>> doc #etc etc >>> del db['database'] Notes on implementation: - `last_doc` is assigned on every loop, because there doesn't seem to be an easy way to know if something is the last item in the iteration. """ last_doc = None for row in db.view(view_name, limit=limit+1, include_docs=include_docs, **opts): last_doc = row.key, row.id yield row.doc if last_doc: for doc in page(db, view_name, limit, inc_docs=inc_docs, startkey=last_doc[0], startkey_docid=last_doc[1]): yield doc
[ "Here's something to get you started. You didn't specify what *opts might be; if you only need startkey and startkey_docid to start the recursion, and not some other fields, then you can get rid of the extra function.\nObviously, untested.\ndef page_key(db, view_name, limit, startkey, startkey_docid, inc_docs=True...
[ 0, 0, 0 ]
[]
[]
[ "couchdb", "python" ]
stackoverflow_0003826647_couchdb_python.txt
Q: PyQt4 SIGNAL/SLOT problem when using sub-directories Thanks in advance for taking the time to read this. Apologies that it is somewhat verbose. But hopefully it fully explains the problem. Stripped code demonstrating the issue is included. I'm having an issue with PyQt4 SIGNAL/SLOTS. While I can make everything work fine if I am writing in a single file, I can't make things work if I some of the functions I wish to use are moved to sub-directories/classes. I've looked through the Python Bindings document I can see how this works when using a single file. But what I am trying to do is this: main.py file in root dir which contains the MainWindow __init__ code. This file imports a number of widgets. Each widget is stored in its own sub-directory. All sub-directories contain an __init__.py file. These sub-directories are inside of a directory called 'bin', which is itself in the root dir Some of these widgets need to have SIGNAL/SLOT links between them This is where I fall down. So the file structure is: - main.py - bin/textEditor/__init__.py - bin/textEditor/plugin.py - bin/logWindow/__init__.py - bin/logWindow/plugin.py The following code shows the problem. This code creates a very basic main window that contains a central QTextEdit() widget and a dockable QTextEdit() widget. All that happens is that when the text in the central widget is changed, the same text is shown in the dockable widget. The example works. But it does so by connecting the signal textChanged() in the bin/textEditor/plugin.py file that creates the central QTextEdit() with a function in main.py. I would like it to do exactly the same thing but connexted to the updateUi function in bin/textEditor/plugin.py If anyone could shed some light on this, I would be hugely grateful. I'm sure it is simple. But direction to any tutorials that cover this or statements that I am doing it all very wrong are equally appreciated!. Thanks again for your time: ### main.py import os import sys # Import PyQT modules from PyQt4.QtCore import * from PyQt4.QtGui import * # Start the main class class MainWindow(QMainWindow): # Initialise def __init__(self, parent=None): super(MainWindow, self).__init__(parent) # Name and size the main window self.setWindowTitle("EDITOR/LOG") self.resize(800, 600) import bin.logWindow.plugin as logWindow logWindow.create(self) import bin.textEditor.plugin as textEditor textEditor.create(self) def updateUi(self): # I can connect to this function from within bin/textEditor/plugin.py (see # below) but I want to connect to the function located in # bin/textEditor/plugin.py instead text = self.editor.toPlainText() self.logWidget.setText(text) # Run the app def main(): app = QApplication(sys.argv) form = MainWindow() form.show() app.exec_() # Call main main() The code inside of the two plugin files is: ### bin/textEditor/plugin.py # Import PyQT modules from PyQt4.QtCore import * from PyQt4.QtGui import * def create(self): # Add a dockable widget self.logDockWidget = QDockWidget("Log", self) self.logDockWidget.setObjectName("LogDockWidget") self.logDockWidget.setAllowedAreas(Qt.LeftDockWidgetArea| Qt.RightDockWidgetArea) self.logWidget = QTextEdit() self.logDockWidget.setWidget(self.logWidget) self.addDockWidget(Qt.LeftDockWidgetArea, self.logDockWidget) And ### bin/logWindow/plugin.py Import PyQT modules from PyQt4.QtCore import * from PyQt4.QtGui import * def create(self): # Create a text editing box self.editor = QTextEdit() # Add to main window self.setCentralWidget(self.editor) # connect text change to update log window. This is presumably what I need to # change so that it connects to the function below instead of the on in main.py self.connect(self.editor, SIGNAL("textChanged()"), self.updateUi) def updateUi(self): text = self.editor.toPlainText() self.logWidget.setText(text) A: For starters, is there a reason you're using a very old version of the PyQt release document? The new one is: here There are a few things you are doing that are a bit unusual. Generally import statements in python are placed at the top of the file (to more easily see dependencies), but I assume you're doing this to support a more generalized import system for plugins in the future. It seems like the basic problem is you're trying to connect a signal source to a slot in another object, without storing that other object in a particular place. To do this you probably need to either make the connection in main, make a neutral "updateUi" slot that emits it's own special signal that all the plugins are waiting for, or just keep a reference to those subobjects in main and be careful with the initialization order.
PyQt4 SIGNAL/SLOT problem when using sub-directories
Thanks in advance for taking the time to read this. Apologies that it is somewhat verbose. But hopefully it fully explains the problem. Stripped code demonstrating the issue is included. I'm having an issue with PyQt4 SIGNAL/SLOTS. While I can make everything work fine if I am writing in a single file, I can't make things work if I some of the functions I wish to use are moved to sub-directories/classes. I've looked through the Python Bindings document I can see how this works when using a single file. But what I am trying to do is this: main.py file in root dir which contains the MainWindow __init__ code. This file imports a number of widgets. Each widget is stored in its own sub-directory. All sub-directories contain an __init__.py file. These sub-directories are inside of a directory called 'bin', which is itself in the root dir Some of these widgets need to have SIGNAL/SLOT links between them This is where I fall down. So the file structure is: - main.py - bin/textEditor/__init__.py - bin/textEditor/plugin.py - bin/logWindow/__init__.py - bin/logWindow/plugin.py The following code shows the problem. This code creates a very basic main window that contains a central QTextEdit() widget and a dockable QTextEdit() widget. All that happens is that when the text in the central widget is changed, the same text is shown in the dockable widget. The example works. But it does so by connecting the signal textChanged() in the bin/textEditor/plugin.py file that creates the central QTextEdit() with a function in main.py. I would like it to do exactly the same thing but connexted to the updateUi function in bin/textEditor/plugin.py If anyone could shed some light on this, I would be hugely grateful. I'm sure it is simple. But direction to any tutorials that cover this or statements that I am doing it all very wrong are equally appreciated!. Thanks again for your time: ### main.py import os import sys # Import PyQT modules from PyQt4.QtCore import * from PyQt4.QtGui import * # Start the main class class MainWindow(QMainWindow): # Initialise def __init__(self, parent=None): super(MainWindow, self).__init__(parent) # Name and size the main window self.setWindowTitle("EDITOR/LOG") self.resize(800, 600) import bin.logWindow.plugin as logWindow logWindow.create(self) import bin.textEditor.plugin as textEditor textEditor.create(self) def updateUi(self): # I can connect to this function from within bin/textEditor/plugin.py (see # below) but I want to connect to the function located in # bin/textEditor/plugin.py instead text = self.editor.toPlainText() self.logWidget.setText(text) # Run the app def main(): app = QApplication(sys.argv) form = MainWindow() form.show() app.exec_() # Call main main() The code inside of the two plugin files is: ### bin/textEditor/plugin.py # Import PyQT modules from PyQt4.QtCore import * from PyQt4.QtGui import * def create(self): # Add a dockable widget self.logDockWidget = QDockWidget("Log", self) self.logDockWidget.setObjectName("LogDockWidget") self.logDockWidget.setAllowedAreas(Qt.LeftDockWidgetArea| Qt.RightDockWidgetArea) self.logWidget = QTextEdit() self.logDockWidget.setWidget(self.logWidget) self.addDockWidget(Qt.LeftDockWidgetArea, self.logDockWidget) And ### bin/logWindow/plugin.py Import PyQT modules from PyQt4.QtCore import * from PyQt4.QtGui import * def create(self): # Create a text editing box self.editor = QTextEdit() # Add to main window self.setCentralWidget(self.editor) # connect text change to update log window. This is presumably what I need to # change so that it connects to the function below instead of the on in main.py self.connect(self.editor, SIGNAL("textChanged()"), self.updateUi) def updateUi(self): text = self.editor.toPlainText() self.logWidget.setText(text)
[ "For starters, is there a reason you're using a very old version of the PyQt release document? The new one is: here\nThere are a few things you are doing that are a bit unusual. Generally import statements in python are placed at the top of the file (to more easily see dependencies), but I assume you're doing this ...
[ 2 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0003827013_pyqt_pyqt4_python_qt_qt4.txt
Q: Extract data from large structured file using Java/Python I have a large text file (~100MB) that need to be parsed to extract information. I would like to find an efficient way of doing it. The file is structured in block: Mon, 01 Jan 2010 01:01:01 Token1 = ValueXYZ Token2 = ValueABC Token3 = ValuePQR ... TokenX = Value123 Mon, 01 Jan 2010 01:02:01 Token1 = ValueXYZ Token2 = ValueABC Token3 = ValuePQR ... TokenY = Value456 Is there a library that could help in parsing this file? (In Java, Python, any command line tool) Edit: I know the question is vague, but the key element is not the way to read a file, parse it with regex, etc. I was looking more in a library, or tools suggestions in terms of performance. For example, Antlr could have been a possibility, but this tool loads the whole file in memory, which is not good. Thanks! A: Usually, we do something like this. The re library pretty much handles it. The use of a generator function copes the the nested structure. def gen_blocks( my_file ): header_pat= re.compile( r"\w3, \d2 \w3 \d4 \d2:\d2:\d2" ) detail_pat = re.compile( r"\s2\S*\s+=\s+\S*" ) lines = [] for line in my_file: hdr_match=header_pat.match( line ) if hdr_match: if lines: yield header, lines lines= [] header= hdr.match.groups() continue dtl_match= detail_pat.match( line ) if dtl_match: lines.append( dtl_match.groups() ) continue # Neither kind of line, maybe blank or maybe an error if lines: yield header, lines for header, lines in gen_blocks( some_file ): print header, lines A: IMO this data is so well structured that an external package to process it isn't needed. It probably wouldn't take more than a few minutes to write the parser for it. It would run pretty fast. A: Rather than incurring the extra library dependency, and getting up the learning curve with that new library, it would seem more efficient to just write vanilla code. My algorithm would look something like this (using quick and sloppy Java): // HOLDER FOR ALL THE DATA OBJECT THAT ARE EXTRACTED FROM THE FILE ArrayList allDataObjects = new ArrayList(); // BUFFER FOR THE CURRENT DATA OBJECT BEING EXTRACTED MyDataObject workingObject = null; // BUILT-IN JAVA PARSER TO HELP US DETERMINE WHETHER OR NOT A LINE REPRESENTS A DATE SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss"); // PARSE THROUGH THE FILE LINE-BY-LINE BufferedReader inputFile = new BufferedReader(new FileReader(new File("myFile.txt"))); String currentLine = ""; while((currentLine = inputFile.readLine()) != null) { try { // CHECK WHETHER OR NOT THE CURRENT LINE IS A DATE Date parsedDate = dateFormat.parse(currentLine.trim()); } catch(ParseException pe) { // THE CURRENT LINE IS NOT A DATE. THAT MEANS WE'RE // STILL PULLING IN TOKENS FOR THE LAST DATA OBJECT. workingObject.parseAndAddToken(currentLine); continue; } // THE ONLY WAY WE REACH THIS CODE IS IF THE CURRENT LINE // REPRESENTS A DATE, WHICH MEANS WE'RE STARTING ON A NEW // DATA OBJECT. ADD THE LAST DATA OBJECT TO THE LIST, // AND START UP A NEW WORKING DATA OBJECT. if(workingObject != null) allDataObjects.add(workingObject); workingObject = new MyDataObject(); workingObject.parseAndSetDate(currentLine); } inputFile.close(); // NOW YOU'RE READY TO DO WHATEVER WITH "allDataObjects" Of course, you'd have to flesh out the missing functionality for the "MyDataObject" class. However, this basically does what you're asking for in about 20 or so lines of code (stripping out the comments) and not external library dependencies. A: Since that's a custom format, there's likely no library available. So write one yourself. Here's a kickoff example, assuming that the file format is consitent as you posted in the question. You only may want to use a List<Block> instead: Map<Date, Map<String, String>> blocks = new LinkedHashMap<Date, Map<String, String>>(); SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.ENGLISH); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream("/input.txt"), "UTF-8")); Date date = null; Map<String, String> block = null; for (String line; (line = reader.readLine()) != null;) { line = line.trim(); if (date == null) { date = sdf.parse(line); block = new LinkedHashMap<String, String>(); blocks.put(date, block); } else if (!line.isEmpty()) { String[] parts = line.split("\\s*=\\s*"); block.put(parts[0], parts[1]); } else { date = null; } } } finally { if (reader != null) try { reader.close(); } catch (IOException ignore) {} } To verify the contents, use this: for (Entry<Date, Map<String, String>> block : blocks.entrySet()) { System.out.println(block.getKey()); for (Entry<String, String> token : block.getValue().entrySet()) { System.out.println("\t" + token.getKey() + " = " + token.getValue()); } System.out.println(); } A: For efficient parsing of files, especially on a big file, you can use awk. An example $ awk -vRS= '{print "====>" $0}' file ====>Mon, 01 Jan 2010 01:01:01 Token1 = ValueXYZ Token2 = ValueABC Token3 = ValuePQR ... TokenX = Value123 ====>Mon, 01 Jan 2010 01:02:01 Token1 = ValueXYZ Token2 = ValueABC Token3 = ValuePQR ... TokenY = Value456 ====>Mon, 01 Jan 2010 01:03:01 Token1 = ValueXYZ Token2 = ValueABC Token3 = ValuePQR As you can see with the arrows , each record is now one block from the "====>" arrows to the next (by setting Record separator RS to blanks). you can then set field separator, eg a newline $ awk -vRS= -vFS="\n" '{print "====>" $1}' file ====>Mon, 01 Jan 2010 01:01:01 ====>Mon, 01 Jan 2010 01:02:01 ====>Mon, 01 Jan 2010 01:03:01 So in the above example, every 1st field is the date/time stamp. To get "token1" for example, you could do this $ awk -vRS= -vFS="\n" '{for(i=1;i<=NF;i++) if ($i ~/Token1/){ print $i} }' file Token1 = ValueXYZ Token1 = ValueXYZ Token1 = ValueXYZ
Extract data from large structured file using Java/Python
I have a large text file (~100MB) that need to be parsed to extract information. I would like to find an efficient way of doing it. The file is structured in block: Mon, 01 Jan 2010 01:01:01 Token1 = ValueXYZ Token2 = ValueABC Token3 = ValuePQR ... TokenX = Value123 Mon, 01 Jan 2010 01:02:01 Token1 = ValueXYZ Token2 = ValueABC Token3 = ValuePQR ... TokenY = Value456 Is there a library that could help in parsing this file? (In Java, Python, any command line tool) Edit: I know the question is vague, but the key element is not the way to read a file, parse it with regex, etc. I was looking more in a library, or tools suggestions in terms of performance. For example, Antlr could have been a possibility, but this tool loads the whole file in memory, which is not good. Thanks!
[ "Usually, we do something like this. The re library pretty much handles it. The use of a generator function copes the the nested structure.\ndef gen_blocks( my_file ):\n header_pat= re.compile( r\"\\w3, \\d2 \\w3 \\d4 \\d2:\\d2:\\d2\" )\n detail_pat = re.compile( r\"\\s2\\S*\\s+=\\s+\\S*\" )\n lines = []...
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "file", "java", "performance", "python" ]
stackoverflow_0003825160_file_java_performance_python.txt
Q: Matplotlib point annotation, no scaling I'd like to annotate a plot in matplotlib with filled and non-filled dots. I can create a circle patch, but the circle scales with my axes which is not my desired effect. I can achieve this with plt.plot(x,y,'.',markersize=10) plt.plot(x,y,'o',markersize=10) but both markers are filled even if I set markerfacecolor=None. A: From the sources it looks like you need to set markerfacecolor to 'none' and None. Can you try this? Ref : http://www.mathworks.com/help/techdoc/ref/errorbarseriesproperties.html
Matplotlib point annotation, no scaling
I'd like to annotate a plot in matplotlib with filled and non-filled dots. I can create a circle patch, but the circle scales with my axes which is not my desired effect. I can achieve this with plt.plot(x,y,'.',markersize=10) plt.plot(x,y,'o',markersize=10) but both markers are filled even if I set markerfacecolor=None.
[ "From the sources it looks like you need to set markerfacecolor to 'none' and None.\nCan you try this?\nRef : http://www.mathworks.com/help/techdoc/ref/errorbarseriesproperties.html\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003827247_matplotlib_python.txt
Q: Trying to format Google App Engine DateTimeProperty for template I'm using the Tornado framework (Python) on GAE. I'm still kind of new to the whole MVC concept and GAE... and having a dang of a time trying to figure out how to do this. I have a table (model) Post with the fields user, text, creation_date. I pull all the posts in the code and then send it to the template. I want to format the creation_date field so it's formatted a bit nicer. Something like M-d-Y. I know I use strptime or strftime to format the creation_date. But I'm not sure how to do it before I send posts to the template. Here is what I use to get the posts and send it to the template... class HomeHandler(BaseHandler): def get(self): posts = Post.all() posts.order("-creation_date") self.render('home.html', posts=posts) UPDATE: posts = Post.all().order("-creation_date").fetch(50) posts = [{'text': post.text} for post in posts] for post in posts: print post.text Error message I get: AttributeError: 'dict' object has no attribute 'text' A: Assuming you are using Tornado's template module, it includes the datetime module. I have not used Tornado's template module, but you should be able to use: entity.datetime_property.strftime('%m-%d-%y') If you want to process your models before sending them to the template try something like: class HomeHandler(BaseHandler): def get(self): posts = Post.all().order("-creation_date").fetch(50) posts = [{'author': post.author, 'subject': post.subject, 'date': post.date} for post in posts] self.render('home.html', posts=posts) Within your template posts will be a list of dictionaries containing the fields author, subject, and date. Use fetch to limit the number of posts you return; it will improve performance by grabbing (up to) 50 entities at once instead of grabbing them in smaller batches.
Trying to format Google App Engine DateTimeProperty for template
I'm using the Tornado framework (Python) on GAE. I'm still kind of new to the whole MVC concept and GAE... and having a dang of a time trying to figure out how to do this. I have a table (model) Post with the fields user, text, creation_date. I pull all the posts in the code and then send it to the template. I want to format the creation_date field so it's formatted a bit nicer. Something like M-d-Y. I know I use strptime or strftime to format the creation_date. But I'm not sure how to do it before I send posts to the template. Here is what I use to get the posts and send it to the template... class HomeHandler(BaseHandler): def get(self): posts = Post.all() posts.order("-creation_date") self.render('home.html', posts=posts) UPDATE: posts = Post.all().order("-creation_date").fetch(50) posts = [{'text': post.text} for post in posts] for post in posts: print post.text Error message I get: AttributeError: 'dict' object has no attribute 'text'
[ "Assuming you are using Tornado's template module, it includes the datetime module. I have not used Tornado's template module, but you should be able to use:\nentity.datetime_property.strftime('%m-%d-%y')\n\nIf you want to process your models before sending them to the template try something like:\nclass HomeHandl...
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003826441_google_app_engine_python.txt
Q: (Usage of Class Variables) Pythonic - or nasty habit learnt from java? Hello Pythoneers: the following code is only a mock up of what I'm trying to do, but it should illustrate my question. I would like to know if this is dirty trick I picked up from Java programming, or a valid and Pythonic way of doing things: basically I'm creating a load of instances, but I need to track 'static' data of all the instances as they are created. class Myclass: counter=0 last_value=None def __init__(self,name): self.name=name Myclass.counter+=1 Myclass.last_value=name And some output of using this simple class , showing that everything is working as I expected: >>> x=Myclass("hello") >>> print x.name hello >>> print Myclass.last_value hello >>> y=Myclass("goodbye") >>> print y.name goodbye >>> print x.name hello >>> print Myclass.last_value goodbye So is this a generally acceptable way of doing this kind of thing, or an anti-pattern ? [For instance, I'm not too happy that I can apparently set the counter from both within the class(good) and outside of it(bad); also not keen on having to use full namespace 'Myclass' from within the class code itself - just looks bulky; and lastly I'm initially setting values to 'None' - probably I'm aping static-typed languages by doing this?] I'm using Python 2.6.2 and the program is single-threaded. A: Class variables are perfectly Pythonic in my opinion. Just watch out for one thing. An instance variable can hide a class variable: x.counter = 5 # creates an instance variable in the object x. print x.counter # instance variable, prints 5 print y.counter # class variable, prints 2 print myclass.counter # class variable, prints 2 A: Do. Not. Have. Stateful. Class. Variables. It's a nightmare to debug, since the class object now has special features. Stateful classes conflate two (2) unrelated responsibilities: state of object creation and the created objects. Do not conflate responsibilities because it "seems" like they belong together. In this example, the counting of created objects is the responsibility of a Factory. The objects which are created have completely unrelated responsibilities (which can't easily be deduced from the question). Also, please use Upper Case Class Names. class MyClass( object ): def __init__(self, name): self.name=name def myClassFactory( iterable ): for i, name in enumerate( iterable ): yield MyClass( name ) The sequence counter is now part of the factory, where the state and counts should be maintained. In a separate factory. [For folks playing Code Golf, this is shorter. But that's not the point. The point is that the class is no longer stateful.] It's not clear from question how Myclass instances get created. Lacking any clue, there isn't much more than can be said about how to use the factory. An iterable is the usual culprit. Perhaps something that iterates through a list or a file or some other iterable data structure. Also -- for folks just of the boat from Java -- the factory object is just a function. Nothing more is needed. Since the example on the question is perfectly unclear, it's hard to know why (1) two unique objects are created with (2) a counter. The two unique objects are already two unique objects and a counter isn't needed. For example, the static variables in the Myclass are never referenced anywhere. That makes it very, very hard to understand the example. x, y = myClassFactory( [ "hello", "goodbye" ] ) If the count or last value where actually used for something, then a perhaps meaningful example could be created. A: You don't have to use a class variable here; this is a perfectly valid case for using globals: _counter = 0 _last_value = None class Myclass(obj): def __init__(self, name): self.name = name global _counter, _last_value _counter += 1 _last_value = name I have a feeling some people will knee-jerk against globals out of habit, so a quick review may be in order of what's wrong--and not wrong--with globals. Globals traditionally are variables which are visible and changeable, unscoped, from anywhere in the program. This is a problem with globals in languages like C. It's completely irrelevant to Python; these "globals" are scoped to the module. The class name "Myclass" is equally global; both names are scoped identically, in the module they're contained in. Most variables--in Python equally to C++--are logically part of instances of objects or locally scoped, but this is cleared shared state across all users of the class. I don't have any strong inclination against using class variables for this (and using a factory is completely unnecessary), but globals are how I'd generally do it. A: You can solve this problem by splitting the code into two separate classes. The first class will be for the object you are trying to create: class MyClass(object): def __init__(self, name): self.Name = name And the second class will create the objects and keep track of them: class MyClassFactory(object): Counter = 0 LastValue = None @classmethod def Build(cls, name): inst = MyClass(name) cls.Counter += 1 cls.LastValue = inst.Name return inst This way, you can create new instances of the class as needed, but the information about the created classes will still be correct. >>> x = MyClassFactory.Build("Hello") >>> MyClassFactory.Counter 1 >>> MyClassFactory.LastValue 'Hello' >>> y = MyClassFactory.Build("Goodbye") >>> MyClassFactory.Counter 2 >>> MyClassFactory.LastValue 'Goodbye' >>> x.Name 'Hello' >>> y.Name 'Goodbye' Finally, this approach avoids the problem of instance variables hiding class variables, because MyClass instances have no knowledge of the factory that created them. >>> x.Counter Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'MyClass' object has no attribute 'Counter' A: Is this pythonic? Well, it's definitely more pythonic than having global variables for a counter and the value of the most recent instance. It's said in Python that there's only one right way to do anything. I can't think of a better way to implement this, so keep going. Despite the fact that many will criticize you for "non-pythonic" solutions to problems (like the needless object-orientation that Java coders like or the "do-it-yourself" attitude that many from C and C++ bring), in most cases your Java habits will not send you to Python hell. And beyond that, who cares if it's "pythonic"? It works, and it's not a performance issue, is it?
(Usage of Class Variables) Pythonic - or nasty habit learnt from java?
Hello Pythoneers: the following code is only a mock up of what I'm trying to do, but it should illustrate my question. I would like to know if this is dirty trick I picked up from Java programming, or a valid and Pythonic way of doing things: basically I'm creating a load of instances, but I need to track 'static' data of all the instances as they are created. class Myclass: counter=0 last_value=None def __init__(self,name): self.name=name Myclass.counter+=1 Myclass.last_value=name And some output of using this simple class , showing that everything is working as I expected: >>> x=Myclass("hello") >>> print x.name hello >>> print Myclass.last_value hello >>> y=Myclass("goodbye") >>> print y.name goodbye >>> print x.name hello >>> print Myclass.last_value goodbye So is this a generally acceptable way of doing this kind of thing, or an anti-pattern ? [For instance, I'm not too happy that I can apparently set the counter from both within the class(good) and outside of it(bad); also not keen on having to use full namespace 'Myclass' from within the class code itself - just looks bulky; and lastly I'm initially setting values to 'None' - probably I'm aping static-typed languages by doing this?] I'm using Python 2.6.2 and the program is single-threaded.
[ "Class variables are perfectly Pythonic in my opinion.\nJust watch out for one thing. An instance variable can hide a class variable:\nx.counter = 5 # creates an instance variable in the object x.\nprint x.counter # instance variable, prints 5\nprint y.counter # class variable, prints 2\nprint myclass.counter #...
[ 7, 4, 2, 2, 1 ]
[]
[]
[ "class", "coding_style", "python" ]
stackoverflow_0003826077_class_coding_style_python.txt
Q: Importing between two applications in a django project I've got two applications (app1 and app2) in my django project. I'm curious if there is a way to import things between applications. baseProject --app1 ----models.py ----etc.. --app2 ----models.py ----etc.. I'd like to be able, while in app2, to import something from the models section of app1. Is there an intended method to do this or am I planning bad architecture. A: You can definitely do that, just import it as usual. Many authentication/registration-related apps import models from the "django.contrib.auth" app that comes with Django. You are free to import from any app, whether you wrote it or not. You just need to make sure the apps are on your PYTHONPATH, so that they can be imported. That said, it's always good to consider your design before importing things across apps. Make sure you're not creating a situation where you have a circular dependency between apps. A: What you're proposing is fine and accepted practice. From app2, you can simply do: from app1.models import SomeModel. For example, you're probably used to importing the User model from the django.contrib.auth app. This is part of the intended benefit of the reusability of django apps.
Importing between two applications in a django project
I've got two applications (app1 and app2) in my django project. I'm curious if there is a way to import things between applications. baseProject --app1 ----models.py ----etc.. --app2 ----models.py ----etc.. I'd like to be able, while in app2, to import something from the models section of app1. Is there an intended method to do this or am I planning bad architecture.
[ "You can definitely do that, just import it as usual. Many authentication/registration-related apps import models from the \"django.contrib.auth\" app that comes with Django. You are free to import from any app, whether you wrote it or not.\nYou just need to make sure the apps are on your PYTHONPATH, so that they...
[ 5, 1 ]
[]
[]
[ "django", "import", "python" ]
stackoverflow_0003827542_django_import_python.txt
Q: Python kill thread I'm trying to kill a thread in python. An exception would be the preferred way to do it, as a graceful exit of the run method of the thread through a try:except: pair would allow to close resources. I tried : Is there any way to kill a Thread in Python? , but is specifies that is doesn't work while the code is executing a system call (like time.sleep). Is there a way to raise an exception in another thread (or process, in don't mind,) that work no mater what the thread is executing? A: In general, raising asynchronous exceptions is difficult to handle properly. This is because, rather than having single, specific points of code where an exception may be generated--and therefore where exception handling needs to be tested--instead, an exception may be generated after any bytecode instruction. This makes it much harder to implement and fully test exception handling. That said, it can be done--but, presently, not safely in Python. Raising an exception asynchronously in Python is dangerous, because you might raise it during an exception handler, which will raise another exception and prevent cleanup from occurring properly. See my answer at How to limit execution time of a function call in Python. It's possible to signal some forms of sleep to cancel, but there's no general infrastructure for this in Python. You're much better off either avoiding the need to kill a thread, or moving the thread to a process, where you can send a signal to the whole process and exit cleanly.
Python kill thread
I'm trying to kill a thread in python. An exception would be the preferred way to do it, as a graceful exit of the run method of the thread through a try:except: pair would allow to close resources. I tried : Is there any way to kill a Thread in Python? , but is specifies that is doesn't work while the code is executing a system call (like time.sleep). Is there a way to raise an exception in another thread (or process, in don't mind,) that work no mater what the thread is executing?
[ "In general, raising asynchronous exceptions is difficult to handle properly. This is because, rather than having single, specific points of code where an exception may be generated--and therefore where exception handling needs to be tested--instead, an exception may be generated after any bytecode instruction. T...
[ 4 ]
[]
[]
[ "multithreading", "python", "sleep" ]
stackoverflow_0003827545_multithreading_python_sleep.txt
Q: Python and C interaction - callback function I'm trying to make a key logger for Mac OS for one of my research projects. I have a C code which will grab keystroke and write them to a text file. (The following code I have taken out some not important stuff) What I need to do now is just like PyHook, instead of write the data to a text file, to pass a Python callback function to the C code and make it passes back the key input to Python, so I can do necessary analysis with Python. I have look for how to do it, but honestly I have no idea how to approach this, as I am not used to C programming or Python extensions. Any help would be greatly appreciated. #include <Carbon/Carbon.h> #include <ApplicationServices/ApplicationServices.h> #include <unistd.h> #include <stdio.h> #include <sys/time.h> #define NUM_RECORDING_EVENT_TYPES 5 #define RECORD 0 #define MOUSEACTION 0 #define KEYSTROKE 1 // maximum expected line length, for fgets #define LINE_LENGTH 80 #define kShowMouse TRUE OSStatus RUIRecordingEventOccurred(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData); void prepareToRecord(); // install the event handler, wait for record signal // note that keyboard character codes are found in Figure C2 of the document // Inside Macintosh: Text available from http://developer.apple.com char * keyStringForKeyCode(int keyCode); // get the representation of the Mac keycode // Global Variables int dieNow = 0; // should the program terminate int ifexit = 0; // Exit state char *filename = NULL; // Log file name FILE *fd = NULL; // Log file descriptor int typecount = 0; // count keystroke to periodically save to a txt file struct timeval thetime; // for gettimeofday long currenttime; // the current time in milliseconds int main() { filename = "test.txt"; fd = fopen(filename, "a"); // Get RUI ready to record or play, based off of mode prepareToRecord(); return EXIT_SUCCESS; } // event handler for RUI recorder OSStatus RUIRecordingEventOccurred(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData) { // Determine class and kind of event int eventClass = GetEventClass(theEvent); int eventKind = GetEventKind(theEvent); /* Handle Keyboard Events */ if((eventClass == kEventClassKeyboard) && (eventKind == kEventRawKeyDown)) /* key release implied */ { int keyCode, modifiers; // what did the user press? any modifier keys down? // gather keystroke information GetEventParameter(theEvent, kEventParamKeyCode, typeInteger, NULL, sizeof(keyCode), NULL, &keyCode); GetEventParameter(theEvent, kEventParamKeyModifiers, typeInteger, NULL, sizeof(modifiers), NULL, &modifiers); // What time is it? gettimeofday(&thetime, NULL); currenttime =(((thetime.tv_sec*1000000) + (thetime.tv_usec))); fprintf(fd, "%s\n", keyStringForKeyCode(keyCode)); } return EXIT_SUCCESS; } void prepareToRecord() { EventRecord event; // holds an event for examination // Types of events to listen for EventTypeSpec eventTypes[NUM_RECORDING_EVENT_TYPES] = {{kEventClassKeyboard, kEventRawKeyDown}}; // Install the event handler InstallEventHandler(GetEventMonitorTarget(), NewEventHandlerUPP(RUIRecordingEventOccurred), NUM_RECORDING_EVENT_TYPES, eventTypes, nil, nil); // event loop - get events until die command do { WaitNextEvent((everyEvent),&event,GetCaretTime(),nil); } while (dieNow == 0); } char * keyStringForKeyCode(int keyCode) { // return key char switch (keyCode) { case 0: return("a"); default: return("Empty"); // Unknown key, Return "Empty" } } A: It's easy - Just Follow the instructions - Calling Python Functions from C (Update March 2022: for Python3, see the corresponding chapter in Extending and Embedding the Python Interpreter). Alternatively if you are trying to call C/C++ functions from Python you can use SWIG or one of Python's module CTypes
Python and C interaction - callback function
I'm trying to make a key logger for Mac OS for one of my research projects. I have a C code which will grab keystroke and write them to a text file. (The following code I have taken out some not important stuff) What I need to do now is just like PyHook, instead of write the data to a text file, to pass a Python callback function to the C code and make it passes back the key input to Python, so I can do necessary analysis with Python. I have look for how to do it, but honestly I have no idea how to approach this, as I am not used to C programming or Python extensions. Any help would be greatly appreciated. #include <Carbon/Carbon.h> #include <ApplicationServices/ApplicationServices.h> #include <unistd.h> #include <stdio.h> #include <sys/time.h> #define NUM_RECORDING_EVENT_TYPES 5 #define RECORD 0 #define MOUSEACTION 0 #define KEYSTROKE 1 // maximum expected line length, for fgets #define LINE_LENGTH 80 #define kShowMouse TRUE OSStatus RUIRecordingEventOccurred(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData); void prepareToRecord(); // install the event handler, wait for record signal // note that keyboard character codes are found in Figure C2 of the document // Inside Macintosh: Text available from http://developer.apple.com char * keyStringForKeyCode(int keyCode); // get the representation of the Mac keycode // Global Variables int dieNow = 0; // should the program terminate int ifexit = 0; // Exit state char *filename = NULL; // Log file name FILE *fd = NULL; // Log file descriptor int typecount = 0; // count keystroke to periodically save to a txt file struct timeval thetime; // for gettimeofday long currenttime; // the current time in milliseconds int main() { filename = "test.txt"; fd = fopen(filename, "a"); // Get RUI ready to record or play, based off of mode prepareToRecord(); return EXIT_SUCCESS; } // event handler for RUI recorder OSStatus RUIRecordingEventOccurred(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData) { // Determine class and kind of event int eventClass = GetEventClass(theEvent); int eventKind = GetEventKind(theEvent); /* Handle Keyboard Events */ if((eventClass == kEventClassKeyboard) && (eventKind == kEventRawKeyDown)) /* key release implied */ { int keyCode, modifiers; // what did the user press? any modifier keys down? // gather keystroke information GetEventParameter(theEvent, kEventParamKeyCode, typeInteger, NULL, sizeof(keyCode), NULL, &keyCode); GetEventParameter(theEvent, kEventParamKeyModifiers, typeInteger, NULL, sizeof(modifiers), NULL, &modifiers); // What time is it? gettimeofday(&thetime, NULL); currenttime =(((thetime.tv_sec*1000000) + (thetime.tv_usec))); fprintf(fd, "%s\n", keyStringForKeyCode(keyCode)); } return EXIT_SUCCESS; } void prepareToRecord() { EventRecord event; // holds an event for examination // Types of events to listen for EventTypeSpec eventTypes[NUM_RECORDING_EVENT_TYPES] = {{kEventClassKeyboard, kEventRawKeyDown}}; // Install the event handler InstallEventHandler(GetEventMonitorTarget(), NewEventHandlerUPP(RUIRecordingEventOccurred), NUM_RECORDING_EVENT_TYPES, eventTypes, nil, nil); // event loop - get events until die command do { WaitNextEvent((everyEvent),&event,GetCaretTime(),nil); } while (dieNow == 0); } char * keyStringForKeyCode(int keyCode) { // return key char switch (keyCode) { case 0: return("a"); default: return("Empty"); // Unknown key, Return "Empty" } }
[ "It's easy - Just Follow the instructions - Calling Python Functions from C (Update March 2022: for Python3, see the corresponding chapter in Extending and Embedding the Python Interpreter).\nAlternatively if you are trying to call C/C++ functions from Python you can use SWIG or one of Python's module CTypes\n" ]
[ 4 ]
[]
[]
[ "c", "python" ]
stackoverflow_0003827780_c_python.txt
Q: using python.ctypes with cygwin I want to use python's (2.6.5) ctypes with cygwin, but I don't know how to load a dll. I tried various variants like >>> form ctypes import * >>> cdll.LoadLibrary("/lib/libcairo.dll.a") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/ctypes/__init__.py", line 431, in LoadLibrary return self._dlltype(name) File "/usr/lib/python2.6/ctypes/__init__.py", line 353, in __init__ self._handle = _dlopen(self._name, mode) OSError: Permission denied A: You won't be able to load an import library with the Python ctypes module; it has to be an actual DLL. I used both the cygwin crypt library and the crypt DLL import library as examples with a late model Cygwin on Win7. Python 2.6.5 (r265:79063, Jun 12 2010, 17:07:01) [GCC 4.3.4 20090804 (release) 1] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> from ctypes import * >>> cdll.LoadLibrary('cygcrypt-0.dll') <CDLL 'cygcrypt-0.dll', handle 380000 at 7ef4564c> >>> >>> >>> cdll.LoadLibrary('libcrypt.dll.a') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/ctypes/__init__.py", line 431, in LoadLibrary return self._dlltype(name) File "/usr/lib/python2.6/ctypes/__init__.py", line 353, in __init__ self._handle = _dlopen(self._name, mode) OSError: Permission denied
using python.ctypes with cygwin
I want to use python's (2.6.5) ctypes with cygwin, but I don't know how to load a dll. I tried various variants like >>> form ctypes import * >>> cdll.LoadLibrary("/lib/libcairo.dll.a") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/ctypes/__init__.py", line 431, in LoadLibrary return self._dlltype(name) File "/usr/lib/python2.6/ctypes/__init__.py", line 353, in __init__ self._handle = _dlopen(self._name, mode) OSError: Permission denied
[ "You won't be able to load an import library with the Python ctypes module; it has to be an actual DLL. I used both the cygwin crypt library and the crypt DLL import library as examples with a late model Cygwin on Win7.\n\nPython 2.6.5 (r265:79063, Jun 12 2010, 17:07:01)\n[GCC 4.3.4 20090804 (release) 1] on cygwin\...
[ 4 ]
[]
[]
[ "ctypes", "cygwin", "python" ]
stackoverflow_0003826484_ctypes_cygwin_python.txt
Q: How to get out of def () for example i have def Hello(): and here is the code def Hello(): F = 'Y' if F == 'Y': #here i want get out of the Hello() to Hey()! by how! A: To exit the 'Hello' function: def Hello(): F = 'Y' if F == 'Y': return You can use 'return' to exit a function before the end (though there is a school of thought that frowns on this, as it makes it slightly harder to form a solid picture of the execution flow). This will go on to the 'Hey' function if you called it with e.g.: Hello() Hey() Or, to 'jump' to the 'Hey' function, use: def Hello(): F = 'Y' if F == 'Y': Hey() ...but this means the call stack will still contain the data for the 'Hello' function - so when you return from the 'Hey' function, you will be returning to within the 'Hello' function, and then out of that.
How to get out of def ()
for example i have def Hello(): and here is the code def Hello(): F = 'Y' if F == 'Y': #here i want get out of the Hello() to Hey()! by how!
[ "To exit the 'Hello' function:\ndef Hello():\n F = 'Y'\n if F == 'Y':\n return\n\nYou can use 'return' to exit a function before the end (though there is a school of thought that frowns on this, as it makes it slightly harder to form a solid picture of the execution flow).\nThis will go on to the 'Hey' function i...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0003828135_python.txt
Q: Transfer files from windows machine to remote solaris machine using python script i used following code to establish connection between my local machine and the remote machine : import os, sys, ftplib nonpassive=False remotesite= '10.88.203.21:22' remoteuser='root' remotepass='v-peg8!@#' localdir= "c:\\.." print "connecting" connection=ftplib.FTP(remotesite) print "successfully connected" connection.login(remoteuser,remotepass) if nonpassive: connection.set_pasv(False) But its giving me following error: socket.gaierror: [Errno 11001] getaddrinfo failed.. can somebody plz help me out with this. A: You need to specify the port as a separate argument, not in the way you have it in remotesite. Try: remotesite = '10.88.203.21' port = 22 connection = ftplib.FTP(remotesite, port) See the FTP docs for more information. A: If its port 22, then you are using wrong port, since most systems use 22 for SSH protocol. Assuming that 22 is normal SSH port, you should really use scp/sftp. (try paramiko for Python). If you are sure the remote server is running FTP, then use the default port 21.
Transfer files from windows machine to remote solaris machine using python script
i used following code to establish connection between my local machine and the remote machine : import os, sys, ftplib nonpassive=False remotesite= '10.88.203.21:22' remoteuser='root' remotepass='v-peg8!@#' localdir= "c:\\.." print "connecting" connection=ftplib.FTP(remotesite) print "successfully connected" connection.login(remoteuser,remotepass) if nonpassive: connection.set_pasv(False) But its giving me following error: socket.gaierror: [Errno 11001] getaddrinfo failed.. can somebody plz help me out with this.
[ "You need to specify the port as a separate argument, not in the way you have it in remotesite. Try:\nremotesite = '10.88.203.21'\nport = 22\nconnection = ftplib.FTP(remotesite, port)\n\nSee the FTP docs for more information.\n", "If its port 22, then you are using wrong port, since most systems use 22 for SSH pr...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003827986_python.txt
Q: Google app engine, multiple languages i'm working on on a project with DJango but i'm also thinking about going the Jython route. By doing so...since i'll be using the java instance instead of cpython wouldn't I be able to use java, scala, ruby and other other languages that run on top of the jvm if need be? A: Scala works on GAE. So does Ruby. If you want to know about other JVM languages, google search for google app engine followed by the name of the language of interest. Also see this page. A: I'm not sure how good the Jython Java Interop is. But with Clojure you can generate Java classes pretty easy if it is nessesary (not sure). Clojure is really good for GAE. There are nice librarys, blogs and applications. Like a DSL to work with the Datastore. Librarys: http://github.com/smartrevolution/clj-gae-datastore http://github.com/r0man/appengine-clj Look at this blog: http://elhumidor.blogspot.com/2009/04/clojure-on-google-appengine.html http://compojureongae.posterous.com/ http://www.hackers-with-attitude.com/ This is written in Clojure with the GAE: http://the-deadline.appspot.com/
Google app engine, multiple languages
i'm working on on a project with DJango but i'm also thinking about going the Jython route. By doing so...since i'll be using the java instance instead of cpython wouldn't I be able to use java, scala, ruby and other other languages that run on top of the jvm if need be?
[ "Scala works on GAE.\nSo does Ruby.\nIf you want to know about other JVM languages, google search for google app engine followed by the name of the language of interest.\n\nAlso see this page.\n", "I'm not sure how good the Jython Java Interop is. But with Clojure you can generate Java classes pretty easy if it i...
[ 1, 0 ]
[]
[]
[ "django", "google_app_engine", "python", "scala" ]
stackoverflow_0003825694_django_google_app_engine_python_scala.txt
Q: upload file not working in google app engine it should works but hitting the submit button redirect my page to http://localhost:8082/sign (http://localhost:8082 being the path to my app). There's no such path in my application thus it return a link broken page. Is this a common problem? A: Yes, but this isn't an App Engine problem. If you do a form post to a URL that doesn't exist, it will return a 404 (I'm suspecting you modified the guestbook app, which posts to /sign and didn't change where the post on that app goes to).
upload file not working in google app engine
it should works but hitting the submit button redirect my page to http://localhost:8082/sign (http://localhost:8082 being the path to my app). There's no such path in my application thus it return a link broken page. Is this a common problem?
[ "Yes, but this isn't an App Engine problem. If you do a form post to a URL that doesn't exist, it will return a 404 (I'm suspecting you modified the guestbook app, which posts to /sign and didn't change where the post on that app goes to).\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003828158_google_app_engine_python.txt
Q: GAE webapp application internationalization with Babel How would you go about internationalizing a Google App Engine webapp application using BABEL? I am looking here for all the stages: Marking the strings to be translated. Extracting them. Traslating Configuring your app to load the right language requested by the browser A: 1) use _() (or gettext()) in your code and templates. Translated strings set in the module globals or class definitions should use some form of lazy gettext(), because i18n won't be available when the modules are imported. 2) Extract all translations using pybabel. Here we pass two directories to be scanned: the templates dir and the app dir. This will create a messages.pot file in the /locale directory with all strings found in these directories. babel.cfg is the extraction configuration that varies depending on the template engine you use: $ pybabel extract -F ./babel.cfg -o ./locale/messages.pot ./templates/ ./app/ 3) Initialize a directory for each language. This is done only once. Here we initialize three translations, en_US, es_ES and pt_BR, and use the messages.pot file created on step 2: $ pybabel init -l en_US -d ./locale -i ./locale/messages.pot $ pybabel init -l es_ES -d ./locale -i ./locale/messages.pot $ pybabel init -l pt_BR -d ./locale -i ./locale/messages.pot Translate the messages. They will be in .mo files in each translation directory. After all locales are translated, compile them: $ pybabel compile -f -d ./locale Later, if new translations are added, repeat step 2 and update them using the new .pot file: $ pybabel update -l pt_BR -d ./locale/ -i ./locale/messages.pot Then translate the new strings and compile the translations again. 4) The strategy here may vary. For each request you must set the correct translations to be used, and probably want to cache loaded translations to reuse in subsequent requests.
GAE webapp application internationalization with Babel
How would you go about internationalizing a Google App Engine webapp application using BABEL? I am looking here for all the stages: Marking the strings to be translated. Extracting them. Traslating Configuring your app to load the right language requested by the browser
[ "1) use _() (or gettext()) in your code and templates. Translated strings set in the module globals or class definitions should use some form of lazy gettext(), because i18n won't be available when the modules are imported.\n2) Extract all translations using pybabel. Here we pass two directories to be scanned: the ...
[ 11 ]
[]
[]
[ "google_app_engine", "internationalization", "python", "python_babel", "web_applications" ]
stackoverflow_0003821312_google_app_engine_internationalization_python_python_babel_web_applications.txt
Q: Find text dialog with wxpython Does anyone have a very simple example of using a find dialog with a text component in wxpython? Thanks in advance. A: The use of wx.FindReplaceDialog is not so straighforward as we could expect from its name. This dialog gives you a dialog widget with parameters and entries for a search (or replace) action, You can read these parameters and the string to find from the dialog (actually from the event or from the wx.FindReplaceData object). However reading, searching and/or replacing on a target text and the process to visualize the hit must be implemented separately. This is for example a figure showing the dialog with a string to find and a text control where the string found is coloured. The figure has been produced with the code below. Note however that this code is not fully functional. As it is, it only works for the first search. For a next search you must perform a new string.find() from the current position and you also may want to 'clean' the previously found string giving it its original style. Also the script doesn't make use of the other parameters (search direction, force match case, etc). import wx class MyFrame(wx.Frame): def __init__(self, *args, **kwds): kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.tc = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE|wx.TE_RICH2) self.bt_find = wx.Button(self, -1, "find") self.Bind(wx.EVT_BUTTON, self.on_button, self.bt_find) self.Bind(wx.EVT_FIND, self.on_find) self.pos = 0 self.size = 0 # sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.tc, 1, wx.EXPAND, 0) sizer.Add(self.bt_find, 0, wx.ALIGN_CENTER_HORIZONTAL, 0) self.SetSizer(sizer) sizer.Fit(self) self.Layout() def on_button(self, event): self.txt = self.tc.GetValue() self.data = wx.FindReplaceData() # initializes and holds search parameters self.dlg = wx.FindReplaceDialog(self.tc, self.data, 'Find') self.dlg.Show() def on_find(self, event): fstring = self.data.GetFindString() # also from event.GetFindString() self.pos = self.txt.find(fstring, self.pos) self.size = len(fstring) self.tc.SetStyle(self.pos, self.pos+self.size, wx.TextAttr("red", "black")) if __name__ == "__main__": app = wx.PySimpleApp(0) frame_1 = MyFrame(None, wx.ID_ANY, "") frame_1.Show() app.MainLoop() To make full use of the widget you can check the properties and methods of wx.FindReplaceDialog, wx.FindReplaceData as well as for the events they emit. Alternatively, you could check stani's python editor code. The GUI is wxPython and has a plugin for finding files containing a given text at different deepness of the directory tree. You could get a good hint from there. However it is not an wx.Dialog as you want.
Find text dialog with wxpython
Does anyone have a very simple example of using a find dialog with a text component in wxpython? Thanks in advance.
[ "The use of wx.FindReplaceDialog is not so straighforward as we could expect from its name.\nThis dialog gives you a dialog widget with parameters and entries for a search (or replace) action, You can read these parameters and the string to find from the dialog (actually from the event or from the wx.FindReplaceDat...
[ 3 ]
[ "Use the wiki\nimport wx\n\nclass MyDialog(wx.Dialog):\n def __init__(self, parent, id, title):\n wx.Dialog.__init__(self, parent, id, title)\n\nclass MyApp(wx.App):\n def OnInit(self):\n dia = MyDialog(None, -1, \"simpledialog.py\")\n dia.ShowModal()\n dia.Destroy()\n retur...
[ -2 ]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0003827587_python_wxpython_wxwidgets.txt
Q: Any yahoo messenger lib for python? Is there any lib available to connect to yahoo messenger using either the standard protocol or the http way from python? A: Google is your friend. The Python Package Index has several modules to do with Yahoo, including this one which matches your requirements. A: There is also the Yahoo IM SDK that might help.
Any yahoo messenger lib for python?
Is there any lib available to connect to yahoo messenger using either the standard protocol or the http way from python?
[ "Google is your friend.\nThe Python Package Index has several modules to do with Yahoo, including this one which matches your requirements.\n", "There is also the Yahoo IM SDK that might help.\n" ]
[ 5, 1 ]
[]
[]
[ "python", "yahoo_messenger" ]
stackoverflow_0000997419_python_yahoo_messenger.txt
Q: strange python behaviour with mixing globals/parameters and function named 'top' The following code (not directly in an interpreter, but execute as file) def top(deck): pass def b(): global deck produces the error SyntaxError: name 'deck' is local and global on python2.6.4 and SyntaxError: name 'deck' is parameter and global on python 3.1 python2.4 seems to accept this code, so does the 2.6.4 interactive interpreter. This is already odd; why is 'deck' conflicting if it's a global in one method and a parameter in the other? But it gets weirder. Rename 'top' to basically anything else, and the problem disappears. Can someone explain this behaviour? I feel like I'm missing something very obvious here. Is the name 'top' somehow affecting certain scoping internals? Update This indeed appears to be a bug in the python core. I have filed a bug report. A: It looks like it is a bug in the symbol table handling. Python/symtable.c has some code that (although somewhat obfuscated) does indeed treat 'top' as a special identifier: if (!GET_IDENTIFIER(top) || !symtable_enter_block(st, top, ModuleBlock, (void *)mod, 0)) { PySymtable_Free(st); return NULL; } followed somewhat later by: if (name == GET_IDENTIFIER(top)) st->st_global = st->st_cur->ste_symbols; Further up the file there's a macro: #define GET_IDENTIFIER(VAR) \ ((VAR) ? (VAR) : ((VAR) = PyString_InternFromString(# VAR))) which uses the C preprocessor to initialise the variable top to an interned string with the name of the variable. I think the symbol table must be using the name 'top' to refer to the top level code, but why it doesn't use something that can't conflict with a real variable I have no idea. I would report it as a bug if I were you.
strange python behaviour with mixing globals/parameters and function named 'top'
The following code (not directly in an interpreter, but execute as file) def top(deck): pass def b(): global deck produces the error SyntaxError: name 'deck' is local and global on python2.6.4 and SyntaxError: name 'deck' is parameter and global on python 3.1 python2.4 seems to accept this code, so does the 2.6.4 interactive interpreter. This is already odd; why is 'deck' conflicting if it's a global in one method and a parameter in the other? But it gets weirder. Rename 'top' to basically anything else, and the problem disappears. Can someone explain this behaviour? I feel like I'm missing something very obvious here. Is the name 'top' somehow affecting certain scoping internals? Update This indeed appears to be a bug in the python core. I have filed a bug report.
[ "It looks like it is a bug in the symbol table handling. Python/symtable.c has some code that (although somewhat obfuscated) does indeed treat 'top' as a special identifier:\nif (!GET_IDENTIFIER(top) ||\n !symtable_enter_block(st, top, ModuleBlock, (void *)mod, 0)) {\n PySymtable_Free(st);\n return NULL;\n...
[ 13 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0003828611_python_python_3.x.txt
Q: how to do non blocking accept() in Python? I cannot use threads thus I want to write a server program that can be interrupted after a while: d = show_non_modal_dialog("serving clients") s = socket(...) s.bind(...) s.listen() while (!user_pressed_cancel()) { s.accept() # timed accept for like 1 second if timed_out: continue serve_client close_client_sock } hide_non_modal_dialog(d) A: Use a non-blocking socket and call accept on that. s.setblocking(0) You could also set a timeout for blocking socket operations socket.settimeout(value) There also seems to be an issue in your code accept() returns a (conn, address) pair value. so your code should have been conn, address = s.accept()
how to do non blocking accept() in Python?
I cannot use threads thus I want to write a server program that can be interrupted after a while: d = show_non_modal_dialog("serving clients") s = socket(...) s.bind(...) s.listen() while (!user_pressed_cancel()) { s.accept() # timed accept for like 1 second if timed_out: continue serve_client close_client_sock } hide_non_modal_dialog(d)
[ "Use a non-blocking socket and call accept on that.\ns.setblocking(0)\n\nYou could also set a timeout for blocking socket operations\nsocket.settimeout(value)\n\nThere also seems to be an issue in your code\naccept() returns a (conn, address) pair value. so your code should have been\nconn, address = s.accept()\n\n...
[ 6 ]
[]
[]
[ "nonblocking", "python", "sockets" ]
stackoverflow_0003829067_nonblocking_python_sockets.txt
Q: Cant get a custom ItemDelegate to work first off, im new to python and pyqt so please bear with me. Im using a QTableView with a QSqlTableModel everything works as intended. The last column of the view contains only 0 and 1 as value which i want to display as checkbox and this column should be editable. Ive read that you should subclass QItemDelegate which i did. Unluckily my table wont show the last column as a checkbox. I tried to set the delegate only for the last column (the way i would prefer) using setItemDelegateForColumn(), it didnt work. So i modified it and set it for the entire QTableView using setItemDelegate() reacting only to requests to the last column. It still wont work. Wont work means there are no error messages it just wont do what i say ;) It seems that none of the methods i reimplemented gets ever called except init(). So i guess im missing something fundamental. Ive extracted the relevant lines of code, KSCheckBoxDelegate is my subclass. This is the version where the delegate is set up for the entire QTableView. -- code from applications main class -- self.taglist = QTableView() self.tagmodel = QSqlTableModel() self.tagmodel.setTable("data") self.tagmodel.select() self.taglist.setModel(self.tagmodel) print self.taglist.itemDelegate() myDel = KSCheckBoxDelegate(self) myDel.colnumber = 3 self.taglist.setItemDelegate(myDel) -- KSCheckBoxDelegate.py -- from PyQt4.QtGui import * class KSCheckBoxDelegate(QStyledItemDelegate): colnumber = None def __init__ (self, parent = None): print "KSCheckBoxDelegate::init" QStyledItemDelegate.__init__(self, parent) def createEditor(self, parent, option, index): print "KSCheckBoxDelegate::createEditor" if index.column()==self.colnumber: return QCheckBox(self) else: return QStyledItemDelegate.createEditor(self, parent, option, index) def setEditorData (self, editor, index): print "KSCheckBoxDelegate::setEditorData" if index.column() == self.colnumber: cont = index.model().data(index, Qt.DisplayRole).toString() if cont == "1": editor.setCheckState(Qt.Checked) else: editor.setCheckState(Qt.UnChecked) else: QStyledItemDelegate.setEditorData(self,editor, index) def setModelData (self, editor, model, index): print "KSCheckBoxDelegate::setModelData" if index.column() == self.colnumber: if editor.checkBox.checkState() == Qt.Checked: model.setData(index, 1) else: model.setData(index, 0) else: QStyledItemDelegate.setModelData(self, editor, model, index) Any hints for me on that issue? Furthermore i have difficulties with the currentChanged() signal of the QTableViews selectionModel. Im printing the top right coordinates of the selection. I keep getting wrong indexes (not invalid) when clicking with the left mouse button. Using the cursor keys gets me the right indexes. Using selectionChanged() has the same behaviour. Im actually getting the coordinates of the second last selected cell of the QTableView. For instance im clicking on the coordinates <1,1> <2,1> the second click would show me the coordinates <1,1>. selInd = self.taglist.selectionModel().selectedIndexes() if(len(selInd) > 0): self.xPosData=selInd[0].column() self.yPosData=selInd[0].row() Fixed that by myself, with using QTableView.currentIndex() instead of selectionModel.selectedIndexes() :) And last off using OnManualSubmit as editStrategy doesnt throw an error (return false) when calling submitAll() but doesnt save the data either. It works with choosing OnFieldChange as editStrategy. Which i can live with but is not was i have intended to do. Thanks for your time. Horst A: I think it would be simpler to create your own model basing QSqlTableModel, and for your 0/1 column return QVariant() for QDisplayRole and return Qt::Checked/Qt::Unchecked for Qt::CheckStateRole depending on value. For all other cases return QSqlTableModel::data class MySqlTableModel: public QSqlTableModel { public: // contructors QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) { if(index.column() == 3 /* your 0/1 column */) { if(role == Qt::DisplayRole) { return QVariant(); } else if(role == Qt::CheckStateRole) { QString value = QSqlTableModel::data(index, Qt::DisplayRole).toString(); return value == "1" ? Qt::Checked : Qt::Unchecked; } } return QSqlTableModel::data(index, role); } }; I know it's C++ code, but logic is still same, so just readjust it for Python A: at least i managed to have my delegate show checkboxes with the correct state in display and edit mode. Because i couldnt find a complete description on how to do it ill share it. Maybe other ppl trying to do something similar without having worked with qt ever before. Only one thing is missing, thats the items being editable, i guess its related to the flags question i asked in my opening post. -- KSCheckBoxDelegate.py -- class KSCheckBoxDelegate(QStyledItemDelegate): def __init__ (self, parent = None): print "KSCheckBoxDelegate::init" QStyledItemDelegate.__init__(self, parent) def createEditor(self, parent, option, index): print "KSCheckBoxDelegate::createEditor" return QCheckBox(parent) def setEditorData (self, editor, index): print "KSCheckBoxDelegate::setEditorData" cont = index.model().data(index, Qt.DisplayRole).toString() if cont == "1": editor.setCheckState(Qt.Checked) else: editor.setCheckState(Qt.Unchecked) def setModelData (self, editor, model, index): print "KSCheckBoxDelegate::setModelData" if editor.checkState() == Qt.Checked: model.setData(index, 1) else: model.setData(index, 0) def paint (self, painter, option, index): myopt = QStyleOptionViewItemV4(option) newopt = QStyleOptionButton() newopt.rect = myopt.rect newopt.palette = myopt.palette if index.data().toBool(): newopt.state |= QStyle.State_On QApplication.style().drawControl(QStyle.CE_CheckBox, newopt, painter) def sizeHint (self, option, index): return 18
Cant get a custom ItemDelegate to work
first off, im new to python and pyqt so please bear with me. Im using a QTableView with a QSqlTableModel everything works as intended. The last column of the view contains only 0 and 1 as value which i want to display as checkbox and this column should be editable. Ive read that you should subclass QItemDelegate which i did. Unluckily my table wont show the last column as a checkbox. I tried to set the delegate only for the last column (the way i would prefer) using setItemDelegateForColumn(), it didnt work. So i modified it and set it for the entire QTableView using setItemDelegate() reacting only to requests to the last column. It still wont work. Wont work means there are no error messages it just wont do what i say ;) It seems that none of the methods i reimplemented gets ever called except init(). So i guess im missing something fundamental. Ive extracted the relevant lines of code, KSCheckBoxDelegate is my subclass. This is the version where the delegate is set up for the entire QTableView. -- code from applications main class -- self.taglist = QTableView() self.tagmodel = QSqlTableModel() self.tagmodel.setTable("data") self.tagmodel.select() self.taglist.setModel(self.tagmodel) print self.taglist.itemDelegate() myDel = KSCheckBoxDelegate(self) myDel.colnumber = 3 self.taglist.setItemDelegate(myDel) -- KSCheckBoxDelegate.py -- from PyQt4.QtGui import * class KSCheckBoxDelegate(QStyledItemDelegate): colnumber = None def __init__ (self, parent = None): print "KSCheckBoxDelegate::init" QStyledItemDelegate.__init__(self, parent) def createEditor(self, parent, option, index): print "KSCheckBoxDelegate::createEditor" if index.column()==self.colnumber: return QCheckBox(self) else: return QStyledItemDelegate.createEditor(self, parent, option, index) def setEditorData (self, editor, index): print "KSCheckBoxDelegate::setEditorData" if index.column() == self.colnumber: cont = index.model().data(index, Qt.DisplayRole).toString() if cont == "1": editor.setCheckState(Qt.Checked) else: editor.setCheckState(Qt.UnChecked) else: QStyledItemDelegate.setEditorData(self,editor, index) def setModelData (self, editor, model, index): print "KSCheckBoxDelegate::setModelData" if index.column() == self.colnumber: if editor.checkBox.checkState() == Qt.Checked: model.setData(index, 1) else: model.setData(index, 0) else: QStyledItemDelegate.setModelData(self, editor, model, index) Any hints for me on that issue? Furthermore i have difficulties with the currentChanged() signal of the QTableViews selectionModel. Im printing the top right coordinates of the selection. I keep getting wrong indexes (not invalid) when clicking with the left mouse button. Using the cursor keys gets me the right indexes. Using selectionChanged() has the same behaviour. Im actually getting the coordinates of the second last selected cell of the QTableView. For instance im clicking on the coordinates <1,1> <2,1> the second click would show me the coordinates <1,1>. selInd = self.taglist.selectionModel().selectedIndexes() if(len(selInd) > 0): self.xPosData=selInd[0].column() self.yPosData=selInd[0].row() Fixed that by myself, with using QTableView.currentIndex() instead of selectionModel.selectedIndexes() :) And last off using OnManualSubmit as editStrategy doesnt throw an error (return false) when calling submitAll() but doesnt save the data either. It works with choosing OnFieldChange as editStrategy. Which i can live with but is not was i have intended to do. Thanks for your time. Horst
[ "I think it would be simpler to create your own model basing QSqlTableModel, and for your 0/1 column return QVariant() for QDisplayRole and return Qt::Checked/Qt::Unchecked for Qt::CheckStateRole depending on value. For all other cases return QSqlTableModel::data\nclass MySqlTableModel: public QSqlTableModel\n{\npu...
[ 1, 0 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0003811862_pyqt_pyqt4_python_qt_qt4.txt
Q: Problem with web code generator designer I want to write a web-based code generator for a Python crawler. Its aim is to automatically generate code so a developer doesn't need to write it, but I've run into this problem: in one of my project's webpages, there are some checkboxes, buttons, etc. Each of them generates some Python code and writes it to a common textarea. However, when I uncheck boxes I can't figure out how to remove the corresponding code from the textarea, because it's all been mixed together. For example: Check box 1 -- it writes code snippet 1 to the textarea Check box 2 -- it writes code snippet 2 to the textarea Check box 3 -- it writes code snippet 3 to the textarea Uncheck box 2 -- it needs to somehow remove code snippet 2 from the text area, but leave behind code snippets 1 and 3 Is there some way to fix this problem, or any better solution for the whole code generator project? A: You need to separate out the idea of what code to generate from the events triggering generation. What code is generated is governed by the combined set of all the checkboxes that are checked. Triggering code generation occurs each time any of them are changed. You need to regenerate everything at that time. In detail: Check box 1 -- triggers generation, just code for snippet 1 included Check box 2 -- triggers generation, code for snippets 1 & 2 included Check box 3 -- triggers generation, code for snippets 1, 2 & 3 included Uncheck box 2 -- triggers generation, code for snippets 1 & 3 included
Problem with web code generator designer
I want to write a web-based code generator for a Python crawler. Its aim is to automatically generate code so a developer doesn't need to write it, but I've run into this problem: in one of my project's webpages, there are some checkboxes, buttons, etc. Each of them generates some Python code and writes it to a common textarea. However, when I uncheck boxes I can't figure out how to remove the corresponding code from the textarea, because it's all been mixed together. For example: Check box 1 -- it writes code snippet 1 to the textarea Check box 2 -- it writes code snippet 2 to the textarea Check box 3 -- it writes code snippet 3 to the textarea Uncheck box 2 -- it needs to somehow remove code snippet 2 from the text area, but leave behind code snippets 1 and 3 Is there some way to fix this problem, or any better solution for the whole code generator project?
[ "You need to separate out the idea of what code to generate from the events triggering generation.\nWhat code is generated is governed by the combined set of all the checkboxes that are checked.\nTriggering code generation occurs each time any of them are changed. You need to regenerate everything at that time.\nIn...
[ 0 ]
[]
[]
[ "code_generation", "python", "robot", "web_crawler" ]
stackoverflow_0003829405_code_generation_python_robot_web_crawler.txt
Q: Google appengine-db.key() Hi am going through the docs of GAE and needed a small clarification. If I have my db model something like this:- class Phone(Model): phone_name = db.StringProperty() r = Phone(Nokia, key_name='first') r.put() Now if I have to retrieve this entity but I dont know the key, can I construct the key like this: k=db.Key('Phone','first') and once the key is constructed, can the entity be retrieved like this:- r=db.get(k) A: You're close. The only major difference is that you have to pass the actual class instead of a string representing the class name, and that you have to use the Key.from_path() factory method rather than the default constructor: class Phone(Model): phone_name = db.StringProperty() r = Phone(phone_name='Nokia', key_name='first') r.put() k = db.Key.from_path('Phone', 'first') r = db.get(k) On the whole, however, I have found that relying on auto-generated IDs is usually a better solution than specifying your own key names. Is there a particular reason you're doing the latter?
Google appengine-db.key()
Hi am going through the docs of GAE and needed a small clarification. If I have my db model something like this:- class Phone(Model): phone_name = db.StringProperty() r = Phone(Nokia, key_name='first') r.put() Now if I have to retrieve this entity but I dont know the key, can I construct the key like this: k=db.Key('Phone','first') and once the key is constructed, can the entity be retrieved like this:- r=db.get(k)
[ "You're close. The only major difference is that you have to pass the actual class instead of a string representing the class name, and that you have to use the Key.from_path() factory method rather than the default constructor:\nclass Phone(Model):\n phone_name = db.StringProperty()\n\nr = Phone(phone_name='Nokia...
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003829740_google_app_engine_python.txt
Q: adding a subpackage from a different path I have a python package called zypp. It is generated via swig and the rpm package (called python-zypp) puts it in: rpm -ql python-zypp /usr/lib64/python2.6/site-packages/_zypp.so /usr/lib64/python2.6/site-packages/zypp.py Now, I have a different project which provides an additional sets of APIs. Pure python. Plus some scripts. The layout is: bin/script1 python python/zypp python/zypp/plugins.py python/zypp/__init__.py plugins.py contains a Plugin class. I intended to put this in an rpm, and put it into /usr/lib64/python2.6/site-packages/zypp/plugins.py script1 uses this Plugin class. But as I test it running from git, I would like it to find the module from git too if it is not installed. So it has something like: sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../python')) from zypp.plugins import Plugin However, it seems that if python-zypp is installed on /usr/lib64/python2.6/site-packages/zypp.py, then script1 won't find the plugins submodule anymore. If I uninstall python-zypp, it does. So my question is if it is possible to extend a module by adding submodules, being the submodules being located in a different load path. Or will they always clash? An analogy would be, I have a module foo. And I provide foo.extras in a different load path (which may use foo indeed). The script won't find foo.extras if foo is found first in the system load path. If I only use the custom load path, the script may not find foo module if foo.extras uses it. I have more experience with ruby, but in ruby I could have installed: /usr/lib64/ruby/gems/1.8/gems/foo-1.0/lib/foo/* And I could have in my script: bin/script lib/foo/extras/* I could do in script: $: << File.join(File.dirname(__FILE__), "../lib" and then my script could require foo require foo/extras No mater if foo/extras is installed on the system or in the custom load path. They don't clash. The other way around, I found out that with PYTHONPATH the local zypp.plugins is found first. But then the installed zypp module is not found: import zypp # works, but seems to import the local one from zypp.plugins import Plugin # works, PYTHONPATH finds it first repoinfo = zypp.RepoInfo() # does not work A: If I understand your question correctly, you want to use the development version of that module instead of the installed module. Therefore, you can use PYTHONPATH From the Module Search Path documentation: When a module named spam is imported, the interpreter searches for a file named spam.py in the current directory, and then in the list of directories specified by the environment variable PYTHONPATH. This has the same syntax as the shell variable PATH, that is, a list of directory names. When PYTHONPATH is not set, or when the file is not found there, the search continues in an installation-dependent default path; on Unix, this is usually .:/usr/local/lib/python. So, if the GIT tree of the module directory was "/home/username/some/path", you would change the PYTHONPATH to "/home/username/some/path". Or if the PYTHONPATH variable is already in use, you would append ":/home/username/some/path" to it (note the colon separator). In order to make this permanent, add the line "PYTHONPATH=value" to the file "/etc/environment". sys.path.insert If you have a start script for your program, you could override the module search path using sys.path.insert(0, "somepath"). This is similar to the sys.path.append call you described but inserts the path into the beginning of the list.
adding a subpackage from a different path
I have a python package called zypp. It is generated via swig and the rpm package (called python-zypp) puts it in: rpm -ql python-zypp /usr/lib64/python2.6/site-packages/_zypp.so /usr/lib64/python2.6/site-packages/zypp.py Now, I have a different project which provides an additional sets of APIs. Pure python. Plus some scripts. The layout is: bin/script1 python python/zypp python/zypp/plugins.py python/zypp/__init__.py plugins.py contains a Plugin class. I intended to put this in an rpm, and put it into /usr/lib64/python2.6/site-packages/zypp/plugins.py script1 uses this Plugin class. But as I test it running from git, I would like it to find the module from git too if it is not installed. So it has something like: sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../python')) from zypp.plugins import Plugin However, it seems that if python-zypp is installed on /usr/lib64/python2.6/site-packages/zypp.py, then script1 won't find the plugins submodule anymore. If I uninstall python-zypp, it does. So my question is if it is possible to extend a module by adding submodules, being the submodules being located in a different load path. Or will they always clash? An analogy would be, I have a module foo. And I provide foo.extras in a different load path (which may use foo indeed). The script won't find foo.extras if foo is found first in the system load path. If I only use the custom load path, the script may not find foo module if foo.extras uses it. I have more experience with ruby, but in ruby I could have installed: /usr/lib64/ruby/gems/1.8/gems/foo-1.0/lib/foo/* And I could have in my script: bin/script lib/foo/extras/* I could do in script: $: << File.join(File.dirname(__FILE__), "../lib" and then my script could require foo require foo/extras No mater if foo/extras is installed on the system or in the custom load path. They don't clash. The other way around, I found out that with PYTHONPATH the local zypp.plugins is found first. But then the installed zypp module is not found: import zypp # works, but seems to import the local one from zypp.plugins import Plugin # works, PYTHONPATH finds it first repoinfo = zypp.RepoInfo() # does not work
[ "If I understand your question correctly, you want to use the development version of that module instead of the installed module. Therefore, you can use\n\nPYTHONPATH\nFrom the Module Search Path documentation:\n\nWhen a module named spam is imported, the interpreter searches for a file named spam.py in the current...
[ 2 ]
[]
[]
[ "load_path", "python" ]
stackoverflow_0003829779_load_path_python.txt
Q: Open source Twitter clone (in Ruby/Python) Is there any production ready open source twitter clones written in Ruby or Python ? I am more interested in feature rich implementations, not just bare bones twitter like messages (e.g.: APIs, FBconnect, Notifications, etc) Thanks ! A: I know of twissandra which is an open source clone. Of course I doubt it meets your need of feature rich implementations. A: http://github.com/rnielsen/twetter From their readme: Twetter is an implementation of the twitter.com API, designed for use in situations where internet access is not available but a large number of people have twitter clients and want to tell each other what they are doing, for example a RailsCamp, where it was first developed. The current goal is to have it work with as many third party twitter clients as possible. It has currently been tested with Twitterific, TwitterFox, and Spaz on OSX. A: The following open source alternative to twitter : http://identi.ca/ is written using the the software http://status.net/ . It looks like it is written in PHP too. Also there is http://code.google.com/p/jaikuengine/ which is a microblogging platform for google app engine. This should serve as an example for python implementation. Also look at http://www.typepad.com/go/motion/ A: Found two relevant projects: http://github.com/insoshi/insoshi http://github.com/dmitryame/echowaves/wiki Sadly both appear discontinued
Open source Twitter clone (in Ruby/Python)
Is there any production ready open source twitter clones written in Ruby or Python ? I am more interested in feature rich implementations, not just bare bones twitter like messages (e.g.: APIs, FBconnect, Notifications, etc) Thanks !
[ "I know of twissandra which is an open source clone. Of course I doubt it meets your need of feature rich implementations.\n", "http://github.com/rnielsen/twetter\nFrom their readme:\nTwetter is an implementation of the twitter.com API, designed for use in situations where internet access is not available but a l...
[ 3, 2, 1, 0 ]
[]
[]
[ "python", "ruby", "twitter" ]
stackoverflow_0003758440_python_ruby_twitter.txt
Q: Python, using os.system - Is there a way for Python script to move past this without waiting for call to finish? I am trying to use Python (through Django framework) to make a Linux command line call and have tried both os.system and os.open but for both of these it seems that the Python script hangs after making the command line call as the call is for instantiating a server (so it never "finishes" as its meant to be long-running). I know for doing something like this with other Python code you can use something like celery but I figured there would be a simple way to get it to just make a command line call and not be "tied into it" so that it can just move past, I am wondering if I am doing something wrong... thanks for any advice. I am making the call like this currently os.system("command_to_start_server") also tried: response = os.popen("command_to_start_server") A: I'm not sure, but I think the subprocess module with its Popen is much more flexible than os.popen. If I recall correctly it includes asynchronous process spawning, which I think is what you're looking for. Edit: It's been a while since I used the subprocess module, but if I'm not mistaken, subprocess.Popen returns immediately, and only when you try to communicate with the process (such as reading its output) using subprocess.communicate does your program block waiting for output if there is none. A: You can use django-celery. django-celery provides Celery integration for Django. Celery is a task queue/job queue based on distributed message passing. See this http://ask.github.com/celery/getting-started/first-steps-with-django.html for tutorial how to use it. A: Try: os.system("command_to_start_server &>/dev/null &")
Python, using os.system - Is there a way for Python script to move past this without waiting for call to finish?
I am trying to use Python (through Django framework) to make a Linux command line call and have tried both os.system and os.open but for both of these it seems that the Python script hangs after making the command line call as the call is for instantiating a server (so it never "finishes" as its meant to be long-running). I know for doing something like this with other Python code you can use something like celery but I figured there would be a simple way to get it to just make a command line call and not be "tied into it" so that it can just move past, I am wondering if I am doing something wrong... thanks for any advice. I am making the call like this currently os.system("command_to_start_server") also tried: response = os.popen("command_to_start_server")
[ "I'm not sure, but I think the subprocess module with its Popen is much more flexible than os.popen. If I recall correctly it includes asynchronous process spawning, which I think is what you're looking for.\nEdit: It's been a while since I used the subprocess module, but if I'm not mistaken, subprocess.Popen retur...
[ 9, 2, 0 ]
[]
[]
[ "command_line", "django", "os.system", "python" ]
stackoverflow_0003830036_command_line_django_os.system_python.txt
Q: How to call a self.value in a class function definition in python? How could I call a self.value in a definition of a function? class toto : def __init__(self): self.titi = "titi" def printiti(self,titi=self.titi): print(titi) A: This is how it is done: def printiti(self, titi=None): if titi is None: titi = self.titi print titi This is a common python idiom (setting default value of argument to None and checking it in method's body). A: class Toto: def __init__(self): self.titi = "titi" def printiti(self, titi=None): if titi is None: titi = self.titi print(titi) Class names are generally Upper Case.
How to call a self.value in a class function definition in python?
How could I call a self.value in a definition of a function? class toto : def __init__(self): self.titi = "titi" def printiti(self,titi=self.titi): print(titi)
[ "This is how it is done:\n def printiti(self, titi=None):\n if titi is None:\n titi = self.titi\n print titi\n\nThis is a common python idiom (setting default value of argument to None and checking it in method's body).\n", "class Toto:\n def __init__(self):\n self.titi = \"titi\"\n\n de...
[ 6, 2 ]
[]
[]
[ "class", "function", "python", "self" ]
stackoverflow_0003830447_class_function_python_self.txt
Q: openid with django I found a lot of options but this one https://launchpad.net/django-openid-auth looks good. sadly I can't find examples/HOWTO about this?Does anyone point/redirect me to correct urls? A: Here is a little howto: http://bazaar.launchpad.net/~django-openid-auth/django-openid-auth/trunk/annotate/head:/README.txt Also you have exact usage examples here: http://bazaar.launchpad.net/~django-openid-auth/django-openid-auth/trunk/files/head:/example_consumer/ You could also look at this solution here - in my opinion much better documented: http://github.com/simonw/django-openid/tree/master/django_openid/docs/ Or you could use the best avaible solution (unfortunatelly not free), provided here: https://rpxnow.com/
openid with django
I found a lot of options but this one https://launchpad.net/django-openid-auth looks good. sadly I can't find examples/HOWTO about this?Does anyone point/redirect me to correct urls?
[ "Here is a little howto:\nhttp://bazaar.launchpad.net/~django-openid-auth/django-openid-auth/trunk/annotate/head:/README.txt\nAlso you have exact usage examples here:\nhttp://bazaar.launchpad.net/~django-openid-auth/django-openid-auth/trunk/files/head:/example_consumer/\nYou could also look at this solution here - ...
[ 4 ]
[]
[]
[ "django", "openid", "python" ]
stackoverflow_0003827861_django_openid_python.txt
Q: Can't configure node.js for make install on OS X (Snow Leopard) I cloned the node git repo but the "waf" build tool that comes with node seems to not work with the latest version of Python. $ ./configure Traceback (most recent call last): File "/Users/greim/nodestuff/node/tools/waf-light", line 157, in <module> import Scripting File "/Users/greim/nodestuff/node/tools/wafadmin/Scripting.py", line 146 except Utils.WafError, e: ^ SyntaxError: invalid syntax $ which python /Library/Frameworks/Python.framework/Versions/3.0/bin/python If I understand, that comma is an outdated syntax that doesn't work on Python 3, right? I'd rather not install an old version of Python just to do this. Ideally I'd like to be able to build and install the latest version, rather than depend on others to distribute .dmg files. Rock and hard place? Recommendations? [update] OK, so thanks to all who helped answer this question. Hopefully others will find this on Google. As it turns out I do have Python 2.x on my system (it comes installed by default on OS X) under /usr/bin. So the solution was to update my path (not permanently, just for this one bash session). $ export PATH=/usr/bin:$PATH $ ./configure $ make $ make install Tada! Node is installed on my system. A: Ithe waf project page says Compatibility from Python 2.3 to 3.1 is maintained (and Jython 2.5) I think it currently does this by running 2to3.py when unpacking so if you had run first with python2 then it might be wrong. The waf1.6 branch I think is python3 clean Reading the node.js code the node people expanded waf - which is not how you are meant to use waf. The idea is put the waf binary in the source code - this will expand using the correct version of python OSX does have python 2 so a way of running the build might be to edit the root makefile and replace the first line WAF=python tools/waf-light by WAF=/usr/bin/python tools/waf-light A: Yes the comma is outdated: see http://www.python.org/dev/peps/pep-3110/ Unfortunately, there's not much solution, if you stick with python3 you will have to modify the node code to make it work.
Can't configure node.js for make install on OS X (Snow Leopard)
I cloned the node git repo but the "waf" build tool that comes with node seems to not work with the latest version of Python. $ ./configure Traceback (most recent call last): File "/Users/greim/nodestuff/node/tools/waf-light", line 157, in <module> import Scripting File "/Users/greim/nodestuff/node/tools/wafadmin/Scripting.py", line 146 except Utils.WafError, e: ^ SyntaxError: invalid syntax $ which python /Library/Frameworks/Python.framework/Versions/3.0/bin/python If I understand, that comma is an outdated syntax that doesn't work on Python 3, right? I'd rather not install an old version of Python just to do this. Ideally I'd like to be able to build and install the latest version, rather than depend on others to distribute .dmg files. Rock and hard place? Recommendations? [update] OK, so thanks to all who helped answer this question. Hopefully others will find this on Google. As it turns out I do have Python 2.x on my system (it comes installed by default on OS X) under /usr/bin. So the solution was to update my path (not permanently, just for this one bash session). $ export PATH=/usr/bin:$PATH $ ./configure $ make $ make install Tada! Node is installed on my system.
[ "Ithe waf project page says \n\nCompatibility from Python 2.3 to 3.1 is maintained (and Jython 2.5)\n\nI think it currently does this by running 2to3.py when unpacking so if you had run first with python2 then it might be wrong. The waf1.6 branch I think is python3 clean\nReading the node.js code the node people ex...
[ 3, 1 ]
[]
[]
[ "node.js", "python", "waf" ]
stackoverflow_0003819313_node.js_python_waf.txt
Q: How to read pcks#7 personal digital certificates with python? is it possible to read personal digital certificates with extension Pcks#7 ( http://en.wikipedia.org/wiki/X.509#Certificate_filename_extensions ) with python? I have to develop an application using Django that authenticate its users by reading their certificate. In an initial step we are going to use an external services to accomplish this but it would be nice to understand how to develop a personal solution. Any information about the subject is higly appreciated, thanks! Federico A: You've tagged your question with "django" and you've mentioned logging in users using certificates. Sorry to say the rest of your question doesn't make much sense to me. If your question is "How to I authenticate users in my Django website using SSL certificate authentication?" Then my suggestion would be to use apache to handle the authentication: http://httpd.apache.org/docs/2.0/ssl/ssl_howto.html#accesscontrol And write yourself custom authentication backend to hook this up with Django. http://docs.djangoproject.com/en/dev/topics/auth/#authentication-backends Not tried it myself, I presume it's possible to get mod_ssl to place something useful in the request environment.
How to read pcks#7 personal digital certificates with python?
is it possible to read personal digital certificates with extension Pcks#7 ( http://en.wikipedia.org/wiki/X.509#Certificate_filename_extensions ) with python? I have to develop an application using Django that authenticate its users by reading their certificate. In an initial step we are going to use an external services to accomplish this but it would be nice to understand how to develop a personal solution. Any information about the subject is higly appreciated, thanks! Federico
[ "You've tagged your question with \"django\" and you've mentioned logging in users using certificates. Sorry to say the rest of your question doesn't make much sense to me.\nIf your question is \"How to I authenticate users in my Django website using SSL certificate authentication?\"\nThen my suggestion would be to...
[ 2 ]
[]
[]
[ "digital_certificate", "django", "python" ]
stackoverflow_0003829619_digital_certificate_django_python.txt
Q: textmate >> vim for python - teething troubles: especially indenting I'm (attempting) to move from textmate to vim [macvim to be exact] as my primary editor. I have already installed snipmate - wondering if there are other plugins you would suggest I install? In particular I seem to be having a lot of trouble with indenting (<< seems to really do some very strange/unpredictable things), and I can't seem to find a solution for this - are there plugins I need for this to work properly? Thanks! A: For source code, :h = In a nutshell, in normal mode inside a block you wish to work with: =a{ to re-indent a block. =a} and =aB work as well. =2a{ to re-indent this block and its outer block. If you happen to stand on a brace then =% will re-indent up to the matching brace. >a{ to increase the indent of this block. <a{ to decrease the indent of this block. . repeats the last command, so <a{. decreases the indent of this block twice. Make sure you have filetype set so Vim recognizes the filetype. Indenting is a function of the file type, after all. For text, :h gq gq{ will format this paragraph. gq( will format this sentence. gqgq will format this line. gggqG will format the entire document. A: Set the filetype setting in your vimrc file filetype plugin indent on That should enable filetype plugins and automatic indentation A: I am not sure what you need exactly as I have not used textmate. But I do use these Plugins for VIM. They have helped me a lot.
textmate >> vim for python - teething troubles: especially indenting
I'm (attempting) to move from textmate to vim [macvim to be exact] as my primary editor. I have already installed snipmate - wondering if there are other plugins you would suggest I install? In particular I seem to be having a lot of trouble with indenting (<< seems to really do some very strange/unpredictable things), and I can't seem to find a solution for this - are there plugins I need for this to work properly? Thanks!
[ "For source code,\n:h =\n\nIn a nutshell, in normal mode inside a block you wish to work with:\n\n=a{ to re-indent a block. =a} and =aB work as well.\n=2a{ to re-indent this block and its outer block.\nIf you happen to stand on a brace then =% will re-indent up to the matching brace.\n>a{ to increase the indent of ...
[ 2, 2, 0 ]
[]
[]
[ "macvim", "python", "textmate", "vim" ]
stackoverflow_0003830334_macvim_python_textmate_vim.txt
Q: How do I get some slot/function to be executed when a certain QTableWidgetItem is checked / unchecked in PyQt I have a dynamically created table, that has N rows and M QTableWidgetItems (that are only used as checkboxes) per row - I need to run code that knows the row and the column whenever a checkbox is checked or unchecked. My CheckBox subclass looks like: class CheckBox(QTableWidgetItem): def __init__(self): QTableWidgetItem.__init__(self,1000) self.setTextAlignment(Qt.AlignVCenter | Qt.AlignJustify) self.setFlags(Qt.ItemFlags( Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled )) def stateChanged(self): do_something(self.row(),self.column()) ... Obviously this does not redefine the function that gets called when SIGNAL('stateChanged(int)') -thingy happens, because, well, nothing happens. But, if I do: item = CheckBox() self.connect(item, SIGNAL('stateChanged(int)'), item.stateChanged) In the loop creating the table, I get an error: TypeError: arguments did not match any overloaded call: QObject.connect(QObject, SIGNAL(), QObject, SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'CheckBox' QObject.connect(QObject, SIGNAL(), callable, Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'CheckBox' QObject.connect(QObject, SIGNAL(), SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'CheckBox EDIT: I also tried redefining setCheckState() but apparently that does NOT get called when the item is checked or unchecked. EDIT 2: Furthermore, changing the connect to self.connect(self.table, SIGNAL('itemClicked(item)'), self.table.stateChanged) where table = QTableWidget() does not help either. How do I do this the right way? A: The simplest solution is probably connecting to the cellChanged(int, int) signal of the QTableWidget; take a look at the following example: import sys from PyQt4.QtGui import * from PyQt4.QtCore import * #signal handler def myCellChanged(row, col): print row, col #just a helper function to setup the table def createCheckItem(table, row, col): check = QTableWidgetItem("Test") check.setCheckState(Qt.Checked) table.setItem(row,col,check) app = QApplication(sys.argv) #create the 5x5 table... table = QTableWidget(5,5) map(lambda (row,col): createCheckItem(table, row, col), [(row, col) for row in range(0, 5) for col in range(0, 5)]) table.show() #...and connect our signal handler to the cellChanged(int, int) signal QObject.connect(table, SIGNAL("cellChanged(int, int)"), myCellChanged) app.exec_() It creates a 5x5 table of checkboxes; whenever one of them is checked/unchecked, myCellChanged is called and prints the row and column of the changed checkbox; you can then of course use QTableWidget.item(someRow, someColumn).checkState() to see whether it was checked or unchecked.
How do I get some slot/function to be executed when a certain QTableWidgetItem is checked / unchecked in PyQt
I have a dynamically created table, that has N rows and M QTableWidgetItems (that are only used as checkboxes) per row - I need to run code that knows the row and the column whenever a checkbox is checked or unchecked. My CheckBox subclass looks like: class CheckBox(QTableWidgetItem): def __init__(self): QTableWidgetItem.__init__(self,1000) self.setTextAlignment(Qt.AlignVCenter | Qt.AlignJustify) self.setFlags(Qt.ItemFlags( Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled )) def stateChanged(self): do_something(self.row(),self.column()) ... Obviously this does not redefine the function that gets called when SIGNAL('stateChanged(int)') -thingy happens, because, well, nothing happens. But, if I do: item = CheckBox() self.connect(item, SIGNAL('stateChanged(int)'), item.stateChanged) In the loop creating the table, I get an error: TypeError: arguments did not match any overloaded call: QObject.connect(QObject, SIGNAL(), QObject, SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'CheckBox' QObject.connect(QObject, SIGNAL(), callable, Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'CheckBox' QObject.connect(QObject, SIGNAL(), SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'CheckBox EDIT: I also tried redefining setCheckState() but apparently that does NOT get called when the item is checked or unchecked. EDIT 2: Furthermore, changing the connect to self.connect(self.table, SIGNAL('itemClicked(item)'), self.table.stateChanged) where table = QTableWidget() does not help either. How do I do this the right way?
[ "The simplest solution is probably connecting to the cellChanged(int, int) signal of the QTableWidget; take a look at the following example: \nimport sys\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\n\n#signal handler\ndef myCellChanged(row, col):\n print row, col\n\n#just a helper function to setup t...
[ 2 ]
[]
[]
[ "pyqt4", "python", "qt4", "qtablewidget", "qtablewidgetitem" ]
stackoverflow_0003829349_pyqt4_python_qt4_qtablewidget_qtablewidgetitem.txt
Q: Is there a more elegant / pythonic way to express this construct? itemList = ["a","b","c","d","e","f","g","h"] aa = "NULL" bb = "NULL" cc = "NULL" for item in itemList: aa = bb bb = cc cc = item if aa == "NULL": continue print "%s_%s_%s" % (aa, bb, cc) A: >>> ['_'.join(itemList[i:i+3]) for i in range(len(itemList)-2)] ['a_b_c', 'b_c_d', 'c_d_e', 'd_e_f', 'e_f_g', 'f_g_h'] or if you insist on printing: >>> for i in range(len(itemList)-2): print('_'.join(itemList[i:i+3])) A: import itertools def windows(iterable, length=2): return itertools.izip(*(itertools.islice(it,n,None) for n,it in enumerate(itertools.tee(iterable,length)))) itemList = ["a","b","c","d","e","f","g","h"] for group in windows(itemList,length=3): print('_'.join(group)) SilentGhost's elegant list comprehension is better for this problem. But just to explain why I'm not deleting this post: You may one day want to generate windows from an iterator which is not a list. Since you can't take the length of an iterator without consuming it, (and also since some iterators may be infinite), and since taking slices from an iterator always return new values, you can't use the list comprehension ['_'.join(itemList[i:i+3]) for i in range(len(itemList)-2)] in this case. Then the windows function is actually useful. For example: def itemList(): for x in range(8): yield str(x) for group in windows(itemList(),length=3): print('_'.join(group)) yields 0_1_2 1_2_3 2_3_4 3_4_5 4_5_6 5_6_7 A: You could use a deque. itemList = ["a","b","c","d","e","f","g","h"] buffer = collections.deque(maxlen=3) for item in itemList: buffer.append(item) if len(buffer) != 3: continue print "%s_%s_%s" % (buffer) I don't have a Python interpreter available right now, but I think this should work.
Is there a more elegant / pythonic way to express this construct?
itemList = ["a","b","c","d","e","f","g","h"] aa = "NULL" bb = "NULL" cc = "NULL" for item in itemList: aa = bb bb = cc cc = item if aa == "NULL": continue print "%s_%s_%s" % (aa, bb, cc)
[ ">>> ['_'.join(itemList[i:i+3]) for i in range(len(itemList)-2)]\n['a_b_c', 'b_c_d', 'c_d_e', 'd_e_f', 'e_f_g', 'f_g_h']\n\nor if you insist on printing:\n>>> for i in range(len(itemList)-2):\n print('_'.join(itemList[i:i+3]))\n\n", "import itertools\ndef windows(iterable, length=2):\n return itertools.izip...
[ 9, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003830727_list_python.txt
Q: TypeError: instancemethod expected at least 2 arguments, got 0 Django 1.1.2 & Python 2.6.5 I keep getting this error when executing a seemingly innocent queryset. Looks exactly like the issue described in http://code.djangoproject.com/ticket/7204 However, I'm running Django 1.1.2, which is supposed to have the fix for this bug. Has anybody dealt with something similar before? Here's the code that constructs the query: def get_some_data(self, start_date, end_date): qset = Transaction.txn_objects.get_transactions_between(self.business, start_date, end_date) income_qset = qset.filter(invoiceitem__invoice__customer = self) income_qset = income_qset.exclude( account=F("invoiceitem__taxtypes__account_payable")) sums = income_qset.aggregate(models.Sum('credit_amount')) # fails here Here's an abridged version of the traceback (not very useful): File ".../models.py" in get_income_between 200. sums = income_qset.aggregate(models.Sum('credit_amount')) File ".../lib/python2.6/site-packages/django/db/models/query.py" in aggregate 274. query = self.query.clone() File ".../lib/python2.6/site-packages/django/db/models/sql/query.py" in clone 201. obj.where = deepcopy(self.where, memo=memo) File "/usr/lib/python2.6/copy.py" in deepcopy 173. y = copier(memo) File ".../lib/python2.6/site-packages/django/utils/tree.py" in __deepcopy__ 61. obj.children = deepcopy(self.children, memodict) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_list 228. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 173. y = copier(memo) File ".../lib/python2.6/site-packages/django/utils/tree.py" in __deepcopy__ 61. obj.children = deepcopy(self.children, memodict) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_list 228. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 173. y = copier(memo) File ".../lib/python2.6/site-packages/django/utils/tree.py" in __deepcopy__ 61. obj.children = deepcopy(self.children, memodict) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_list 228. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 173. y = copier(memo) File ".../lib/python2.6/site-packages/django/utils/tree.py" in __deepcopy__ 61. obj.children = deepcopy(self.children, memodict) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_list 228. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 323. y = callable(*args) File "/usr/lib/python2.6/copy_reg.py" in __newobj__ 93. return cls.__new__(cls, *args) Exception Type: TypeError at /reports/income_expense/by_customer/32/ Exception Value: instancemethod expected at least 2 arguments, got 0 A: For the benefit of whoever else might run into this, the error is caused by a combination of using django-multilingual and django.db's F object. Rewriting the code to eliminate F objects solved the issue. The root cause is actually a bug in Python, for more info see http://bugs.python.org/issue1515
TypeError: instancemethod expected at least 2 arguments, got 0
Django 1.1.2 & Python 2.6.5 I keep getting this error when executing a seemingly innocent queryset. Looks exactly like the issue described in http://code.djangoproject.com/ticket/7204 However, I'm running Django 1.1.2, which is supposed to have the fix for this bug. Has anybody dealt with something similar before? Here's the code that constructs the query: def get_some_data(self, start_date, end_date): qset = Transaction.txn_objects.get_transactions_between(self.business, start_date, end_date) income_qset = qset.filter(invoiceitem__invoice__customer = self) income_qset = income_qset.exclude( account=F("invoiceitem__taxtypes__account_payable")) sums = income_qset.aggregate(models.Sum('credit_amount')) # fails here Here's an abridged version of the traceback (not very useful): File ".../models.py" in get_income_between 200. sums = income_qset.aggregate(models.Sum('credit_amount')) File ".../lib/python2.6/site-packages/django/db/models/query.py" in aggregate 274. query = self.query.clone() File ".../lib/python2.6/site-packages/django/db/models/sql/query.py" in clone 201. obj.where = deepcopy(self.where, memo=memo) File "/usr/lib/python2.6/copy.py" in deepcopy 173. y = copier(memo) File ".../lib/python2.6/site-packages/django/utils/tree.py" in __deepcopy__ 61. obj.children = deepcopy(self.children, memodict) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_list 228. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 173. y = copier(memo) File ".../lib/python2.6/site-packages/django/utils/tree.py" in __deepcopy__ 61. obj.children = deepcopy(self.children, memodict) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_list 228. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 173. y = copier(memo) File ".../lib/python2.6/site-packages/django/utils/tree.py" in __deepcopy__ 61. obj.children = deepcopy(self.children, memodict) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_list 228. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 173. y = copier(memo) File ".../lib/python2.6/site-packages/django/utils/tree.py" in __deepcopy__ 61. obj.children = deepcopy(self.children, memodict) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_list 228. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_tuple 235. y.append(deepcopy(a, memo)) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 338. state = deepcopy(state, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 162. y = copier(x, memo) File "/usr/lib/python2.6/copy.py" in _deepcopy_dict 255. y[deepcopy(key, memo)] = deepcopy(value, memo) File "/usr/lib/python2.6/copy.py" in deepcopy 189. y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.6/copy.py" in _reconstruct 323. y = callable(*args) File "/usr/lib/python2.6/copy_reg.py" in __newobj__ 93. return cls.__new__(cls, *args) Exception Type: TypeError at /reports/income_expense/by_customer/32/ Exception Value: instancemethod expected at least 2 arguments, got 0
[ "For the benefit of whoever else might run into this, the error is caused by a combination of using django-multilingual and django.db's F object. Rewriting the code to eliminate F objects solved the issue. \nThe root cause is actually a bug in Python, for more info see http://bugs.python.org/issue1515\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003736112_django_python.txt
Q: Check memory usage of subprocess in Python I'm developing an application in Python on Ubuntu and I'm running external binaries from within python using subprocess. Since these binaries are generated at run time and can go rogue, I need to keep a strict tab on the amount of memory footprint and runtime of these binaries. Is there someway I can limit or monitor the memory usage of these binary programs at runtime? I would really hate to use something like "ps" in subprocess for this purpose. A: You can use Python's resource module to set limits before spawning your subprocess. For monitoring, resource.getrusage() will give you summarized information over all your subprocesses; if you want to see per-subprocess information, you can do the /proc trick in that other comment (non-portable but effective), or layer a Python program in between every subprocess and figure out some communication (portable, ugly, mildly effective). A: Having a PID number of your subprocess you can read all info from proc file-system. Use: /proc/[PID]/smaps (since Linux 2.6.14) This file shows memory consumption for each of the process's mappings. For each of mappings there is a series of lines as follows: or /proc/[PID]/statm Provides information about memory usage, measured in pages. Alternatively you can limit resources which subprocess can aquire with : subprocess.Popen('ulimit -v 1024; ls', shell=True) When given virtual memory limit is reached process fails with out of memory.
Check memory usage of subprocess in Python
I'm developing an application in Python on Ubuntu and I'm running external binaries from within python using subprocess. Since these binaries are generated at run time and can go rogue, I need to keep a strict tab on the amount of memory footprint and runtime of these binaries. Is there someway I can limit or monitor the memory usage of these binary programs at runtime? I would really hate to use something like "ps" in subprocess for this purpose.
[ "You can use Python's resource module to set limits before spawning your subprocess.\nFor monitoring, resource.getrusage() will give you summarized information over all your subprocesses; if you want to see per-subprocess information, you can do the /proc trick in that other comment (non-portable but effective), or...
[ 13, 6 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0003830658_python_subprocess.txt
Q: twisted: no exception trace if error from a callback Consider the following code: df = defer.Deferred() def hah(_): raise ValueError("4") df.addCallback(hah) df.callback(hah) When it runs, that exception just gets eaten. Where did it go? How can I get it to be displayed? Doing defer.setDebugging(True) has no effect. I ask this because other times, I get a printout saying "Unhandled error in Deferred:". How do I get that to happen in this case? I see that if I add an errback to df then the errback gets called with the exception, but all I want to do is print the error and do nothing else, and I don't want to manually add that handler to every deferred I create. A: The exception is still sitting in the Deferred. There are two possible outcomes at this point: You could add an errback to the Deferred. As soon as you do, it will get called with a Failure containing the exception that was raised. You could let the Deferred be garbage collected (explicitly delete df, or return from the function, or lose the reference in any other way). This triggers the ''Unhandled error in Deferred'' code. Because an errback can be added to a Deferred at any time (ie, the first point above), Deferreds don't do anything with otherwise unhandled errors right away. They don't know if the error is really unhandled, or just unhandled so far. It's only when the Deferred is garbage collected that it can be sure no one else is going to handle the exception, so that's when it gets logged. In general, you want to be sure you have errbacks on Deferreds, precisely because it's sometimes hard to predict when a Deferred will get garbage collected. It might be a long time, which means it might be a long time before you learn about the exception if you don't have your own errback attached. This doesn't have to be a terrible burden. Any Deferred (a) which is returned from a callback on another Deferred (b) (ie, when chaining happens) will pass its errors along to b. So (a) doesn't need extra errbacks on it for logging and reporting, only (b) does. If you have a single logical task which is complicated and involves many asynchronous operations, it's almost always the case that all of the Deferreds involved in those operations should channel their results (success or failure) to one main Deferred that represents the logical operation. You often only need special error handling behavior on that one Deferred, and that will let you handle errors from any of the other Deferreds involved.
twisted: no exception trace if error from a callback
Consider the following code: df = defer.Deferred() def hah(_): raise ValueError("4") df.addCallback(hah) df.callback(hah) When it runs, that exception just gets eaten. Where did it go? How can I get it to be displayed? Doing defer.setDebugging(True) has no effect. I ask this because other times, I get a printout saying "Unhandled error in Deferred:". How do I get that to happen in this case? I see that if I add an errback to df then the errback gets called with the exception, but all I want to do is print the error and do nothing else, and I don't want to manually add that handler to every deferred I create.
[ "The exception is still sitting in the Deferred. There are two possible outcomes at this point:\n\nYou could add an errback to the Deferred. As soon as you do, it will get called with a Failure containing the exception that was raised.\nYou could let the Deferred be garbage collected (explicitly delete df, or ret...
[ 7 ]
[]
[]
[ "deferred", "error_handling", "python", "twisted" ]
stackoverflow_0003826233_deferred_error_handling_python_twisted.txt
Q: ensuring dynamic image urls in a web-app: use a blob store? I want to serve images in a web-app using sessions such that the links to the images expire once the session has expired. If I show the actual links to the filesystem store of the images, say http://www.mywebapp.com/images/foo1.jpg this clearly makes stopping future requests for the image (one the user has signed out of the session) difficult to stop. Which is why I was considering placing the images in a sqlite db, and serving them from there. It seems that using the db for image storage is considered bad practice (though apparently the GAE blob store seems to provide this functionality), so i was trying to figure out what the alternatives would be. 1) Perhaps I do somesort of url-re-writing like so: http://www.mywebapp.com/images/[session_id]/foo1.jpg Thinking of using nginx, but it seems (on a first look) that this will require some hackin to accomplish? 2) Copy the files to a physical directory on the filesystem and delete when the session expires. this seems quite messy though? Are there any standard methods of accomplishing this dynamic image url thing? I'm using web.py - if that helps. Many thanks! A: lighty's mod_secdownload has worked well for me to solve this issue. You can read more about it at http://redmine.lighttpd.net/wiki/1/Docs:ModSecDownload The lighttpd wiki also has a generic article about your problem: http://redmine.lighttpd.net/wiki/1/HowToFightDeepLinking A: Why so complicated? Serve the image under the name which the user supplied (i.e. http://www.mywebapp.com/images/foo1.jpg) Save the images in a directory using a UUID as name. Create a map of file names to UUIDs in the session. In the handler for /images/ look up the real file name in the map. Return 404 if no such entry exists. Otherwise serve the image. When the session is closed, delete all files from the map. In a cron job, delete all images that are older than one day. This way, several users can upload the same image (same name), images get deleted as soon as possible or by the cron job (if the server crashes or something like that).
ensuring dynamic image urls in a web-app: use a blob store?
I want to serve images in a web-app using sessions such that the links to the images expire once the session has expired. If I show the actual links to the filesystem store of the images, say http://www.mywebapp.com/images/foo1.jpg this clearly makes stopping future requests for the image (one the user has signed out of the session) difficult to stop. Which is why I was considering placing the images in a sqlite db, and serving them from there. It seems that using the db for image storage is considered bad practice (though apparently the GAE blob store seems to provide this functionality), so i was trying to figure out what the alternatives would be. 1) Perhaps I do somesort of url-re-writing like so: http://www.mywebapp.com/images/[session_id]/foo1.jpg Thinking of using nginx, but it seems (on a first look) that this will require some hackin to accomplish? 2) Copy the files to a physical directory on the filesystem and delete when the session expires. this seems quite messy though? Are there any standard methods of accomplishing this dynamic image url thing? I'm using web.py - if that helps. Many thanks!
[ "lighty's mod_secdownload has worked well for me to solve this issue. You can read more about it at http://redmine.lighttpd.net/wiki/1/Docs:ModSecDownload\nThe lighttpd wiki also has a generic article about your problem: http://redmine.lighttpd.net/wiki/1/HowToFightDeepLinking\n", "Why so complicated? \nServe the...
[ 2, 1 ]
[ "A combination of your two ideas (copy to a dir, expire when session expires) could be generalized to creating a new dir (could be as simple as a symlink) every 15 minutes. When generating the new symlink, also remove the one that's an hour old by now. Always link to the newest name in your code.\n" ]
[ -1 ]
[ "blob", "nginx", "python", "sqlite", "web_applications" ]
stackoverflow_0003830294_blob_nginx_python_sqlite_web_applications.txt
Q: dynamic values in kwargs I have a layer which helps me populating records from the form to tables and viceversa, it does some input checking, etc. Now several methods of this layer which are called several times in different parts of the webform take the same parameters, so I wanted to pack them at the begining of the codefile. kwargs(): return {"tabla":"nombre_tabla","id":[hf_id.Value] ,"container": Panel1,"MsgBox1": MsgBox1} then I call IA.search(**kwargs) but doing that way the values of the dictionary get fixed with the ones they had in the begining, and one of them is retrieved from a webcontrol so it needs to be dynamic. So I wrapped them in a function def kwargs(): return {"tabla":"nombre_tabla", "id":[hf_id.Value] ,"container": Panel1,"MsgBox1": MsgBox1} and then I call IA.search(*kwargs()) IA.save(*kwargs()) etc. and that way the value of the dictionary which comes from the webform (hf_id) is dynamic and not fixed. But I was wondering if in this case there is another way, a pythonic way, to get the values of the dictionary kwargs to be dynamic and not fixed A: Python objects are pointers (though they are not directly manipulatable by the user.) So if you create a list like this: >>> a = [1, 2, 3] and then store it in a dictionary: >>> b = { 'key': a, 'anotherkey': 'spam' } you will find modifications to the value in the dictionary also modify the original list: >>> b['key'].append(4) >>> print b['key'] [1, 2, 3, 4] >>> print a [1, 2, 3, 4] If you want a copy of an item, so that modifications will not change the original item, then use the copy module. >>> from copy import copy >>> a = [1, 2, 3] >>> b['key'] = copy(a) >>> print b['key'] [1, 2, 3] >>> b['key'].append(4) >>> print b['key'] [1, 2, 3, 4] >>> print a [1, 2, 3]
dynamic values in kwargs
I have a layer which helps me populating records from the form to tables and viceversa, it does some input checking, etc. Now several methods of this layer which are called several times in different parts of the webform take the same parameters, so I wanted to pack them at the begining of the codefile. kwargs(): return {"tabla":"nombre_tabla","id":[hf_id.Value] ,"container": Panel1,"MsgBox1": MsgBox1} then I call IA.search(**kwargs) but doing that way the values of the dictionary get fixed with the ones they had in the begining, and one of them is retrieved from a webcontrol so it needs to be dynamic. So I wrapped them in a function def kwargs(): return {"tabla":"nombre_tabla", "id":[hf_id.Value] ,"container": Panel1,"MsgBox1": MsgBox1} and then I call IA.search(*kwargs()) IA.save(*kwargs()) etc. and that way the value of the dictionary which comes from the webform (hf_id) is dynamic and not fixed. But I was wondering if in this case there is another way, a pythonic way, to get the values of the dictionary kwargs to be dynamic and not fixed
[ "Python objects are pointers (though they are not directly manipulatable by the user.)\nSo if you create a list like this:\n>>> a = [1, 2, 3]\n\nand then store it in a dictionary:\n>>> b = { 'key': a, 'anotherkey': 'spam' }\n\nyou will find modifications to the value in the dictionary also modify the original list:...
[ 2 ]
[]
[]
[ "asp.net", "ironpython", "python", "webforms" ]
stackoverflow_0003830530_asp.net_ironpython_python_webforms.txt
Q: Advanced sorting criteria for a list of nested tuples I have a list of nested tuples of the form: [(a, (b, c)), ...] Now I would like to pick the element which maximizes a while minimizing b and c at the same time. For example in [(7, (5, 1)), (7, (4, 1)), (6, (3, 1))] the winner should be (7, (4, 1)) Any help is appreciated. A: >>> max(lst, key=lambda x: (x[0], -x[1][0], -x[1][1])) (7, (4, 1)) A: In my understanding, you want to sort decreasingly by a, and ascendingly by b, then by c. If that's right, you can do it like so: >>> l=[(7, (5, 1)), (7, (4, 1)), (6, (3, 2)), (6, (3, 1))] >>> sorted(l, key = lambda x: (-x[0], x[1])) [(7, (4, 1)), (7, (5, 1)), (6, (3, 1)), (6, (3, 2))] Picking the "winner" would be as simple as picking the first element. If b and c should be summed up, it would simply be sum(x[1]) instead of x[1] in my example. My key function returns a tuple because Python correctly sorts tuples containing multiple elements: >>> sorted([(1,2), (1,1), (1,-1), (0,5)]) [(0, 5), (1, -1), (1, 1), (1, 2)]
Advanced sorting criteria for a list of nested tuples
I have a list of nested tuples of the form: [(a, (b, c)), ...] Now I would like to pick the element which maximizes a while minimizing b and c at the same time. For example in [(7, (5, 1)), (7, (4, 1)), (6, (3, 1))] the winner should be (7, (4, 1)) Any help is appreciated.
[ ">>> max(lst, key=lambda x: (x[0], -x[1][0], -x[1][1]))\n(7, (4, 1))\n\n", "In my understanding, you want to sort decreasingly by a, and ascendingly by b, then by c. If that's right, you can do it like so:\n>>> l=[(7, (5, 1)), (7, (4, 1)), (6, (3, 2)), (6, (3, 1))]\n>>> sorted(l, key = lambda x: (-x[0], x[1]))\n[...
[ 4, 4 ]
[]
[]
[ "list", "python", "sorting", "tuples" ]
stackoverflow_0003831449_list_python_sorting_tuples.txt
Q: New to Python: Replacing a string by its position in a line Let's say I got a file with three lines of this structure: foo Black sheep: 500 bar What I'd like to do is an iteration to change "Black sheep: 500" to 600, 700 and so on, replacing the old one. I can think of a way of doing it by search&replace, but I'm looking for a more elegant way by replacing a certain position (here pos.3) within the line. For example, in awk/shellscripting, it works like this: cat filename | awk '$1 ~ /Black:/ { print ($1, $2, 600); next }; { print $0 }' awk looks for "Black" in the file and prints the words number one, number two and 600 as well as the rest of the file. Is there something similar in Python? Thank you A: We can simply mimick the awk behaviour in a couple of lines :) for line in lines: if line.startswith('Black'): line_parts = line.split() print line_parts[0], line_parts[1], 600 else: print line Cause that's basically what awk does, split on whitespace. A: >>> for line in open("file"): ... sl=line.split() ... if "Black" in sl[0] : ... sl[2]="600" ... line=' '.join(sl) ... print line.rstrip() ... foo Black sheep: 600 bar
New to Python: Replacing a string by its position in a line
Let's say I got a file with three lines of this structure: foo Black sheep: 500 bar What I'd like to do is an iteration to change "Black sheep: 500" to 600, 700 and so on, replacing the old one. I can think of a way of doing it by search&replace, but I'm looking for a more elegant way by replacing a certain position (here pos.3) within the line. For example, in awk/shellscripting, it works like this: cat filename | awk '$1 ~ /Black:/ { print ($1, $2, 600); next }; { print $0 }' awk looks for "Black" in the file and prints the words number one, number two and 600 as well as the rest of the file. Is there something similar in Python? Thank you
[ "We can simply mimick the awk behaviour in a couple of lines :)\nfor line in lines:\n if line.startswith('Black'):\n line_parts = line.split()\n print line_parts[0], line_parts[1], 600\n else:\n print line\n\nCause that's basically what awk does, split on whitespace.\n", ">>> for line i...
[ 0, 0 ]
[]
[]
[ "python", "replace" ]
stackoverflow_0003831562_python_replace.txt
Q: mod_python Apache configuration I am having issues with getting my Mod Python to work properly. I have followed mod_python manual found here So here is my Apache setup (I am using Virtual Hosts): <VirtualHost *:80> ServerName hostname DocumentRoot "C:/Documents and Settings/username/hostname/www" <Directory "C:/Documents and Settings/username/hostname"> DirectoryIndex index.py AddHandler mod_python .py PythonHandler www.index PythonDebug On </Directory> </VirtualHost> Here is my handler index.py: from mod_python import apache def handler(req): req.content_type = "text\plain" req.write("Hello World!") return apache.OK After setting all that up I get the following error: ImportError: No module named www.index NOTE: The reason I am adding www to index, is because that is what the mod_python tutorial stated: Attempt to import a module by name myscript. (Note that if myscript was in a subdirectory of the directory where PythonHandler was specified, then the import would not work because said subdirectory would not be in the sys.path. One way around this is to use package notation, e.g. "PythonHandler subdir.myscript".) If I use mod_python.publisher as my PythonHandler, everything works fine. Not sure what I am missing here. A: I figured it out. My Directory did not match my DocumentRoot. I appreciate the replies regarding mod_wsgi. I will eventually move to wsgi but I am still learning how to use Python for web development and I basically defaulted to learn using mod_python. A: If you can stop using mod_python as it is abandoned now. mod_wsgi is the way to go.
mod_python Apache configuration
I am having issues with getting my Mod Python to work properly. I have followed mod_python manual found here So here is my Apache setup (I am using Virtual Hosts): <VirtualHost *:80> ServerName hostname DocumentRoot "C:/Documents and Settings/username/hostname/www" <Directory "C:/Documents and Settings/username/hostname"> DirectoryIndex index.py AddHandler mod_python .py PythonHandler www.index PythonDebug On </Directory> </VirtualHost> Here is my handler index.py: from mod_python import apache def handler(req): req.content_type = "text\plain" req.write("Hello World!") return apache.OK After setting all that up I get the following error: ImportError: No module named www.index NOTE: The reason I am adding www to index, is because that is what the mod_python tutorial stated: Attempt to import a module by name myscript. (Note that if myscript was in a subdirectory of the directory where PythonHandler was specified, then the import would not work because said subdirectory would not be in the sys.path. One way around this is to use package notation, e.g. "PythonHandler subdir.myscript".) If I use mod_python.publisher as my PythonHandler, everything works fine. Not sure what I am missing here.
[ "I figured it out. My Directory did not match my DocumentRoot.\nI appreciate the replies regarding mod_wsgi. I will eventually move to wsgi but I am still learning how to use Python for web development and I basically defaulted to learn using mod_python.\n", "If you can stop using mod_python as it is abandoned no...
[ 1, 0 ]
[]
[]
[ "mod_python", "python" ]
stackoverflow_0003831332_mod_python_python.txt
Q: Django randomly order users in admin I am trying to create a Django admin filter that will get random groups of users. At this point, I have two problems: Applying a custom filter to the User model, and Displaying a random set of users. On #1, I've tried using User.username.random_filter = True, but it comes back with an AttributeError saying that User has no attribute username. On #2, I know I can get 50 random users with User.objects.order_by('?')[:50], but I have not been able to figure out how to get the result of such a query to show up in the admin listing. As far as I can tell, the listing is generated by the URL's GET request, but I've not had any luck ordering with it. Any suggestions? A: If I were you (and I am), I would stop trying to integrate this functionality with the Django admin site. Speaking from experience, you'll find that what you're trying to do is much easier to implement as regular views. Sure, it isn't be as pretty, but something that works beats something that's pretty but doesn't work, right? A: It should be fairly easy to do, just create a ModelAdmin with a ordering property. Something like this should do: class UserAdmin(ModelAdmin): ordering = ('?',)
Django randomly order users in admin
I am trying to create a Django admin filter that will get random groups of users. At this point, I have two problems: Applying a custom filter to the User model, and Displaying a random set of users. On #1, I've tried using User.username.random_filter = True, but it comes back with an AttributeError saying that User has no attribute username. On #2, I know I can get 50 random users with User.objects.order_by('?')[:50], but I have not been able to figure out how to get the result of such a query to show up in the admin listing. As far as I can tell, the listing is generated by the URL's GET request, but I've not had any luck ordering with it. Any suggestions?
[ "If I were you (and I am), I would stop trying to integrate this functionality with the Django admin site. Speaking from experience, you'll find that what you're trying to do is much easier to implement as regular views. Sure, it isn't be as pretty, but something that works beats something that's pretty but doesn't...
[ 1, 0 ]
[]
[]
[ "customization", "django_admin", "python" ]
stackoverflow_0003822857_customization_django_admin_python.txt
Q: How do the compression codecs work in Python? I'm querying a database and archiving the results using Python, and I'm trying to compress the data as I write it to the log files. I'm having some problems with it, though. My code looks like this: log_file = codecs.open(archive_file, 'w', 'bz2') for id, f1, f2, f3 in cursor: log_file.write('%s %s %s %s\n' % (id, f1 or 'NULL', f2 or 'NULL', f3)) However, my output file has a size of 1,409,780. Running bunzip2 on the file results in a file with a size of 943,634, and running bzip2 on that results in a size of 217,275. In other words, the uncompressed file is significantly smaller than the file compressed using Python's bzip codec. Is there a way to fix this, other than running bzip2 on the command line? I tried Python's gzip codec (changing the line to codecs.open(archive_file, 'a+', 'zip')) to see if it fixed the problem. I still get large files, but I also get a gzip: archive_file: not in gzip format error when I try to uncompress the file. What's going on there? EDIT: I originally had the file opened in append mode, not write mode. While this may or may not be a problem, the question still holds if the file's opened in 'w' mode. A: As other posters have noted, the issue is that the codecs library doesn't use an incremental encoder to encode the data; instead it encodes every snippet of data fed to the write method as a compressed block. This is horribly inefficient, and just a terrible design decision for a library designed to work with streams. The ironic thing is that there's a perfectly reasonable incremental bz2 encoder already built into Python. It's not difficult to create a "file-like" class which does the correct thing automatically. import bz2 class BZ2StreamEncoder(object): def __init__(self, filename, mode): self.log_file = open(filename, mode) self.encoder = bz2.BZ2Compressor() def write(self, data): self.log_file.write(self.encoder.compress(data)) def flush(self): self.log_file.write(self.encoder.flush()) self.log_file.flush() def close(self): self.flush() self.log_file.close() log_file = BZ2StreamEncoder(archive_file, 'ab') A caveat: In this example, I've opened the file in append mode; appending multiple compressed streams to a single file works perfectly well with bunzip2, but Python itself can't handle it (although there is a patch for it). If you need to read the compressed files you create back into Python, stick to a single stream per file. A: The problem seems to be that output is being written on every write(). This causes each line to be compressed in its own bzip block. I would try building a much larger string (or list of strings if you are worried about performance) in memory before writing it out to the file. A good size to shoot for would be 900K (or more) as that is the block size that bzip2 uses A: The problem is due to your use of append mode, which results in files that contain multiple compressed blocks of data. Look at this example: >>> import codecs >>> with codecs.open("myfile.zip", "a+", "zip") as f: >>> f.write("ABCD") On my system, this produces a file 12 bytes in size. Let's see what it contains: >>> with codecs.open("myfile.zip", "r", "zip") as f: >>> f.read() 'ABCD' Okay, now let's do another write in append mode: >>> with codecs.open("myfile.zip", "a+", "zip") as f: >>> f.write("EFGH") The file is now 24 bytes in size, and its contents are: >>> with codecs.open("myfile.zip", "r", "zip") as f: >>> f.read() 'ABCD' What's happening here is that unzip expects a single zipped stream. You'll have to check the specs to see what the official behavior is with multiple concatenated streams, but in my experience they process the first one and ignore the rest of the data. That's what Python does. I expect that bunzip2 is doing the same thing. So in reality your file is compressed, and is much smaller than the data it contains. But when you run it through bunzip2, you're getting back only the first set of records you wrote to it; the rest is discarded. A: I'm not sure how different this is from the codecs way of doing it but if you use GzipFile from the gzip module you can incrementally append to the file but it's not going to compress very well unless you are writing large amounts of data at a time (maybe > 1 KB). This is just the nature of the compression algorithms. If the data you are writing isn't super important (i.e. you can deal with losing it if your process dies) then you could write a buffered GzipFile class wrapping the imported class that writes out larger chunks of data.
How do the compression codecs work in Python?
I'm querying a database and archiving the results using Python, and I'm trying to compress the data as I write it to the log files. I'm having some problems with it, though. My code looks like this: log_file = codecs.open(archive_file, 'w', 'bz2') for id, f1, f2, f3 in cursor: log_file.write('%s %s %s %s\n' % (id, f1 or 'NULL', f2 or 'NULL', f3)) However, my output file has a size of 1,409,780. Running bunzip2 on the file results in a file with a size of 943,634, and running bzip2 on that results in a size of 217,275. In other words, the uncompressed file is significantly smaller than the file compressed using Python's bzip codec. Is there a way to fix this, other than running bzip2 on the command line? I tried Python's gzip codec (changing the line to codecs.open(archive_file, 'a+', 'zip')) to see if it fixed the problem. I still get large files, but I also get a gzip: archive_file: not in gzip format error when I try to uncompress the file. What's going on there? EDIT: I originally had the file opened in append mode, not write mode. While this may or may not be a problem, the question still holds if the file's opened in 'w' mode.
[ "As other posters have noted, the issue is that the codecs library doesn't use an incremental encoder to encode the data; instead it encodes every snippet of data fed to the write method as a compressed block. This is horribly inefficient, and just a terrible design decision for a library designed to work with str...
[ 2, 1, 0, 0 ]
[]
[]
[ "bzip2", "gzip", "python", "python_2.x" ]
stackoverflow_0003824239_bzip2_gzip_python_python_2.x.txt
Q: matplotlib pyplot colorbar question Dear all, I'm trying to perform a scatter plot with color with an associated color bar. I would like the colorbar to have string values rather than numerical values, as I'm comparing two different data sets each one with different colorvalues (but in any case between a maximum and minimum values). Here the code I'm using import matplotlib.pyplot as plt import numpy as np from numpy import * from matplotlib import rc import pylab from pylab import * from matplotlib import mpl data = np.loadtxt('deltaBinned.txt') data2 = np.loadtxt('deltaHalphaBinned.txt') fig=plt.figure() fig.subplots_adjust(bottom=0.1) ax=fig.add_subplot(111) plt.xlabel(r'$\partial \Delta/\partial\Phi[$mm$/^{\circ}]$',fontsize=16) plt.ylabel(r'$\Delta$ [mm]',fontsize=16) plt.scatter(data[:,0],data[:,1],marker='o',c=data[:,3],s=data[:,3]*1500,cmap=cm.Spectral,vmin=min(data[:,3]),vmax=max(data[:,3])) plt.scatter(data2[:,0],data2[:,1],marker='^',c=data2[:,2],s=data2[:,2]*500,cmap=cm.Spectral,vmin=min(data2[:,2]),vmax=max(data2[:,2])) cbar=plt.colorbar(ticks=[min(data2[:,2]),max(data2[:,2])]) cbar.set_ticks(['Low','High']) cbar.set_label(r'PdF') plt.show() Unfortunately it does not work as cbar.set_ticks does not accept string values. I've read the ling http://matplotlib.sourceforge.net/examples/pylab_examples/colorbar_tick_labelling_demo.html but Iwas not able to adapt it to my case. I apologize if the question is simple but I'm just at the beginning of python programming Nicola. A: cbar.ax.set_yticklabels(['Low','High']) For example, import numpy as np import matplotlib.cm as cm import matplotlib.pyplot as plt data = np.random.random((10, 4)) data2 = np.random.random((10, 4)) plt.subplots_adjust(bottom = 0.1) plt.xlabel(r'$\partial \Delta/\partial\Phi[$mm$/^{\circ}]$', fontsize = 16) plt.ylabel(r'$\Delta$ [mm]', fontsize = 16) plt.scatter( data[:, 0], data[:, 1], marker = 'o', c = data[:, 3], s = data[:, 3]*1500, cmap = cm.Spectral, vmin = min(data[:, 3]), vmax = max(data[:, 3])) plt.scatter( data2[:, 0], data2[:, 1], marker = '^', c = data2[:, 2], s = data2[:, 2]*500, cmap = cm.Spectral, vmin = min(data2[:, 2]), vmax = max(data2[:, 2])) cbar = plt.colorbar(ticks = [min(data2[:, 2]), max(data2[:, 2])]) cbar.ax.set_yticklabels(['Low', 'High']) cbar.set_label(r'PdF') plt.show() produces
matplotlib pyplot colorbar question
Dear all, I'm trying to perform a scatter plot with color with an associated color bar. I would like the colorbar to have string values rather than numerical values, as I'm comparing two different data sets each one with different colorvalues (but in any case between a maximum and minimum values). Here the code I'm using import matplotlib.pyplot as plt import numpy as np from numpy import * from matplotlib import rc import pylab from pylab import * from matplotlib import mpl data = np.loadtxt('deltaBinned.txt') data2 = np.loadtxt('deltaHalphaBinned.txt') fig=plt.figure() fig.subplots_adjust(bottom=0.1) ax=fig.add_subplot(111) plt.xlabel(r'$\partial \Delta/\partial\Phi[$mm$/^{\circ}]$',fontsize=16) plt.ylabel(r'$\Delta$ [mm]',fontsize=16) plt.scatter(data[:,0],data[:,1],marker='o',c=data[:,3],s=data[:,3]*1500,cmap=cm.Spectral,vmin=min(data[:,3]),vmax=max(data[:,3])) plt.scatter(data2[:,0],data2[:,1],marker='^',c=data2[:,2],s=data2[:,2]*500,cmap=cm.Spectral,vmin=min(data2[:,2]),vmax=max(data2[:,2])) cbar=plt.colorbar(ticks=[min(data2[:,2]),max(data2[:,2])]) cbar.set_ticks(['Low','High']) cbar.set_label(r'PdF') plt.show() Unfortunately it does not work as cbar.set_ticks does not accept string values. I've read the ling http://matplotlib.sourceforge.net/examples/pylab_examples/colorbar_tick_labelling_demo.html but Iwas not able to adapt it to my case. I apologize if the question is simple but I'm just at the beginning of python programming Nicola.
[ "cbar.ax.set_yticklabels(['Low','High'])\n\nFor example,\nimport numpy as np\nimport matplotlib.cm as cm\nimport matplotlib.pyplot as plt\n\ndata = np.random.random((10, 4))\ndata2 = np.random.random((10, 4))\nplt.subplots_adjust(bottom = 0.1)\nplt.xlabel(r'$\\partial \\Delta/\\partial\\Phi[$mm$/^{\\circ}]$', fonts...
[ 11 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003831569_matplotlib_python.txt
Q: Best way to change the value of "settings" from within a Python test case? I'm writing unit tests in Python for the first time, for a Django app. I've struck a problem. In order to test a particular piece of functionality, I need to change the value of one of the app's settings. Here's my first attempt: def test_in_list(self): mango.settings.META_LISTS = ('tags',) tags = Document(filepath).meta['tags'] self.assertEqual(tags, [u'Markdown', u'Django', u'Mango']) What I'm trying to do is change the value of META_LISTS such that the new value is used when the Document object is created. The relevant imports are... # tests.py from mango.models import Document import mango.settings # models.py from mango.settings import * If I've understood correctly, since models.py has already imported the names from mango.settings, changing the value of META_LISTS within mango.settings will not alter the value of META_LISTS within mango.models. It's possible – likely even – that I'm going about this in completely the wrong way. What's the correct way to alter the value of such a "setting" from within a test case? Edit: I failed to mention that the file models.py contains vanilla Python classes rather than Django models. I certainly need to rename this file! A: In models.py, use import mango.settings. You can then set a variable in your test code like you would any other: mango.settings.foo = 'bar' A module is a singleton. You can change the values in its namespace from anywhere in your code. But this won't work if you use from mango.settings import *, since that expression copies the values in the module into the current namespace. A: Will this setting be used throughout the tests? In that case one solution would be to create a settings file for testing. For e.g. add a settings_for_tests.py. # settings_for_tests.py from settings import * # Get everything from default settings file. # Override just what is required. META_LISTS = ('tags',) And then run your tests thus: $ python ./manage.py test mango --settings=settings_for_tests This will ensure that the models in the test database get created using the test settings and not the default settings. If you are doing this it also makes sense to move the settings files inside a directory. For e.g. project | |_ settings | | | |_ __init__.py # Contains merely from settings import * | |_ settings.py | |_ settings_for_tests.py | |_ apps | A: For changing settings in TestCases i use modified version of this snippet http://www.djangosnippets.org/snippets/1011/ Here is my modification of this snippet http://github.com/dominno/django-moderation/blob/master/src/moderation/tests/utils/testsettingsmanager.py Then i create file with my test settings and then i use(example from my project): class SerializationTestCase(SettingsTestCase): fixtures = ['test_users.json', 'test_moderation.json'] test_settings = 'moderation.tests.settings.generic' def setUp(self): self.user = User.objects.get(username='moderator') self.profile = UserProfile.objects.get(user__username='moderator') def test_serialize_of_object(self): """Test if object is propertly serialized to json""" json_field = SerializedObjectField() self.assertEqual(json_field._serialize(self.profile), '[{"pk": 1, "model": "test_app.userprofile", "fields": '\ '{"url": "http://www.google.com", "user": 1, '\ '"description": "Old description"}}]', ) It will keep track of the original settings and let easily revert them back when test is finished. A: There's a simpler way to do this. Use multiple settings files -- each under proper configuration control. We do this. We have a master settings module that has the "applies always" settings. Middleware, installed applications, other settings unique to our applications. We have "subclass" settings which (a) import the master settings and then (b) introduce platform-specific (or stage-specific, or customer-specific) settings. This is where our Windows file path stuff is isolated. Plus the locations of the static media files. Plus customer-specific template paths, etc. We break our test scripts into several parts. The "default' tests.py does basic model, form and view-function tests that must work on all platforms, all development stages (dev, test, qa, etc.) and all customers. We have separate unit test scripts which require special settings for particularly complex fixtures. These are not in tests.py and don't run automatically. They require An explicit call to Django's utilities to setup and teardown test environments. See http://docs.djangoproject.com/en/1.2/topics/testing/#module-django.test.utils how you would recommend testing a silly function which returns "hello" when a particular setting is truthy, and "goodbye" when falsy This may be an indication of a poor design. Test-Driven Design (TDD) suggests that you should have designed this so that it's testable without an elaborate, complex setup. If you must do it through settings, what are you really tesing? That the settings values propagate into your code? That's silly. You should trust that the framework works. Indeed, you have to assume the framework works, otherwise, you're obligated to test every feature of the framework. You should have a function which accepts settings.SOME_SETTING as an argument so that you can test it as a stand-alone unit without fussing around to get the entire environment correct. You have to trust that the environment and framework actually work.
Best way to change the value of "settings" from within a Python test case?
I'm writing unit tests in Python for the first time, for a Django app. I've struck a problem. In order to test a particular piece of functionality, I need to change the value of one of the app's settings. Here's my first attempt: def test_in_list(self): mango.settings.META_LISTS = ('tags',) tags = Document(filepath).meta['tags'] self.assertEqual(tags, [u'Markdown', u'Django', u'Mango']) What I'm trying to do is change the value of META_LISTS such that the new value is used when the Document object is created. The relevant imports are... # tests.py from mango.models import Document import mango.settings # models.py from mango.settings import * If I've understood correctly, since models.py has already imported the names from mango.settings, changing the value of META_LISTS within mango.settings will not alter the value of META_LISTS within mango.models. It's possible – likely even – that I'm going about this in completely the wrong way. What's the correct way to alter the value of such a "setting" from within a test case? Edit: I failed to mention that the file models.py contains vanilla Python classes rather than Django models. I certainly need to rename this file!
[ "In models.py, use import mango.settings. You can then set a variable in your test code like you would any other:\nmango.settings.foo = 'bar'\n\nA module is a singleton. You can change the values in its namespace from anywhere in your code.\nBut this won't work if you use from mango.settings import *, since that ex...
[ 6, 2, 2, 1 ]
[]
[]
[ "django", "namespaces", "python", "unit_testing" ]
stackoverflow_0003830000_django_namespaces_python_unit_testing.txt
Q: Printing negative values as hex in python I have the following code snippet in C++: for (int x = -4; x < 5; ++x) printf("hex x %d 0x%08X\n", x, x); And its output is hex x -4 0xFFFFFFFC hex x -3 0xFFFFFFFD hex x -2 0xFFFFFFFE hex x -1 0xFFFFFFFF hex x 0 0x00000000 hex x 1 0x00000001 hex x 2 0x00000002 hex x 3 0x00000003 hex x 4 0x00000004 If I try the same thing in python: for x in range(-4,5): print "hex x", x, hex(x) I get the following hex x -4 -0x4 hex x -3 -0x3 hex x -2 -0x2 hex x -1 -0x1 hex x 0 0x0 hex x 1 0x1 hex x 2 0x2 hex x 3 0x3 hex x 4 0x4 Or this: for x in range(-4,5): print "hex x %d 0x%08X" % (x,x) Which gives: hex x -4 0x-0000004 hex x -3 0x-0000003 hex x -2 0x-0000002 hex x -1 0x-0000001 hex x 0 0x00000000 hex x 1 0x00000001 hex x 2 0x00000002 hex x 3 0x00000003 hex x 4 0x00000004 This is not what I expected. Is there some formatting trick I am missing that will turn -4 into 0xFFFFFFFC instead of -0x04? A: You need to explicitly restrict the integer to 32-bits: for x in range(-4,5): print "hex x %d 0x%08X" % (x, x & 0xffffffff)
Printing negative values as hex in python
I have the following code snippet in C++: for (int x = -4; x < 5; ++x) printf("hex x %d 0x%08X\n", x, x); And its output is hex x -4 0xFFFFFFFC hex x -3 0xFFFFFFFD hex x -2 0xFFFFFFFE hex x -1 0xFFFFFFFF hex x 0 0x00000000 hex x 1 0x00000001 hex x 2 0x00000002 hex x 3 0x00000003 hex x 4 0x00000004 If I try the same thing in python: for x in range(-4,5): print "hex x", x, hex(x) I get the following hex x -4 -0x4 hex x -3 -0x3 hex x -2 -0x2 hex x -1 -0x1 hex x 0 0x0 hex x 1 0x1 hex x 2 0x2 hex x 3 0x3 hex x 4 0x4 Or this: for x in range(-4,5): print "hex x %d 0x%08X" % (x,x) Which gives: hex x -4 0x-0000004 hex x -3 0x-0000003 hex x -2 0x-0000002 hex x -1 0x-0000001 hex x 0 0x00000000 hex x 1 0x00000001 hex x 2 0x00000002 hex x 3 0x00000003 hex x 4 0x00000004 This is not what I expected. Is there some formatting trick I am missing that will turn -4 into 0xFFFFFFFC instead of -0x04?
[ "You need to explicitly restrict the integer to 32-bits:\nfor x in range(-4,5):\n print \"hex x %d 0x%08X\" % (x, x & 0xffffffff)\n\n" ]
[ 19 ]
[]
[]
[ "number_formatting", "python" ]
stackoverflow_0003831833_number_formatting_python.txt
Q: Task fanout - how to bulk add Tasks to the Queue - more than 5 I am using a task (queueing-task) to queue multiple others tasks — fanout. When I try to use Queue.add with task argument being a list of Task instances with more than 5 element's and in transaction… I get this error. JointException: taskqueue.DatastoreError caused by: <class 'google.appengine.api.datastore_errors.BadRequestError'> Too many messages, maximum allowed 5 Is there another way to queue more than 5 tasks in a transaction? Or... Maybe I don't need a transaction, cause: I don't care if any of those tasks get queued twice anyway, and if queueing will fail for any of them, then the whole queueing-task will be re run. So tell me how do I queue more than 5 tasks in a transaction or tell me to not use transaction cause I don't really need one. A: One solution close to solving your problem is to add one transactional task that fans-out the remaining tasks. Just add the one fan-out task in your existing transaction. Unless there is a business logic reason to do so, do not re-run a task that has already run. Preventing tasks from being re-inserted (i.e. duplicated) is straightforward and saves resources. Your fan-out task will basically look like: class FanOutTask(webapp.RequestHandler): def get(self): name = self.request.get('name') params = deserialize(self.request.get('params')) try: task_params = params.get('stuff') taskqueue.add(url='/worker/1', name=name + '-1', params=task_params) except TaskAlreadyExistsError: pass try: task_params = params.get('more') taskqueue.add(url='/worker/2', name=name + '-2', params=task_params) except TaskAlreadyExistsError: pass Adding the fan-out task transactionally ensures it is enqueued. Errors resulting from the task already being run get caught and ignored, other errors cause the fan-out task to re-run. With this pattern you can insert many sub-tasks pretty easily.
Task fanout - how to bulk add Tasks to the Queue - more than 5
I am using a task (queueing-task) to queue multiple others tasks — fanout. When I try to use Queue.add with task argument being a list of Task instances with more than 5 element's and in transaction… I get this error. JointException: taskqueue.DatastoreError caused by: <class 'google.appengine.api.datastore_errors.BadRequestError'> Too many messages, maximum allowed 5 Is there another way to queue more than 5 tasks in a transaction? Or... Maybe I don't need a transaction, cause: I don't care if any of those tasks get queued twice anyway, and if queueing will fail for any of them, then the whole queueing-task will be re run. So tell me how do I queue more than 5 tasks in a transaction or tell me to not use transaction cause I don't really need one.
[ "One solution close to solving your problem is to add one transactional task that fans-out the remaining tasks. Just add the one fan-out task in your existing transaction.\nUnless there is a business logic reason to do so, do not re-run a task that has already run. Preventing tasks from being re-inserted (i.e. du...
[ 2 ]
[]
[]
[ "google_app_engine", "python", "task_queue" ]
stackoverflow_0003831197_google_app_engine_python_task_queue.txt
Q: Focus-follows-mouse in wxPython? I'm developing an application that contains a number of panes. See the screenshot: The left settings pane is a wx.ScrolledPanel that contains a number of wx.Panels. The top events pane is a wx.grid.Grid. The bottom data pane is a wx.Panel that contains a wx.grid.Grid. The middle plot pane is a wx.Panel containing an enthought chaco plot. The right detector pane is a wx.Panel. I would like to implement focus follows mouse so that when I move my mouse over the plot I can immediately zoom in or out using my scroll wheel without first clicking on the plot to give it the focus. Similarly when I move my mouse over the left settings , the top events or the bottom data panes I would like to be able to immediately scroll the window using the scroll wheel without first clicking on the window. Currently I defined a function: def focusFollowsMouse(window): window.Bind(wx.EVT_ENTER_WINDOW, lambda event: window.SetFocus()) I would like to apply this function only on the four top-level panes: plot, settings, events and data. However I need to call this function for each sub-panel or control in each of the top-level panes to get this to work. For example I need to apply this function individually to the Measurement Settings, Analysis Parameters, View Settings etc. panels. Most likely the EVT_ENTER_WINDOW event is not propagated to parent windows. Is there a way to get this to work without applying focusFollowsMouse to each and every sub-panel or control? Thanks A: This is Windows' behaviour - it works as you expect under GTK. Personally, I'd leave your app as it is, for consistency with other Windows applications, and install WizMouse
Focus-follows-mouse in wxPython?
I'm developing an application that contains a number of panes. See the screenshot: The left settings pane is a wx.ScrolledPanel that contains a number of wx.Panels. The top events pane is a wx.grid.Grid. The bottom data pane is a wx.Panel that contains a wx.grid.Grid. The middle plot pane is a wx.Panel containing an enthought chaco plot. The right detector pane is a wx.Panel. I would like to implement focus follows mouse so that when I move my mouse over the plot I can immediately zoom in or out using my scroll wheel without first clicking on the plot to give it the focus. Similarly when I move my mouse over the left settings , the top events or the bottom data panes I would like to be able to immediately scroll the window using the scroll wheel without first clicking on the window. Currently I defined a function: def focusFollowsMouse(window): window.Bind(wx.EVT_ENTER_WINDOW, lambda event: window.SetFocus()) I would like to apply this function only on the four top-level panes: plot, settings, events and data. However I need to call this function for each sub-panel or control in each of the top-level panes to get this to work. For example I need to apply this function individually to the Measurement Settings, Analysis Parameters, View Settings etc. panels. Most likely the EVT_ENTER_WINDOW event is not propagated to parent windows. Is there a way to get this to work without applying focusFollowsMouse to each and every sub-panel or control? Thanks
[ "This is Windows' behaviour - it works as you expect under GTK. Personally, I'd leave your app as it is, for consistency with other Windows applications, and install WizMouse\n" ]
[ 2 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0003785938_python_wxpython_wxwidgets.txt
Q: How to search the correct directory for imports I am trying to test some code. The main script requires imports from a number of subdirectories. The structure of the scripts is like this (I edited it to make it clear that dir1 and 2 are subdirectories of build): build ascript.py dir1 script2.py dir2 script3.py subdir1 script4.py script5.py subdir2 script6.py . . . Note: Not a complete representation. I was told to test SCRIPT2 through command shell, change to the build directory and then type: SET PYTHONPATH="." python dir1/script2.py That script one has an import statement: from dir2.script3 import * Script3 calls an import from scripts that are in one or more of the dir or subdir folders So when run the command SET . . . (see above) I get no output. Thinking that this is a me problem not a code problem I copied dir2 to C:\PROGRAM FILES\python264 ran the same instructions at the CMD prompt and I got some partial output This tells me that the SET PYTHONPATH is not working as expected in Windows XP. I hope this question makes sense. In response to SLOTT's request - however, after reading his question I understood that one problem is that I did not understand that I was in fact submitting two commands Note there is a script called node in the directory named html which is a subdirectory of parsers2 which is a subdirectory of core which is at the same level as exp Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\burchkealey.UNO_CBA>cd c:\ C:\>cd c:\texttool1\build C:\texttool1\build>set pythonpath="." C:\texttool1\build>python exp/extract_section.py c:\testextract\c40545.htm Traceback (most recent call last): File "exp/extract_section.py", line 4, in <module> from core.parsers2.html.node import * ImportError: No module named core.parsers2.html.node C:\texttool1\build> A: The commands set PYTHONPATH=C:\texttool1\build and dir1\script2.py should work perfectly. Make sure you type them as two commands in the same console (or in one batch script) use the absolute path to the folder containing the modules Moreover, executable scripts are often written in a way that they must be executed from the directory in which the executable lies. Try to start "extract_section.py" in its directory instead of from the parent folder. By the way, it's unusual to name a top package "core", but the code does a global import from that package (from core.parsers2.html.node import *). Or is "core" contained in another package? Maybe this should rather be a local import (from .core.parsers2.html.node import *)? A: I haven't had much luck with PYTHONPATH on XP either. You may need to give a relative path for your include, or you can add the directory to the syspath: sys.path.append('biglongdirectory') It's strongly discouraged, though... instead, there's this option
How to search the correct directory for imports
I am trying to test some code. The main script requires imports from a number of subdirectories. The structure of the scripts is like this (I edited it to make it clear that dir1 and 2 are subdirectories of build): build ascript.py dir1 script2.py dir2 script3.py subdir1 script4.py script5.py subdir2 script6.py . . . Note: Not a complete representation. I was told to test SCRIPT2 through command shell, change to the build directory and then type: SET PYTHONPATH="." python dir1/script2.py That script one has an import statement: from dir2.script3 import * Script3 calls an import from scripts that are in one or more of the dir or subdir folders So when run the command SET . . . (see above) I get no output. Thinking that this is a me problem not a code problem I copied dir2 to C:\PROGRAM FILES\python264 ran the same instructions at the CMD prompt and I got some partial output This tells me that the SET PYTHONPATH is not working as expected in Windows XP. I hope this question makes sense. In response to SLOTT's request - however, after reading his question I understood that one problem is that I did not understand that I was in fact submitting two commands Note there is a script called node in the directory named html which is a subdirectory of parsers2 which is a subdirectory of core which is at the same level as exp Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\burchkealey.UNO_CBA>cd c:\ C:\>cd c:\texttool1\build C:\texttool1\build>set pythonpath="." C:\texttool1\build>python exp/extract_section.py c:\testextract\c40545.htm Traceback (most recent call last): File "exp/extract_section.py", line 4, in <module> from core.parsers2.html.node import * ImportError: No module named core.parsers2.html.node C:\texttool1\build>
[ "The commands set PYTHONPATH=C:\\texttool1\\build and dir1\\script2.py should work perfectly. Make sure you\n\ntype them as two commands in the same console (or in one batch script)\nuse the absolute path to the folder containing the modules\n\nMoreover, executable scripts are often written in a way that they must ...
[ 1, 0 ]
[]
[]
[ "environment_variables", "path", "python", "windows_xp" ]
stackoverflow_0003832114_environment_variables_path_python_windows_xp.txt
Q: 403 error when trying to run CherryPy behind Apache I am trying to run CherryPy behind Apache using mod_rewrite, as described in the CherryPy documentation (BehindApache, ModRewrite), and it is not working. Edit: Earlier, my description of this problem was somewhat inaccurate. It seems like I forgot to restart Apache during some of my attempts. I have revised the question significantly. When I run my program (a very simple "hello world" program similar to the first tutorial file that comes with CherryPy), it seems to work fine. If I run curl "http://127.0.0.1:8080" from my server, I can see the output, and I see some sort of record of it in the CherryPy log. However, if I try to access the site from my browser, I get a 403 Forbidden error saying "You don't have permission to access / on this server.". I do not see any record of it in the CherryPy log. I tried putting the RewriteRule (RewriteRule ^(.*) http://127.0.0.1:8080$1 [proxy]) in the appropriate VirtualHost section of my httpd.conf file, both with and without the slash, and both times I got the same error. In my Apache error log, I see lines like this: [Mon Sep 27 15:54:11 2010] [error] [client 123.45.67.89] attempt to make remote request from mod_rewrite without proxy enabled: proxy:http://127.0.0.1:8080/ I tried putting the RewriteRule in the .htaccess file of my site instead, and I got 404 Not Found errors, with lines like this in my error log: [Mon Sep 27 13:31:54 2010] [error] [client 123.45.67.89] Attempt to serve directory: proxy:http://127.0.0.1:8080/ I still didn't see any entries in the CherryPy log. I decided to see what would happen if I tried to access the site without CherryPy running, and I got the same thing. It is as if Apache is trying unsuccessfully to communicate with the CherryPy program if I put the line in httpd.conf, and completely unaware of it when I put the line in .htaccess. Does anyone here know why this is happening, and what to do about it? I have tried everything I could think of. My site is running on a DreamHost private server with Debian 4.3.2-1.1, Apache 2.2.15, Python 2.6.5, and CherryPy 3.1.2. Edit 2: lazy1, I tried your suggestion and it did not help. I am getting the same 403 errors. A: I run CherryPy behind Apache in a very similar way. Apache serves static content itself, and any URLs starting with 'cp' are servied by CherryPy. CherryPy is listening on port 8500. Here's what works for me in httpd.conf: RewriteMap escape int:escape [...] RewriteRule ^/cp\/(.*) http://localhost:8500/cp/${escape:$1} [L,P] This is inside the VirtualHost definition (well, the RewriteMap line is outside it, but you get the picture) Obviously you have to make sure mod_proxy is getting loaded. Check the RewriteRule documentation as well. In my CherryPy config, I have: server.socket_host = "127.0.0.1" server.socket_port = 8500 Good luck! A: You might want to try and bind cherrypy to 0.0.0.0 (all interfaces) cherrypy.config.update({"server.socket_host" : "0.0.0.0"})
403 error when trying to run CherryPy behind Apache
I am trying to run CherryPy behind Apache using mod_rewrite, as described in the CherryPy documentation (BehindApache, ModRewrite), and it is not working. Edit: Earlier, my description of this problem was somewhat inaccurate. It seems like I forgot to restart Apache during some of my attempts. I have revised the question significantly. When I run my program (a very simple "hello world" program similar to the first tutorial file that comes with CherryPy), it seems to work fine. If I run curl "http://127.0.0.1:8080" from my server, I can see the output, and I see some sort of record of it in the CherryPy log. However, if I try to access the site from my browser, I get a 403 Forbidden error saying "You don't have permission to access / on this server.". I do not see any record of it in the CherryPy log. I tried putting the RewriteRule (RewriteRule ^(.*) http://127.0.0.1:8080$1 [proxy]) in the appropriate VirtualHost section of my httpd.conf file, both with and without the slash, and both times I got the same error. In my Apache error log, I see lines like this: [Mon Sep 27 15:54:11 2010] [error] [client 123.45.67.89] attempt to make remote request from mod_rewrite without proxy enabled: proxy:http://127.0.0.1:8080/ I tried putting the RewriteRule in the .htaccess file of my site instead, and I got 404 Not Found errors, with lines like this in my error log: [Mon Sep 27 13:31:54 2010] [error] [client 123.45.67.89] Attempt to serve directory: proxy:http://127.0.0.1:8080/ I still didn't see any entries in the CherryPy log. I decided to see what would happen if I tried to access the site without CherryPy running, and I got the same thing. It is as if Apache is trying unsuccessfully to communicate with the CherryPy program if I put the line in httpd.conf, and completely unaware of it when I put the line in .htaccess. Does anyone here know why this is happening, and what to do about it? I have tried everything I could think of. My site is running on a DreamHost private server with Debian 4.3.2-1.1, Apache 2.2.15, Python 2.6.5, and CherryPy 3.1.2. Edit 2: lazy1, I tried your suggestion and it did not help. I am getting the same 403 errors.
[ "I run CherryPy behind Apache in a very similar way. Apache serves static content itself, and any URLs starting with 'cp' are servied by CherryPy. CherryPy is listening on port 8500. Here's what works for me in httpd.conf:\nRewriteMap escape int:escape\n [...]\nRewriteRule ^/cp\\/(.*) http://localhost:8500/cp/${e...
[ 4, 0 ]
[]
[]
[ "apache", "cherrypy", "python" ]
stackoverflow_0003807711_apache_cherrypy_python.txt
Q: Install particular version with easy_install I'm trying to install lxml. I've had a look at the website, and version 2.2.8 looked reasonable to me but when I did easy_install lxml, it installed version 2.3.beta1 which is not really what I want I presume. What is the best way to fix this and how can I force easy_install to install a particular version? (Mac os x 10.6) A: I believe the way to specify a version would be like this: easy_install lxml==2.2.8 I (and most other Python users I suspect) stopped using easy_install and started using pip some time ago, so a solution in those terms is: easy_install pip pip install lxml==2.2.8 (pip has several benefits, including an uninstall command) A: From the easy_install documentation: easy_install PackageName==1.2.3 A: You should do something like this: easy_install "lxml==2.2.8"
Install particular version with easy_install
I'm trying to install lxml. I've had a look at the website, and version 2.2.8 looked reasonable to me but when I did easy_install lxml, it installed version 2.3.beta1 which is not really what I want I presume. What is the best way to fix this and how can I force easy_install to install a particular version? (Mac os x 10.6)
[ "I believe the way to specify a version would be like this:\neasy_install lxml==2.2.8\n\nI (and most other Python users I suspect) stopped using easy_install and started using pip some time ago, so a solution in those terms is:\neasy_install pip\npip install lxml==2.2.8\n\n(pip has several benefits, including an un...
[ 142, 18, 7 ]
[]
[]
[ "easy_install", "python", "version" ]
stackoverflow_0003833011_easy_install_python_version.txt
Q: Is there a way to call a function right before a PyQt application ends? I am collecting usage stats for my applications which include how much each session lasts. However, I can't seem to be able to save this information because None Of the signals I tried yet actually succeeds to call my report_session function. This are the signals I have already tried: lastWindowClosed() aboutToQuit() destroyed() Either these signals never get emitted or the application does not live long enough after that to run anything else. Here is my main: app = QtGui.QApplication(sys.argv) ui = MainWindow() ui.app = app QtCore.QObject.connect(ui, QtCore.SIGNAL("destroyed()"), ui.report_session) ui.show() logger.info('Started!') splash.finish(ui) sys.exit(app.exec_()) A: The method that Mark Byers posted will run after the main widget has been closed, meaning that its controls will no longer be available. If you need to work with any values from controls on your form, you will want to capture the close event and do your work there: class MainWidget(QtGui.QWidget): #... def closeEvent(self, event): print "closing PyQtTest" self.SaveSettings() # report_session() Also, see the Message Box example in the ZetCode tutorial First programs in PyQt4 toolkit (near the end of the page). This shows how to accept or cancel the close request. A: Put the code between app.exec_ and sys.exit: ret = app.exec_() # Your code that must run when the application closes goes here sys.exit(ret) A: To ensure that a Python function gets called at process termination, in general (with or without Qt involved;-), you can use the atexit module of the standard Python library: import atexit def whatever(): ... atexit.register(whatever) Out of prudence I would recommend against using a bound method instead of a function for this purpose -- it "should" work, but the destruction-phase of a process is always somewhat delicate, and the simpler you keep it, the better. atexit won't trigger for a sufficiently-hard crash of a process, of course (e.g., if the process is killed with a kill -9, then by definition it's not given a chance to run any termination code) -- the OS sees to that;-). If you need to handle any crash no matter how hard you must do so from a separate "watchdog" process, a substantially subtler issue. A: Found this answer which involves overloading closeEvent(). it worked perfectly for me.
Is there a way to call a function right before a PyQt application ends?
I am collecting usage stats for my applications which include how much each session lasts. However, I can't seem to be able to save this information because None Of the signals I tried yet actually succeeds to call my report_session function. This are the signals I have already tried: lastWindowClosed() aboutToQuit() destroyed() Either these signals never get emitted or the application does not live long enough after that to run anything else. Here is my main: app = QtGui.QApplication(sys.argv) ui = MainWindow() ui.app = app QtCore.QObject.connect(ui, QtCore.SIGNAL("destroyed()"), ui.report_session) ui.show() logger.info('Started!') splash.finish(ui) sys.exit(app.exec_())
[ "The method that Mark Byers posted will run after the main widget has been closed, meaning that its controls will no longer be available. \nIf you need to work with any values from controls on your form, you will want to capture the close event and do your work there:\nclass MainWidget(QtGui.QWidget):\n\n #...\n...
[ 8, 5, 5, 1 ]
[]
[]
[ "pyqt", "pyqt4", "python", "signals_slots", "user_interface" ]
stackoverflow_0003832880_pyqt_pyqt4_python_signals_slots_user_interface.txt
Q: How can I retrieve a Google Talk users Status Message I'd like to be able to retrieve a users Google Talk Status Message with Python, it's really hard to find documentation on how to use some of the libraries out there. A: I don't have anything to hand with xmpp installed, but here's some old code I had lying around that might help you. You'll want to update the USERNAME/PASSWORD to your own values for test purposes. Things to note: users logged in to Google Talk get a random presence string on their userid: that doesn't matter if you are trying to get the status of some other user, but if you want to write some code so want to communicate with yourself you need to distinguish the user logged in from GMail or a GTalk client from the test program. Hence the code searches through the userids. Also, if you read the status immediately after logging in you probably won't get anything. There's a delay in the code because it takes a little while for the status to become available. """Send a single GTalk message to myself""" import xmpp import time _SERVER = 'talk.google.com', 5223 USERNAME = 'someuser@gmail.com' PASSWORD = 'whatever' def sendMessage(tojid, text, username=USERNAME, password=PASSWORD): jid = xmpp.protocol.JID(username) client = xmpp.Client(jid.getDomain(), debug=[]) #self.client.RegisterHandler('message', self.message_cb) if not client: print 'Connection failed!' return con = client.connect(server=_SERVER) print 'connected with', con auth = client.auth(jid.getNode(), password, 'botty') if not auth: print 'Authentication failed!' return client.RegisterHandler('message', message_cb) roster = client.getRoster() client.sendInitPresence() if '/' in tojid: tail = tojid.split('/')[-1] t = time.time() + 1 while time.time() < t: client.Process(1) time.sleep(0.1) if [ res for res in roster.getResources(tojid) if res.startswith(tail) ]: break for res in roster.getResources(tojid): if res.startswith(tail): tojid = tojid.split('/', 1)[0] + '/' + res print "sending to", tojid id = client.send(xmpp.protocol.Message(tojid, text)) t = time.time() + 1 while time.time() < t: client.Process(1) time.sleep(0.1) print "status", roster.getStatus(tojid) print "show", roster.getShow(tojid) print "resources", roster.getResources(tojid) client.disconnect() def message_cb(session, message): print ">", message sendMessage(USERNAME + '/Talk', "This is an automatically generated gtalk message: did you get it?")
How can I retrieve a Google Talk users Status Message
I'd like to be able to retrieve a users Google Talk Status Message with Python, it's really hard to find documentation on how to use some of the libraries out there.
[ "I don't have anything to hand with xmpp installed, but here's some old code I had lying around that might help you. You'll want to update the USERNAME/PASSWORD to your own values for test purposes.\nThings to note: users logged in to Google Talk get a random presence string on their userid: that doesn't matter if ...
[ 0 ]
[]
[]
[ "google_talk", "python", "xmpp" ]
stackoverflow_0003831641_google_talk_python_xmpp.txt
Q: Python IMAP call I am using the imap library to access my unread messages on gmail and to print out the subjects, is there a way to make sure that the messages being read are still tagged as unread. Thanks A: Use PEEK instead. For example, something like: typ, data = imap_conn.fetch(uid, '(BODY.PEEK[TEXT])') A: For info, Yours is an inverse question of this one Parse Gmail with Python and mark all older than date as "read" Use peek, so that you do not affect the message. But you should also be able to tag the message as unseen.
Python IMAP call
I am using the imap library to access my unread messages on gmail and to print out the subjects, is there a way to make sure that the messages being read are still tagged as unread. Thanks
[ "Use PEEK instead. For example, something like:\ntyp, data = imap_conn.fetch(uid, '(BODY.PEEK[TEXT])')\n\n", "For info, Yours is an inverse question of this one\n\nParse Gmail with Python and mark all older than date as \"read\"\n\nUse peek, so that you do not affect the message.\nBut you should also be able to ...
[ 3, 1 ]
[]
[]
[ "email", "imap", "python" ]
stackoverflow_0003833428_email_imap_python.txt
Q: Python: numpy and matplotlib anomaly This is the first time I am using matplotlib and numpy. Here goes the problem: If I goto python cli, the intended code works fine. Here is that code >>> from numpy import * >>> y = array([1,2]) >>> y = append(y, y[len(y) - 1]+1) >>> y array([1, 2, 3]) But if I use it with matplotlib in a script I get this error. line 26, in onkeypress y = append(y, y[len(y) - 1]+1) UnboundLocalError: local variable 'y' referenced before assignment Here is my script: from matplotlib.pyplot import figure, show from numpy import * figzoom = figure() axzoom = figzoom.add_subplot(111, xlim=(0,10), ylim=(0, 10),autoscale_on=True) x = array([1, 2 ]) y = array([1, 10 ]) def onkeypress(event): if event.key == "up": y = append(y, y[len(y) - 1]+1) x = append(x, x[len(x) - 1] ) axzoom.plot(x,y) I tried "append"ing to a different array,say y1, and then y = y1.copy(). But I still get the same error. I must be missing something trivial here???!!! A: When you assign to a variable inside a function, python creates a new variable that has local scope, and this new variable also hides the global variable. So, the x and y inside onkeypress are local to the function. Hence, from python's point of view, they are uninitialized, and hence the error. As GWW points out - declaring x, y as global will solve the problem. Also, if you do not assign x, y any new value, but only use their previously existing value, those values will refer to the global x, y. A: It may work if you change the variables to global def onkeypress(event): global y, x ... A: Unless you include global y in your onkeypress() function, the y you're assigning to is scoped locally to the function. You can't use y on the right side of the assignment statement in which you're defining the local variable.
Python: numpy and matplotlib anomaly
This is the first time I am using matplotlib and numpy. Here goes the problem: If I goto python cli, the intended code works fine. Here is that code >>> from numpy import * >>> y = array([1,2]) >>> y = append(y, y[len(y) - 1]+1) >>> y array([1, 2, 3]) But if I use it with matplotlib in a script I get this error. line 26, in onkeypress y = append(y, y[len(y) - 1]+1) UnboundLocalError: local variable 'y' referenced before assignment Here is my script: from matplotlib.pyplot import figure, show from numpy import * figzoom = figure() axzoom = figzoom.add_subplot(111, xlim=(0,10), ylim=(0, 10),autoscale_on=True) x = array([1, 2 ]) y = array([1, 10 ]) def onkeypress(event): if event.key == "up": y = append(y, y[len(y) - 1]+1) x = append(x, x[len(x) - 1] ) axzoom.plot(x,y) I tried "append"ing to a different array,say y1, and then y = y1.copy(). But I still get the same error. I must be missing something trivial here???!!!
[ "When you assign to a variable inside a function, python creates a new variable that has local scope, and this new variable also hides the global variable.\nSo, the x and y inside onkeypress are local to the function. Hence, from python's point of view, they are uninitialized, and hence the error.\nAs GWW points ou...
[ 3, 2, 2 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0003833717_matplotlib_numpy_python.txt
Q: What's BLUE from CCP Stackless presentations? In Stackless Python in Eve, there is some talk about "BLUE" objects in Python. Does anyone know details about this technology? A: It's a codename for a framework CCP probably developed internally for EVE Online. EVE Online installations come with blue.dll. There is a python API to it (import blue). Digging into blue.dll reveals: Description: CCP Blue Framework $ strings blue.dll | egrep "python|Py" | less BlueObjectBuilderPython BlueEventToPython IBluePyOS IPythonEvents IPythonMethods IPythonNumeric PythonEvents BlueEventToPython BlueObjectBuilderPython Proxy object builder that calls a python method to construct the object. BeOS::Python BlueOS/mShutdownPythonCallbacks Py_FatalError: %s Fatal Python error: %s PumpOS::end PumpPython s|O:PyCreateInstance Thunker for constructing python objects. python file object api Python object Python object pointer An unrepresentable Python object PyOS::StacklessIoDispatch PyOS::Run Watchdog PyOS::Create Tasklet PyOS::PyError PyOS::Synchro Tick Python Logs Runs a python script. Enable python ref. stack trace Returns the python and blue reference counts Error while calling Python logging callback function. Disabling logging in Python! BluePyOS BluePyOS/mThreads
What's BLUE from CCP Stackless presentations?
In Stackless Python in Eve, there is some talk about "BLUE" objects in Python. Does anyone know details about this technology?
[ "It's a codename for a framework CCP probably developed internally for EVE Online. EVE Online installations come with blue.dll. There is a python API to it (import blue).\nDigging into blue.dll reveals:\nDescription: CCP Blue Framework\n$ strings blue.dll | egrep \"python|Py\" | less\nBlueObjectBuilderPython\nBlueE...
[ 3 ]
[]
[]
[ "python", "stackless" ]
stackoverflow_0003831954_python_stackless.txt
Q: Forcing an interrupt between threads through a singleton object (academic) I'm sure this is not a very pythonic situation. But I'm not actually using this in any production code, I'm just considering how (if?) this could work. It doesn't have to be python specific, but I'd like a solution that at least WORKS within python framework. Basically, I have a thread safe singleton object that implements __enter__ and __exit__ (so it can be used with with. Singleton(): l = threading.Lock() __enter__(): l.acquire() __exit__(): l.release() In my example, one thread gets the singleton, and inside the with statement it enters an infinite loop. def infinite(): with Singleton(): while True: pass The goal of this experiment is to get the infinite thread out of its infinite loop WITHOUT killing the thread. Specifically using the Singleton object. First I was thinking of using an exception called from a different thread: Singleton(): .... def killMe(): raise exception But this obviously doesn't raise the exception in the other thread. What I thought next is that since the enter and exit methods acquire a class variable lock, is there any method that can be called on the Lock that will cause the thread that has acquired it to throw an exception? Or, what I would probably do in C++ is just delete this or somehow call the destructor of the object from itself. Is there ANY way to do this in python? I know that if it's possible it will be a total hack job. But again, this is basically a thought experiment. A: In Python, there is a somewhat undocumented way of raising an exception in another thread, though there are some caveats. See this recipe for "killable threads": http://code.activestate.com/recipes/496960-thread2-killable-threads/ http://sebulba.wikispaces.com/recipe+thread2
Forcing an interrupt between threads through a singleton object (academic)
I'm sure this is not a very pythonic situation. But I'm not actually using this in any production code, I'm just considering how (if?) this could work. It doesn't have to be python specific, but I'd like a solution that at least WORKS within python framework. Basically, I have a thread safe singleton object that implements __enter__ and __exit__ (so it can be used with with. Singleton(): l = threading.Lock() __enter__(): l.acquire() __exit__(): l.release() In my example, one thread gets the singleton, and inside the with statement it enters an infinite loop. def infinite(): with Singleton(): while True: pass The goal of this experiment is to get the infinite thread out of its infinite loop WITHOUT killing the thread. Specifically using the Singleton object. First I was thinking of using an exception called from a different thread: Singleton(): .... def killMe(): raise exception But this obviously doesn't raise the exception in the other thread. What I thought next is that since the enter and exit methods acquire a class variable lock, is there any method that can be called on the Lock that will cause the thread that has acquired it to throw an exception? Or, what I would probably do in C++ is just delete this or somehow call the destructor of the object from itself. Is there ANY way to do this in python? I know that if it's possible it will be a total hack job. But again, this is basically a thought experiment.
[ "In Python, there is a somewhat undocumented way of raising an exception in another thread, though there are some caveats. See this recipe for \"killable threads\":\nhttp://code.activestate.com/recipes/496960-thread2-killable-threads/\nhttp://sebulba.wikispaces.com/recipe+thread2\n" ]
[ 1 ]
[]
[]
[ "multithreading", "python", "singleton" ]
stackoverflow_0003833659_multithreading_python_singleton.txt
Q: Using a try/catch to retry the same method I have a class whose methods require that a certain class field exists correctly. That class field is set in the constructor and it's read from a config file, and it may or may not get the correct data from that config file. If the data is incorrect, it will have the wrong data in the class field and the class method will throw an exception. If that happens, what I want to do is run the method again but with a different call to the class constructor. Is this something that is reasonably handled in a try:catch? Because the method MAY throw the same exception even with the correct class field. So what I want is to have the first time the method is called, the exception is caught and then the method run again. But on the 2nd run if the exception is thrown I want it to propagate. So: try: MyClass().method() except MyException: MyClass(True).method() Is there an obvious flaw to this? Or a better way to do this without using counters, or flags, or other ugly helper objects? A: I'm a bit surprised that you don't want the MyClass instance to stick around for later use, but, given that this is your intention, your code is correct and concise -- it does what you state you want without any "obvious flaw". I'm not sure which objects you think ugly and which ones you think pretty, but without introducing some "helper objects" I can't even think of another way to achieve your stated requirements!-) A: What you're doing is fine; if the method throws the same exception from within the exception handler, it will be propagated and not caught by the same handler. A: Sounds like you're talking about sort of Factory method. I would create a separate Creator class to handle such situation.
Using a try/catch to retry the same method
I have a class whose methods require that a certain class field exists correctly. That class field is set in the constructor and it's read from a config file, and it may or may not get the correct data from that config file. If the data is incorrect, it will have the wrong data in the class field and the class method will throw an exception. If that happens, what I want to do is run the method again but with a different call to the class constructor. Is this something that is reasonably handled in a try:catch? Because the method MAY throw the same exception even with the correct class field. So what I want is to have the first time the method is called, the exception is caught and then the method run again. But on the 2nd run if the exception is thrown I want it to propagate. So: try: MyClass().method() except MyException: MyClass(True).method() Is there an obvious flaw to this? Or a better way to do this without using counters, or flags, or other ugly helper objects?
[ "I'm a bit surprised that you don't want the MyClass instance to stick around for later use, but, given that this is your intention, your code is correct and concise -- it does what you state you want without any \"obvious flaw\". I'm not sure which objects you think ugly and which ones you think pretty, but witho...
[ 3, 1, 0 ]
[]
[]
[ "exception", "exception_handling", "python" ]
stackoverflow_0003833378_exception_exception_handling_python.txt
Q: testing for numeric equality when variable is modified inside loop I am new to python and I was writing something like: t = 0. while t<4.9: t = t + 0.1 if t == 1.: ... do something ... I noticed that the if statement was never being executed. So I modified the code to look like this: ''' Case a''' t = 0. while t<4.9: t = t + 0.1 print(t) print(t == 5.) When I run this I get: >>> ================================ RESTART ================================ >>> 5.0 False This was a surprise because I expected the comparison to test as True. Then, I tried the following two cases: ''' Case b''' t = 0 while t<5: t = t + 1 print(t) print(t == 5) ''' Case c''' t = 0. while t<5: t = t + 0.5 print(t) print(t == 5) When I run the last 2 cases (b and c) the comparison in the final statement tests as True. I do not understand why it is so or why it seems that the behavior is not consistent. What am I doing wrong? A: The problem is that binary floating point arithmetic is not precise so you will get small errors in the calculations. In particular the number 0.1 has no exact binary representation. When you calculate using floating point numbers the very small errors cause the result to be slightly incorrect from what you might expect and that makes the equality test fail. This small error might not be visible when printing the float with the default string representation. Try using repr instead, as this gives a slightly more accurate representation of the number (but still not 100% accurate): >>> print(repr(t)) 4.999999999999998 >>> print(t == 5.) False To get an accurate string representation of a float you can use the format method: >>> print '{0:.60f}'.format(t) 4.999999999999998223643160599749535322189331054687500000000000 >>> print '{0:.60f}'.format(0.1) 0.100000000000000005551115123125782702118158340454101562500000 A general rule with floating point arithmetic is to never make equality comparisons. The reason why it works when you used 0.5 is because 0.5 does have an exact representation as a binary floating point number so you don't see any problem in that case. Similarly it would work for 0.25 or 0.125. If you need precise calculations you can use a decimal type instead. from decimal import Decimal step = Decimal('0.1') t = Decimal(0) while t < Decimal(5): t += step print(t) print(t == Decimal(5)) Result: 5.0 True A: NEVER try to test floats for equality. Floats are often not exactly what you inputted them to be. In [43]: .1 Out[43]: 0.10000000000000001 So it's much safer to only test floats with inequalities. If you need to test if two floats are nearly equal, use a utility function like near: def near(a,b,rtol=1e-5,atol=1e-8): try: return abs(a-b)<(atol+rtol*abs(b)) except TypeError: return False The rtol parameter allows you to specify relative tolerance. (abs(a-b)/abs(b)) < rtol The atol parameter allows you to specify absolute tolerance. abs(a-b) < atol So for example, you could write t = 0. while t<4.9: t = t + 0.1 if near(t,1.): print('Hiya')
testing for numeric equality when variable is modified inside loop
I am new to python and I was writing something like: t = 0. while t<4.9: t = t + 0.1 if t == 1.: ... do something ... I noticed that the if statement was never being executed. So I modified the code to look like this: ''' Case a''' t = 0. while t<4.9: t = t + 0.1 print(t) print(t == 5.) When I run this I get: >>> ================================ RESTART ================================ >>> 5.0 False This was a surprise because I expected the comparison to test as True. Then, I tried the following two cases: ''' Case b''' t = 0 while t<5: t = t + 1 print(t) print(t == 5) ''' Case c''' t = 0. while t<5: t = t + 0.5 print(t) print(t == 5) When I run the last 2 cases (b and c) the comparison in the final statement tests as True. I do not understand why it is so or why it seems that the behavior is not consistent. What am I doing wrong?
[ "The problem is that binary floating point arithmetic is not precise so you will get small errors in the calculations. In particular the number 0.1 has no exact binary representation. When you calculate using floating point numbers the very small errors cause the result to be slightly incorrect from what you might ...
[ 7, 4 ]
[]
[]
[ "floating_point", "python" ]
stackoverflow_0003834253_floating_point_python.txt
Q: pygtk: What class should my custom widgets inherit from? When making a custom widget in pygtk, what class should it inherit from? I want to be able to put the widget inside other widgets, but I don't want other people to put stuff in mine. Usually I make my widgets inherit from gtk.HBox or gtk.VBox, and that works fine, but it is possible then for someone to do a pack_start() on my widget and cause strange things to happen. I'd inherit from gtk.Widget but then how do I add things to it? I'd inherit from gtk.Container or gtk.Bin but the docs say they are abstract classes. A: If your custom widget contains other (probably standard) widgets, you could simply raise an exception in the overridden pack_ methods. That way, nobody can put stuff in it (easily). Inside your class, you then have to use super(...).pack_xxx instead of self.pack_xxx. But it's probably better to derive from gtk.Container. Then you'll have to implement its abstract methods like do_add(self, widget). In case you only draw custom content (no children), there's no need to derive from a container widget. See the tutorial on pygtk.org.
pygtk: What class should my custom widgets inherit from?
When making a custom widget in pygtk, what class should it inherit from? I want to be able to put the widget inside other widgets, but I don't want other people to put stuff in mine. Usually I make my widgets inherit from gtk.HBox or gtk.VBox, and that works fine, but it is possible then for someone to do a pack_start() on my widget and cause strange things to happen. I'd inherit from gtk.Widget but then how do I add things to it? I'd inherit from gtk.Container or gtk.Bin but the docs say they are abstract classes.
[ "If your custom widget contains other (probably standard) widgets, you could simply raise an exception in the overridden pack_ methods. That way, nobody can put stuff in it (easily). Inside your class, you then have to use super(...).pack_xxx instead of self.pack_xxx.\nBut it's probably better to derive from gtk.Co...
[ 0 ]
[]
[]
[ "gtk", "inheritance", "pygtk", "python" ]
stackoverflow_0003834570_gtk_inheritance_pygtk_python.txt
Q: Python - what is the accepted money calculation technique? Take the following example: >>> from decimal import Decimal >>> nrml_price = Decimal('0.59') >>> discounted = nrml_price / 3 # Taking 2/3 off the price with a coupon Decimal('0.1966666666666666666666666667') # Customers don't have fractions of a penny >>> (nrml_price / 3).quantize(D('0.00')) # So I quantize to get 2 decimal places Decimal('0.20') # Ca fait combien? Cest vingt cents. The problem is that I've now technically charged the customer for more than the expected price, albeit by less than 3/10 of a cent, but nonetheless it is technically incorrect. How do I overcome a problem like this? Do I ignore it as a fact of life, or is there an accepted way to do this sort of thing (e.g. always charge the customer the nearest penny down)? A: "is there an accepted way to do this sort of thing" Yes. Accountants do it all the time. Indeed COBOL does this really well. The Python decimal package has a bunch of rounding options that you set in the context. Almost always the decimal.ROUND_HALF_DOWN or decimal.ROUND_HALF_EVEN options are what you want in your context. When building software for retail management like this, there will be corporate policies in place, managed by real accountants, which specify what should be done. Ask the accountant who works with this line of business what the policy is. A: The answer here may actually depend more on your transaction processor. Does your transaction processor allow you to transfer amounts of currency that are not whole numbers of cents? What about irrational value currency amounts? Say the discount was the square root of the normal price? Most vendors (thats you here) will simply round up and keep the difference, in whole cents.
Python - what is the accepted money calculation technique?
Take the following example: >>> from decimal import Decimal >>> nrml_price = Decimal('0.59') >>> discounted = nrml_price / 3 # Taking 2/3 off the price with a coupon Decimal('0.1966666666666666666666666667') # Customers don't have fractions of a penny >>> (nrml_price / 3).quantize(D('0.00')) # So I quantize to get 2 decimal places Decimal('0.20') # Ca fait combien? Cest vingt cents. The problem is that I've now technically charged the customer for more than the expected price, albeit by less than 3/10 of a cent, but nonetheless it is technically incorrect. How do I overcome a problem like this? Do I ignore it as a fact of life, or is there an accepted way to do this sort of thing (e.g. always charge the customer the nearest penny down)?
[ "\"is there an accepted way to do this sort of thing\"\nYes. Accountants do it all the time.\nIndeed COBOL does this really well.\nThe Python decimal package has a bunch of rounding options that you set in the context. Almost always the decimal.ROUND_HALF_DOWN or decimal.ROUND_HALF_EVEN options are what you want ...
[ 8, 5 ]
[]
[]
[ "concurrency", "currency", "python" ]
stackoverflow_0003834657_concurrency_currency_python.txt
Q: Python: Compare dict with a static reference? I have to check if a dictionary is the same as it was yesterday, if it has changed. In PHP I could have serialized an array and compared the resulting strings from yesterday and today. However, I don't know how to do it in Py. I've read a little about Pickle and maybe it could be done with md5 somehow? So basically I need a way to dismantle a dict into a comparable, storable value that is not a file and can be hardcoded into .py file. Thanks, A.R. A: The problem with dictionaries is their undefined order. You must make sure you always get the same result of equal dictionaries (if you want to compare them as strings). You could do it in multiple ways: 1) Python hash (only for checking equality; hash implementation might be specific to the Python version!) print hash(str(sorted({1 : 2, 3 : 4}.items()))) 2) MD5 (best if you only want to check equality) import hashlib print hashlib.md5(str(sorted({1 : 2, 3 : 4}.items()))).hexdigest() 3) Pickling (serialization) import pickle serializedString = pickle.dumps({1 : 2, 3 : 4}) The pickle module has different protocols (and I think it doesn't sort the dictionary items), so you can't do string comparison. You have to unpickle the data to a dictionary and then compare the old and new dictionary directly (d = pickle.loads(serializedString)). 4) Item tuple representation (serialization) According to your comment, you want something embeddable into Python source code. As S.Lott suggested, you can use the object representation of someDictionary.items(), which is a list containing all (key, value) combinations as tuples (most probably unsorted): >>> repr({1 : 2, 3 : 4}.items()) '[(1, 2), (3, 4)]' You can copy-and-paste this representation into your source code if you want the object serialized as a string . A: You could use JSON to get what you are asking for. from django.utils import simplejson as json dict_1 = {'a': 1, 'b': 2, 'c': 3} dict_2 = {'a': 2, 'b': 7, 'd': 9} dict_1_str = json.dumps(dict_1, sort_keys=True) dict_2_str = json.dumps(dict_2, sort_keys=True) if dict_1_str == dict_2_str: # do something with the new dict... pass The dict_X_str variables will contain a serialized version of the dict. You can store it in memcahce or the datastore for later comparison. A: pickle is definitely what you're looking for. A: pickle.dumps(set(yourdict.items())) A: By using pickle you could create a new DictProperty allowing you to put the dict in the datastore and retrieve it later for comparison. Here is one implementation: Can I store a python dictionary in google's BigTable datastore without serializing it explicitly? A: If you do this, you get an object which is consistent and comparable. It has a well-defined and predictable order. You can use difflib to find differences. Further, you can trivially rebuild the high-performance dictionary from it. static = list(sorted(some_dict.items())) a_dict= dict( static )
Python: Compare dict with a static reference?
I have to check if a dictionary is the same as it was yesterday, if it has changed. In PHP I could have serialized an array and compared the resulting strings from yesterday and today. However, I don't know how to do it in Py. I've read a little about Pickle and maybe it could be done with md5 somehow? So basically I need a way to dismantle a dict into a comparable, storable value that is not a file and can be hardcoded into .py file. Thanks, A.R.
[ "The problem with dictionaries is their undefined order. You must make sure you always get the same result of equal dictionaries (if you want to compare them as strings).\nYou could do it in multiple ways:\n1) Python hash (only for checking equality; hash implementation might be specific to the Python version!)\npr...
[ 4, 1, 0, 0, 0, 0 ]
[]
[]
[ "compare", "dictionary", "google_app_engine", "python" ]
stackoverflow_0003834571_compare_dictionary_google_app_engine_python.txt
Q: Tornado Web Framework Mysql connection handling I have recently been exploring the Tornado web framework to serve a lot of consistent connections by lots of different clients. I have a request handler that basically takes an RSA encrypted string and decrypts it. The decrypted text is an XML string that gets parsed by a SAX document handler that I have written. Everything works perfectly fine and the execution time (per HTTP request) was roughly 100 milliseconds (with decryption and parsing). The XML contains the Username and Password hash of the user. I want to connect to a MySQL server to verify that the username matches the password hash supplied by the application. When I add basically the following code: conn = MySQLdb.connect (host = "192.168.1.12", user = "<useraccount>", passwd = "<Password>", db = "<dbname>") cursor = conn.cursor() safe_username = MySQLdb.escape_string(XMLLoginMessage.username) safe_pass_hash = MySQLdb.escape_string(XMLLoginMessage.pass_hash) sql = "SELECT * FROM `mrad`.`users` WHERE `username` = '" + safe_username + "' AND `password` = '" + safe_pass_hash + "' LIMIT 1;" cursor.execute(sql) cursor.close() conn.close() The time it takes to execute the HTTP request shoots up to 4 - 5 seconds! I believe this is incurred in the time it takes to connect to the MySql database server itself. My question is how can I speed this up? Can I declare the MySQL connection in the global scope and access it in the request handlers by creating a new cursor, or will that run into concurrency issues because of the asynchronous design of Tornado? Basically, how can I not have to incur a new connection to a MySQL server EVERY Http request, so it only takes a fraction of a second instead of multiple seconds to implement. Also, please note, the SQL server is actually on the same physical machine as the Tornado Web Server instance Update I just ran a simple MySQL query through a profiler, the same code below. The call to 'connections.py' init function took 4.944 seconds to execute alone. That doesn't seem right, does it? Update 2 I think that running with one connection (or even a few with a very simple DB conn pool) will be fast enough to handle the throughput I'm expecting per tornado web server instance. If 1,000 clients need to access a query, typical query times being in the thousands of seconds, the unluckiest client would only have to wait one second to retrieve the data. A: An SQL connection should not take 5 seconds. Try to not issue a query and see if that improves your performance - which it should. The Mysqldb module has a threadsafety of "1", which means the module is thread safe, but connections cannot be shared amongst threads. You can implement a connection pool as an alternative. Lastly, the DB-API has a parameter replacement form for queries which would not require manually concatenating a query and escaping parameters: cur.execute("SELECT * FROM blach WHERE x = ? AND y = ?", (x,y)) A: Consider SQLAlchemy, which provides a nicer abstraction over DBAPI and also provides connection pooling, etc. (You can happily ignore its ORM and just use the SQL-toolkit) (Also, you're not doing blocking database calls in the asynchronous request handlers?) A: Declare it in the base handler, it will be called once per application.
Tornado Web Framework Mysql connection handling
I have recently been exploring the Tornado web framework to serve a lot of consistent connections by lots of different clients. I have a request handler that basically takes an RSA encrypted string and decrypts it. The decrypted text is an XML string that gets parsed by a SAX document handler that I have written. Everything works perfectly fine and the execution time (per HTTP request) was roughly 100 milliseconds (with decryption and parsing). The XML contains the Username and Password hash of the user. I want to connect to a MySQL server to verify that the username matches the password hash supplied by the application. When I add basically the following code: conn = MySQLdb.connect (host = "192.168.1.12", user = "<useraccount>", passwd = "<Password>", db = "<dbname>") cursor = conn.cursor() safe_username = MySQLdb.escape_string(XMLLoginMessage.username) safe_pass_hash = MySQLdb.escape_string(XMLLoginMessage.pass_hash) sql = "SELECT * FROM `mrad`.`users` WHERE `username` = '" + safe_username + "' AND `password` = '" + safe_pass_hash + "' LIMIT 1;" cursor.execute(sql) cursor.close() conn.close() The time it takes to execute the HTTP request shoots up to 4 - 5 seconds! I believe this is incurred in the time it takes to connect to the MySql database server itself. My question is how can I speed this up? Can I declare the MySQL connection in the global scope and access it in the request handlers by creating a new cursor, or will that run into concurrency issues because of the asynchronous design of Tornado? Basically, how can I not have to incur a new connection to a MySQL server EVERY Http request, so it only takes a fraction of a second instead of multiple seconds to implement. Also, please note, the SQL server is actually on the same physical machine as the Tornado Web Server instance Update I just ran a simple MySQL query through a profiler, the same code below. The call to 'connections.py' init function took 4.944 seconds to execute alone. That doesn't seem right, does it? Update 2 I think that running with one connection (or even a few with a very simple DB conn pool) will be fast enough to handle the throughput I'm expecting per tornado web server instance. If 1,000 clients need to access a query, typical query times being in the thousands of seconds, the unluckiest client would only have to wait one second to retrieve the data.
[ "An SQL connection should not take 5 seconds. Try to not issue a query and see if that improves your performance - which it should.\nThe Mysqldb module has a threadsafety of \"1\", which means the module is thread safe, but connections cannot be shared amongst threads. You can implement a connection pool as an alte...
[ 1, 1, 0 ]
[]
[]
[ "mysql", "persistent_connection", "python", "time", "tornado" ]
stackoverflow_0001920012_mysql_persistent_connection_python_time_tornado.txt
Q: Can PHP be more like python? Possible Duplicate: Does PHP have an equivalent to Python's list comprehension syntax? Does PHP have any equivalent of the simple and awesome list comprehension in python? Specifically, can I do a = [x for x in xrange(1,20)] in PHP w/o annoying loops? A: I think this will set you free: http://code.google.com/p/php-lc/ A: Correct me if I'm wrong, but isn't the python 'x for x in xrange' a loop? A: $a = range(1,19);
Can PHP be more like python?
Possible Duplicate: Does PHP have an equivalent to Python's list comprehension syntax? Does PHP have any equivalent of the simple and awesome list comprehension in python? Specifically, can I do a = [x for x in xrange(1,20)] in PHP w/o annoying loops?
[ "I think this will set you free: http://code.google.com/p/php-lc/\n", "Correct me if I'm wrong, but isn't the python 'x for x in xrange' a loop?\n", "$a = range(1,19);\n\n" ]
[ 2, 0, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0003834281_php_python.txt
Q: How to use mod_passenger for Turbogears 2? What do I put in passenger_wsgi.py for a Turbogears2 site? Since it's possible for Django to use mod_passenger, I'm trying to use mod_passenger with Turbogears2. So far, I've found a passenger_wsgi.py for Turbogears1, but I don't know where to start to make a passenger_wsgi.py for a Turbogears2 site. Here's the Turbogears1 example: http://github.com/weyert/passenger-turbogears-example/blob/master/passenger_wsgi.py A: I think the right question would be: how to write a WSGI file for Turbogears 2. If you have a WSGI file that works on other WSGI-compliant servers like mod_wsgi or Green Unicorn then it should work on Phusion Passenger as well.
How to use mod_passenger for Turbogears 2?
What do I put in passenger_wsgi.py for a Turbogears2 site? Since it's possible for Django to use mod_passenger, I'm trying to use mod_passenger with Turbogears2. So far, I've found a passenger_wsgi.py for Turbogears1, but I don't know where to start to make a passenger_wsgi.py for a Turbogears2 site. Here's the Turbogears1 example: http://github.com/weyert/passenger-turbogears-example/blob/master/passenger_wsgi.py
[ "I think the right question would be: how to write a WSGI file for Turbogears 2. If you have a WSGI file that works on other WSGI-compliant servers like mod_wsgi or Green Unicorn then it should work on Phusion Passenger as well.\n" ]
[ 0 ]
[]
[]
[ "passenger", "python", "turbogears", "turbogears2" ]
stackoverflow_0003757740_passenger_python_turbogears_turbogears2.txt
Q: Python class-dependent template? i want to create a widget depending on the class of the object, is there a simple way to do that in mako? for example class A might have attributes A and B while class B might have attributes A, B and C is there a pattern for this? i want to make a super class that they but inherit, but if I have a function print and call it by calling obj.print(), but i don't want to put template code into class functions for example, i have a widget that goes <div>obj.a</div> <div>obj.b</div> <div>obj.c</div> <div>obj.d</div> but if it's object B, i want it to go <div>obj.a</div> <div>obj.b</div> <div>obj.c</div> etc, but was wondering if theres a clean way to do it A: Make a method which returns [a, b] in class A and [a, b, c] in class B. Then you can do: % for stuff in thing.return_list_of_stuff: <div>${stuff}</div> % endfor (I've never used mako, so the syntax might be incorect.)
Python class-dependent template?
i want to create a widget depending on the class of the object, is there a simple way to do that in mako? for example class A might have attributes A and B while class B might have attributes A, B and C is there a pattern for this? i want to make a super class that they but inherit, but if I have a function print and call it by calling obj.print(), but i don't want to put template code into class functions for example, i have a widget that goes <div>obj.a</div> <div>obj.b</div> <div>obj.c</div> <div>obj.d</div> but if it's object B, i want it to go <div>obj.a</div> <div>obj.b</div> <div>obj.c</div> etc, but was wondering if theres a clean way to do it
[ "Make a method which returns [a, b] in class A and [a, b, c] in class B.\nThen you can do: \n% for stuff in thing.return_list_of_stuff:\n <div>${stuff}</div>\n% endfor\n\n(I've never used mako, so the syntax might be incorect.)\n" ]
[ 1 ]
[]
[]
[ "mako", "python", "templates" ]
stackoverflow_0003835116_mako_python_templates.txt
Q: Python, using subprocess.Popen to make linux command line call? I'm getting "[Errno 2] No such file or directory" I'm trying to follow the info I can find about subprocess.Popen as I want to make a linux command line call.. I am trying as below but am getting the error "[Errno 2] No such file or directory". I'm not trying to open a file so I don't understand this error, and it works fine (although with other issues relating to waiting for the process to finish when I don't want it to) when I use a regular os.popen. I can't seem to figure out how to do this properly, any advice is appreciated. EDIT: THE COMMAND I AM USING IS COMPLEX AND VARIABLIZED, it would be too out-of-context to include it here, I think its suffice to say that the code works when I use os.popen and not when I do the new way, so no, the "linux command line call" is obviously not the call I am using subprocess.Popen([r"linux command line call"]) >>> [Errno 2] No such file or directory A: import subprocess proc=subprocess.Popen(['ls','-l']) # <-- Change the command here proc.communicate() Popen expects a list of strings. The first string is typically the program to be run, followed by its arguments. Sometimes when the command is complicated, it's convenient to use shlex.split to compose the list for you: import shlex proc=subprocess.Popen(shlex.split('ls -l')) proc.communicate()
Python, using subprocess.Popen to make linux command line call? I'm getting "[Errno 2] No such file or directory"
I'm trying to follow the info I can find about subprocess.Popen as I want to make a linux command line call.. I am trying as below but am getting the error "[Errno 2] No such file or directory". I'm not trying to open a file so I don't understand this error, and it works fine (although with other issues relating to waiting for the process to finish when I don't want it to) when I use a regular os.popen. I can't seem to figure out how to do this properly, any advice is appreciated. EDIT: THE COMMAND I AM USING IS COMPLEX AND VARIABLIZED, it would be too out-of-context to include it here, I think its suffice to say that the code works when I use os.popen and not when I do the new way, so no, the "linux command line call" is obviously not the call I am using subprocess.Popen([r"linux command line call"]) >>> [Errno 2] No such file or directory
[ "import subprocess \nproc=subprocess.Popen(['ls','-l']) # <-- Change the command here\nproc.communicate()\n\nPopen expects a list of strings. The first string is typically the program to be run, followed by its arguments. Sometimes when the command is complicated, it's convenient to use shlex.split to compose t...
[ 17 ]
[]
[]
[ "command_line", "popen", "python", "subprocess" ]
stackoverflow_0003835400_command_line_popen_python_subprocess.txt
Q: Flatten a dictionary of dictionaries (2 levels deep) of lists I'm trying to wrap my brain around this but it's not flexible enough. In my Python script I have a dictionary of dictionaries of lists. (Actually it gets a little deeper but that level is not involved in this question.) I want to flatten all this into one long list, throwing away all the dictionary keys. Thus I want to transform {1: {'a': [1, 2, 3], 'b': [0]}, 2: {'c': [4, 5, 1], 'd': [3, 8]}} to [1, 2, 3, 0, 4, 5, 1, 3, 8] I could probably set up a map-reduce to iterate over items of the outer dictionary to build a sublist from each subdictionary and then concatenate all the sublists together. But that seems inefficient for large data sets, because of the intermediate data structures (sublists) that will get thrown away. Is there a way to do it in one pass? Barring that, I would be happy to accept a two-level implementation that works... my map-reduce is rusty! Update: For those who are interested, below is the code I ended up using. Note that although I asked above for a list as output, what I really needed was a sorted list; i.e. the output of the flattening could be any iterable that can be sorted. def genSessions(d): """Given the ipDict, return an iterator that provides all the sessions, one by one, converted to tuples.""" for uaDict in d.itervalues(): for sessions in uaDict.itervalues(): for session in sessions: yield tuple(session) ... # Flatten dict of dicts of lists of sessions into a list of sessions. # Sort that list by start time sessionsByStartTime = sorted(genSessions(ipDict), key=operator.itemgetter(0)) # Then make another copy sorted by end time. sessionsByEndTime = sorted(sessionsByStartTime, key=operator.itemgetter(1)) Thanks again to all who helped. [Update: replaced nthGetter() with operator.itemgetter(), thanks to @intuited.] A: I hope you realize that any order you see in a dict is accidental -- it's there only because, when shown on screen, some order has to be picked, but there's absolutely no guarantee. Net of ordering issues among the various sublists getting catenated, [x for d in thedict.itervalues() for alist in d.itervalues() for x in alist] does what you want without any inefficiency nor intermediate lists. A: A recursive function may work: def flat(d, out=[]): for val in d.values(): if isinstance(val, dict): flat(d, out) else: out+= val If you try it with : >>> d = {1: {'a': [1, 2, 3], 'b': [0]}, 2: {'c': [4, 5, 6], 'd': [3, 8]}} >>> out = [] >>> flat(d, out) >>> print out [1, 2, 3, 0, 4, 5, 6, 3, 8] Notice that dictionaries have no order, so the list is in random order. You can also return out (at the end of the loop) and don't call the function with a list argument. def flat(d, out=[]): for val in d.values(): if isinstance(val, dict): flat(d, out) else: out+= val return out call as: my_list = flat(d) A: edit: re-read the original question and reworked answer to assume that all non-dictionaries are lists to be flattened. In cases where you're not sure how far down the dictionaries go, you would want to use a recursive function. @Arrieta has already posted a function that recursively builds a list of non-dictionary values. This one is a generator that yields successive non-dictionary values in the dictionary tree: def flatten(d): """Recursively flatten dictionary values in `d`. >>> hat = {'cat': ['images/cat-in-the-hat.png'], ... 'fish': {'colours': {'red': [0xFF0000], 'blue': [0x0000FF]}, ... 'numbers': {'one': [1], 'two': [2]}}, ... 'food': {'eggs': {'green': [0x00FF00]}, ... 'ham': ['lean', 'medium', 'fat']}} >>> set_of_values = set(flatten(hat)) >>> sorted(set_of_values) [1, 2, 255, 65280, 16711680, 'fat', 'images/cat-in-the-hat.png', 'lean', 'medium'] """ try: for v in d.itervalues(): for nested_v in flatten(v): yield nested_v except AttributeError: for list_v in d: yield list_v The doctest passes the resulting iterator to the set function. This is likely to be what you want, since, as Mr. Martelli points out, there's no intrinsic order to the values of a dictionary, and therefore no reason to keep track of the order in which they were found. You may want to keep track of the number of occurrences of each value; this information will be lost if you pass the iterator to set. If you want to track that, just pass the result of flatten(hat) to some other function instead of set. Under Python 2.7, that other function could be collections.Counter. For compatibility with less-evolved pythons, you can write your own function or (with some loss of efficiency) combine sorted with itertools.groupby.
Flatten a dictionary of dictionaries (2 levels deep) of lists
I'm trying to wrap my brain around this but it's not flexible enough. In my Python script I have a dictionary of dictionaries of lists. (Actually it gets a little deeper but that level is not involved in this question.) I want to flatten all this into one long list, throwing away all the dictionary keys. Thus I want to transform {1: {'a': [1, 2, 3], 'b': [0]}, 2: {'c': [4, 5, 1], 'd': [3, 8]}} to [1, 2, 3, 0, 4, 5, 1, 3, 8] I could probably set up a map-reduce to iterate over items of the outer dictionary to build a sublist from each subdictionary and then concatenate all the sublists together. But that seems inefficient for large data sets, because of the intermediate data structures (sublists) that will get thrown away. Is there a way to do it in one pass? Barring that, I would be happy to accept a two-level implementation that works... my map-reduce is rusty! Update: For those who are interested, below is the code I ended up using. Note that although I asked above for a list as output, what I really needed was a sorted list; i.e. the output of the flattening could be any iterable that can be sorted. def genSessions(d): """Given the ipDict, return an iterator that provides all the sessions, one by one, converted to tuples.""" for uaDict in d.itervalues(): for sessions in uaDict.itervalues(): for session in sessions: yield tuple(session) ... # Flatten dict of dicts of lists of sessions into a list of sessions. # Sort that list by start time sessionsByStartTime = sorted(genSessions(ipDict), key=operator.itemgetter(0)) # Then make another copy sorted by end time. sessionsByEndTime = sorted(sessionsByStartTime, key=operator.itemgetter(1)) Thanks again to all who helped. [Update: replaced nthGetter() with operator.itemgetter(), thanks to @intuited.]
[ "I hope you realize that any order you see in a dict is accidental -- it's there only because, when shown on screen, some order has to be picked, but there's absolutely no guarantee.\nNet of ordering issues among the various sublists getting catenated,\n[x for d in thedict.itervalues()\n for alist in d.itervalues...
[ 19, 6, 6 ]
[]
[]
[ "data_structures", "dictionary", "mapreduce", "python" ]
stackoverflow_0003835192_data_structures_dictionary_mapreduce_python.txt
Q: Python line remover Hi I have a large file that I want to delete the lines that contain the text ALL and print the file without spaces with just the remaining lines. I started a program sourcefile = open('C:\\scoresfinal.txt', 'r') filename2 = open('C:\\nohet.txt', 'w') offending = ["HET"] def fixup( filename ): fin = open( filename ) fout = open( filename2 , "w") for line in fin.readlines(): if True in [item in line for item in offending]: continue fout.write(line) fin.close() fout.close() fixup(sourcefile) but it doesn't work. any help? here is my error: Traceback (most recent call last): File "C:/Python Make Small File/hetcut2.py", line 18, in <module> fixup(sourcefile) File "C:/Python Make Small File/hetcut2.py", line 9, in fixup fin = open( filename ) TypeError: coercing to Unicode: need string or buffer, file found A: sourcefile = open('C:\\scoresfinal.txt', 'r') defines sourcefile as a file object. So fixup(sourcefile) assigns sourcefile to be the value of the local variable filename in the fixup function. Calling open(filename) thus tries to open an already-open file object, when open expected a string naming a file or filepath. You could fix the code this way: sourcefile = 'C:\\scoresfinal.txt' filename2 = 'C:\\nohet.txt' offending = ["HET"] def fixup( filename ): with open( filename ) as fin: with open( filename2 , "w") as fout: for line in fin: if any(item in line for item in offending): continue fout.write(line) fixup(sourcefile) The with open(...) as f statement is available in Python2.6 or better. In Python2.5 you can use the with statement if you put from __future__ import with_statement The advantage of doing it this way is that you are guaranteed to close the file handles with Python exits the with-block. (Notice the explicit calls to fin.close() and fout.close() were removed.) Using with is not necessary to solve your immediate problem, but it is the future standard idiom in Python, so you might as well get used to it. A: In the beginning, you open a file and store the handle inside of filename2. Then within the function, you are trying to use that filename2 as a – well – filename, when it is instead a handle to an already opened file. If you want that to work, you have to set filename2 to the actual filename: filename2 = 'C:\\nohet.txt' Also, you should consider moving the target pathname into the function parameters, so it doesn't depend on some global variable. Oh, and the same applies to sourcefile which is a file handle as well but which your function tries to use as a filename as well. edit: Like this: def fixup( source, target, badWords ): fin = open( source ) fout = open( target , "w" ) for line in fin: if any( ( word in line ) for word in badWords ): continue fout.write( line ) fin.close() fout.close() offending = ["HET"] fixup( 'C:\\scoresfinal.txt', 'C:\\nohet.txt', offending ) A: 2) sourcefile and filename2 are files, not a string. A: The question has already been answered (you are "opening the files twice") but I thought I should point out that you could tidy the code somewhat: def fixup( filename ): with fin as open(filename), fout as open(filename2 , "w") for line in fin: if not any(word in line for word in offending): fout.write(line) Also, you should consider using better variable names. fixup, filename, filename2 (ugh!) are not very illuminating.
Python line remover
Hi I have a large file that I want to delete the lines that contain the text ALL and print the file without spaces with just the remaining lines. I started a program sourcefile = open('C:\\scoresfinal.txt', 'r') filename2 = open('C:\\nohet.txt', 'w') offending = ["HET"] def fixup( filename ): fin = open( filename ) fout = open( filename2 , "w") for line in fin.readlines(): if True in [item in line for item in offending]: continue fout.write(line) fin.close() fout.close() fixup(sourcefile) but it doesn't work. any help? here is my error: Traceback (most recent call last): File "C:/Python Make Small File/hetcut2.py", line 18, in <module> fixup(sourcefile) File "C:/Python Make Small File/hetcut2.py", line 9, in fixup fin = open( filename ) TypeError: coercing to Unicode: need string or buffer, file found
[ "sourcefile = open('C:\\\\scoresfinal.txt', 'r')\n\ndefines sourcefile as a file object. So \nfixup(sourcefile)\n\nassigns sourcefile to be the value of the local variable filename in the fixup function.\nCalling open(filename) thus tries to open an already-open file object, when open expected a string naming a fil...
[ 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003834949_python.txt
Q: python kata problem: Color not working When I try to run the python koans, I don't get the colors, instead I get the ANSI color codes. I want to get the colors. It seems to be using colorama under the hood. I try to run colorama sample code in the interpeter and get syntax errors and/or assert errors. Second if can't fix first: How do I get to strip out the ansi color codes. I tried various values of strip=True, and Convert=False to no avail. Please help. A: Sorry about that! The ansi colors are a very recent feature, and I haven't got around to adding a command line option to turn it off yet. Its coming very soon though! In the meantime taking a slightly older version would get around the problem. Here's how you can do it through mercurial: hg clone https://gregmalcolm@bitbucket.org/gregmalcolm/python_koans hg update -r 80 and this should work for git: git clone http://github.com/gregmalcolm/python_koans git checkout -b nocolor a410591b5aaeec57a4a8 This is actually the first complaint I've had of the color not working. What OS/terminal are you running from?
python kata problem: Color not working
When I try to run the python koans, I don't get the colors, instead I get the ANSI color codes. I want to get the colors. It seems to be using colorama under the hood. I try to run colorama sample code in the interpeter and get syntax errors and/or assert errors. Second if can't fix first: How do I get to strip out the ansi color codes. I tried various values of strip=True, and Convert=False to no avail. Please help.
[ "Sorry about that!\nThe ansi colors are a very recent feature, and I haven't got around to adding a command line option to turn it off yet. Its coming very soon though!\nIn the meantime taking a slightly older version would get around the problem. Here's how you can do it through mercurial:\nhg clone https://gregma...
[ 0 ]
[]
[]
[ "ansi_colors", "python" ]
stackoverflow_0003814714_ansi_colors_python.txt
Q: Wrong output in Python - as per my logic Can someone tell me why my program is working weird. I am trying to sort list1 in ascending order. This code is part of my quick sort program I am trying to write. As per my logic which I am applying in this code, and I checked manually too, the output should be [1,2,3,4,5]. However the output is coming out to be [1,2,2,4,5]. Can you tell what's going wrong? list1=[3,2,1,5,4] n_list1=len(list1) count=0 for position1, item1 in enumerate(list1[0:n_list1]): temp=item1 count=count+1 for position2 in range(count,n_list1): if list1[position1]>list1[position2]: list1[position1]=list1[position2] list1[position2]=temp temp=list1[position1] print list1 EDIT: What I am trying to do is like this: I start comparing the first element with the following (n-1) elements and swap the smallest element with the first one. Now I go to 2nd element and compare it with the following (n-2) elements and swap with the smallest element among those (n-2) elements. Like this I move forward. Note: This is part of my quicksort program and it is not in itself quicksort. This part is for the list1 to which I assign numbers less than pivot. Another code will be for list2 where I will assign numbers greater than pivot. A: Since you do count = count + 1 right before the innermost for, you never get to reach the first position of list1 (list1[0]), which is the element "3". [Edit] Looking more carefully at your code, there seems to be a lot of confusion. For instance, on list1[position1]=list1[position2] list1[position2]=temp temp=list1[position1] You're losing list1[position1]: you're overwriting it with list[position2], before trying to save it at the temp variable. Try moving temp=list1[position1] to the first line after the if. And, honestly, your implementation is overly complicated. I suggest you try writing it in pseudo-code, try to actually understand what's going on, and then re-implement it. A: The answer provided by rbp is absolutely correct! Also, I guess you could simplify the above by remove count itself, also directly enumerate the list and use the python idiom - a, b = b, a to swap the values list1=[3,2,1,6,5,4] n_list1 = len(list1) for position1, item1 in enumerate(list1): for position2 in range(position1,n_list1): if list1[position1]>list1[position2]: list1[position1] , list1[position2] = list1[position2], list1[position1] print list1 Output: [1, 2, 3, 4, 5, 6] [Edit: About the idiom] >>> a = 4 >>> b = 5 >>> a , b = b, a >>> a 5 >>> b 4 >>> c = 5 >>> d = 6 >>> t = c >>> c = d >>> d = t >>> c 6 >>> d 5 >>> A: A small improvement to pyfunc's correct answer... This line for position2 in range(position1,n_list1) can be for position2 in range(position1+1,n_list1) and will save you a little time.
Wrong output in Python - as per my logic
Can someone tell me why my program is working weird. I am trying to sort list1 in ascending order. This code is part of my quick sort program I am trying to write. As per my logic which I am applying in this code, and I checked manually too, the output should be [1,2,3,4,5]. However the output is coming out to be [1,2,2,4,5]. Can you tell what's going wrong? list1=[3,2,1,5,4] n_list1=len(list1) count=0 for position1, item1 in enumerate(list1[0:n_list1]): temp=item1 count=count+1 for position2 in range(count,n_list1): if list1[position1]>list1[position2]: list1[position1]=list1[position2] list1[position2]=temp temp=list1[position1] print list1 EDIT: What I am trying to do is like this: I start comparing the first element with the following (n-1) elements and swap the smallest element with the first one. Now I go to 2nd element and compare it with the following (n-2) elements and swap with the smallest element among those (n-2) elements. Like this I move forward. Note: This is part of my quicksort program and it is not in itself quicksort. This part is for the list1 to which I assign numbers less than pivot. Another code will be for list2 where I will assign numbers greater than pivot.
[ "Since you do count = count + 1 right before the innermost for, you never get to reach the first position of list1 (list1[0]), which is the element \"3\". \n[Edit] Looking more carefully at your code, there seems to be a lot of confusion. For instance, on\n list1[position1]=list1[position2]\n list1[po...
[ 4, 2, 0 ]
[]
[]
[ "list", "python", "quicksort" ]
stackoverflow_0003834378_list_python_quicksort.txt
Q: Rewriting An URL With Regular Expression Substitution in Routes In my Pylons app, some content is located at URLs that look like http://mysite/data/31415. Users can go to that URL directly, or search for "31415" via the search page. My constraints, however, mean that http://mysite/data/000031415 should go to the same page as the above, as should searches for "0000000000031415." Can I strip leading zeroes from that string in Routes itself, or do I need to do that substitution in the controller file? If it's possible to do it in routing.py, I'd rather do it there - but I can't quite figure it out from the documentation that I'm reading. A: You can actually do that via conditional functions, since they let you modify the variables from the URL in place. A: I know I am cheating by introducing a different routing library, since I haven't used Routes, but here's how this is done with Werkzeug's routing package. It lets you specify that a given fragment of the path is an integer. You can also implement a more specialized "converter" by inheriting werkzeug.routing.BaseConverter, if you wanted to parse something more interesting (e.g. a UUID). Perhaps, Routes has a similar mechanism in place for specialized path-fragment-parsing needs. import unittest from werkzeug.routing import Map, Rule class RoutingWithInts(unittest.TestCase): m = Map([Rule('/data/<int:record_locator>', endpoint='data_getter')]) def test_without_leading_zeros(self): urls = self.m.bind('localhost') endpoint, urlvars = urls.match('/data/31415') self.assertEquals({'record_locator': 31415}, urlvars) def test_with_leading_zeros(self): urls = self.m.bind('localhost') endpoint, urlvars = urls.match('/data/000031415') self.assertEquals({'record_locator': 31415}, urlvars) unittest.main()
Rewriting An URL With Regular Expression Substitution in Routes
In my Pylons app, some content is located at URLs that look like http://mysite/data/31415. Users can go to that URL directly, or search for "31415" via the search page. My constraints, however, mean that http://mysite/data/000031415 should go to the same page as the above, as should searches for "0000000000031415." Can I strip leading zeroes from that string in Routes itself, or do I need to do that substitution in the controller file? If it's possible to do it in routing.py, I'd rather do it there - but I can't quite figure it out from the documentation that I'm reading.
[ "You can actually do that via conditional functions, since they let you modify the variables from the URL in place. \n", "I know I am cheating by introducing a different routing library, since I haven't used Routes, but here's how this is done with Werkzeug's routing package. It lets you specify that a given fra...
[ 1, 0 ]
[]
[]
[ "pylons", "python", "routes" ]
stackoverflow_0002464844_pylons_python_routes.txt
Q: How do I specify a range of unicode characters How do I specify a range of unicode characters from ' ' (space) to \u00D7FF? I have a regular expression like r'[\u0020-\u00D7FF]' and it won't compile saying that it's a bad range. I am new to Unicode regular expressions so I haven't had this problem before. Is there a way to make this compile or a regular expression that I'm forgetting or haven't learned yet? A: The syntax of your unicode range will not do what you expect. The raw r'' string prevents \u escapes from being parsed, and the regex engine will not do this. The only range in this set is [0-\]: >>> re.compile(r'[\u0020-\u00d7ff]', re.DEBUG) in literal 117 literal 48 literal 48 literal 50 range (48, 117) literal 48 literal 48 literal 100 literal 55 literal 102 literal 102 Making it a Unicode literal causes \u parsing while leaving other backslashes alone (although that’s not a concern here), but the leading zeroes are messing it up. The syntax is \uxxxx or \Uxxxxxxxx, so it’s parsed as "\u00d7, f, f". >>> re.compile(ur'[\u0020-\u00d7ff]', re.DEBUG) in range (32, 215) literal 102 literal 102 Removing the leading zeroes or switching to \U0000d7ff will fix it: >>> re.compile(ur'[\u0020-\ud7ff]', re.DEBUG) in range (32, 55295) A: If you're using Python 2.x, you should make sure you're specifying a unicode string (with u'', or the "unicode" built-in): >>> r = re.compile(u'[\u0020-\uD7FF]') >>> r.search(u'foo \uD7F0 bar') <_sre.SRE_Match object at 0xb7084950> r.search(u' ') <_sre.SRE_Match object at 0xb7084b48> Using raw strings (as you are, with r'') gives you the (ascii) string composed by "backstroke" + the letter "u" plus the number 0 plus...
How do I specify a range of unicode characters
How do I specify a range of unicode characters from ' ' (space) to \u00D7FF? I have a regular expression like r'[\u0020-\u00D7FF]' and it won't compile saying that it's a bad range. I am new to Unicode regular expressions so I haven't had this problem before. Is there a way to make this compile or a regular expression that I'm forgetting or haven't learned yet?
[ "The syntax of your unicode range will not do what you expect.\n\nThe raw r'' string prevents \\u escapes from being parsed, and the regex engine will not do this. The only range in this set is [0-\\]:\n>>> re.compile(r'[\\u0020-\\u00d7ff]', re.DEBUG)\nin\n literal 117\n literal 48\n literal 48\n literal 50\n ...
[ 34, 5 ]
[]
[]
[ "python", "regex", "unicode" ]
stackoverflow_0003835917_python_regex_unicode.txt
Q: Toplevel widgets in Tkinter I have a Toplevel widget I'd like it so that it would never appear within the confines of the main Tk window. Basically so that when the Toplevel appears it doesn't cover up any of the main Tk window. A: You want to use wm_geometry and a tiny bit of math to calculate and set a suitable starting position for the second toplevel. A: You could just set up a separate toplevel, cf: self.newwindow = Toplevel(self) self.newwindow.title('New Window') and then embed the widget in the separate toplevel.
Toplevel widgets in Tkinter
I have a Toplevel widget I'd like it so that it would never appear within the confines of the main Tk window. Basically so that when the Toplevel appears it doesn't cover up any of the main Tk window.
[ "You want to use wm_geometry and a tiny bit of math to calculate and set a suitable starting position for the second toplevel.\n", "You could just set up a separate toplevel, cf:\nself.newwindow = Toplevel(self)\nself.newwindow.title('New Window')\n\nand then embed the widget in the separate toplevel. \n" ]
[ 1, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003836086_python_tkinter.txt
Q: Finding the character occupying a particular index in a string I have a the string 'Hello', I need to find out what characters occupy which indexes. Pseudo-code: string = 'Hello' a = string.index(0) b = string.index(4) print a , b a would be 'H' and b would be 'o'. A: a = "Hello" print a[0] print a[4] A: String (str) in Python is a sequence type, and thus can be accessed with []: my_string = 'Hello' a = my_string[0] b = my_string[4] print a, b # Prints H o This means it also supports slicing, which is the standard way to get a substring in Python: print my_string[1:3] # Prints el A: I think he is asking for this for index,letter in enumerate('Hello'): print 'Index Position ',index, 'The Letter ', letter And maybe we want to explore some data structures so lets add a dictionary - I can do this lazily since I know that index values are unique index_of_letters={} for index,letter in enumerate('Hello'): index_of_letters[index]=letter index_of_letters
Finding the character occupying a particular index in a string
I have a the string 'Hello', I need to find out what characters occupy which indexes. Pseudo-code: string = 'Hello' a = string.index(0) b = string.index(4) print a , b a would be 'H' and b would be 'o'.
[ "a = \"Hello\"\nprint a[0]\nprint a[4]\n\n", "String (str) in Python is a sequence type, and thus can be accessed with []:\nmy_string = 'Hello'\n\na = my_string[0]\nb = my_string[4]\n\nprint a, b # Prints H o\n\nThis means it also supports slicing, which is the standard way to get a substring in Python:\nprint my...
[ 4, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003835861_python.txt
Q: Swapping token values in a string through regex I have tokenized names (strings), with the tokens separated by underscores, which will always contain a "side" token by the value of M, L, or R. The presence of that value is guaranteed to be unique (no repetitions or dangers that other tokens might get similar values). In example: foo_M_bar_type foo_R_bar_type foo_L_bar_type I'd like, in a single regex, to swap L for R and viceversa whenever found, and M to be left untouched. IE the above would become: foo_M_bar_type foo_L_bar_type foo_R_bar_type when pushed through this ideal expression. This was what I thought to be a 10 minutes exercise while writing some simple stuff, that I couldn't quite crack as concisely as I wanted to. The problem itself was of course trivial to solve with one condition that changes the pattern, but I'd love some help doing it within a single re.sub() Of course any food for thought is always welcome, but this being an intellectual exercise that me and a couple colleagues failed at I'd love to see it cracked that way. And yes, I'm fully aware it might not be considered very Pythonic, nor ideal, to solve the problem with a regex, but humour me please :) Thanks in advance A: This answer [ab]uses the replacement function: >>> s = "foo_M_bar_type foo_R_bar_type foo_L_bar_type" >>> import re >>> re.sub("_[LR]_", lambda m: {'_L_':'_R_','_R_':'_L_'}[m.group()], s) 'foo_M_bar_type foo_L_bar_type foo_R_bar_type' >>>
Swapping token values in a string through regex
I have tokenized names (strings), with the tokens separated by underscores, which will always contain a "side" token by the value of M, L, or R. The presence of that value is guaranteed to be unique (no repetitions or dangers that other tokens might get similar values). In example: foo_M_bar_type foo_R_bar_type foo_L_bar_type I'd like, in a single regex, to swap L for R and viceversa whenever found, and M to be left untouched. IE the above would become: foo_M_bar_type foo_L_bar_type foo_R_bar_type when pushed through this ideal expression. This was what I thought to be a 10 minutes exercise while writing some simple stuff, that I couldn't quite crack as concisely as I wanted to. The problem itself was of course trivial to solve with one condition that changes the pattern, but I'd love some help doing it within a single re.sub() Of course any food for thought is always welcome, but this being an intellectual exercise that me and a couple colleagues failed at I'd love to see it cracked that way. And yes, I'm fully aware it might not be considered very Pythonic, nor ideal, to solve the problem with a regex, but humour me please :) Thanks in advance
[ "This answer [ab]uses the replacement function:\n>>> s = \"foo_M_bar_type foo_R_bar_type foo_L_bar_type\"\n>>> import re\n>>> re.sub(\"_[LR]_\", lambda m: {'_L_':'_R_','_R_':'_L_'}[m.group()], s)\n'foo_M_bar_type foo_L_bar_type foo_R_bar_type'\n>>>\n\n" ]
[ 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003836335_python_regex.txt
Q: Two Tkinter Questions Is it possible to change the color of certain particular bits of text in the entry widget, or does it all have to be the same color? Is it possible to change the Tk logo in the top right to a different image? A: 1) No, you cannot change the color of just a part of the text in an entry widget. If you need to do that you can use a Text widget. From effbot, the best tkinter reference on the web: When to use the Entry Widget The entry widget is used to enter text strings. This widget allows the user to enter one line of text, in a single font. To enter multiple lines of text, use the Text widget. The Text widget has this capability thanks to the Tag concept see http://effbot.org/tkinterbook/text.htm 2) Yes root = Tk() root.wm_iconbitmap('my_icon.ico') root.mainloop()
Two Tkinter Questions
Is it possible to change the color of certain particular bits of text in the entry widget, or does it all have to be the same color? Is it possible to change the Tk logo in the top right to a different image?
[ "1) No, you cannot change the color of just a part of the text in an entry widget. If you need to do that you can use a Text widget. \nFrom effbot, the best tkinter reference on the web:\n\nWhen to use the Entry Widget\nThe entry widget is used to enter text strings. This widget allows the user to enter one line of...
[ 3 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003836625_python_tkinter.txt
Q: pyapns - hexlified_token_str i try to test pyapns. There is a mention of the hexlified_token_str in the documentation. My token is stored in base64 format. I try to do this >>> notify('myapp', base64.decodestring('Sl96FJtZbZDZECSP3EedQJbsXdtlV+LXWd4+jbzvbHM='), {'aps':{'alert': 'Hello!'}}) But I'm wrong. Traceback (most recent call last): File "<stdin>", line 1, in <module> File "build/bdist.linux-i686/egg/pyapns/client.py", line 54, in notify File "build/bdist.linux-i686/egg/pyapns/client.py", line 76, in _xmlrpc_thread File "/usr/lib/python2.5/xmlrpclib.py", line 1147, in __call__ return self.__send(self.__name, args) File "/usr/lib/python2.5/xmlrpclib.py", line 1437, in __request verbose=self.__verbose File "/usr/lib/python2.5/xmlrpclib.py", line 1201, in request return self._parse_response(h.getfile(), sock) File "/usr/lib/python2.5/xmlrpclib.py", line 1340, in _parse_response return u.close() File "/usr/lib/python2.5/xmlrpclib.py", line 787, in close raise Fault(**self._stack[0]) xmlrpclib.Fault: <Fault 8002: "Can't deserialize input: not well-formed (invalid token): line 9, column 18"> How do I do hexlified it correctly ? A: It was too late yesterday ... It did the job : binascii.hexlify(base64.decodestring('Sl96FJtZbZDZECSP3EedQJbsXdtlV+LXWd4+jbzvbHM=')) It was just an obsolete token !
pyapns - hexlified_token_str
i try to test pyapns. There is a mention of the hexlified_token_str in the documentation. My token is stored in base64 format. I try to do this >>> notify('myapp', base64.decodestring('Sl96FJtZbZDZECSP3EedQJbsXdtlV+LXWd4+jbzvbHM='), {'aps':{'alert': 'Hello!'}}) But I'm wrong. Traceback (most recent call last): File "<stdin>", line 1, in <module> File "build/bdist.linux-i686/egg/pyapns/client.py", line 54, in notify File "build/bdist.linux-i686/egg/pyapns/client.py", line 76, in _xmlrpc_thread File "/usr/lib/python2.5/xmlrpclib.py", line 1147, in __call__ return self.__send(self.__name, args) File "/usr/lib/python2.5/xmlrpclib.py", line 1437, in __request verbose=self.__verbose File "/usr/lib/python2.5/xmlrpclib.py", line 1201, in request return self._parse_response(h.getfile(), sock) File "/usr/lib/python2.5/xmlrpclib.py", line 1340, in _parse_response return u.close() File "/usr/lib/python2.5/xmlrpclib.py", line 787, in close raise Fault(**self._stack[0]) xmlrpclib.Fault: <Fault 8002: "Can't deserialize input: not well-formed (invalid token): line 9, column 18"> How do I do hexlified it correctly ?
[ "It was too late yesterday ...\nIt did the job :\nbinascii.hexlify(base64.decodestring('Sl96FJtZbZDZECSP3EedQJbsXdtlV+LXWd4+jbzvbHM='))\n\nIt was just an obsolete token !\n" ]
[ 1 ]
[]
[]
[ "apple_push_notifications", "python" ]
stackoverflow_0003833988_apple_push_notifications_python.txt
Q: unit testing a python function which invokes a vim subprocess I've written a function which opens a vim editor with the given filename when called.. How can I do the unittest of these types of operations.... A: To unit test something like this you must mock/stub out your dependencies. In this case lets say you are launching vim by calling os.system("vim"). In your unit test you can stub out that function call doing something like: def launchVim(): os.system("vim") def testThatVimIsLaunched(): try: realSystem = os.system called = [] def stubSystem(command): if command == "vim": called.append(True) os.system = stubSystem launchVim() # function under test assert(called == [True]) finally: os.system = realSystem For more details on mocking and stubbing take a look at this article Update: I added the try/finally to restore the original system function as suggested by Dave Kirby A: This is no longer unittesting but integration testing. Why do you need to launch vim? Usually, you would 'mock' this, simulate the process spawning and depend on the fact that python's subprocess module is well tested. To accomplish this in your code, you can, for example, subclass the class that implements your functionality and override the method that's responsible for spawning. Then test this subclass. I.e. class VimSpawner(object): # your actual code, to be tested ... def spawn(self): ... do subprocess magic def other_logic(self): ... self.spawn() class TestableVimSpawner(VimSpawner): def spawn(self): ... mock the spawning self.ididit = True class Test(..): def test_spawning(self): t = TestableVimSpawner() t.other_logic() self.failUnless(t.ididit)
unit testing a python function which invokes a vim subprocess
I've written a function which opens a vim editor with the given filename when called.. How can I do the unittest of these types of operations....
[ "To unit test something like this you must mock/stub out your dependencies. In this case lets say you are launching vim by calling os.system(\"vim\").\nIn your unit test you can stub out that function call doing something like:\ndef launchVim():\n os.system(\"vim\")\n\ndef testThatVimIsLaunched():\n try:\n ...
[ 6, 5 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0003836411_python_unit_testing.txt
Q: django python: How to use the source instead of the egg? I was having some issues with a Django app called "django-categories" The developer told me to use the source instead of the egg. How do I do that? A: On the github page you link to, there's a "download source" link. Use that to download a zip or tar archive, then unzip it and make sure that the "categories" directory is in your PYTHONPATH. A: Just copy the categories directory to your project directory(where all your other apps go) and add it to installed apps and run syncdb or schema migration and you should be up and running.
django python: How to use the source instead of the egg?
I was having some issues with a Django app called "django-categories" The developer told me to use the source instead of the egg. How do I do that?
[ "On the github page you link to, there's a \"download source\" link. Use that to download a zip or tar archive, then unzip it and make sure that the \"categories\" directory is in your PYTHONPATH.\n", "Just copy the categories directory to your project directory(where all your other apps go) and add it to instal...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003837008_django_python.txt
Q: Updating sitemap from django to google webmaster doesn't work Our website gets updated almost everyday. We need to update the sitemap to the google webmasters every time there are new pages added. We have tried using ping_google() along with the required set of arguments and google and it never seem to update the sitemap on webmasters. To log the response, we re-wrote the function and logged the response given below: 2010-10-01 09:00:02,489 DEBUG Sitemap Response: <html><meta http-equiv="content-type" content="text/html; charset=UTF-8"> <head><title>Google Webmaster Tools - Sitemap Notification Received</title> <meta name="robots" content="noindex, noodp"> <script src="https://ssl.google-analytics.com/urchin.js" type="text/javascript"> </script> <script type="text/javascript"> _uacct="UA-18009-2"; _utcp="/webmasters/"; _uanchor=1; urchinTracker(); </script></head> <body><h2>Sitemap Notification Received</h2> <br> Your Sitemap has been successfully added to our list of Sitemaps to crawl. If this is the first time you are notifying Google about this Sitemap, please add it via <a href="http://www.google.com/webmasters/tools/">http://www.google.com/webmasters/tools/</a> so you can track its status. Please note that we do not add all submitted URLs to our index, and we cannot make any predictions or guarantees about when or if they will appear.</body></html> The response seem to look fine. But the sitemap never gets updated on webmasters. We are using django 1.1. Is there any alternative to update the sitemap on webmasters other than the ping_google() A: Can you post the link to your sitemaps file. If you have set priority for most of the URL's in your sitemap high, google might think it's kind of spamming and will not bother to download sitemap. Also check the change frequency in your sitemap. If your sitemap is fine and content really changes everyday, google will automatically download it even if you don't ping it.
Updating sitemap from django to google webmaster doesn't work
Our website gets updated almost everyday. We need to update the sitemap to the google webmasters every time there are new pages added. We have tried using ping_google() along with the required set of arguments and google and it never seem to update the sitemap on webmasters. To log the response, we re-wrote the function and logged the response given below: 2010-10-01 09:00:02,489 DEBUG Sitemap Response: <html><meta http-equiv="content-type" content="text/html; charset=UTF-8"> <head><title>Google Webmaster Tools - Sitemap Notification Received</title> <meta name="robots" content="noindex, noodp"> <script src="https://ssl.google-analytics.com/urchin.js" type="text/javascript"> </script> <script type="text/javascript"> _uacct="UA-18009-2"; _utcp="/webmasters/"; _uanchor=1; urchinTracker(); </script></head> <body><h2>Sitemap Notification Received</h2> <br> Your Sitemap has been successfully added to our list of Sitemaps to crawl. If this is the first time you are notifying Google about this Sitemap, please add it via <a href="http://www.google.com/webmasters/tools/">http://www.google.com/webmasters/tools/</a> so you can track its status. Please note that we do not add all submitted URLs to our index, and we cannot make any predictions or guarantees about when or if they will appear.</body></html> The response seem to look fine. But the sitemap never gets updated on webmasters. We are using django 1.1. Is there any alternative to update the sitemap on webmasters other than the ping_google()
[ "Can you post the link to your sitemaps file. \nIf you have set priority for most of the URL's in your sitemap high, google might think it's kind of spamming and will not bother to download sitemap. \nAlso check the change frequency in your sitemap.\nIf your sitemap is fine and content really changes everyday, goog...
[ 0 ]
[]
[]
[ "django", "google_search_console", "python", "sitemap", "urllib" ]
stackoverflow_0003836529_django_google_search_console_python_sitemap_urllib.txt
Q: Continous loop and exiting in python I have a script that runs continuously when invoked and every 5 minutes checks my gmail inbox. To get it to run every 5 minutes I am using the time.sleep() function. However I would like user to end the script anytime my pressing q, which it seems cant be done when using time.sleep(). Any suggestions on how i can do this? Ali A: You can use select() on sys.stdin combined with a timeout. Roughly speaking, your main loop will look like this (untested): while True: r,w,e = select.select([sys.stdin], [], [], 600) if sys.stdin in r: # data available on sys.stdin if sys.stdin.read() == 'q': break # do gmail stuff To be able to read a single character from stdin you will need to put stdin in unbuffered mode. An alternative is described here. If you want to keep things simple, just require the user to hit enter after the 'q' The -u flag I mentioned earlier won't work: it may put pyton in unbuffered mode but not your terminal. Alternatively, ncursus may be of help here. I'm merely hinting, I don't have much experience with this; if I want a fancy user interface, I'd use TkInter. A: Ok. try this python code... (Tested in linux. Most probably wont work on Windows - thanks to Aaron's input on that) This is derived (copied and modified) from http://code.activestate.com/recipes/572182-how-to-implement-kbhit-on-linux/ import sys, termios, atexit from select import select delay = 1 # in seconds - change this for your needs # save the terminal settings fd = sys.stdin.fileno() new_term = termios.tcgetattr(fd) old_term = termios.tcgetattr(fd) # new terminal setting unbuffered new_term[3] = (new_term[3] & ~termios.ICANON & ~termios.ECHO) # switch to normal terminal def set_normal_term(): termios.tcsetattr(fd, termios.TCSAFLUSH, old_term) # switch to unbuffered terminal def set_curses_term(): termios.tcsetattr(fd, termios.TCSAFLUSH, new_term) def getch(): return sys.stdin.read(1) def kbhit(): dr,dw,de = select([sys.stdin], [], [], delay) return dr <> [] def check_mail(): print 'Checking mail' if __name__ == '__main__': atexit.register(set_normal_term) set_curses_term() while 1: if kbhit(): ch = getch() break check_mail() print 'done' A: If you really wanted to (and wanted to waste a lot of resources), you could cut your loop into 200 ms chunks. So sleep 200 ms, check input, repeat until five minutes elapse, and then check your inbox. I wouldn't recommend it, though. While it's sleeping, though, the process is blocked and won't receive input until the sleep ends. Oh, as an added note, if you hit the key while it's sleeping, it should still go into the buffer, so it'll get pulled out when the sleep ends and input is finally read, IIRC.
Continous loop and exiting in python
I have a script that runs continuously when invoked and every 5 minutes checks my gmail inbox. To get it to run every 5 minutes I am using the time.sleep() function. However I would like user to end the script anytime my pressing q, which it seems cant be done when using time.sleep(). Any suggestions on how i can do this? Ali
[ "You can use select() on sys.stdin combined with a timeout. Roughly speaking, your main loop will look like this (untested):\nwhile True:\n r,w,e = select.select([sys.stdin], [], [], 600)\n if sys.stdin in r: # data available on sys.stdin\n if sys.stdin.read() == 'q':\n break\n # do gmail...
[ 3, 1, 0 ]
[]
[]
[ "continuous", "python" ]
stackoverflow_0003836620_continuous_python.txt
Q: "SyntaxError: unexpected EOF while parsing" when using input() I have 2 Python scripts which are main_menu.py and inputip.py. The problem occurs when I press "enter" to be redirected to main_menu.py when my function finishes in inputip.py. The script does not allow me to redirect to main_menu.py instead it shows this error on the Windows command prompt: Traceback (most recent call last): File "C:\python\main_menu.py", line 32, in ? execfile('C:\python\Inputip.py') File "C:\python\Inputip.py", line 11, in ? input ("\nSelect enter to proceed back to Main Menu\n") File "<string>", line 0 ^ SyntaxError: unexpected EOF while parsing Here are my codes (main_menu.py): def menu(): #print what options you have print "Welcome to Simple Network Program" print " " print "Please enter a following option to proceed" print " " print "2) View Personal IP Address" print " " return input ("Select an Option here: ") loop = 1 choice = 0 while loop == 1: choice = menu() if choice == 1: execfile('Inputip.py') elif choice == 5: loop = 0 print "Thank you for using the Simple Network Program!" The code (inputip.py): #! /usr/bin/python # To change this template, choose Tools | Templates # and open the template in the editor. import socket import os print ("\n\n"+socket.gethostbyname(socket.gethostname())) input ("\nSelect enter to proceed back to Main Menu\n") execfile('C:\python\main_menu.py') The error seems to be pointing to the execfile. Some advice on the codes would be great. Thanks! A: Unless you are using python 3.x (but your question is not tagged as such), don't use input. Use raw_input in stead. It will return strings, so convert them to int first, or do a string comparison. E.g. x = raw_input("Choice") if x == '1': do_this()
"SyntaxError: unexpected EOF while parsing" when using input()
I have 2 Python scripts which are main_menu.py and inputip.py. The problem occurs when I press "enter" to be redirected to main_menu.py when my function finishes in inputip.py. The script does not allow me to redirect to main_menu.py instead it shows this error on the Windows command prompt: Traceback (most recent call last): File "C:\python\main_menu.py", line 32, in ? execfile('C:\python\Inputip.py') File "C:\python\Inputip.py", line 11, in ? input ("\nSelect enter to proceed back to Main Menu\n") File "<string>", line 0 ^ SyntaxError: unexpected EOF while parsing Here are my codes (main_menu.py): def menu(): #print what options you have print "Welcome to Simple Network Program" print " " print "Please enter a following option to proceed" print " " print "2) View Personal IP Address" print " " return input ("Select an Option here: ") loop = 1 choice = 0 while loop == 1: choice = menu() if choice == 1: execfile('Inputip.py') elif choice == 5: loop = 0 print "Thank you for using the Simple Network Program!" The code (inputip.py): #! /usr/bin/python # To change this template, choose Tools | Templates # and open the template in the editor. import socket import os print ("\n\n"+socket.gethostbyname(socket.gethostname())) input ("\nSelect enter to proceed back to Main Menu\n") execfile('C:\python\main_menu.py') The error seems to be pointing to the execfile. Some advice on the codes would be great. Thanks!
[ "Unless you are using python 3.x (but your question is not tagged as such), don't use input. Use raw_input in stead. It will return strings, so convert them to int first, or do a string comparison. E.g.\nx = raw_input(\"Choice\")\nif x == '1': \n do_this()\n\n" ]
[ 1 ]
[]
[]
[ "input", "python", "python_2.x", "syntax_error" ]
stackoverflow_0003837546_input_python_python_2.x_syntax_error.txt
Q: Is there a way to use the java browsing perspective of eclipse for python? I'd like to use the browsing perspective ("column view") of eclipse for Python development. Is there a way to do this? A: please look http://www.pydev.org
Is there a way to use the java browsing perspective of eclipse for python?
I'd like to use the browsing perspective ("column view") of eclipse for Python development. Is there a way to do this?
[ "please look http://www.pydev.org\n" ]
[ 2 ]
[]
[]
[ "eclipse", "perspective", "python" ]
stackoverflow_0003837456_eclipse_perspective_python.txt
Q: PHP HTTP server? Ports 80, 443-444, 1000-3000, 8000-9000. (No-Apache) I will upgrading to Linux Debian 6.0 "Squeeze" on the server soon and I want to know how I can use Python as a web-server on many ports dedicated for different things.. Ports Directory Description 80, 443 /var/www/sitegen/ Take all domains and generate a site from the SQL DB 444, 1000-3000 /var/www/manager/ Take 444 as a PHP server manager and the rest to be forwarded to serial hardware. 8000-9000 The VMs DIR Forward the port to port 80 (or 443 by settings) on the VMs. This Means that the port 443 could be used for many sites (powered by the same code just diffrent in the SQL DB) A: This isn't a PHP question as the PHP interpreter doesn't directly listen on ports. On Linux, it will (usually) run inside Apache. Apache can be configured to listen to multiple ports, and even on a per-virtual host basis. Also, be aware that the nature of HTTPS makes it impossible for multiple virtual hosts to use their own SSL certificate and still all listen on the same port. They will each need their own certificate and need to listen on their own port. In addition, sending specific ports to virtual machines running on the box is nothing to do with the web server, let alone the execution environment. This is a mix of configuring the port forwarding inside the virtual network, coupled with local web server configuration in your virtual machines. A: In python: import os from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class myHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write("This is working") def main(): try: server = HTTPServer(("", 8080), myHandler) print "Sever is up.." server.serve_forever() except KeyboardInterrupt: print print "Bye, Bye!" server.socket.close() if __name__ == "__main__": main()
PHP HTTP server? Ports 80, 443-444, 1000-3000, 8000-9000. (No-Apache)
I will upgrading to Linux Debian 6.0 "Squeeze" on the server soon and I want to know how I can use Python as a web-server on many ports dedicated for different things.. Ports Directory Description 80, 443 /var/www/sitegen/ Take all domains and generate a site from the SQL DB 444, 1000-3000 /var/www/manager/ Take 444 as a PHP server manager and the rest to be forwarded to serial hardware. 8000-9000 The VMs DIR Forward the port to port 80 (or 443 by settings) on the VMs. This Means that the port 443 could be used for many sites (powered by the same code just diffrent in the SQL DB)
[ "This isn't a PHP question as the PHP interpreter doesn't directly listen on ports. On Linux, it will (usually) run inside Apache. Apache can be configured to listen to multiple ports, and even on a per-virtual host basis.\nAlso, be aware that the nature of HTTPS makes it impossible for multiple virtual hosts to us...
[ 2, 0 ]
[]
[]
[ "apache", "debian_based", "php", "ports", "python" ]
stackoverflow_0003836631_apache_debian_based_php_ports_python.txt