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: When a faster python? There was the Unladen Swallow project that aims to get a faster python, but it seems to be stopped : Is there a way to get a faster python, I mean faster than C-Python, without the use of psyco ? A: You could write hot code paths in Cython, Pyrex or Shedskin. That would have the positive side effect of forcing you to benchmark your code to find the hot paths in the first place, which in turn could lead to the (not implausible) revelation that Python performance may not be the actual bottleneck in your code. A: Sure. Use one of the variants that uses a JITer, such as IronPython, Jython, or PyPy. A: I agree with the previous poster. Cython is the most elegant way to make python equally compete even with C. And its all coding in python, which makes it great for those who dont know C. IF you really want to get your hands dirty , really really dirty, there is CorePy. Corepy gives you the ability to call assembler commands from inside python. Because these are python functions , they can even be used with idle or ipython for real time extremely low level coding. That also means that there is no need to compile and because its a inlinner that means that you can mix python code with assembly code via CorePy. Extremely flexible. Of course coding in assembly is a feat by itself , and that means that you dont need to know only Assembly but also the internals of your machine, very well. But it cant get any faster than Assembly so , if you really insane about speed give CorePy a try , it might impress you . Here is the link. http://www.corepy.org/ Also dont forget about ctypes, its not as fast as cython but its way faster than python and its cool that you can use any DLL with them. No need for compile at all.They also come onboard python , so there is nothing to install. A: I saw pypy to be very fast on some tests : have a look
When a faster python?
There was the Unladen Swallow project that aims to get a faster python, but it seems to be stopped : Is there a way to get a faster python, I mean faster than C-Python, without the use of psyco ?
[ "You could write hot code paths in Cython, Pyrex or Shedskin. That would have the positive side effect of forcing you to benchmark your code to find the hot paths in the first place, which in turn could lead to the (not implausible) revelation that Python performance may not be the actual bottleneck in your code. \...
[ 4, 3, 3, 1 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0004132493_performance_python.txt
Q: Python datetime not including DST when using pytz timezone If I convert a UTC datetime to swedish format, summertime is included (CEST). However, while creating a datetime with sweden as the timezone, it gets CET instead of CEST. Why is this? >>> # Modified for readability >>> import pytz >>> import datetime >>> sweden = pytz.timezone('Europe/Stockholm') >>> >>> datetime.datetime(2010, 4, 20, 16, 20, tzinfo=pytz.utc).astimezone(sweden) datetime(2010, 4, 20, 18, 20, tzinfo=<... 'Europe/Stockholm' CEST+2:00:00 DST>) >>> >>> datetime.datetime(2010, 4, 20, 18, 20, tzinfo=sweden) datetime(2010, 4, 20, 18, 20, tzinfo=<... 'Europe/Stockholm' CET+1:00:00 STD>) >>> A: The sweden object specifies the CET time zone by default but contains enough information to know when CEST starts and stop. In the first example, you create a datetime object and convert it to local time. The sweden object knows that the UTC time you passed occurs during daylight savings time and can convert it appropriately. In the second example, the datetime constructor always interprets your input as not-daylight-savings-time and returns an appropriate object. If datetime treated your input as wall-clock time and chose the appropriate daylight-savings setting for you, there would be an ambiguity during the time of year when clocks are set back. On a wall-clock the same hour occurs twice. Hence, datetime forces you to specify which timezone you're using when you create the datetime object. A: Timezone abbreviations are not unique. For example "IST" could refer to "Irish Standard Time", "Iranian Standard Time", "Indian Standard Time" or "Isreali Standard Time". You shouldn't rely on parsing that, and instead should use zoneinfo timezones.
Python datetime not including DST when using pytz timezone
If I convert a UTC datetime to swedish format, summertime is included (CEST). However, while creating a datetime with sweden as the timezone, it gets CET instead of CEST. Why is this? >>> # Modified for readability >>> import pytz >>> import datetime >>> sweden = pytz.timezone('Europe/Stockholm') >>> >>> datetime.datetime(2010, 4, 20, 16, 20, tzinfo=pytz.utc).astimezone(sweden) datetime(2010, 4, 20, 18, 20, tzinfo=<... 'Europe/Stockholm' CEST+2:00:00 DST>) >>> >>> datetime.datetime(2010, 4, 20, 18, 20, tzinfo=sweden) datetime(2010, 4, 20, 18, 20, tzinfo=<... 'Europe/Stockholm' CET+1:00:00 STD>) >>>
[ "The sweden object specifies the CET time zone by default but contains enough information to know when CEST starts and stop.\nIn the first example, you create a datetime object and convert it to local time. The sweden object knows that the UTC time you passed occurs during daylight savings time and can convert it ...
[ 13, 0 ]
[]
[]
[ "datetime", "python", "pytz", "timezone", "utc" ]
stackoverflow_0002659908_datetime_python_pytz_timezone_utc.txt
Q: Python import trouble I am having some trouble importing a class from a particular module. The class is in the module my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7 This code works import my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7 which means to access my class I have to do my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7.MyClass But this does not from my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7 import MyClass Neither does this import my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7 as my_name Both Give this error saying AttributeError: 'module' object has no attribute my_module7' This has me completely stumped and I have been working on it for a couple of weeks now. Any suggestions? EDIT - I cant change the structure unfortunately as it is imposed by the system I am using A: Looks like a circular import. Gordon McMillan says: Circular imports are fine where both modules use the “import ” form of import. They fail when the 2nd module wants to grab a name out of the first (“from module import name”) and the import is at the top level. That’s because names in the 1st are not yet available, because the first module is busy importing the 2nd. A: I think you may want to consider an alternate design in the first place (redesigning your module breakdown so it's a flatter setup), but as that isn't your question try: import my_module1.my_module2.my_modu...<etc> my_name = my_module1.my_module2.my_modu...<etc> my_name.MyClass A module is a first class object in python, so you can alias them with variables.
Python import trouble
I am having some trouble importing a class from a particular module. The class is in the module my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7 This code works import my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7 which means to access my class I have to do my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7.MyClass But this does not from my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7 import MyClass Neither does this import my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7 as my_name Both Give this error saying AttributeError: 'module' object has no attribute my_module7' This has me completely stumped and I have been working on it for a couple of weeks now. Any suggestions? EDIT - I cant change the structure unfortunately as it is imposed by the system I am using
[ "Looks like a circular import.\nGordon McMillan says:\nCircular imports are fine where both modules use the “import ” form of import. They fail when the 2nd module wants to grab a name out of the first (“from module import name”) and the import is at the top level. That’s because names in the 1st are not yet availa...
[ 3, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0004135207_import_python.txt
Q: Facebook Events and timezones, how to convert UTC datetime to what facebook expects? My application needs to create facebook events. Everything works fine, but I can't get the timezones correct. The start/end dates are all wrong. Facebook's Event API docs say this: Note: The start_time and end_time are the times that were input by the event creator, converted to UTC after assuming that they were in Pacific time (Daylight Savings or Standard, depending on the date of the event), then converted into Unix epoch time. (source) I can't figure out what that means. My web application is a python (django) site. Given a datetime object which has the start/end time in UTC, what is the magical incantation of pytz calls to get the correct time to send to facebook? A: It means that if the user enters "12 am" you're supposed to assume its "12 am pacific time", convert that to UTC so its "8 am GMT" and turn that into a unix epoch. You can do it like this: import datetime, calendar date_local = datetime.datetime.now() # some date in some timezone date_utc = date_local.utctimetuple() unix_time = calendar.timegm(date_utc) # to unix time A: "Unix epoch time" simply means "number of seconds since January 1, 1970 (not counting leap seconds)". By the way, that Facebook Event API description is so bizarre, I can't believe it is right as described. What they seem to be asking for is: The time that was input by the event creator; Interpreted as if a local time in the Pacific time zone, with the daylight saving rules for that zone in effect; Converted to UTC. I live in the timezone UTC+0. So if I schedule an event at 2010-11-09 12:00:00 UTC, the time that actually gets submitted to Facebook is (the Unix time corresponding to) 2010-11-09 20:00:00 UTC. How can that be right? Maybe I've misunderstood.
Facebook Events and timezones, how to convert UTC datetime to what facebook expects?
My application needs to create facebook events. Everything works fine, but I can't get the timezones correct. The start/end dates are all wrong. Facebook's Event API docs say this: Note: The start_time and end_time are the times that were input by the event creator, converted to UTC after assuming that they were in Pacific time (Daylight Savings or Standard, depending on the date of the event), then converted into Unix epoch time. (source) I can't figure out what that means. My web application is a python (django) site. Given a datetime object which has the start/end time in UTC, what is the magical incantation of pytz calls to get the correct time to send to facebook?
[ "It means that if the user enters \"12 am\" you're supposed to assume its \"12 am pacific time\", convert that to UTC so its \"8 am GMT\" and turn that into a unix epoch.\nYou can do it like this:\nimport datetime, calendar\n\ndate_local = datetime.datetime.now() # some date in some timezone\ndate_utc = date_local....
[ 2, 1 ]
[]
[]
[ "datetime", "facebook", "python", "timezone" ]
stackoverflow_0004134718_datetime_facebook_python_timezone.txt
Q: Proper way to construct MySQL queries in python? After starting with python last week after coming from php I am wondering what is the best way to build a MySQL query. I am using Python's MySQLdb module. After doing some research it seems the best way is something similar to the following code below: def updateEmployee(employee): try: cursor = db.cursor() cursor.execute(""" UPDATE `employee2` SET `employeeID`=%s, `parentNameN`=%s, `firstName`=%s, `lastName`=%s, `title`=%s, `room`=%s, `locCode`=%s, `posOrg`=%s WHERE `employee2`.`nameN`=%s """, (employee["employeeID"], employee["parentNameN"], employee["firstName"], employee["lastName"], employee["title"], employee["room"], employee["locCode"], employee["posOrg"], employee["nameN"])) db.commit() print employee["nameN"]+" updated" except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit(1) This is all great except, when this errors I get something such as "Error 1064: You have an error in your SQL syntax:..." which is nice, it says my query was syntactically incorrect. So I got that part, but how can I view the query in question? Is there a way I can construct this query outside of the cursor.execute so that in situations where I get generic error messages I can at least do a "print query"? A: You don't need backquotes in your query. Mistake is here `posOrg`:%s SET `employeeID`=%s, `parentNameN`=%s, `firstName`=%s, `lastName`=%s, `title`=%s, `room`=%s, `locCode`=%s, **`posOrg`:%s**
Proper way to construct MySQL queries in python?
After starting with python last week after coming from php I am wondering what is the best way to build a MySQL query. I am using Python's MySQLdb module. After doing some research it seems the best way is something similar to the following code below: def updateEmployee(employee): try: cursor = db.cursor() cursor.execute(""" UPDATE `employee2` SET `employeeID`=%s, `parentNameN`=%s, `firstName`=%s, `lastName`=%s, `title`=%s, `room`=%s, `locCode`=%s, `posOrg`=%s WHERE `employee2`.`nameN`=%s """, (employee["employeeID"], employee["parentNameN"], employee["firstName"], employee["lastName"], employee["title"], employee["room"], employee["locCode"], employee["posOrg"], employee["nameN"])) db.commit() print employee["nameN"]+" updated" except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit(1) This is all great except, when this errors I get something such as "Error 1064: You have an error in your SQL syntax:..." which is nice, it says my query was syntactically incorrect. So I got that part, but how can I view the query in question? Is there a way I can construct this query outside of the cursor.execute so that in situations where I get generic error messages I can at least do a "print query"?
[ "You don't need backquotes in your query. Mistake is here `posOrg`:%s\nSET `employeeID`=%s, `parentNameN`=%s, `firstName`=%s, `lastName`=%s,\n `title`=%s, `room`=%s, `locCode`=%s, **`posOrg`:%s**\n\n" ]
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0004135683_mysql_python.txt
Q: In asyncore how can i send data to all or some of the clients? I'm building a little MMORPG and im trying to use asyncore rather then threading. 1) How would i send data to certain clients, because in threading a saved each clients socket and current in a dictionary a with its unique id as a key. So how could i subjective send data to all the clients. Thankyou, please say if i didnt give enough information A: I find it great that you want to move to asynchronous programming instead of threading, since it is so much reliable and easier to debug. However, asyncore is a bad library to do so. I don't advise you use it at all, since it requires a significant rewrite to do simple things like read standard io. I suggest you move to twisted - it is a great asynchronous framework, well tested and developed, with good api documentation and good community support. Regardless of your decision on which library to use, I find this series of blog posts by Dave Peticolas to be a great source of beginner information on asynchronous programming. Please read it. There are some games under development using twisted. One example is Minions of Mirth - I never played it but it seems cool. There's also divmod's imaginary - it's a simulationist's take on the realm of role playing, interactive fiction, and multiplayer dungeons. It incorporates gameplay features from each area while attempting to provide a richer environment than is generally available from existing systems. Hope I helped.
In asyncore how can i send data to all or some of the clients?
I'm building a little MMORPG and im trying to use asyncore rather then threading. 1) How would i send data to certain clients, because in threading a saved each clients socket and current in a dictionary a with its unique id as a key. So how could i subjective send data to all the clients. Thankyou, please say if i didnt give enough information
[ "I find it great that you want to move to asynchronous programming instead of threading, since it is so much reliable and easier to debug. \nHowever, asyncore is a bad library to do so. I don't advise you use it at all, since it requires a significant rewrite to do simple things like read standard io.\nI suggest yo...
[ 1 ]
[]
[]
[ "asyncore", "python", "sockets" ]
stackoverflow_0004135793_asyncore_python_sockets.txt
Q: How do I write a string equation solver in python? Thanks in advance! I am writing a program to check if a is true and then return True or False. I need to split it up at the equal sign and then check if the 1st item in the list is equal to the second item and vise-versa. Here is what I have so far: def s_equation(a): equal=a.split("=") A: left, right = a.split("=") assert left == right You're gonna need to give us more details than that if you want a useful answer. Are you trying to write a full computer algebra system (like e.g. Mathematica)? That's a biiiiig project and has already been done several times. Consider using something like Sage. Edit: math beat me to the punch, although I would recommend using ast.literal_eval instead of eval unless you trust the input you will receive. A: You can use eval() to evaluate each part of the equation: def s_equation(a): left, right = a.split('=') return eval(left) == eval(right) Some tests: >>> s_equation('1+1+1=3') True >>> s_equation('2*2=8') False A: You don't really give enough information to answer your question well. Do you want to test it as an identity (ie test the algebra) or as an instantaneous equality? For the former, (install sympy first): import sympy def s_equation(a): x = sympy.Symbol('x') y = sympy.Symbol('y') left, right = a.split('=') return eval (left + '==' + right) usage: s_equation('x+x = x*2') #True s_equation('x+y**2 = y+x**2') #False
How do I write a string equation solver in python?
Thanks in advance! I am writing a program to check if a is true and then return True or False. I need to split it up at the equal sign and then check if the 1st item in the list is equal to the second item and vise-versa. Here is what I have so far: def s_equation(a): equal=a.split("=")
[ "left, right = a.split(\"=\")\nassert left == right\n\n\nYou're gonna need to give us more details than that if you want a useful answer. Are you trying to write a full computer algebra system (like e.g. Mathematica)? That's a biiiiig project and has already been done several times. Consider using something like Sa...
[ 4, 3, 0 ]
[]
[]
[ "algebra", "equation", "python", "solver" ]
stackoverflow_0004135105_algebra_equation_python_solver.txt
Q: HDF5 internal data organization and NumPy usage as hdf5 documentation says, HDF5 stores data using NumPy "It is built on top of the HDF5 library, the Python language and the NumPy package. It features an object-oriented interface that, combined with C extensions for the performance-critical parts of the code, makes it a fast yet extremely easy-to-use tool for interactively storing and retrieving very large amounts of data" ... "PyTables uses these NumPy containers as in-memory buffers to push the I/O bandwith towards the platform limits." So what's the mechanism? How does PyTables are using NumPy?In the end, they generate plain hdf5 accessible from other languages... A: HDF5 is a C language library. HDF5 stores numbers, including floats, in a platform independent manner (scroll down to the table titled "Examples of Native Datatypes and Corresponding C Types," there's more information in the Users Guide). PyTables simply converts from the HDF5 datatype to a NumPy datatype. And it mixes Python code and native code to reduce I/O overhead.
HDF5 internal data organization and NumPy usage
as hdf5 documentation says, HDF5 stores data using NumPy "It is built on top of the HDF5 library, the Python language and the NumPy package. It features an object-oriented interface that, combined with C extensions for the performance-critical parts of the code, makes it a fast yet extremely easy-to-use tool for interactively storing and retrieving very large amounts of data" ... "PyTables uses these NumPy containers as in-memory buffers to push the I/O bandwith towards the platform limits." So what's the mechanism? How does PyTables are using NumPy?In the end, they generate plain hdf5 accessible from other languages...
[ "HDF5 is a C language library. HDF5 stores numbers, including floats, in a platform independent manner (scroll down to the table titled \"Examples of Native Datatypes and Corresponding C Types,\" there's more information in the Users Guide).\nPyTables simply converts from the HDF5 datatype to a NumPy datatype. An...
[ 1 ]
[]
[]
[ "hdf5", "numpy", "pytables", "python" ]
stackoverflow_0004135293_hdf5_numpy_pytables_python.txt
Q: Poisson simulation not working as expected? I have a simple script to set up a Poisson distribution by constructing an array of "events" of probability = 0.1, and then counting the number of successes in each group of 10. It almost works, but the distribution is not quite right (P(0) should equal P(1), but is instead about 90% of P(1)). It's like there's an off-by-one kind of error, but I can't figure out what it is. The script uses the Counter class from here (because I have Python 2.6 and not 2.7) and the grouping uses itertools as discussed here. It's not a stochastic issue, repeats give pretty tight results, and the overall mean looks good, group size looks good. Any ideas where I've messed up? from itertools import izip_longest import numpy as np import Counter def groups(iterable, n=3, padvalue=0): "groups('abcde', 3, 'x') --> ('a','b','c'), ('d','e','x')" return izip_longest(*[iter(iterable)]*n, fillvalue=padvalue) def event(): f = 0.1 r = np.random.random() if r < f: return 1 return 0 L = [event() for i in range(100000)] rL = [sum(g) for g in groups(L,n=10)] print len(rL) print sum(list(L)) C = Counter.Counter(rL) for i in range(max(C.keys())+1): print str(i).rjust(2), C[i] $ python script.py 10000 9949 0 3509 1 3845 2 1971 3 555 4 104 5 15 6 1 $ python script.py 10000 10152 0 3417 1 3879 2 1978 3 599 4 115 5 12 A: I did a combinatorial reality check on your math, and it looks like your results are correct actually. P(0) should not be roughly equivalent to P(1) .9^10 = 0.34867844 = probability of 0 events .1 * .9^9 * (10 choose 1) = .1 * .9^9 * 10 = 0.387420489 = probability of 1 event I wonder if you accidentally did your math thusly: .1 * .9^10 * (10 choose 1) = 0.34867844 = incorrect probability of 1 event
Poisson simulation not working as expected?
I have a simple script to set up a Poisson distribution by constructing an array of "events" of probability = 0.1, and then counting the number of successes in each group of 10. It almost works, but the distribution is not quite right (P(0) should equal P(1), but is instead about 90% of P(1)). It's like there's an off-by-one kind of error, but I can't figure out what it is. The script uses the Counter class from here (because I have Python 2.6 and not 2.7) and the grouping uses itertools as discussed here. It's not a stochastic issue, repeats give pretty tight results, and the overall mean looks good, group size looks good. Any ideas where I've messed up? from itertools import izip_longest import numpy as np import Counter def groups(iterable, n=3, padvalue=0): "groups('abcde', 3, 'x') --> ('a','b','c'), ('d','e','x')" return izip_longest(*[iter(iterable)]*n, fillvalue=padvalue) def event(): f = 0.1 r = np.random.random() if r < f: return 1 return 0 L = [event() for i in range(100000)] rL = [sum(g) for g in groups(L,n=10)] print len(rL) print sum(list(L)) C = Counter.Counter(rL) for i in range(max(C.keys())+1): print str(i).rjust(2), C[i] $ python script.py 10000 9949 0 3509 1 3845 2 1971 3 555 4 104 5 15 6 1 $ python script.py 10000 10152 0 3417 1 3879 2 1978 3 599 4 115 5 12
[ "I did a combinatorial reality check on your math, and it looks like your results are correct actually. P(0) should not be roughly equivalent to P(1)\n.9^10 = 0.34867844 = probability of 0 events\n.1 * .9^9 * (10 choose 1) = .1 * .9^9 * 10 = 0.387420489 = probability of 1 event\n\nI wonder if you accidentally did y...
[ 1 ]
[]
[]
[ "poisson", "python" ]
stackoverflow_0004135837_poisson_python.txt
Q: Twisted daemon unittest I've started a client/server project at work using Twisted (I'm a newcomer, so not much experience). I probably did setup things the wrong way/order, because now I'm a little stuck with a Daemon server (using twistd --python to launch it). I'm wondering if I've to re-implement the server as a standard process to use it in my unittest module? Here's part of the code to launch the server as a Daemon in the server module (you'll probably recognize part of krondo's articles in this): class TwistedHawkService(service.Service): def startService(self): '''''' service.Service.startService(self) log.msg('TwistedHawkService running ...') # Configuration port = 10000 iface = 'localhost' topService = service.MultiService() thService = TwistedHawkService() thService.setServiceParent(topService) factory = ReceiverFactory(thService) tcpService = internet.TCPServer(port, factory, interface=iface) tcpService.setServiceParent(topService) application = service.Application("TwistedHawkService") topService.setServiceParent(application) I tried copy/pasting the configuration part in the setUp method: from mfxTwistedHawk.client import mfxTHClient from mfxTwistedHawk.server import mfxTHServer class RequestTestCase(TestCase): def setUp(self): # Configuration port = 10000 iface = 'localhost' self.topService = service.MultiService() thService = mfxTHServer.TwistedHawkService() thService.setServiceParent(self.topService) factory = mfxTHServer.ReceiverFactory(thService) tcpService = internet.TCPServer(port, factory, interface=iface) tcpService.setServiceParent(self.topService) application = service.Application("TwistedHawkService") self.topService.setServiceParent(application) def test_connection(self): mfxTHClient.requestMain('someRequest') ... but of course using trial unittest.py doesn't start it a daemon, so my client can't reach it. Any advice of how to setup things would be appreciated. Thanks! Edit: Managed to make everything works with this and this, but still feel unsure about the whole thing: def setUp(self): # Configuration port = 10000 iface = 'localhost' service = mfxTHServer.TwistedHawkService() factory = mfxTHServer.ReceiverFactory(service) self.server = reactor.listenTCP(port, factory, interface=iface) Is it ok to have a daemon implementation for production and standard process for unittest? A: Is it ok to have a daemon implementation for production and standard process for unittest? Your unit test isn't for Twisted's daemonization functionality. It's for the custom application/protocol/server/whatever functionality that you implemented. In general, in a unit test, you want to involve as little code as possible. So in general, it's quite okay, and even preferable, to have your unit tests not daemonize. In fact, you probably want to write some unit tests that don't even listen on a real TCP port, but just call methods on your service, factory, and protocol classes.
Twisted daemon unittest
I've started a client/server project at work using Twisted (I'm a newcomer, so not much experience). I probably did setup things the wrong way/order, because now I'm a little stuck with a Daemon server (using twistd --python to launch it). I'm wondering if I've to re-implement the server as a standard process to use it in my unittest module? Here's part of the code to launch the server as a Daemon in the server module (you'll probably recognize part of krondo's articles in this): class TwistedHawkService(service.Service): def startService(self): '''''' service.Service.startService(self) log.msg('TwistedHawkService running ...') # Configuration port = 10000 iface = 'localhost' topService = service.MultiService() thService = TwistedHawkService() thService.setServiceParent(topService) factory = ReceiverFactory(thService) tcpService = internet.TCPServer(port, factory, interface=iface) tcpService.setServiceParent(topService) application = service.Application("TwistedHawkService") topService.setServiceParent(application) I tried copy/pasting the configuration part in the setUp method: from mfxTwistedHawk.client import mfxTHClient from mfxTwistedHawk.server import mfxTHServer class RequestTestCase(TestCase): def setUp(self): # Configuration port = 10000 iface = 'localhost' self.topService = service.MultiService() thService = mfxTHServer.TwistedHawkService() thService.setServiceParent(self.topService) factory = mfxTHServer.ReceiverFactory(thService) tcpService = internet.TCPServer(port, factory, interface=iface) tcpService.setServiceParent(self.topService) application = service.Application("TwistedHawkService") self.topService.setServiceParent(application) def test_connection(self): mfxTHClient.requestMain('someRequest') ... but of course using trial unittest.py doesn't start it a daemon, so my client can't reach it. Any advice of how to setup things would be appreciated. Thanks! Edit: Managed to make everything works with this and this, but still feel unsure about the whole thing: def setUp(self): # Configuration port = 10000 iface = 'localhost' service = mfxTHServer.TwistedHawkService() factory = mfxTHServer.ReceiverFactory(service) self.server = reactor.listenTCP(port, factory, interface=iface) Is it ok to have a daemon implementation for production and standard process for unittest?
[ "\nIs it ok to have a daemon implementation for production and standard process for unittest?\n\nYour unit test isn't for Twisted's daemonization functionality. It's for the custom application/protocol/server/whatever functionality that you implemented. In general, in a unit test, you want to involve as little co...
[ 0 ]
[]
[]
[ "daemon", "python", "twisted" ]
stackoverflow_0004136096_daemon_python_twisted.txt
Q: recursive method returning original value So I'm trying to learn python on my own, and am doing coding puzzles. I came across one that pretty much ask for the best position to stand in line to win a contest. The person running the contest gets rid of people standing in odd number positions. So for example if 1, 2, 3, 4, 5 It would get rid of the odd positions leaving 2, 4 Would get rid of the remaining odd positions leaving 4 as the winner. When I'm debugging the code seems to be working, but it's returning [1,2,3,4,5] instead of the expected [4] Here is my code: def findWinner(contestants): if (len(contestants) != 1): remainingContestants = [] for i, contestant in enumerate(contestants, 1): if (isEven(i)): remainingContestants.append(contestant) findWinner(remainingContestants) return contestants Am I not seeing a logic error or is there something else that I'm not seeing? A: You must return the value from the recurse function to the caller function: return findWinner(remainingContestants) else you would return just the original value without any changes. def findWinner(contestants): if (len(contestants) != 1): remainingContestants = [] for i, contestant in enumerate(contestants, 1): if (isEven(i)): remainingContestants.append(contestant) return findWinner(remainingContestants) # here the value must be return return contestants # without the return above, it will just return this value(original) A: How about this: def findWinner(contestants): return [contestants[2**int(math.log(len(contestants),2))-1]] I know its not what the questions really about but I had to =P. I cant just look at all that work for finding the greatest power of 2 less than contestants and not point it out. or if you don't like the 'artificial' solution and would like to actually perform the process: def findWinner2(c): while len(c) > 1: c = [obj for index, obj in enumerate(c, 1) if index % 2 == 0] #or c = c[1::2] thanks desfido return c A: you shold use return findWinner(remaingContestants) otherwise, of course, your list will never be updated and so your func is gonna always return containts however, see the PEP8 for style guide on python code: http://www.python.org/dev/peps/pep-0008/ the func isEven is probably an overkill...just write if not num % 2 finally, recursion in python isn't recommended; make something like def find_winner(alist): while len(alist) > 1: to_get_rid = [] for pos, obj in enumerate(alist, 1): if pos % 2: to_get_rid.append(obj) alist = [x for x in alist if not (x in to_get_rid)] return alist A: Is there a reason you're iterating over the list instead of using a slice? Doesn't seem very python-y to not use them to me. Additionally, you might want to do something sensible in the case of an empty list. You'll currently go into an infinite loop. I'd write your function as def findWinner(contestants): if not contestants: raise Exception if len(contestants)==1: return contestants[0] return findWinner(contestants[1::2]) (much as @jon_darkstar's point, this is a bit tangential to the question you are explicitly asking, but still a good practice to engage in over what you're doing) A: You are missing a return at the line where you call "findWinner"
recursive method returning original value
So I'm trying to learn python on my own, and am doing coding puzzles. I came across one that pretty much ask for the best position to stand in line to win a contest. The person running the contest gets rid of people standing in odd number positions. So for example if 1, 2, 3, 4, 5 It would get rid of the odd positions leaving 2, 4 Would get rid of the remaining odd positions leaving 4 as the winner. When I'm debugging the code seems to be working, but it's returning [1,2,3,4,5] instead of the expected [4] Here is my code: def findWinner(contestants): if (len(contestants) != 1): remainingContestants = [] for i, contestant in enumerate(contestants, 1): if (isEven(i)): remainingContestants.append(contestant) findWinner(remainingContestants) return contestants Am I not seeing a logic error or is there something else that I'm not seeing?
[ "You must return the value from the recurse function to the caller function:\nreturn findWinner(remainingContestants)\n\nelse you would return just the original value without any changes.\ndef findWinner(contestants):\n if (len(contestants) != 1):\n remainingContestants = []\n for i, contestant in ...
[ 3, 3, 1, 1, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0004136193_python_recursion.txt
Q: Pros and cons of using sqlite3 vs custom table implementation I noticed that a significant part of my (pure Python) code deals with tables. Of course, I have class Table which supports the basic functionality, but I end up adding more and more features to it, such as queries, validation, sorting, indexing, etc. I to wonder if it's a good idea to remove my class Table, and refactor the code to use a regular relational database that I will instantiate in-memory. Here's my thinking so far: Performance of queries and indexing would improve but communication between Python code and the separate database process might be less efficient than between Python functions. I assume that is too much overhead, so I would have to go with sqlite which comes with Python and lives in the same process. I hope this means it's a pure performance gain (at the cost of non-standard SQL definition and limited features of sqlite). With SQL, I will get a lot more powerful features than I would ever want to code myself. Seems like a clear advantage (even with sqlite). I won't need to debug my own implementation of tables, but debugging mistakes in SQL are hard since I can't put breakpoints or easily print out interim state. I don't know how to judge the overall impact of my code reliability and debugging time. The code will be easier to read, since instead of calling my own custom methods I would write SQL (everyone who needs to maintain this code knows SQL). However, the Python code to deal with database might be uglier and more complex than the code that uses pure Python class Table. Again, I don't know which is better on balance. Any corrections to the above, or anything else I should think about? A: SQLite does not run in a separate process. So you don't actually have any extra overhead from IPC. But IPC overhead isn't that big, anyway, especially over e.g., UNIX sockets. If you need multiple writers (more than one process/thread writing to the database simultaneously), the locking overhead is probably worse, and MySQL or PostgreSQL would perform better, especially if running on the same machine. The basic SQL supported by all three of these databases is the same, so benchmarking isn't that painful. You generally don't have to do the same type of debugging on SQL statements as you do on your own implementation. SQLite works, and is fairly well debugged already. It is very unlikely that you'll ever have to debug "OK, that row exists, why doesn't the database find it?" and track down a bug in index updating. Debugging SQL is completely different than procedural code, and really only ever happens for pretty complicated queries. As for debugging your code, you can fairly easily centralize your SQL calls and add tracing to log the queries you are running, the results you get back, etc. The Python SQLite interface may already have this (not sure, I normally use Perl). It'll probably be easiest to just make your existing Table class a wrapper around SQLite. I would strongly recommend not reinventing the wheel. SQLite will have far fewer bugs, and save you a bunch of time. (You may also want to look into Firefox's fairly recent switch to using SQLite to store history, etc., I think they got some pretty significant speedups from doing so.) Also, SQLite's well-optimized C implementation is probably quite a bit faster than any pure Python implementation. A: You could try to make a sqlite wrapper with the same interface as your class Table, so that you keep your code clean and you get the sqlite performences. A: If you're doing database work, use a database, if your not, then don't. Using tables, it sound's like you are. I'd recommend using an ORM to make it more pythonic. SQLAlchemy is the most flexible (though it's not strictly just an ORM).
Pros and cons of using sqlite3 vs custom table implementation
I noticed that a significant part of my (pure Python) code deals with tables. Of course, I have class Table which supports the basic functionality, but I end up adding more and more features to it, such as queries, validation, sorting, indexing, etc. I to wonder if it's a good idea to remove my class Table, and refactor the code to use a regular relational database that I will instantiate in-memory. Here's my thinking so far: Performance of queries and indexing would improve but communication between Python code and the separate database process might be less efficient than between Python functions. I assume that is too much overhead, so I would have to go with sqlite which comes with Python and lives in the same process. I hope this means it's a pure performance gain (at the cost of non-standard SQL definition and limited features of sqlite). With SQL, I will get a lot more powerful features than I would ever want to code myself. Seems like a clear advantage (even with sqlite). I won't need to debug my own implementation of tables, but debugging mistakes in SQL are hard since I can't put breakpoints or easily print out interim state. I don't know how to judge the overall impact of my code reliability and debugging time. The code will be easier to read, since instead of calling my own custom methods I would write SQL (everyone who needs to maintain this code knows SQL). However, the Python code to deal with database might be uglier and more complex than the code that uses pure Python class Table. Again, I don't know which is better on balance. Any corrections to the above, or anything else I should think about?
[ "SQLite does not run in a separate process. So you don't actually have any extra overhead from IPC. But IPC overhead isn't that big, anyway, especially over e.g., UNIX sockets. If you need multiple writers (more than one process/thread writing to the database simultaneously), the locking overhead is probably worse,...
[ 5, 4, 0 ]
[]
[]
[ "performance", "python", "sqlite" ]
stackoverflow_0004136800_performance_python_sqlite.txt
Q: Define variables in template based on user being staff or not I'm trying to display an HTML table of values with about 20 columns where say staff users see one subset of columns, and non-staff users see another subset of columns. I may want to define further types of users later. Now right now I have three static header rows so the template looks like <table> <tr> <th>Col A</th> {% if user.is_staff %}<th>Col B</th>{% endif %} ... {% if not user.is_staff %}<th>Col K</th>{% endif %} </tr> <tr> <td>Col A second header</td> {% if user.is_staff %}<td>Col B second header</td>{% endif %} ... {% if not user.is_staff %}<td>Col K second header</td>{% endif %}</tr> <tr><td>Col A third header</td> ... </tr> {% for obj in object_list %} <tr> <td>{{ obj.col_a }}</td> {% if user.is_staff %}<td>{{ obj.col_b }}</td>{% endif %} ... {% if not user.is_staff %}<td>{{ obj.col_k }}</td>{% endif %} </tr> {% endfor %}</table> However, I find non-DRY as every time, if I want to change if a user-type can see a column, I have to change it in 4 places. Or if I want to define multiple different classes of users, I'd have to have complicated if statements. I'd prefer something like {% if show_col_a %}<td>{{obj.col_a }}</td>{{% endif %} Where I can define at the top of the template (or possibly in the view) that user.is_staff can see show_col_a. Is something like this possible? I'm using a generic view (object_list). Maybe modify all users to have attributes user.show_col_a somehow and do {% if user.show_col_a %}? I'm not sure how to add boolean attributes to users. EDIT: May want multiple users with custom views (e.g., staff_view; admin_view, unprivileged, etc.), so if statements would get unwieldy. A cell's contents is typically more complicated than {{ obj.col_b }}; tried simplifying problem to get to the point. E.g.: <td>{% if obj.custom_address %} {{ obj.custom_address.webprint|safe }} {% else %} {{ obj.business.address.webprint|safe }} {% endif %}</td> Also while multiple templates would work with a simple switch like: {% if user.is_staff %} {% include "template_staff.html" %} {% else %}{% if user.is_admin %} {% include "template_admin.html" %} {% else %} {% include "template_other.html" %} {% endif %} {% endif %} I find its not DRY at all; e.g., every edit to a template has to be replicated in three template. I guess I could make a script that read generates the three templates from some super_template outside of django but its getting very inelegant. A: This depends a lot on what view you have and templates. Ways to do: make a public template and staff template and add a simple method to change the templates on the fly for the views. make a template tag: {% is_staff myvar %} tag code: class IsStaffNode(Node): def __init__(self, var): self.var = var def render(self, context): if context['user'].is_staff(): return var.resolve(context) return "" @register.tag def is_staff(parser, token): var = parser.compile_filter(token.split_contents()[1]) return IsStaffNode(var) Homework: make it a block tag to include the td's so that it's shown either all or none. {% isstaff myvar %}<td>{{ myvar }}</td>{% endisstaff %} This way is more labor intensive than 2 different templates, but if you want to try, manipulating the context (or creating a separate context for the block only) might be useful. Make a context processor that would fill the context with some variables if the user is staff, or not if not. Make a tag that would include the template (inherit from IncludeNode) and manipulate the context.
Define variables in template based on user being staff or not
I'm trying to display an HTML table of values with about 20 columns where say staff users see one subset of columns, and non-staff users see another subset of columns. I may want to define further types of users later. Now right now I have three static header rows so the template looks like <table> <tr> <th>Col A</th> {% if user.is_staff %}<th>Col B</th>{% endif %} ... {% if not user.is_staff %}<th>Col K</th>{% endif %} </tr> <tr> <td>Col A second header</td> {% if user.is_staff %}<td>Col B second header</td>{% endif %} ... {% if not user.is_staff %}<td>Col K second header</td>{% endif %}</tr> <tr><td>Col A third header</td> ... </tr> {% for obj in object_list %} <tr> <td>{{ obj.col_a }}</td> {% if user.is_staff %}<td>{{ obj.col_b }}</td>{% endif %} ... {% if not user.is_staff %}<td>{{ obj.col_k }}</td>{% endif %} </tr> {% endfor %}</table> However, I find non-DRY as every time, if I want to change if a user-type can see a column, I have to change it in 4 places. Or if I want to define multiple different classes of users, I'd have to have complicated if statements. I'd prefer something like {% if show_col_a %}<td>{{obj.col_a }}</td>{{% endif %} Where I can define at the top of the template (or possibly in the view) that user.is_staff can see show_col_a. Is something like this possible? I'm using a generic view (object_list). Maybe modify all users to have attributes user.show_col_a somehow and do {% if user.show_col_a %}? I'm not sure how to add boolean attributes to users. EDIT: May want multiple users with custom views (e.g., staff_view; admin_view, unprivileged, etc.), so if statements would get unwieldy. A cell's contents is typically more complicated than {{ obj.col_b }}; tried simplifying problem to get to the point. E.g.: <td>{% if obj.custom_address %} {{ obj.custom_address.webprint|safe }} {% else %} {{ obj.business.address.webprint|safe }} {% endif %}</td> Also while multiple templates would work with a simple switch like: {% if user.is_staff %} {% include "template_staff.html" %} {% else %}{% if user.is_admin %} {% include "template_admin.html" %} {% else %} {% include "template_other.html" %} {% endif %} {% endif %} I find its not DRY at all; e.g., every edit to a template has to be replicated in three template. I guess I could make a script that read generates the three templates from some super_template outside of django but its getting very inelegant.
[ "This depends a lot on what view you have and templates.\nWays to do:\n\nmake a public template and staff template and add a simple method to change the templates on the fly for the views.\nmake a template tag:\n{% is_staff myvar %}\n\ntag code:\nclass IsStaffNode(Node):\n def __init__(self, var):\n self....
[ 2 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0004136785_django_django_templates_python.txt
Q: How to write a python program that read the input and convert it to pre-defined 14-segments characters with turtle graphics? I have written the turtle graphics functions that define the fourteen segments, and the functions that assemble these segments to form characters, e.g. def MethodA (width) : top_stroke(width) middle_stroke(width) left_stroke right_stroke(width) I have all the definitions ready, but how do I let python to read an input and convert the characters of the input into the fourteen segments forms, which I defined previously? Idealy, if I enter "Pizza", the program should produce the output of the characters 'PIZZA' in the fourteen-segments form. Any suggestions are welcomed and appreciated. Thanks, A: You could define a dictionary with function references like this: Characters = { 'A': MethodA, 'B': MethodB, # ... } Then, for a string s: s = "Pizza" for c in s: c = c.upper() # to fold lowercase into upper case if c in Characters: Characters[c](width) This code works using Characters[c] to look up the function reference in the dictionary, then the (width) causes the function to be called (with a width parameter, as the function expects).
How to write a python program that read the input and convert it to pre-defined 14-segments characters with turtle graphics?
I have written the turtle graphics functions that define the fourteen segments, and the functions that assemble these segments to form characters, e.g. def MethodA (width) : top_stroke(width) middle_stroke(width) left_stroke right_stroke(width) I have all the definitions ready, but how do I let python to read an input and convert the characters of the input into the fourteen segments forms, which I defined previously? Idealy, if I enter "Pizza", the program should produce the output of the characters 'PIZZA' in the fourteen-segments form. Any suggestions are welcomed and appreciated. Thanks,
[ "You could define a dictionary with function references like this:\nCharacters = {\n 'A': MethodA,\n 'B': MethodB,\n # ...\n}\n\nThen, for a string s:\ns = \"Pizza\"\nfor c in s:\n c = c.upper() # to fold lowercase into upper case\n if c in Characters:\n Characters[c](width)\n\nThis code works...
[ 1 ]
[]
[]
[ "python", "turtle_graphics" ]
stackoverflow_0004137040_python_turtle_graphics.txt
Q: Grouping a queryset by another related model I have two models: class Stop(models.Model): line = models.ForeignKey(TransitLine, related_name='stops') name = models.CharField(max_length=32) approved_ts = models.DateTimeField(null=True, blank=True) class TransitLine(models.Model): name = models.CharField(max_length=32) desc = models.CharField(max_length=64) And I have a queryset: Stop.objects.filter(approved_ts__isnull=False) However, when I send the results of this query to the template, I want it grouped by TransitLine. How would I approach this? For clarification, in the end, I want the template to look something like this: <ul> {% for tl in transit_line_list %} <li> {{ tl.name }}: {% for s in tl.stops.all %} {{ s.name }} {% endfor %} </li> {% endfor %} </ul> A: In the template, you can use regroup ... You must order them by TransitLine, while you filter the queryset using Stop.objects.filter(approved_ts__isnull=False).order_by('line') You can check the documentation... A: If I understand correctly, you should really just give the template a queryset of TranslitLines. Rather than creating a queryset of Stops, add an approved_stops() method to your TransitLine class like this: class TransitLine(models.Model): name = models.CharField(max_length=32) desc = models.CharField(max_length=64) def approved_stops(self): return self.stops.filter(approved_ts__isnull=False) Then add 'transit_line_list': TransitLine.objects.all() to the template's context and change {% for s in tl.stops.all %} in the template to {% for s in tl.approved_stops.all %}. A: Do the following: TransitLine.objects.filter(stops__in=Stops.objects.filter(approved_ts=True)).distinct().order_by('name') This query selects only the lines that have approved stops. JFYI: to find lines that have any stops, do TransitLine.objects.exclude(stops__id=None).order_by('name')
Grouping a queryset by another related model
I have two models: class Stop(models.Model): line = models.ForeignKey(TransitLine, related_name='stops') name = models.CharField(max_length=32) approved_ts = models.DateTimeField(null=True, blank=True) class TransitLine(models.Model): name = models.CharField(max_length=32) desc = models.CharField(max_length=64) And I have a queryset: Stop.objects.filter(approved_ts__isnull=False) However, when I send the results of this query to the template, I want it grouped by TransitLine. How would I approach this? For clarification, in the end, I want the template to look something like this: <ul> {% for tl in transit_line_list %} <li> {{ tl.name }}: {% for s in tl.stops.all %} {{ s.name }} {% endfor %} </li> {% endfor %} </ul>
[ "In the template, you can use regroup ...\nYou must order them by TransitLine, while you filter the queryset using\nStop.objects.filter(approved_ts__isnull=False).order_by('line')\n\nYou can check the documentation...\n", "If I understand correctly, you should really just give the template a queryset of Translit...
[ 1, 0, 0 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0004130880_django_django_queryset_python.txt
Q: Can not install hcluster from pypi under python 2.6 on xp I am using the setup.py file supplied with hcluster with the following lines added: sys.path.append("c:\\Program Files\\Python26\\Lib\\site-packages\\hcluster-0.2.0") sys.path.append("c:\\Program Files\\Python26\\Lib\\site-packages\\hcluster-0.2.0\\hcluster") Then used setup.py as follows: "c:\program files\python26\python.exe" "c:\Program Files\Python26\Lib\site-packages\hcluster-0.2.0\setup.py" install I get the following error messages: running install running build running build_py error: package directory 'hcluster' does not exist Don't know if it trying to read or write hcluster. Any help appreciated A: You don't need to add packages in site-packages in sys.path. Did you copy the hcluster in site-package manually? It is not the correct way to do it. 2.1 You should have the hcluster outside the site-packages say in your home directory and then run "python setup.py install" 2.2 This will put the package after build into site-package directory. This is where all external package reside by default after they are installed. Remove the folders related to hcluster from site-packages and install with instruction 2. Read the following to understand your error: http://docs.python.org/install/index.html
Can not install hcluster from pypi under python 2.6 on xp
I am using the setup.py file supplied with hcluster with the following lines added: sys.path.append("c:\\Program Files\\Python26\\Lib\\site-packages\\hcluster-0.2.0") sys.path.append("c:\\Program Files\\Python26\\Lib\\site-packages\\hcluster-0.2.0\\hcluster") Then used setup.py as follows: "c:\program files\python26\python.exe" "c:\Program Files\Python26\Lib\site-packages\hcluster-0.2.0\setup.py" install I get the following error messages: running install running build running build_py error: package directory 'hcluster' does not exist Don't know if it trying to read or write hcluster. Any help appreciated
[ "\nYou don't need to add packages in site-packages in sys.path. \nDid you copy the hcluster in site-package manually? It is not the correct way to do it.\n2.1 You should have the hcluster outside the site-packages say in your home directory and then run \"python setup.py install\"\n2.2 This will put the package aft...
[ 1 ]
[]
[]
[ "hcluster", "python" ]
stackoverflow_0004137159_hcluster_python.txt
Q: Python & wxPython - Code Critique - Short Hand / Convenience / Repetition I'd actually like to start by admitting that I'm terrified to ask this question. That said, I have the following combination of classes: A Dialog Class: class formDialog(wx.Dialog): def __init__(self, parent, id = -1, panel = None, title = _("Unnamed Dialog"), modal = False, sizes = (400, -1)): wx.Dialog.__init__(self, parent, id, _(title), style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) if panel is not None: self._panel = panel(self) self._panel.SetSizeHints(*sizes) ds = wx.GridBagSizer(self._panel._gap, self._panel._gap) ds.Add(self._panel, (0, 0), (1, 1), wx.EXPAND | wx.ALL, self._panel._gap) ds.Add(wx.StaticLine(self), (1, 0), (1, 1), wx.EXPAND | wx.RIGHT | wx.LEFT, self._panel._gap) self.bs = self.CreateButtonSizer(self._panel._form['Buttons']) ds.Add(self.bs, (2, 0), (1, 1), wx.ALIGN_RIGHT | wx.ALL, self._panel._gap) ds.AddGrowableCol(0) ds.AddGrowableRow(0) self.SetSizerAndFit(ds) self.Center() self.Bind(wx.EVT_BUTTON, self._panel.onOk, id = wx.ID_OK) self.Bind(wx.EVT_BUTTON, self._panel.onClose, id = wx.ID_CANCEL) self.Bind(wx.EVT_CLOSE, self._panel.onClose) if modal: self.ShowModal() else: self.Show() A Form Class: class Form(wx.Panel): reqFields = [ ('Defaults', {}), ('Disabled', []) ] def __init__(self, parent = None, id = -1, gap = 2, sizes = (-1, -1)): wx.Panel.__init__(self, parent, id) self.SetSizeHints(*sizes) self._gap = gap self.itemMap = {} if hasattr(self, '_form'): # There are a number of fields which need to exist in the form # dictionary. Set them to defaults if they don't exist already. for k, d in self.reqFields: if not self._form.has_key(k): self._form[k] = d self._build() def _build(self): """ The Build Method automates sizer creation and element placement by parsing a properly constructed object. """ # The Main Sizer for the Panel. panelSizer = wx.GridBagSizer(self._gap, self._gap) # Parts is an Ordered Dictionary of regions for the form. for group, (key, data) in enumerate(self._form['Parts'].iteritems()): flags, sep, display = key.rpartition('-') #@UnusedVariable # HR signifies a Horizontal Rule for spacing / layout. No Data Field. if display == 'HR': element = wx.StaticLine(self) style = wx.EXPAND # Any other value contains elements that need to be placed. else: element = wx.Panel(self, -1) # The Row Sizer rowSizer = wx.GridBagSizer(self._gap, self._gap) for row, field in enumerate(data): for col, item in enumerate(field): style = wx.EXPAND | wx.ALL pieces = item.split('-') # b for Buttons if pieces[0] == 'b': control = wx._controls.Button(element, -1, pieces[1]) # custom items - Retrieve from the _form object if pieces[0] == 'custom': control = self._form[pieces[1]](element) # The row in the Grid needs to resize for Lists. panelSizer.AddGrowableRow(group) # Now the Row has to grow with the List as well. rowSizer.AddGrowableRow(row) # custom2 - Same as custom, but does not expand if pieces[0] == 'custom2': control = self._form[pieces[1]](element) style = wx.ALL # c for CheckBox if pieces[0] == 'c': control = wx.CheckBox(element, label = _(pieces[2]), name = pieces[1]) control.SetValue(int(self._form['Defaults'].get(pieces[1], 0))) # d for Directory Picker if pieces[0] == 'd': control = wx.DirPickerCtrl(element, name = pieces[1]) control.GetTextCtrl().SetEditable(False) control.GetTextCtrl().SetName(pieces[1]) control.GetTextCtrl().SetValue(self._form['Defaults'].get(pieces[1], '')) # f for File Browser if pieces[0] == 'f': control = wx.FilePickerCtrl(element, name = pieces[1], wildcard = pieces[2]) control.GetTextCtrl().SetEditable(False) control.GetTextCtrl().SetValue(self._form['Defaults'].get(pieces[1], '')) # f2 for Save File if pieces[0] == 'f2': control = wx.FilePickerCtrl(element, name = pieces[1], style = wx.FLP_SAVE | wx.FLP_OVERWRITE_PROMPT | wx.FLP_USE_TEXTCTRL, wildcard = pieces[2]) control.GetTextCtrl().SetEditable(False) # h for Horizontal Rule - layout helper. if pieces[0] == 'h': control = wx.StaticLine(element) style = wx.EXPAND # l for Label (StaticText) if pieces[0] == 'l': control = wx.StaticText(element, label = _(pieces[1])) # Labels do not expand - override default style. style = wx.ALL | wx.ALIGN_CENTER_VERTICAL # p for Password (TextCtrl with Style) if pieces[0] == 'p': control = wx.TextCtrl(element, name = pieces[1], style = wx.TE_PASSWORD) control.SetValue(self._form['Defaults'].get(pieces[1], '')) # s for ComboBox (Select) if pieces[0] == 's': control = wx.ComboBox(element, name = pieces[1], choices = self._form['Options'].get(pieces[1], []), style = wx.CB_READONLY) control.SetValue(self._form['Defaults'].get(pieces[1], '')) # s2 for Spin Control if pieces[0] == 's2': control = wx.SpinCtrl(element, name = pieces[1], size = (55, -1), min = int(pieces[2]), max = int(pieces[3])) control.SetValue(int(self._form['Defaults'].get(pieces[1], 1))) # Spin Ctrl's do not expand. style = wx.ALL # t for TextCtrl if pieces[0] == 't': control = wx.TextCtrl(element, name = pieces[1]) try: control.SetValidator(self._form['Validators'][pieces[1]]) except KeyError: pass # No Validator Specified. control.SetValue(self._form['Defaults'].get(pieces[1], '')) # tr for Readonly TextCtrl if pieces[0] == 'tr': control = wx.TextCtrl(element, name = pieces[1], style = wx.TE_READONLY) control.SetValue(self._form['Defaults'].get(pieces[1], '')) # Check for elements disabled by default. Store reference to # Element in itemMap for reference by other objects later. if len(pieces) > 1: if pieces[1] in self._form['Disabled']: control.Enable(False) self.itemMap[pieces[1]] = control # Place the control in the row. rowSizer.Add(control, (row, col), (1, 1), style, self._gap) if style == wx.EXPAND | wx.ALL: rowSizer.AddGrowableCol(col) if 'NC' not in flags: sb = wx.StaticBox(element, -1, _(display)) sz = wx.StaticBoxSizer(sb, wx.VERTICAL) sz.Add(rowSizer, 1, flag = wx.EXPAND) element.SetSizerAndFit(sz) else: element.SetSizerAndFit(rowSizer) panelSizer.Add(element, (group, 0), (1, 1), wx.EXPAND | wx.ALL, self._gap) panelSizer.AddGrowableCol(0) self.SetSizerAndFit(panelSizer) def getDescendants(self, elem, list): children = elem.GetChildren() list.extend(children) for child in children: self.getDescendants(child, list) def getFields(self): fields = [] self.getDescendants(self, fields) # This removes children we can't retrieve values from. This should result # in a list that only contains form fields, removing all container elements. fields = filter(lambda x: hasattr(x, 'GetValue'), fields) return fields def onOk(self, evt): self.onClose(evt) def onClose(self, evt): self.GetParent().Destroy() The Form is meant to be used by subclassing like so: class createQueue(Form): def __init__(self, parent): self._form = { 'Parts' : OrderedDict([ ('Queue Name', [ ('t-Queue Name',) ]) ]), 'Buttons' : wx.OK | wx.CANCEL } Form.__init__(self, parent) class generalSettings(Form): def __init__(self, parent): self._form = { 'Parts': OrderedDict([ ('Log Settings', [ ('l-Remove log messages older than: ', 's2-interval-1-10', 's-unit') ]), ('Folder Settings', [ ('l-Spool Folder Location:', 'd-dir'), ('l-Temp Folder Location:', 'd-temp') ]), ('Email Notifications', [ ('l-Alert Email To:', 't-alert_to'), ('l-Alert Email From:', 't-alert_from'), ('l-Status Email From:', 't-status_from'), ('l-Alert Email Server:', 't-alert_host'), ('l-Login:', 't-alert_login'), ('l-Password:', 'p-alert_password') ]), ('Admin User', [ ('c-req_admin-Require Admin Rights to make changes.',) ]), ('Miscellaneous', [ ('l-Print Worker Tasks:', 's2-printtasks-1-256', 'l-Job Drag Options:', 's-jobdrop') ]) ]), 'Options': { 'unit': ['Hours', 'Days', 'Months'], 'jobdrop': ['Move Job to Queue', 'Copy Job to Queue'] }, 'Buttons': wx.OK | wx.CANCEL } Form.__init__(self, parent) These might be used like so: formDialog(parent, panel = createQueue, title = 'Create a Queue', sizes = (200, -1)) formDialog(parent, panel = generalSettings, title = "General Settings") Whew, that's a ton, and thanks to anyone who makes it down this far. The idea is that I want something that takes care of the monotonous parts of layout in wxPython. I am designing a user interface that will need to create 100's of different Dialogs and Forms. I wanted something that would allow me to generate the forms dynamically from a structured object. I'd like to hear other developers' thoughts on this kind of approach. The closest I've seen to something similar is Drupal's Form API. I feel like it is viable for these reasons: Easily rearrange fields. No need to create / manage Sizers manually. Compound / complex forms can be created easily. Display helper elements (StaticBoxSizers, Static Lines) are easily added. I am concerned that it is an undesirable approach for these reasons: Long _build() function body in the Form Class. May not be clear to other developers at first glance. Uses Structured Strings to define fields. There may be a better way. Any thoughts, constructive, destructive, or otherwise will all be appreciated. Thanks! A: You should also try wxFormDesigner or XRCed. A: Since you're using wx, you should study wxglade. It's a graphical GUI builder which you use to build your GUI and it generates a .wxg file with the layout, and you can load that into your script. The file is actually just xml, so you can programatically generate it and dynamically load different GUIs from it. Maybe that helps.
Python & wxPython - Code Critique - Short Hand / Convenience / Repetition
I'd actually like to start by admitting that I'm terrified to ask this question. That said, I have the following combination of classes: A Dialog Class: class formDialog(wx.Dialog): def __init__(self, parent, id = -1, panel = None, title = _("Unnamed Dialog"), modal = False, sizes = (400, -1)): wx.Dialog.__init__(self, parent, id, _(title), style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) if panel is not None: self._panel = panel(self) self._panel.SetSizeHints(*sizes) ds = wx.GridBagSizer(self._panel._gap, self._panel._gap) ds.Add(self._panel, (0, 0), (1, 1), wx.EXPAND | wx.ALL, self._panel._gap) ds.Add(wx.StaticLine(self), (1, 0), (1, 1), wx.EXPAND | wx.RIGHT | wx.LEFT, self._panel._gap) self.bs = self.CreateButtonSizer(self._panel._form['Buttons']) ds.Add(self.bs, (2, 0), (1, 1), wx.ALIGN_RIGHT | wx.ALL, self._panel._gap) ds.AddGrowableCol(0) ds.AddGrowableRow(0) self.SetSizerAndFit(ds) self.Center() self.Bind(wx.EVT_BUTTON, self._panel.onOk, id = wx.ID_OK) self.Bind(wx.EVT_BUTTON, self._panel.onClose, id = wx.ID_CANCEL) self.Bind(wx.EVT_CLOSE, self._panel.onClose) if modal: self.ShowModal() else: self.Show() A Form Class: class Form(wx.Panel): reqFields = [ ('Defaults', {}), ('Disabled', []) ] def __init__(self, parent = None, id = -1, gap = 2, sizes = (-1, -1)): wx.Panel.__init__(self, parent, id) self.SetSizeHints(*sizes) self._gap = gap self.itemMap = {} if hasattr(self, '_form'): # There are a number of fields which need to exist in the form # dictionary. Set them to defaults if they don't exist already. for k, d in self.reqFields: if not self._form.has_key(k): self._form[k] = d self._build() def _build(self): """ The Build Method automates sizer creation and element placement by parsing a properly constructed object. """ # The Main Sizer for the Panel. panelSizer = wx.GridBagSizer(self._gap, self._gap) # Parts is an Ordered Dictionary of regions for the form. for group, (key, data) in enumerate(self._form['Parts'].iteritems()): flags, sep, display = key.rpartition('-') #@UnusedVariable # HR signifies a Horizontal Rule for spacing / layout. No Data Field. if display == 'HR': element = wx.StaticLine(self) style = wx.EXPAND # Any other value contains elements that need to be placed. else: element = wx.Panel(self, -1) # The Row Sizer rowSizer = wx.GridBagSizer(self._gap, self._gap) for row, field in enumerate(data): for col, item in enumerate(field): style = wx.EXPAND | wx.ALL pieces = item.split('-') # b for Buttons if pieces[0] == 'b': control = wx._controls.Button(element, -1, pieces[1]) # custom items - Retrieve from the _form object if pieces[0] == 'custom': control = self._form[pieces[1]](element) # The row in the Grid needs to resize for Lists. panelSizer.AddGrowableRow(group) # Now the Row has to grow with the List as well. rowSizer.AddGrowableRow(row) # custom2 - Same as custom, but does not expand if pieces[0] == 'custom2': control = self._form[pieces[1]](element) style = wx.ALL # c for CheckBox if pieces[0] == 'c': control = wx.CheckBox(element, label = _(pieces[2]), name = pieces[1]) control.SetValue(int(self._form['Defaults'].get(pieces[1], 0))) # d for Directory Picker if pieces[0] == 'd': control = wx.DirPickerCtrl(element, name = pieces[1]) control.GetTextCtrl().SetEditable(False) control.GetTextCtrl().SetName(pieces[1]) control.GetTextCtrl().SetValue(self._form['Defaults'].get(pieces[1], '')) # f for File Browser if pieces[0] == 'f': control = wx.FilePickerCtrl(element, name = pieces[1], wildcard = pieces[2]) control.GetTextCtrl().SetEditable(False) control.GetTextCtrl().SetValue(self._form['Defaults'].get(pieces[1], '')) # f2 for Save File if pieces[0] == 'f2': control = wx.FilePickerCtrl(element, name = pieces[1], style = wx.FLP_SAVE | wx.FLP_OVERWRITE_PROMPT | wx.FLP_USE_TEXTCTRL, wildcard = pieces[2]) control.GetTextCtrl().SetEditable(False) # h for Horizontal Rule - layout helper. if pieces[0] == 'h': control = wx.StaticLine(element) style = wx.EXPAND # l for Label (StaticText) if pieces[0] == 'l': control = wx.StaticText(element, label = _(pieces[1])) # Labels do not expand - override default style. style = wx.ALL | wx.ALIGN_CENTER_VERTICAL # p for Password (TextCtrl with Style) if pieces[0] == 'p': control = wx.TextCtrl(element, name = pieces[1], style = wx.TE_PASSWORD) control.SetValue(self._form['Defaults'].get(pieces[1], '')) # s for ComboBox (Select) if pieces[0] == 's': control = wx.ComboBox(element, name = pieces[1], choices = self._form['Options'].get(pieces[1], []), style = wx.CB_READONLY) control.SetValue(self._form['Defaults'].get(pieces[1], '')) # s2 for Spin Control if pieces[0] == 's2': control = wx.SpinCtrl(element, name = pieces[1], size = (55, -1), min = int(pieces[2]), max = int(pieces[3])) control.SetValue(int(self._form['Defaults'].get(pieces[1], 1))) # Spin Ctrl's do not expand. style = wx.ALL # t for TextCtrl if pieces[0] == 't': control = wx.TextCtrl(element, name = pieces[1]) try: control.SetValidator(self._form['Validators'][pieces[1]]) except KeyError: pass # No Validator Specified. control.SetValue(self._form['Defaults'].get(pieces[1], '')) # tr for Readonly TextCtrl if pieces[0] == 'tr': control = wx.TextCtrl(element, name = pieces[1], style = wx.TE_READONLY) control.SetValue(self._form['Defaults'].get(pieces[1], '')) # Check for elements disabled by default. Store reference to # Element in itemMap for reference by other objects later. if len(pieces) > 1: if pieces[1] in self._form['Disabled']: control.Enable(False) self.itemMap[pieces[1]] = control # Place the control in the row. rowSizer.Add(control, (row, col), (1, 1), style, self._gap) if style == wx.EXPAND | wx.ALL: rowSizer.AddGrowableCol(col) if 'NC' not in flags: sb = wx.StaticBox(element, -1, _(display)) sz = wx.StaticBoxSizer(sb, wx.VERTICAL) sz.Add(rowSizer, 1, flag = wx.EXPAND) element.SetSizerAndFit(sz) else: element.SetSizerAndFit(rowSizer) panelSizer.Add(element, (group, 0), (1, 1), wx.EXPAND | wx.ALL, self._gap) panelSizer.AddGrowableCol(0) self.SetSizerAndFit(panelSizer) def getDescendants(self, elem, list): children = elem.GetChildren() list.extend(children) for child in children: self.getDescendants(child, list) def getFields(self): fields = [] self.getDescendants(self, fields) # This removes children we can't retrieve values from. This should result # in a list that only contains form fields, removing all container elements. fields = filter(lambda x: hasattr(x, 'GetValue'), fields) return fields def onOk(self, evt): self.onClose(evt) def onClose(self, evt): self.GetParent().Destroy() The Form is meant to be used by subclassing like so: class createQueue(Form): def __init__(self, parent): self._form = { 'Parts' : OrderedDict([ ('Queue Name', [ ('t-Queue Name',) ]) ]), 'Buttons' : wx.OK | wx.CANCEL } Form.__init__(self, parent) class generalSettings(Form): def __init__(self, parent): self._form = { 'Parts': OrderedDict([ ('Log Settings', [ ('l-Remove log messages older than: ', 's2-interval-1-10', 's-unit') ]), ('Folder Settings', [ ('l-Spool Folder Location:', 'd-dir'), ('l-Temp Folder Location:', 'd-temp') ]), ('Email Notifications', [ ('l-Alert Email To:', 't-alert_to'), ('l-Alert Email From:', 't-alert_from'), ('l-Status Email From:', 't-status_from'), ('l-Alert Email Server:', 't-alert_host'), ('l-Login:', 't-alert_login'), ('l-Password:', 'p-alert_password') ]), ('Admin User', [ ('c-req_admin-Require Admin Rights to make changes.',) ]), ('Miscellaneous', [ ('l-Print Worker Tasks:', 's2-printtasks-1-256', 'l-Job Drag Options:', 's-jobdrop') ]) ]), 'Options': { 'unit': ['Hours', 'Days', 'Months'], 'jobdrop': ['Move Job to Queue', 'Copy Job to Queue'] }, 'Buttons': wx.OK | wx.CANCEL } Form.__init__(self, parent) These might be used like so: formDialog(parent, panel = createQueue, title = 'Create a Queue', sizes = (200, -1)) formDialog(parent, panel = generalSettings, title = "General Settings") Whew, that's a ton, and thanks to anyone who makes it down this far. The idea is that I want something that takes care of the monotonous parts of layout in wxPython. I am designing a user interface that will need to create 100's of different Dialogs and Forms. I wanted something that would allow me to generate the forms dynamically from a structured object. I'd like to hear other developers' thoughts on this kind of approach. The closest I've seen to something similar is Drupal's Form API. I feel like it is viable for these reasons: Easily rearrange fields. No need to create / manage Sizers manually. Compound / complex forms can be created easily. Display helper elements (StaticBoxSizers, Static Lines) are easily added. I am concerned that it is an undesirable approach for these reasons: Long _build() function body in the Form Class. May not be clear to other developers at first glance. Uses Structured Strings to define fields. There may be a better way. Any thoughts, constructive, destructive, or otherwise will all be appreciated. Thanks!
[ "You should also try wxFormDesigner or XRCed.\n", "Since you're using wx, you should study wxglade. It's a graphical GUI builder which you use to build your GUI and it generates a .wxg file with the layout, and you can load that into your script.\nThe file is actually just xml, so you can programatically generate...
[ 2, 0 ]
[]
[]
[ "automation", "layout", "python", "repeat", "wxpython" ]
stackoverflow_0004135829_automation_layout_python_repeat_wxpython.txt
Q: Python pickle seems to break inside class, but not in command line script I've been trying to unpickle some dictionaries from the database. I've reverted to using the marshal module, but was still wondering why pickle is having such a difficult time unserializing some data. Here is a command line python session showing essentially what I am trying to do: >>> a = {'service': 'amazon', 'protocol': 'stream', 'key': 'lajdfoau09424jojf.flv'} >>> import pickle; import base64 >>> pickled = base64.b64encode(pickle.dumps(a)) >>> pickled 'KGRwMApTJ3Byb3RvY29sJwpwMQpTJ3N0cmVhbScKcDIKc1Mna2V5JwpwMwpTJ2xhamRmb2F1MDk0MjRqb2pmLmZsdicKcDQKc1Mnc2VydmljZScKcDUKUydhbWF6b24nCnA2CnMu' >>> unpickled = pickle.loads(base64.b64decode(pickled)) >>> unpickled {'protocol': 'stream', 'service': 'amazon', 'key': 'lajdfoau09424jojf.flv'} >>> unpickled['service'] 'amazon' This works all fine, but when I try this inside of a factory method for a class, it seems like the pickle.loads part errors out. The strings I am trying to load are pickled the same way as above. I've even tried copying the exact string that is pickled in the command line session above and just trying to unpickle that, but with no success. Here is the code for this latter attempt: class Resource: _service = 'unknown' _protocol = 'unknown' _key = 'unknown' ''' Factory method that creates an appropriate instance of one of Resource’s subclasses based on the type of data provided (the data being a serialized dictionary with at least the keys 'service', 'protocol', and 'key'). @param resource_data (string) -- the data used to create the new Resource instance. ''' @staticmethod def resource_factory(resource_data): # Unpack the raw resource data and then create the appropriate Resource instance and return. resource_data = "KGRwMApTJ3Byb3RvY29sJwpwMQpTJ3N0cmVhbScKcDIKc1Mna2V5JwpwMwpTJ2xhamRmb2F1MDk0MjRqb2pmLmZsdicKcDQKc1Mnc2VydmljZScKcDUKUydhbWF6b24nCnA2CnMu" #hack to just see if we can unpickle this string logging.debug("Creating resource: " + resource_data) unencoded = base64.b64decode(resource_data) logging.debug("Unencoded is: " + unencoded) unpacked = pickle.loads(unencoded) logging.debug("Unpacked: " + unpacked) service = unpacked['service'] protocol = unpacked['protocol'] key = unpacked['key'] if (service == 'amazon'): return AmazonResource(service=service, protocol=protocol, key=key) elif (service == 'fs'): return FSResource(service=service, protocol=protocol, key=key) A: Your code works. How are you testing it? import logging import base64 import pickle class Resource: @staticmethod def resource_factory(resource_data): resource_data = "KGRwMApTJ3Byb3RvY29sJwpwMQpTJ3N0cmVhbScKcDIKc1Mna2V5JwpwMwpTJ2xhamRmb2F1MDk0MjRqb2pmLmZsdicKcDQKc1Mnc2VydmljZScKcDUKUydhbWF6b24nCnA2CnMu" #hack to just see if we can unpickle this string # logging.debug("Creating resource: " + resource_data) unencoded = base64.b64decode(resource_data) # logging.debug("Unencoded is: " + unencoded) unpacked = pickle.loads(unencoded) logging.debug("Unpacked: " + repr(unpacked)) service = unpacked['service'] protocol = unpacked['protocol'] key = unpacked['key'] logging.basicConfig(level=logging.DEBUG) Resource.resource_factory('') yields # DEBUG:root:Unpacked: {'protocol': 'stream', 'service': 'amazon', 'key': 'lajdfoau09424jojf.flv'} A: I was able to solve this after making some simplifications and then debugging in django. The main issue was that there were some errors in the Resource class itself that were preventing the correct completion of the resource_factory method. First, I was trying to concatenate a string and dictionary, which was throwing an error. I also had some errors elsewhere in the class where I was referring to the instance variables _service, _protocol, and key withouth the '' (typos). In any case, the interesting thing was that when I used this code within Django's custom field infrastructure, the errors would get caught and I did not see any actual message indicating the problem. The debug statements suggested it was a problem with loads, but actually it was a problem with the debug statement itself and some code that came later. When I tried to implement this behavior using model properties instead of custom model fields for the data I was saving, the errors actually got printed out correctly and I was able to quickly debug.
Python pickle seems to break inside class, but not in command line script
I've been trying to unpickle some dictionaries from the database. I've reverted to using the marshal module, but was still wondering why pickle is having such a difficult time unserializing some data. Here is a command line python session showing essentially what I am trying to do: >>> a = {'service': 'amazon', 'protocol': 'stream', 'key': 'lajdfoau09424jojf.flv'} >>> import pickle; import base64 >>> pickled = base64.b64encode(pickle.dumps(a)) >>> pickled 'KGRwMApTJ3Byb3RvY29sJwpwMQpTJ3N0cmVhbScKcDIKc1Mna2V5JwpwMwpTJ2xhamRmb2F1MDk0MjRqb2pmLmZsdicKcDQKc1Mnc2VydmljZScKcDUKUydhbWF6b24nCnA2CnMu' >>> unpickled = pickle.loads(base64.b64decode(pickled)) >>> unpickled {'protocol': 'stream', 'service': 'amazon', 'key': 'lajdfoau09424jojf.flv'} >>> unpickled['service'] 'amazon' This works all fine, but when I try this inside of a factory method for a class, it seems like the pickle.loads part errors out. The strings I am trying to load are pickled the same way as above. I've even tried copying the exact string that is pickled in the command line session above and just trying to unpickle that, but with no success. Here is the code for this latter attempt: class Resource: _service = 'unknown' _protocol = 'unknown' _key = 'unknown' ''' Factory method that creates an appropriate instance of one of Resource’s subclasses based on the type of data provided (the data being a serialized dictionary with at least the keys 'service', 'protocol', and 'key'). @param resource_data (string) -- the data used to create the new Resource instance. ''' @staticmethod def resource_factory(resource_data): # Unpack the raw resource data and then create the appropriate Resource instance and return. resource_data = "KGRwMApTJ3Byb3RvY29sJwpwMQpTJ3N0cmVhbScKcDIKc1Mna2V5JwpwMwpTJ2xhamRmb2F1MDk0MjRqb2pmLmZsdicKcDQKc1Mnc2VydmljZScKcDUKUydhbWF6b24nCnA2CnMu" #hack to just see if we can unpickle this string logging.debug("Creating resource: " + resource_data) unencoded = base64.b64decode(resource_data) logging.debug("Unencoded is: " + unencoded) unpacked = pickle.loads(unencoded) logging.debug("Unpacked: " + unpacked) service = unpacked['service'] protocol = unpacked['protocol'] key = unpacked['key'] if (service == 'amazon'): return AmazonResource(service=service, protocol=protocol, key=key) elif (service == 'fs'): return FSResource(service=service, protocol=protocol, key=key)
[ "Your code works. How are you testing it?\nimport logging\nimport base64\nimport pickle\nclass Resource:\n @staticmethod\n def resource_factory(resource_data):\n resource_data = \"KGRwMApTJ3Byb3RvY29sJwpwMQpTJ3N0cmVhbScKcDIKc1Mna2V5JwpwMwpTJ2xhamRmb2F1MDk0MjRqb2pmLmZsdicKcDQKc1Mnc2VydmljZScKcDUKUydhbWF...
[ 0, 0 ]
[]
[]
[ "django", "django_models", "pickle", "python", "serialization" ]
stackoverflow_0004135615_django_django_models_pickle_python_serialization.txt
Q: Python regex non-capturing issue? I was trying to get all quoted (" or ') substrings from a string excluding the quotation marks. I came up with this: "((?:').*[^'](?:'))|((?:\").*[^\"](?:\"))" For some reason the matching string still contains the quotation marks in it. Any reason why ? Sincerely, nikita.utiu. A: You could do it with lookahead and lookbehind assertions: >>> match = re.search(r"(?<=').*?(?=')", "a 'quoted' string. 'second' quote") >>> print match.group(0) quoted A: Using non-capturing groups doesn’t mean that they are not captured at all. They just don’t create separate capturing groups like normal groups do. But the structure of the regular expression requires that the quotation marks are part of the match: "('[^']*'|\"[^\"]*\")" Then just remove the surrounding quotation marks when processing the matched parts with matched_string[1:-1]. A: You could try: import shlex ... lexer = shlex.shlex(your_input_string) quoted = [piece.strip("'\"") for piece in lexer if piece.startswith("'") or piece.startswith('"')] shlex (lexical analysis) takes care of escaped quotes for you. Though note that it does not work with unicode strings.
Python regex non-capturing issue?
I was trying to get all quoted (" or ') substrings from a string excluding the quotation marks. I came up with this: "((?:').*[^'](?:'))|((?:\").*[^\"](?:\"))" For some reason the matching string still contains the quotation marks in it. Any reason why ? Sincerely, nikita.utiu.
[ "You could do it with lookahead and lookbehind assertions:\n>>> match = re.search(r\"(?<=').*?(?=')\", \"a 'quoted' string. 'second' quote\")\n>>> print match.group(0)\nquoted\n\n", "Using non-capturing groups doesn’t mean that they are not captured at all. They just don’t create separate capturing groups like no...
[ 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004136987_python_regex.txt
Q: Setting the value of a model field based on user authentication in Django I'm trying to selectively process a field in my Django/Python application based on whether a user is logged in or not. Basically, I have a model similar to the following: class Resource(models.Model): uploaded = models.DateTimeField() name = models.CharField(max_length=200) description = models.CharField(max_length=500, blank=True) file = models.CharField(max_length=200) What I want to do is for the file attribute to be set to one value if the user happens to be logged in (and has access to this resource based on a test against some permissions backend), and another value if the user is not logged in. So, when any client code tries to access Resource.file, it will get something like the following if the user is not logged in 'http://mysite.com/dummy_resource_for_people_without_access'. However, if the user is logged in and passes some tests for permissions, then the value of resource.file will actually be the true url of that resource (including any security keys etc. to access that resource). From what I've read, it seems that you can only take account of the currently logged in user by passing that through the request context from a view function to the model. However, in the above use case I am trying to control the access more closely in the model without needing the client code to call a special function. A: Your best bet is to create a function used to access the file attribute, and check there. In general, it would possible to turn the attribute into a descriptor which does it implicitly, but Django's metaclass magic would impede that. In general however, Django is designed to handle authentication at the view-level (and does it very cleanly). If you need database layer authentication, consider a different setup, such as CouchDB. A: Just in case anyone's interested, I solved the above issue by actually creating a custom model field in django that could then have a method that takes a user to generate a URI. So, in the database, I store a key to the resource as above in the file column. However, now the file column is some custom field: class CustomFileField(models.CharField): def to_python(self, value): ... return CustomFileResource(value) class CustomFileResource: def __init__(self, *args, **kwargs): .... def uri(usr): #this method then gets the uri selectively based on the user . The pattern above is nice because I can wrap the db field and then create a specific method for getting the uri based on who is trying to access it.
Setting the value of a model field based on user authentication in Django
I'm trying to selectively process a field in my Django/Python application based on whether a user is logged in or not. Basically, I have a model similar to the following: class Resource(models.Model): uploaded = models.DateTimeField() name = models.CharField(max_length=200) description = models.CharField(max_length=500, blank=True) file = models.CharField(max_length=200) What I want to do is for the file attribute to be set to one value if the user happens to be logged in (and has access to this resource based on a test against some permissions backend), and another value if the user is not logged in. So, when any client code tries to access Resource.file, it will get something like the following if the user is not logged in 'http://mysite.com/dummy_resource_for_people_without_access'. However, if the user is logged in and passes some tests for permissions, then the value of resource.file will actually be the true url of that resource (including any security keys etc. to access that resource). From what I've read, it seems that you can only take account of the currently logged in user by passing that through the request context from a view function to the model. However, in the above use case I am trying to control the access more closely in the model without needing the client code to call a special function.
[ "Your best bet is to create a function used to access the file attribute, and check there. In general, it would possible to turn the attribute into a descriptor which does it implicitly, but Django's metaclass magic would impede that.\nIn general however, Django is designed to handle authentication at the view-lev...
[ 0, 0 ]
[]
[]
[ "django", "django_models", "django_sessions", "python" ]
stackoverflow_0004092821_django_django_models_django_sessions_python.txt
Q: Recommendations for a Python library that can capture still images from a Flash/HTML5 video? Part of a web application I am developing requires the ability to capture still images from a Flash or HTML5 video playing with in a browser. Is there a Python library out there that could help me along with this task? UPDATE Actually, users of this web app will also have to have the ability to Draw a crop box on top of the Flash/HTML5 video player Be able to resize that box if necessary Capture the image with in the crop box frame Have that image be saves and sent to the server Also, this video image crop/capture tool will also have to be restricted to the perimeter of the video frame. I don't want users getting confused and potentially capturing an image outside of the video frame because all we are concerned about is the content of the video. A: What about capturing it inside Flash and sending it as BiteArray to the server? A: If you know Python, http://pyjs.org could be useful. EDIT I just saw there's "Python" written on the title, so you obviously know Python. My bad, i'm overtired.
Recommendations for a Python library that can capture still images from a Flash/HTML5 video?
Part of a web application I am developing requires the ability to capture still images from a Flash or HTML5 video playing with in a browser. Is there a Python library out there that could help me along with this task? UPDATE Actually, users of this web app will also have to have the ability to Draw a crop box on top of the Flash/HTML5 video player Be able to resize that box if necessary Capture the image with in the crop box frame Have that image be saves and sent to the server Also, this video image crop/capture tool will also have to be restricted to the perimeter of the video frame. I don't want users getting confused and potentially capturing an image outside of the video frame because all we are concerned about is the content of the video.
[ "What about capturing it inside Flash and sending it as BiteArray to the server?\n", "If you know Python, http://pyjs.org could be useful.\nEDIT\nI just saw there's \"Python\" written on the title, so you obviously know Python. My bad, i'm overtired.\n" ]
[ 1, 0 ]
[]
[]
[ "flash", "html5_video", "image_capture", "python", "screen_capture" ]
stackoverflow_0004129858_flash_html5_video_image_capture_python_screen_capture.txt
Q: Redirect method call and pass caller along automatically I'm building a modular app and I wanted all Objects of a certain type to be able to call a management object, and automatically have their own instance passed along. Scenario: My application consists of a framework and plugins that are being loaded at runtime. One of these plugins provides functionality that operates in a separate contexts for each plugin. Simply put: It receives the instance of the caller plugin and only operates with data associated with this plugin. In order to avoid confusion in the following description, lets refer to the callee as management object and to the caller as worker object. There is going to be one management object and multiple plugins: Plugin + : 1 Management Object I would like the worker object to be able to access the management functionality, without the need to specify the instance of the worker instance explicitly in the parameter list. Instead, I'd like the management methods to look, as if they belonged to the worker object - so that the passing of the caller argument is transparent and implicit. One possibility would be, to register all new management methods with the worker class directly. However, I don't like this "namespace pollution". Instead, I'd like them to be accessible via an attribute so that the meaning is clear. Keep in mind, that this behaviour is added at runtime, and I do not wish to modify the Plugin class itself. Also, multiple plugins may already have been instantiated at that time, but I need this to work for all current and future instances. The idea I've come up with, is to combine the descriptor __get__ and __getattr__ methods in one object. The __get__ method will be used, to determine the instance of the caller. The __getattr__ method will be used, to dynamically wrap the method that is being supposed to be called from the management object. The code I've come up with looks like this: my_management_object = getItHere() class Wrapper(object): def __init__(self): self._caller = None def __getattr__(self, name): method = getattr(my_management_object, name) def wrapper(*args, **kwargs): return method(self._caller, *args, **kwargs) return wrapper def __get__(self, caller, type): self._caller = caller return self MyPluginClass._manage = Wrapper() So now, I can do: obj = MyPluginClass() obj._manage.doSomethingForMe() #vs: getMyManagementObject().doSomethingForMe(obj) I have tested it and it seems to work. I was wondering whether there are any pitfalls in this method or whether there are more pythonic ways to do this. I'm pretty new to the Descriptor stuff so I may have overlooked something. A: If all you're doing is accessing attributes, use a descriptor. It appears that you're implementing a descriptor-like design and calling it a "Wrapper". A descriptor will probably be slightly simpler and more consistent with all the other places in Python that use descriptors. http://docs.python.org/reference/datamodel.html#descriptors Making this a more typical descriptor class may save you some work.
Redirect method call and pass caller along automatically
I'm building a modular app and I wanted all Objects of a certain type to be able to call a management object, and automatically have their own instance passed along. Scenario: My application consists of a framework and plugins that are being loaded at runtime. One of these plugins provides functionality that operates in a separate contexts for each plugin. Simply put: It receives the instance of the caller plugin and only operates with data associated with this plugin. In order to avoid confusion in the following description, lets refer to the callee as management object and to the caller as worker object. There is going to be one management object and multiple plugins: Plugin + : 1 Management Object I would like the worker object to be able to access the management functionality, without the need to specify the instance of the worker instance explicitly in the parameter list. Instead, I'd like the management methods to look, as if they belonged to the worker object - so that the passing of the caller argument is transparent and implicit. One possibility would be, to register all new management methods with the worker class directly. However, I don't like this "namespace pollution". Instead, I'd like them to be accessible via an attribute so that the meaning is clear. Keep in mind, that this behaviour is added at runtime, and I do not wish to modify the Plugin class itself. Also, multiple plugins may already have been instantiated at that time, but I need this to work for all current and future instances. The idea I've come up with, is to combine the descriptor __get__ and __getattr__ methods in one object. The __get__ method will be used, to determine the instance of the caller. The __getattr__ method will be used, to dynamically wrap the method that is being supposed to be called from the management object. The code I've come up with looks like this: my_management_object = getItHere() class Wrapper(object): def __init__(self): self._caller = None def __getattr__(self, name): method = getattr(my_management_object, name) def wrapper(*args, **kwargs): return method(self._caller, *args, **kwargs) return wrapper def __get__(self, caller, type): self._caller = caller return self MyPluginClass._manage = Wrapper() So now, I can do: obj = MyPluginClass() obj._manage.doSomethingForMe() #vs: getMyManagementObject().doSomethingForMe(obj) I have tested it and it seems to work. I was wondering whether there are any pitfalls in this method or whether there are more pythonic ways to do this. I'm pretty new to the Descriptor stuff so I may have overlooked something.
[ "If all you're doing is accessing attributes, use a descriptor. It appears that you're implementing a descriptor-like design and calling it a \"Wrapper\". A descriptor will probably be slightly simpler and more consistent with all the other places in Python that use descriptors.\nhttp://docs.python.org/reference/...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0004136972_python.txt
Q: Context processors, passing a session which doesn't exist Hay All, I've got a simple context processor which looks within a session and if a 'user' key exists. If it does i want to return it to the template. Here's my context Processor def get_user_details(request): user = request.session['user'] data = { 'user':user } return data and here is a sample view def render_home(request): return render_to_response("home", context_instance=RequestContext(request)) If the session['user'] doesn't exists, i want it to silently fail, or return False or Null. Because the key doesnt exist within the session, i get a KeyError. Any idea's how to fix this? A: You can get a default value like None this way: request.session.get('user', None). Just like in normal Python dicts. A: user = request.session.get('user', None) or, user = None if 'user' in request.session: user = request.session['user'] A: def get_user_details(request): try: user = request.session['user'] except KeyError: return data = { 'user':user } return data Or if you want to catch it further away, do this instead: def render_home(request): try: return render_to_response("home", context_instance=RequestContext(request)) except KeyError: return
Context processors, passing a session which doesn't exist
Hay All, I've got a simple context processor which looks within a session and if a 'user' key exists. If it does i want to return it to the template. Here's my context Processor def get_user_details(request): user = request.session['user'] data = { 'user':user } return data and here is a sample view def render_home(request): return render_to_response("home", context_instance=RequestContext(request)) If the session['user'] doesn't exists, i want it to silently fail, or return False or Null. Because the key doesnt exist within the session, i get a KeyError. Any idea's how to fix this?
[ "You can get a default value like None this way: request.session.get('user', None). Just like in normal Python dicts.\n", "user = request.session.get('user', None)\n\nor,\nuser = None\nif 'user' in request.session:\n user = request.session['user']\n\n", "def get_user_details(request):\n try:\n user...
[ 3, 3, 0 ]
[]
[]
[ "django", "python", "session" ]
stackoverflow_0004138088_django_python_session.txt
Q: How to check if a file is open for writing on windows in python? We have a process here at work where an input file is created by SAS. That input file is then read by a legacy application and that legacy application creates results. SAS then reads the results and summarizes them. A non-programmer usually takes care of these actions one by one. So the person just creates the input file. They know when it is done, and then they run the legacy application, and they know when that is done. Then they run the summary program. I have a situation where my boss wants to run about 100 variations. I have access to 3 or 4 computers that share a network drive. Here is my plan: Use computer A, I start creating the 100 input files, one by one. Using computer B, I run the legacy program on each input file. I would like to start running the program when input is ready. So if input1 is done being created on computer A, I want to run the legacy application on input1 on computer B while input2 is being created on computer A. I know python best, so I will probably use python to glue all of this together. Now I know there is a lot of things I could do, but I think this approach is adequate and will allow me to just get the job done for the time being. I don't really have time to design and test a very elegant solution that would take advantage of all the cores on all the machines or use a database to help me synchronize all of this. I appreciate suggestions like this, but I really just want to know if there is a way, in python, to tell if a file on a network drive is open for writing by any application on any computer? If not, I will probably just come up with a dumb way to create an indicator that the job is done - like create a file "doneA" where if it exists, it means the "input1" file is complete. For example. I would add a step to the sas program that creates an indicator file after the input file has been created. Sorry for the really long explanation, but I just don't want you to waste your time offering alternate solutions that I probably will not be able to implement. I have read this question and its responses. I don't think I can use anything like lsof b/c these files would be open on different computers. A: Write output to a temp file. When done writing, close it, then rename it to the name the other program is waiting for. That way, the file only appears when it is ready to be read. A: if there is a way, in python, to tell if a file on a network drive is open for writing by any application on any computer? Not really. Windows will let you open the file several times and really muck things up. You have to use some explicit synchronization. Rather than synchronize each of the three steps 100 different ways, my preference is to do the following. Create 100 copies of the three-step dance. Don't worry about synchronization among the steps. for variant in range(100): name= "variant_{0}.bat".format(variant) with open(name,"w") as script: print( "run some SAS thing", file=script ) print( "run some legacy thing", file=script ) print( "run some SAS thing", file=script ) subprocess.Popen( "start {0}".format(name), shell=True ) I suspect that this will crush the life out of your processor by running all 100 in parallel. As a practical matter, you probably don't want to actually use subprocess.Popen() in Python. As a practical matter you probably want to create several of these "start variant_x" batch files that can run a few variants in parallel. You can create some kind of master bat file that runs a sequence of processing steps. Each step starts several parallel 3-step variants.
How to check if a file is open for writing on windows in python?
We have a process here at work where an input file is created by SAS. That input file is then read by a legacy application and that legacy application creates results. SAS then reads the results and summarizes them. A non-programmer usually takes care of these actions one by one. So the person just creates the input file. They know when it is done, and then they run the legacy application, and they know when that is done. Then they run the summary program. I have a situation where my boss wants to run about 100 variations. I have access to 3 or 4 computers that share a network drive. Here is my plan: Use computer A, I start creating the 100 input files, one by one. Using computer B, I run the legacy program on each input file. I would like to start running the program when input is ready. So if input1 is done being created on computer A, I want to run the legacy application on input1 on computer B while input2 is being created on computer A. I know python best, so I will probably use python to glue all of this together. Now I know there is a lot of things I could do, but I think this approach is adequate and will allow me to just get the job done for the time being. I don't really have time to design and test a very elegant solution that would take advantage of all the cores on all the machines or use a database to help me synchronize all of this. I appreciate suggestions like this, but I really just want to know if there is a way, in python, to tell if a file on a network drive is open for writing by any application on any computer? If not, I will probably just come up with a dumb way to create an indicator that the job is done - like create a file "doneA" where if it exists, it means the "input1" file is complete. For example. I would add a step to the sas program that creates an indicator file after the input file has been created. Sorry for the really long explanation, but I just don't want you to waste your time offering alternate solutions that I probably will not be able to implement. I have read this question and its responses. I don't think I can use anything like lsof b/c these files would be open on different computers.
[ "Write output to a temp file. When done writing, close it, then rename it to the name the other program is waiting for. That way, the file only appears when it is ready to be read.\n", "\nif there is a way, in python, to tell if a file on a network drive is open for writing by any application on any computer?\n...
[ 2, 1 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0004138015_python_windows.txt
Q: python - simplejson not serializing when i try to serialize the list variable returned by the database query, an error of 'non-serializable is returned. But when i hardcode the same exact string in, or so it seems...serialization works. Any ideas why? car_list = Car.objects.get(id=query).all_cars.values('id','name').order_by('name') #car_list = [{'id': 9L, 'name': u"Porche"}, {'id': 6L, 'name': u'Toyota'}, {'id': 7L, 'name': u'Hugo'}, {'id': 3L, 'name': u'Honda'}] data = { 'list':car_list } print simplejson.dumps(data) A: simplejson cannot serialize Django types. Pass the result to list() to turn it into something simplejson can serialize.
python - simplejson not serializing
when i try to serialize the list variable returned by the database query, an error of 'non-serializable is returned. But when i hardcode the same exact string in, or so it seems...serialization works. Any ideas why? car_list = Car.objects.get(id=query).all_cars.values('id','name').order_by('name') #car_list = [{'id': 9L, 'name': u"Porche"}, {'id': 6L, 'name': u'Toyota'}, {'id': 7L, 'name': u'Hugo'}, {'id': 3L, 'name': u'Honda'}] data = { 'list':car_list } print simplejson.dumps(data)
[ "simplejson cannot serialize Django types. Pass the result to list() to turn it into something simplejson can serialize.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0004138296_python.txt
Q: Copied python egg no longer works I needed to make a change to a 3rd party library, so I edited the files in the egg (which is not zipped). The egg lives in site-packages in a virtualenv. Everything works fine on my dev machine, but when I copied the egg to another machine, the module can longer be found to import. I'm sure I went about this the wrong way, but I'm hoping there's a way to fix it. A: A quick fix to your problem should be by adding the full path of the egg to a .pth file which should exist in the sys-path (in your case site-packages).
Copied python egg no longer works
I needed to make a change to a 3rd party library, so I edited the files in the egg (which is not zipped). The egg lives in site-packages in a virtualenv. Everything works fine on my dev machine, but when I copied the egg to another machine, the module can longer be found to import. I'm sure I went about this the wrong way, but I'm hoping there's a way to fix it.
[ "A quick fix to your problem should be by adding the full path of the egg to a .pth file which should exist in the sys-path (in your case site-packages).\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004137917_python.txt
Q: exchanging data through pipes between C# and cPython I have what (I think) is a relatively simple task. I have to provide to some C# app a way to invoke my Python app and pass some data for processing and receive back the results at the end of the Python task (both are GUI apps. I thought that pipes would do the job nicely with the C# side creating a named pipe thus using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("Demo", PipeDirection.InOut)) {// Wait for a client to connect pipeServer.WaitForConnection(); the app can p/invoke the python app passing the name of the pipe in sysarg, etc. on the python side, once the pipe name is known and using win32pipe something like message = 'a test' pipeName = '\\\\.\\pipe\\Demo' win32pipe.CallNamedPipe(pipeName, message, 4096 , win32pipe.NMPWAIT_WAIT_FOREVER) should work. What happens is that the C# detects the incoming connection but the python side "crashes" on an infamous error:(87,'CallNmaedPipe",'The parameter is incorrect'). I'm no expert on pipes and am at loss to see what might be wrong here. A: CallNamedPipe requires a pipe that is created in PIPE_TYPE_MESSAGE; your C# code creates a pipe in PIPE_TYPE_BYTE. So you either need to create a pipe in message mode in C# (using a constructor that expects PipeTransmissionMode), or use WriteFile to put data into the pipe.
exchanging data through pipes between C# and cPython
I have what (I think) is a relatively simple task. I have to provide to some C# app a way to invoke my Python app and pass some data for processing and receive back the results at the end of the Python task (both are GUI apps. I thought that pipes would do the job nicely with the C# side creating a named pipe thus using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("Demo", PipeDirection.InOut)) {// Wait for a client to connect pipeServer.WaitForConnection(); the app can p/invoke the python app passing the name of the pipe in sysarg, etc. on the python side, once the pipe name is known and using win32pipe something like message = 'a test' pipeName = '\\\\.\\pipe\\Demo' win32pipe.CallNamedPipe(pipeName, message, 4096 , win32pipe.NMPWAIT_WAIT_FOREVER) should work. What happens is that the C# detects the incoming connection but the python side "crashes" on an infamous error:(87,'CallNmaedPipe",'The parameter is incorrect'). I'm no expert on pipes and am at loss to see what might be wrong here.
[ "CallNamedPipe requires a pipe that is created in PIPE_TYPE_MESSAGE; your C# code creates a pipe in PIPE_TYPE_BYTE. So you either need to create a pipe in message mode in C# (using a constructor that expects PipeTransmissionMode), or use WriteFile to put data into the pipe.\n" ]
[ 1 ]
[]
[]
[ "c#", "ipc", "pipe", "python" ]
stackoverflow_0004138124_c#_ipc_pipe_python.txt
Q: Why does mechanize list one form? If you run the following program: import mechanize br = mechanize.Browser() br.open("http://hansardindex.ontla.on.ca/hansarde.asp") for f in br.forms(): print f.name Only one line of output is printed. However if you visit the page there are many forms with names such as "DateFrom". Why does mechanize not list the other forms? A: There is a difference between 'Forms' and 'Input'. A form can contain many input fields. see http://www.w3schools.com/html/html_forms.asp Mechanize is right there is only ONE form but with multiple input fields. What you probably want to do is access the input fields by name. So for example setting the 'searchcontents' input field works like this: form = forms[0] form["searchcontents"] = "keyword" for more information, please have a look at the mechanize documentation at http://wwwsearch.sourceforge.net/mechanize/forms.html
Why does mechanize list one form?
If you run the following program: import mechanize br = mechanize.Browser() br.open("http://hansardindex.ontla.on.ca/hansarde.asp") for f in br.forms(): print f.name Only one line of output is printed. However if you visit the page there are many forms with names such as "DateFrom". Why does mechanize not list the other forms?
[ "There is a difference between 'Forms' and 'Input'. A form can contain many input fields.\nsee http://www.w3schools.com/html/html_forms.asp\nMechanize is right there is only ONE form but with multiple input fields.\nWhat you probably want to do is access the input fields by name. So for example setting the 'searchc...
[ 3 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0004138522_mechanize_python.txt
Q: One-to-many relationships in Django I'm trying to create a One-to-many relationship in Django. In my example, I have a news post, which may have several images associated with it. However, different news posts will never share images. As far as I can see, there are two ways to do this: Through a ManyToManyField, which creates a multi-select tool in the admin panel, which shows all the images ever uploaded, or through a ForeignKeyField in the PostImage class, which results in there not being any option to add new images when creating a new news post on the admin panel. Since the users of the admin panel will not be at all technically-inclined, I would like two things, if possible: Add several images on the "Create new news post" page, without having any images from other news posts as a choice Less importantly, replace the multi-select box with checkboxes, or anything less confusing than a multi-select box. How can I achieve this? A: The second part is the easier one: You want the horizontal javascript filter If you go with a ManyToManyField, you could filter those choices by using a Custom Manager. If you use a ForeignKey, you would want to use one of the Admin Inlines. If you really never re-use images, use the inlines.
One-to-many relationships in Django
I'm trying to create a One-to-many relationship in Django. In my example, I have a news post, which may have several images associated with it. However, different news posts will never share images. As far as I can see, there are two ways to do this: Through a ManyToManyField, which creates a multi-select tool in the admin panel, which shows all the images ever uploaded, or through a ForeignKeyField in the PostImage class, which results in there not being any option to add new images when creating a new news post on the admin panel. Since the users of the admin panel will not be at all technically-inclined, I would like two things, if possible: Add several images on the "Create new news post" page, without having any images from other news posts as a choice Less importantly, replace the multi-select box with checkboxes, or anything less confusing than a multi-select box. How can I achieve this?
[ "The second part is the easier one:\nYou want the horizontal javascript filter\nIf you go with a ManyToManyField, you could filter those choices by using a Custom Manager. \nIf you use a ForeignKey, you would want to use one of the Admin Inlines. If you really never re-use images, use the inlines. \n" ]
[ 3 ]
[]
[]
[ "django", "one_to_many", "python" ]
stackoverflow_0004138833_django_one_to_many_python.txt
Q: Is there a python unit test framework that gives compact error output when comparing strings Using the Java JUnit framework and comparing the strings "abcde" and "abde" you would get the error output 'expected:<...b[c]d...> but was: <...b[]d...>' Using python unittest I get "abcde" != "abde" which is not all as useful if you are dealing with long strings. So my question is: Is there a python unit test framework that gives the same compact output as JUnit for Java? A: The unittest2 package is a backport (to Python >= 2.4) of features that are native to the PyUnit (unittest) framework in Python 2.7. It includes enhanced string comparison features. http://www.voidspace.org.uk/python/articles/unittest2.shtml#unicode-string-comparison
Is there a python unit test framework that gives compact error output when comparing strings
Using the Java JUnit framework and comparing the strings "abcde" and "abde" you would get the error output 'expected:<...b[c]d...> but was: <...b[]d...>' Using python unittest I get "abcde" != "abde" which is not all as useful if you are dealing with long strings. So my question is: Is there a python unit test framework that gives the same compact output as JUnit for Java?
[ "The unittest2 package is a backport (to Python >= 2.4) of features that are native to the PyUnit (unittest) framework in Python 2.7.\nIt includes enhanced string comparison features.\n\nhttp://www.voidspace.org.uk/python/articles/unittest2.shtml#unicode-string-comparison\n" ]
[ 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0004138662_python_unit_testing.txt
Q: Simple Python server How can I start a simple python server that will allow me to connect to sockets from some outer source ? I've tried : import SocketServer class MyUDPHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request[0].strip() socket = self.request[1] print "%s wrote:" % self.client_address[0] print data socket.sendto(data.upper(), self.client_address) if __name__ == "__main__": HOST, PORT = "localhost", 80 try: server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler) print("works") server.serve_forever() serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.bind((socket.gethostname(), 80)) serversocket.listen(5) except: print("nope") while True: (clientsocket, address) = serversocket.accept() ct = client_thread(clientsocket) ct.run() But when I'm sending something to the server I don't get any info. How can I change this code to see if someone is sending some data ? EDIT Now I've found this code : class mysocket: """demonstration class only - coded for clarity, not efficiency """ def __init__(self, sock=None): if sock is None: self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock def connect(self, host, port): self.sock.connect((host, port)) def mysend(self, msg): totalsent = 0 while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError("socket connection broken") totalsent = totalsent + sent def myreceive(self): msg = '' while len(msg) < MSGLEN: chunk = self.sock.recv(MSGLEN-len(msg)) if chunk == '': raise RuntimeError("socket connection broken") msg = msg + chunk return msg but how to use this stuff to just listen to sockets and receive data sent ? A: The simplest solution is SocketServer, which is part of the Python standard library.
Simple Python server
How can I start a simple python server that will allow me to connect to sockets from some outer source ? I've tried : import SocketServer class MyUDPHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request[0].strip() socket = self.request[1] print "%s wrote:" % self.client_address[0] print data socket.sendto(data.upper(), self.client_address) if __name__ == "__main__": HOST, PORT = "localhost", 80 try: server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler) print("works") server.serve_forever() serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.bind((socket.gethostname(), 80)) serversocket.listen(5) except: print("nope") while True: (clientsocket, address) = serversocket.accept() ct = client_thread(clientsocket) ct.run() But when I'm sending something to the server I don't get any info. How can I change this code to see if someone is sending some data ? EDIT Now I've found this code : class mysocket: """demonstration class only - coded for clarity, not efficiency """ def __init__(self, sock=None): if sock is None: self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock def connect(self, host, port): self.sock.connect((host, port)) def mysend(self, msg): totalsent = 0 while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError("socket connection broken") totalsent = totalsent + sent def myreceive(self): msg = '' while len(msg) < MSGLEN: chunk = self.sock.recv(MSGLEN-len(msg)) if chunk == '': raise RuntimeError("socket connection broken") msg = msg + chunk return msg but how to use this stuff to just listen to sockets and receive data sent ?
[ "The simplest solution is SocketServer, which is part of the Python standard library.\n" ]
[ 2 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0004139140_python_sockets.txt
Q: Python: best way to serve multiple users? I have a (game) server that I am writing in python (3.1), and have a few questions on that. The client program uses the socket module to connect to the server. Multiple people may be connecting at any time, and I need a way to handle that. Would the best way be to employ the multi/sub processing module, and start a new process for each user who logs in, or is there a better way ? Files will be used to store data. Do I need a lot of complex Queuing to handle file I/O ? Is there an easy way to serve an entire file to the client, e.g. for an automated update ? Thanks in advance! A: Don't reinvent the wheel use Twisted.
Python: best way to serve multiple users?
I have a (game) server that I am writing in python (3.1), and have a few questions on that. The client program uses the socket module to connect to the server. Multiple people may be connecting at any time, and I need a way to handle that. Would the best way be to employ the multi/sub processing module, and start a new process for each user who logs in, or is there a better way ? Files will be used to store data. Do I need a lot of complex Queuing to handle file I/O ? Is there an easy way to serve an entire file to the client, e.g. for an automated update ? Thanks in advance!
[ "Don't reinvent the wheel use Twisted.\n" ]
[ 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0004139345_multithreading_python.txt
Q: How to call python functions when running from terminal Say i have code that does something complicated and prints the result, but for the purposes of this post say it just does this: class tagFinder: def descendants(context, tag): print context print tag But say i have multiple functions in this class. How can i run this function? Or even when say i do python filename.py.. How can i call that function and provide inputs for context and tag? A: ~ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import filename >>> a = tagFinder() >>> a.descendants(arg1, arg2) # output A: This will throw an error >>> class tagFinder: ... def descendants(context, tag): ... print context ... print tag ... >>> >>> a = tagFinder() >>> a.descendants('arg1', 'arg2') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: descendants() takes exactly 2 arguments (3 given) >>> Your method should have first arg as self. class tagFinder: def descendants(self, context, tag): print context print tag Unless 'context' is meant to refer to self. In that case, you would call with single argument. >>> a.descendants('arg2') A: You could pass a short snippet of python code on stdin: python <<< 'import filename; filename.tagFinder().descendants(None, "p")' # The above is a bash-ism equivalent to: echo 'import filename; filename.tagFinder().descendants(None, "p")' | python
How to call python functions when running from terminal
Say i have code that does something complicated and prints the result, but for the purposes of this post say it just does this: class tagFinder: def descendants(context, tag): print context print tag But say i have multiple functions in this class. How can i run this function? Or even when say i do python filename.py.. How can i call that function and provide inputs for context and tag?
[ "~ python\nPython 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) \n[GCC 4.4.3] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import filename\n>>> a = tagFinder()\n>>> a.descendants(arg1, arg2)\n # output\n\n", "This will throw an error\n>>> class tagFinder:\n... def...
[ 4, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004139436_python.txt
Q: Trouble installing MySQLdb for second version of Python The context: I'm working on some Python scripts on an Ubuntu server. I need to use some code written in Python 2.7 but our server has Python 2.5. We installed 2.7 as a second instance of Python so we wouldn't break anything reliant on 2.5. Now I need to install the MySQLdb package. I assume I can't do this the easy way by running apt-get install python-mysqldb because it will likely just reinstall to python 2.5, so I am just trying to install it manually. The Problem: In the MySQL-python-1.2.3 directory I try to run python2.7 setup.py build and get an error that states: sh: /etc/mysql/my.cnf: Permission denied along with a Traceback that says setup.py couldn't find the file. Note that the setup.py script looks for a mysql_config file in the $PATH directories by default, but the mysql config file for our server is /etc/mysql/my.cnf, so I changed the package's site.cfg file to match. I checked the permissions for the file, which are -rw-r--r--. I tried running the script as root and got the same error. Any suggestions? A: As far as I'm aware, there is a very significant difference between "mysql_config" and "my.cnf". "mysql_config" is usually located in the "bin" folder of your MySQL install and when executed, spits out various filesystem location information about your install. "my.cnf" is a configuration script used by MySQL itself. In short, when the script asks for "mysql_config", it should be taken to literally mean the executable file with a name of "mysql_config" and not the textual configuration file you're feeding it. MYSQLdb needs the "mysql_config" file so that it knows which libraries to use. That's it. It does not read your MySQL configuration directly. The errors you are experiencing can be put down to; It's trying to open the wrong file and running into permission trouble. Even after it has tried to open that file, it still can't find the "mysql_config" file. From here, you need to locate your MySQL installation's "bin" folder and check it contains "mysql_config". Then you can edit the folder path into the "site.cnf" file and you should be good to go. A: Are you sure that file isn't hardcoded in some other portion of the build process? Why not just add it to you $PATH for the duration of the build? Does the script need to write that file for some reason? Does the build script use su or sudo to attempt to become some other user? Are you absolutely sure about both the permissions and the fact that you ran the script as root? It's a really weird thing if you still can't get to it. Are you using a chroot or a virtualenv?
Trouble installing MySQLdb for second version of Python
The context: I'm working on some Python scripts on an Ubuntu server. I need to use some code written in Python 2.7 but our server has Python 2.5. We installed 2.7 as a second instance of Python so we wouldn't break anything reliant on 2.5. Now I need to install the MySQLdb package. I assume I can't do this the easy way by running apt-get install python-mysqldb because it will likely just reinstall to python 2.5, so I am just trying to install it manually. The Problem: In the MySQL-python-1.2.3 directory I try to run python2.7 setup.py build and get an error that states: sh: /etc/mysql/my.cnf: Permission denied along with a Traceback that says setup.py couldn't find the file. Note that the setup.py script looks for a mysql_config file in the $PATH directories by default, but the mysql config file for our server is /etc/mysql/my.cnf, so I changed the package's site.cfg file to match. I checked the permissions for the file, which are -rw-r--r--. I tried running the script as root and got the same error. Any suggestions?
[ "As far as I'm aware, there is a very significant difference between \"mysql_config\" and \"my.cnf\".\n\n\"mysql_config\" is usually located in the \"bin\" folder of your MySQL install and when executed, spits out various filesystem location information about your install.\n\"my.cnf\" is a configuration script used...
[ 2, 0 ]
[]
[]
[ "configuration_files", "mysql", "permissions", "python" ]
stackoverflow_0004138504_configuration_files_mysql_permissions_python.txt
Q: Using a custom collection extending from a dict() with SqlAlchemy I'm trying to use a custom collection to "connect" (or relate) two classes but I haven't been able to do it. Maybe I got the whole concept of the SqlAlchemy custom collections wrong, but let me explain what I am doing (and see if someone can give me a hint, or something) I have a Parent class (which some of you will remember from other questions) with a couple of connectors fields (kind of lists) in it. One of the connectors will store instances of a Child() class whose type is "VR" and the other will store children with a "CC" type. I don't really need persistence for the collection used to store the children, but I need it to be of an special class so it will have some methods that I have implemented and that need to be there. That would be the "ZepConnector" class (and, for purposes of the example, it's method foo() is the one I need to use). As you can see in the following lines, I randomly test its availability in the addChild1() method of the Parent. --------------------- Parent.py ----------------- from megrok import rdb from sqlalchemy import Column from sqlalchemy import and_ from sqlalchemy.orm import relationship from sqlalchemy.types import Integer from sqlalchemy.types import String from mylibraries.database.tests.Child import Child from mylibraries.database.tests.Tables import testMetadata from mylibraries.database.tests.ZepConnector import ZepConnector class Parent(rdb.Model): rdb.metadata(testMetadata) rdb.tablename("parents_table") rdb.tableargs(schema='test2', useexisting=False) id = Column("id", Integer, primary_key=True, nullable=False, unique=True) _whateverField1 = Column("whatever_field1", String(16)) #Irrelevant _whateverField2 = Column("whatever_field2", String(16)) #Irrelevant child1 = relationship( "Child", uselist=True, primaryjoin=lambda: and_((Parent.id == Child.parent_id), (Child.type == "VR")), collection_class=ZepConnector("VR") ) child2 = relationship( "Child", uselist=True, primaryjoin=lambda: and_((Parent.id == Child.parent_id), (Child.type == "CC")), collection_class=ZepConnector("CC") ) def __init__(self): print "Parent __init__" self._whateverField1 = "Whatever1" self._whateverField2 = "Whatever2" self.child1 = ZepConnector("VR") self.child2 = ZepConnector("CC") def addChild1(self, child): if isinstance(child, Child): print("::addChild1 > Testing .foo method: " + str(self.child1.foo())) # The line above doesn't really makes much # but testing the accessibility of the .foo() method. # As I'll explain later, it doesn't work self.child1.append(child) def addChild2(self, child): if isinstance(child, Child): self.child2.append(child) Please note that I'm using megrok. For those who are not familiar with it, allow me to explain that it is just a tool that maps the Python class to an SqlAlchemy mapper itself and makes it a little bit more "programmer friendly" when using the Grok framework. I guess The mapping of the Parent() class in regular SqlAlchemy would resemble something like: mapper(Parent, parents_table, properties={ id = Column("id", Integer, primary_key=True, nullable=False, unique=True) _whateverField1 = Column("whatever_field1", String(16)) #Irrelevant _whateverField2 = Column("whatever_field2", String(16)) #Irrelevant child1 = relationship( # etc, etc, etc }) # but I'm 100%... erm... 90%... erm... 70% certain that using that tool is not what lead me to ask what I'm going to ask here (I mean: I don't think is interfering with the SqlAlchemy Custom Collections thing) A child is a very simple class: --------------- Child.py -------------------------- import random from megrok import rdb from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy.types import Integer from sqlalchemy.types import String from mylibraries.database.tests.Tables import testMetadata class Child(rdb.Model): rdb.metadata(testMetadata) rdb.tablename("children_table") rdb.tableargs(schema='test2', useexisting=False) parent_id = Column("parent_id", Integer, ForeignKey("test2.parents_table.id"), primary_key=True) type = Column("type", String(2), nullable=True, primary_key=True) hasher = Column("hasher", String(5)) def __init__(self): self.type = None self.hasher = self.generateHasher() def setType(self, typeParameter): if typeParameter in set(["VR", "CC"]): self.type = typeParameter @staticmethod def generateHasher(): retval = str() for i in random.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 5): retval += i return retval Let's say every Child instance will have a unique "hasher" field that can be used as a key in a dictionary (the example above is far away from the reality, but it illustrates a little bit how the Child will work and for being able to create a test) And now my custom connector. I want it to behave as a list or a set (more like a set, although I don't mind much) but it's a class that inherits from dict. -------------------- ZepConnector.py -------------------- from sqlalchemy.orm.collections import collection class ZepConnector(dict): __emulates__ = list def __init__(self, type): self.type = type # The 'type' will be "VR" or "CC" and it will be stamped # on every Child() class added through this ZepConnector def foo(self): return True @collection.appender def append(self, item): #Appends a child to itself if self.foo(): item.setType(self.type) self[item.hasher] = item @collection.remover def remove(self, item): try: del self[item.hasher] except ValueError, e: print("::remove > Got exception when trying to remove entry=" + str(item.hasher) + ". The exception is: " + str(e)) def extend(self, items): pass But I don't know why, the "ZepConnector" instances in the Parent class don't seem to be of a "ZepConnector" type but of an "InstrumentedList": When in the addChild1 method of Parent() I try to test the .foo() method (which should just print "True") I get this error: AttributeError: 'InstrumentedList' object has no attribute 'foo' Showing whole traceback: Traceback (most recent call last): File "/home/ae/mytests-cms/grokserver/eggs/zope.publisher-3.12.0-py2.4.egg/zope/publisher/publish.py", line 134, in publish result = publication.callObject(request, obj) File "/home/ae/mytests-cms/grokserver/eggs/grok-1.1rc1-py2.4.egg/grok/publication.py", line 89, in callObject return super(ZopePublicationSansProxy, self).callObject(request, ob) File "/home/ae/mytests-cms/grokserver/eggs/zope.app.publication-3.10.2-py2.4.egg/zope/app/publication/zopepublication.py", line 205, in callObject return mapply(ob, request.getPositionalArguments(), request) File "/home/ae/mytests-cms/grokserver/eggs/zope.publisher-3.12.0-py2.4.egg/zope/publisher/publish.py", line 109, in mapply return debug_call(obj, args) File "/home/ae/mytests-cms/grokserver/eggs/zope.publisher-3.12.0-py2.4.egg/zope/publisher/publish.py", line 115, in debug_call return obj(*args) File "/home/ae/mytests-cms/grokserver/eggs/grokcore.view-1.13.2-py2.4.egg/grokcore/view/components.py", line 101, in __call__ return mapply(self.render, (), self.request) File "/home/ae/mytests-cms/grokserver/eggs/zope.publisher-3.12.0-py2.4.egg/zope/publisher/publish.py", line 109, in mapply return debug_call(obj, args) File "/home/ae/mytests-cms/grokserver/eggs/zope.publisher-3.12.0-py2.4.egg/zope/publisher/publish.py", line 115, in debug_call return obj(*args) File "/home/ae/mytests-cms/grokserver/src/grokserver/app.py", line 1575, in render mylibraries.database.tests.Test.runWholeTest() File "/home/ae/mytests-cms/mylibraries/database/tests/Test.py", line 54, in runWholeTest __test() File "/home/ae/mytests-cms/mylibraries/database/tests/Test.py", line 35, in __test parent.addChild1(child) File "/home/ae/mytests-cms/mylibraries/database/tests/Parent.py", line 54, in addChild1 print("::addChild1 > Testing .foo method: " + str(self.child1.foo())) AttributeError: 'InstrumentedList' object has no attribute 'foo' Debug at: http://127.0.0.1:8080/_debug/view/1289342582 It's strange... The init method of the ZepConnector is properly executed... but when I try to use it, it doesn't seem to be ZepConnector... I did a couple of more tests, but all unsuccessful: In a second try I wrote: class ZepConnector(dict): __emulates__ = set but this even makes things worse, because I get: TypeError: Incompatible collection type: ZepConnector is not list-like In a third (or second point two) try, I though... "well... if it's saying that ZepConnector is not a list, maybe telling the Parent() not to use a list in the relationship may help... Maybe stating that the collection_class is a ZepConnector makes ynnecessary the uselist parameter in the relationship..." And so I wrote: child1 = relationship( "Child", uselist = False, primaryjoin=lambda: and_((Parent.id == Child.parent_id),(Child.type == "VR")), collection_class=ZepConnector("VR") ) But that threw a creepy exception talking about a field which I shouldn't see and that I don't want to see... ever... :-D AttributeError: 'ZepConnector' object has no attribute '_sa_instance_state' I am using Python2.4 and SqlAlchemy 0.6.6, just in case it's relevant. If someone has any ideas, guidance, counseling... whatever... I'd really appreciate you sharing it with me... erm... us... Thank you in advance! (if you have reached this line, you certainly deserve a "thank you" just for your patience reading this huge post) A: Got it. I had also asked the same question in the SqlAlchemy google group and I just got an answer. http://groups.google.com/group/sqlalchemy/msg/5c8fc09a75fd4fa7 Quote: So this is incorrect - collection_class takes a class or other callable as an argument that will produce an instance of your collection. The ZepConnector source you have below indicates that ZepConnector("VR") is an instance of the collection. You need to use a lambda: there. The other errors you're getting would appear to extend from that (and is also why init is called on ZepConnector - you're calling it yourself). Thanks to Michael Bayer (and to all the people that tried to help, even by reading such a humongous post)
Using a custom collection extending from a dict() with SqlAlchemy
I'm trying to use a custom collection to "connect" (or relate) two classes but I haven't been able to do it. Maybe I got the whole concept of the SqlAlchemy custom collections wrong, but let me explain what I am doing (and see if someone can give me a hint, or something) I have a Parent class (which some of you will remember from other questions) with a couple of connectors fields (kind of lists) in it. One of the connectors will store instances of a Child() class whose type is "VR" and the other will store children with a "CC" type. I don't really need persistence for the collection used to store the children, but I need it to be of an special class so it will have some methods that I have implemented and that need to be there. That would be the "ZepConnector" class (and, for purposes of the example, it's method foo() is the one I need to use). As you can see in the following lines, I randomly test its availability in the addChild1() method of the Parent. --------------------- Parent.py ----------------- from megrok import rdb from sqlalchemy import Column from sqlalchemy import and_ from sqlalchemy.orm import relationship from sqlalchemy.types import Integer from sqlalchemy.types import String from mylibraries.database.tests.Child import Child from mylibraries.database.tests.Tables import testMetadata from mylibraries.database.tests.ZepConnector import ZepConnector class Parent(rdb.Model): rdb.metadata(testMetadata) rdb.tablename("parents_table") rdb.tableargs(schema='test2', useexisting=False) id = Column("id", Integer, primary_key=True, nullable=False, unique=True) _whateverField1 = Column("whatever_field1", String(16)) #Irrelevant _whateverField2 = Column("whatever_field2", String(16)) #Irrelevant child1 = relationship( "Child", uselist=True, primaryjoin=lambda: and_((Parent.id == Child.parent_id), (Child.type == "VR")), collection_class=ZepConnector("VR") ) child2 = relationship( "Child", uselist=True, primaryjoin=lambda: and_((Parent.id == Child.parent_id), (Child.type == "CC")), collection_class=ZepConnector("CC") ) def __init__(self): print "Parent __init__" self._whateverField1 = "Whatever1" self._whateverField2 = "Whatever2" self.child1 = ZepConnector("VR") self.child2 = ZepConnector("CC") def addChild1(self, child): if isinstance(child, Child): print("::addChild1 > Testing .foo method: " + str(self.child1.foo())) # The line above doesn't really makes much # but testing the accessibility of the .foo() method. # As I'll explain later, it doesn't work self.child1.append(child) def addChild2(self, child): if isinstance(child, Child): self.child2.append(child) Please note that I'm using megrok. For those who are not familiar with it, allow me to explain that it is just a tool that maps the Python class to an SqlAlchemy mapper itself and makes it a little bit more "programmer friendly" when using the Grok framework. I guess The mapping of the Parent() class in regular SqlAlchemy would resemble something like: mapper(Parent, parents_table, properties={ id = Column("id", Integer, primary_key=True, nullable=False, unique=True) _whateverField1 = Column("whatever_field1", String(16)) #Irrelevant _whateverField2 = Column("whatever_field2", String(16)) #Irrelevant child1 = relationship( # etc, etc, etc }) # but I'm 100%... erm... 90%... erm... 70% certain that using that tool is not what lead me to ask what I'm going to ask here (I mean: I don't think is interfering with the SqlAlchemy Custom Collections thing) A child is a very simple class: --------------- Child.py -------------------------- import random from megrok import rdb from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy.types import Integer from sqlalchemy.types import String from mylibraries.database.tests.Tables import testMetadata class Child(rdb.Model): rdb.metadata(testMetadata) rdb.tablename("children_table") rdb.tableargs(schema='test2', useexisting=False) parent_id = Column("parent_id", Integer, ForeignKey("test2.parents_table.id"), primary_key=True) type = Column("type", String(2), nullable=True, primary_key=True) hasher = Column("hasher", String(5)) def __init__(self): self.type = None self.hasher = self.generateHasher() def setType(self, typeParameter): if typeParameter in set(["VR", "CC"]): self.type = typeParameter @staticmethod def generateHasher(): retval = str() for i in random.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 5): retval += i return retval Let's say every Child instance will have a unique "hasher" field that can be used as a key in a dictionary (the example above is far away from the reality, but it illustrates a little bit how the Child will work and for being able to create a test) And now my custom connector. I want it to behave as a list or a set (more like a set, although I don't mind much) but it's a class that inherits from dict. -------------------- ZepConnector.py -------------------- from sqlalchemy.orm.collections import collection class ZepConnector(dict): __emulates__ = list def __init__(self, type): self.type = type # The 'type' will be "VR" or "CC" and it will be stamped # on every Child() class added through this ZepConnector def foo(self): return True @collection.appender def append(self, item): #Appends a child to itself if self.foo(): item.setType(self.type) self[item.hasher] = item @collection.remover def remove(self, item): try: del self[item.hasher] except ValueError, e: print("::remove > Got exception when trying to remove entry=" + str(item.hasher) + ". The exception is: " + str(e)) def extend(self, items): pass But I don't know why, the "ZepConnector" instances in the Parent class don't seem to be of a "ZepConnector" type but of an "InstrumentedList": When in the addChild1 method of Parent() I try to test the .foo() method (which should just print "True") I get this error: AttributeError: 'InstrumentedList' object has no attribute 'foo' Showing whole traceback: Traceback (most recent call last): File "/home/ae/mytests-cms/grokserver/eggs/zope.publisher-3.12.0-py2.4.egg/zope/publisher/publish.py", line 134, in publish result = publication.callObject(request, obj) File "/home/ae/mytests-cms/grokserver/eggs/grok-1.1rc1-py2.4.egg/grok/publication.py", line 89, in callObject return super(ZopePublicationSansProxy, self).callObject(request, ob) File "/home/ae/mytests-cms/grokserver/eggs/zope.app.publication-3.10.2-py2.4.egg/zope/app/publication/zopepublication.py", line 205, in callObject return mapply(ob, request.getPositionalArguments(), request) File "/home/ae/mytests-cms/grokserver/eggs/zope.publisher-3.12.0-py2.4.egg/zope/publisher/publish.py", line 109, in mapply return debug_call(obj, args) File "/home/ae/mytests-cms/grokserver/eggs/zope.publisher-3.12.0-py2.4.egg/zope/publisher/publish.py", line 115, in debug_call return obj(*args) File "/home/ae/mytests-cms/grokserver/eggs/grokcore.view-1.13.2-py2.4.egg/grokcore/view/components.py", line 101, in __call__ return mapply(self.render, (), self.request) File "/home/ae/mytests-cms/grokserver/eggs/zope.publisher-3.12.0-py2.4.egg/zope/publisher/publish.py", line 109, in mapply return debug_call(obj, args) File "/home/ae/mytests-cms/grokserver/eggs/zope.publisher-3.12.0-py2.4.egg/zope/publisher/publish.py", line 115, in debug_call return obj(*args) File "/home/ae/mytests-cms/grokserver/src/grokserver/app.py", line 1575, in render mylibraries.database.tests.Test.runWholeTest() File "/home/ae/mytests-cms/mylibraries/database/tests/Test.py", line 54, in runWholeTest __test() File "/home/ae/mytests-cms/mylibraries/database/tests/Test.py", line 35, in __test parent.addChild1(child) File "/home/ae/mytests-cms/mylibraries/database/tests/Parent.py", line 54, in addChild1 print("::addChild1 > Testing .foo method: " + str(self.child1.foo())) AttributeError: 'InstrumentedList' object has no attribute 'foo' Debug at: http://127.0.0.1:8080/_debug/view/1289342582 It's strange... The init method of the ZepConnector is properly executed... but when I try to use it, it doesn't seem to be ZepConnector... I did a couple of more tests, but all unsuccessful: In a second try I wrote: class ZepConnector(dict): __emulates__ = set but this even makes things worse, because I get: TypeError: Incompatible collection type: ZepConnector is not list-like In a third (or second point two) try, I though... "well... if it's saying that ZepConnector is not a list, maybe telling the Parent() not to use a list in the relationship may help... Maybe stating that the collection_class is a ZepConnector makes ynnecessary the uselist parameter in the relationship..." And so I wrote: child1 = relationship( "Child", uselist = False, primaryjoin=lambda: and_((Parent.id == Child.parent_id),(Child.type == "VR")), collection_class=ZepConnector("VR") ) But that threw a creepy exception talking about a field which I shouldn't see and that I don't want to see... ever... :-D AttributeError: 'ZepConnector' object has no attribute '_sa_instance_state' I am using Python2.4 and SqlAlchemy 0.6.6, just in case it's relevant. If someone has any ideas, guidance, counseling... whatever... I'd really appreciate you sharing it with me... erm... us... Thank you in advance! (if you have reached this line, you certainly deserve a "thank you" just for your patience reading this huge post)
[ "Got it. \nI had also asked the same question in the SqlAlchemy google group and I just got an answer.\nhttp://groups.google.com/group/sqlalchemy/msg/5c8fc09a75fd4fa7\nQuote:\n\nSo this is incorrect -\n collection_class takes a class or\n other callable as an argument that\n will produce an instance of your\n c...
[ 2 ]
[]
[]
[ "collections", "inheritance", "python", "sqlalchemy" ]
stackoverflow_0004135315_collections_inheritance_python_sqlalchemy.txt
Q: How to create Unix and Linux binaries from Python code Anybody know how this can be done? I took a look at cx_Freeze, but it seems that it doesn't compile everything necessary into one binary (i.e., the python builtins aren't present). A: The standard freeze tool (from Tools/freeze) can be used to make fully-standalone binaries on Unix, including all extension modules and builtins (and omitting anything that is not directly or indirectly imported).
How to create Unix and Linux binaries from Python code
Anybody know how this can be done? I took a look at cx_Freeze, but it seems that it doesn't compile everything necessary into one binary (i.e., the python builtins aren't present).
[ "The standard freeze tool (from Tools/freeze) can be used to make fully-standalone binaries on Unix, including all extension modules and builtins (and omitting anything that is not directly or indirectly imported).\n" ]
[ 4 ]
[]
[]
[ "cross_compiling", "linux", "python", "unix" ]
stackoverflow_0004138886_cross_compiling_linux_python_unix.txt
Q: Python tips for memory optimization I need to optimize the RAM usage of my application. PLEASE spare me the lectures telling me I shouldn't care about memory when coding Python. I have a memory problem because I use very large default-dictionaries (yes, I also want to be fast). My current memory consumption is 350MB and growing. I already cannot use shared hosting and if my Apache opens more processes the memory doubles and triples... and it is expensive. I have done extensive profiling and I know exactly where my problems are. I have several large (>100K entries) dictionaries with Unicode keys. A dictionary starts at 140 bytes and grows fast, but the bigger problem is the keys. Python optimizes strings in memory (or so I've read) so that lookups can be ID comparisons ('interning' them). Not sure this is also true for unicode strings (I was not able to 'intern' them). The objects stored in the dictionary are lists of tuples (an_object, an int, an int). my_big_dict[some_unicode_string].append((my_object, an_int, another_int)) I already found that it is worth while to split to several dictionaries because the tuples take a lot of space... I found that I could save RAM by hashing the strings before using them as keys! But then, sadly, I ran into birthday collisions on my 32 bit system. (side question: is there a 64-bit key dictionary I can use on a 32-bit system?) Python 2.6.5 on both Linux(production) and Windows. Any tips on optimizing memory usage of dictionaries / lists / tuples? I even thought of using C - I don't care if this very small piece of code is ugly. It is just a singular location. Thanks in advance! A: I suggest the following: store all the values in a DB, and keep an in-memory dictionary with string hashes as keys. If a collision occurs, fetch values from the DB, otherwise (vast majority of the cases) use the dictionary. Effectively, it will be a giant cache. A problem with dictionaries in Python is that they use a lot of space: even an int-int dictionary uses 45-80 bytes per key-value pair on a 32-bit system. At the same time, an array.array('i') uses only 8 bytes per a pair of ints, and with a little bit of bookkeeping one can implement a reasonably fast array-based int → int dictionary. Once you have a memory-efficient implementation of an int-int dictionary, split your string → (object, int, int) dictionary into three dictionaries and use hashes instead of full strings. You'll get one int → object and two int → int dictionaries. Emulate the int → object dictionary as follows: keep a list of objects and store indexes of the objects as values of an int → int dictionary. I do realize there's a considerable amount of coding involved to get an array-based dictionary. I had had problem similar to yours and I have implemented a reasonably fast, very memory-efficient, generic hash-int dictionary. Here's my code (BSD license). It is array-based (8 bytes per pair), it takes care of key hashing and collision checking, it keeps the array (several smaller arrays, actually) ordered during writes and does binary search on reads. Your code is reduced to something like: dictionary = HashIntDict(checking = HashIntDict.CHK_SHOUTING) # ... database.store(k, v) try: dictionary[k] = v except CollisionError: pass # ... try: v = dictionary[k] except CollisionError: v = database.fetch(k) The checking parameter specifies what happens when a collision occurs: CHK_SHOUTING raises CollisionError on reads and writes, CHK_DELETING returns None on reads and remains silent on writes, CHK_IGNORING doesn't do collision checking. What follows is a brief description of my implementation, optimization hints are welcome! The top-level data structure is a regular dictionary of arrays. Each array contains up to 2^16 = 65536 integer pairs (square root of 2^32). A key k and a corresponding value v are both stored in k/65536-th array. The arrays are initialized on-demand and kept ordered by keys. Binary search is executed on each read and write. Collision checking is an option. If enabled, an attempt to overwrite an already existing key will remove the key and associated value from the dictionary, add the key to a set of colliding keys, and (again, optionally) raise an exception. A: For a web application you should use a database, the way you're doing it you are creating one copy of your dict for each apache process, which is extremely wasteful. If you have enough memory on the server the database table will be cached in memory (if you don't have enough for one copy of your table, put more RAM into the server). Just remember to put correct indices on your database table or you will get bad performance. A: I've had situations where I've had a collection of large objects that I've needed to sort and filter by different methods based on several metadata properties. I didn't need the larger parts of them so I dumped them to disk. As you data is so simple in type, a quick SQLite database might solve all your problems, even speed things up a little. A: Use shelve or a database to store the data instead of an in-memory dict. A: If you want to stay with the in-memory data store, you could try something like memcached. That way, you can use a single in-memory key/value-store from all the Python processes. There are several python memcached client libraries. A: Redis would be a great option here if you have the option to use it on a shared host - similar to memcached, but optimised for data structures. Redis also supports python bindings. I use it on a day to day basis for number crunching but also in production systems as a datastore and cannot recommend it highly enough. Also, do you have an option to proxy your app behind nginx instead of using Apache? You might find (if allowed) this proxy/webapp arrangement less hungry on resources. Good luck. A: If you want to do extensive optimization and have full control on memory usage you could also write a C/C++ module. Using Swig the code wrapping into Python can be done easily, with some small performance overhead comparing to pure C Python module.
Python tips for memory optimization
I need to optimize the RAM usage of my application. PLEASE spare me the lectures telling me I shouldn't care about memory when coding Python. I have a memory problem because I use very large default-dictionaries (yes, I also want to be fast). My current memory consumption is 350MB and growing. I already cannot use shared hosting and if my Apache opens more processes the memory doubles and triples... and it is expensive. I have done extensive profiling and I know exactly where my problems are. I have several large (>100K entries) dictionaries with Unicode keys. A dictionary starts at 140 bytes and grows fast, but the bigger problem is the keys. Python optimizes strings in memory (or so I've read) so that lookups can be ID comparisons ('interning' them). Not sure this is also true for unicode strings (I was not able to 'intern' them). The objects stored in the dictionary are lists of tuples (an_object, an int, an int). my_big_dict[some_unicode_string].append((my_object, an_int, another_int)) I already found that it is worth while to split to several dictionaries because the tuples take a lot of space... I found that I could save RAM by hashing the strings before using them as keys! But then, sadly, I ran into birthday collisions on my 32 bit system. (side question: is there a 64-bit key dictionary I can use on a 32-bit system?) Python 2.6.5 on both Linux(production) and Windows. Any tips on optimizing memory usage of dictionaries / lists / tuples? I even thought of using C - I don't care if this very small piece of code is ugly. It is just a singular location. Thanks in advance!
[ "I suggest the following: store all the values in a DB, and keep an in-memory dictionary with string hashes as keys. If a collision occurs, fetch values from the DB, otherwise (vast majority of the cases) use the dictionary. Effectively, it will be a giant cache.\nA problem with dictionaries in Python is that the...
[ 13, 4, 2, 1, 1, 1, 0 ]
[]
[]
[ "memory_management", "optimization", "python" ]
stackoverflow_0003021264_memory_management_optimization_python.txt
Q: C++ Allocated Memory Problem It has been a long time since I have programmed in C++, but I recently wrote a little C++ function and am having a little bit of trouble. The function returns a struct, Result, that have some strings in it. I thought I allocated memory for the strings, but jsonResult is sometimes partially overwritten. //The structs struct Interp { int score; char* sentence; char* jsonResult; }; struct Result { int resultCode; char* errorMessage; Interp interp; }; ... //Inside the function Result result; //Store decode const char* jsonResult,* sentence; if (result.resultCode == -1) { LVInterpretation interp = port.GetInterpretation(voiceChannel, 0); result.interp.score = interp.Score(); sentence = interp.InputSentence(); jsonResult = interp.ResultData().Print(SI_FORMAT_ECMA); } //Allocate memory for strings result.interp.jsonResult = new char[strlen(jsonResult) + 1]; strcpy(result.interp.jsonResult, jsonResult); result.interp.sentence = new char[strlen(sentence) + 1]; strcpy(result.interp.sentence, sentence); result.errorMessage = new char[strlen(errorMessage) + 1]; strcpy(result.errorMessage, errorMessage); return result; Other info: I am observing all of this behind the python binding that I wrote, using ctypes. Don't think that is really effecting anything though. A: Use std::string. You won't regret it. A: I'd put money on your problem being in here: jsonResult = interp.ResultData().Print(SI_FORMAT_ECMA); Who 'owns' the char* array returned by Print()? Maybe it's attempting to return a pointer to memory that's out of scope??? example: char* badFunction(void) { char test[100]; strcpy(test,"This is really clever"); // oh, yeah? return test; // returns pointer to data that's out of scope } One other thing. Assign null pointers to sentence, jsonResult, etc when you declare them. Otherwise you could end up strcpy()ing uninitialized data, A: Couple of things: What does "partially overwritten" mean? How do you know this? i.e. what is your expected output vs. what you see? It's not really clear how result.resultCode is set to -1 (or if it is at all), and if it is set, how does the memory get allocated in interp.InputSentence() and interp.ResultData().Print(SI_FORMAT_ECMA)? I'd suggest that your problem lies there The rest of the code should work as long as jsonResult and sentence contain valid null terminated strings.
C++ Allocated Memory Problem
It has been a long time since I have programmed in C++, but I recently wrote a little C++ function and am having a little bit of trouble. The function returns a struct, Result, that have some strings in it. I thought I allocated memory for the strings, but jsonResult is sometimes partially overwritten. //The structs struct Interp { int score; char* sentence; char* jsonResult; }; struct Result { int resultCode; char* errorMessage; Interp interp; }; ... //Inside the function Result result; //Store decode const char* jsonResult,* sentence; if (result.resultCode == -1) { LVInterpretation interp = port.GetInterpretation(voiceChannel, 0); result.interp.score = interp.Score(); sentence = interp.InputSentence(); jsonResult = interp.ResultData().Print(SI_FORMAT_ECMA); } //Allocate memory for strings result.interp.jsonResult = new char[strlen(jsonResult) + 1]; strcpy(result.interp.jsonResult, jsonResult); result.interp.sentence = new char[strlen(sentence) + 1]; strcpy(result.interp.sentence, sentence); result.errorMessage = new char[strlen(errorMessage) + 1]; strcpy(result.errorMessage, errorMessage); return result; Other info: I am observing all of this behind the python binding that I wrote, using ctypes. Don't think that is really effecting anything though.
[ "Use std::string. You won't regret it.\n", "I'd put money on your problem being in here:\njsonResult = interp.ResultData().Print(SI_FORMAT_ECMA);\n\nWho 'owns' the char* array returned by Print()? Maybe it's attempting to return a pointer to memory that's out of scope???\nexample:\n char* badFunction(void)\n {\...
[ 4, 1, 0 ]
[]
[]
[ "c++", "ctypes", "memory_management", "python" ]
stackoverflow_0004139576_c++_ctypes_memory_management_python.txt
Q: Python server for hosting sockets and reading data I'm trying to create a python server that will serve calls from outer source through sockets. So I've skimmed through the docs and copied this code, I can connect but no sent data is shown. What am I doing wrong ? import SocketServer class MyUDPHandler(SocketServer.BaseRequestHandler): def handle(self): self.data = self.rfile.readline().strip() print "%s wrote:" % self.client_address[0] print self.data self.wfile.write(self.data.upper()) if __name__ == "__main__": HOST, PORT = "localhost", 80 try: server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler) print("working") server.serve_forever() serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.bind((socket.gethostname(), 80)) serversocket.listen(5) except: print("not working") while True: (clientsocket, address) = serversocket.accept() ct = client_thread(clientsocket) ct.run() class mysocket: def __init__(self, sock=None): if sock is None: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock def connect(self, host, port): self.sock.connect((host, port)) def mysend(self, msg): totalsent = 0 while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError("socket connection broken") totalsent = totalsent + sent def myreceive(self): msg = '' while len(msg) < MSGLEN: chunk = self.sock.recv(MSGLEN-len(msg)) if chunk == '': raise RuntimeError("socket connection broken") msg = msg + chunk return msg And moreover, if this code is proper - how to use it ? I'm just setting the server now with python server.py which creates an instance of MyUdpHandler but what next ? A: you problem might lie in that server.serve_forever() never returns, it will block your code and nothing beyond it will run. you might have this work better by splitting this across threads: import threading def launch_server(): server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler) print("working") server.serve_forever() #carry on with your other code here. #this belongs at the _bottom_ of your file! not the middle! if __name__ == '__main__': server_thread = threading.Thread(target=launch_server, args=()) server_thread.start()
Python server for hosting sockets and reading data
I'm trying to create a python server that will serve calls from outer source through sockets. So I've skimmed through the docs and copied this code, I can connect but no sent data is shown. What am I doing wrong ? import SocketServer class MyUDPHandler(SocketServer.BaseRequestHandler): def handle(self): self.data = self.rfile.readline().strip() print "%s wrote:" % self.client_address[0] print self.data self.wfile.write(self.data.upper()) if __name__ == "__main__": HOST, PORT = "localhost", 80 try: server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler) print("working") server.serve_forever() serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.bind((socket.gethostname(), 80)) serversocket.listen(5) except: print("not working") while True: (clientsocket, address) = serversocket.accept() ct = client_thread(clientsocket) ct.run() class mysocket: def __init__(self, sock=None): if sock is None: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock def connect(self, host, port): self.sock.connect((host, port)) def mysend(self, msg): totalsent = 0 while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError("socket connection broken") totalsent = totalsent + sent def myreceive(self): msg = '' while len(msg) < MSGLEN: chunk = self.sock.recv(MSGLEN-len(msg)) if chunk == '': raise RuntimeError("socket connection broken") msg = msg + chunk return msg And moreover, if this code is proper - how to use it ? I'm just setting the server now with python server.py which creates an instance of MyUdpHandler but what next ?
[ "you problem might lie in that server.serve_forever() never returns, it will block your code and nothing beyond it will run.\nyou might have this work better by splitting this across threads:\nimport threading\ndef launch_server():\n server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)\n print(\"workin...
[ 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0004139735_python_sockets.txt
Q: Multiple urllib2 connections I want to download multiple images at the same time. For that I'm using threads, each one downloading an image, using urllib2 module. My problem is that even if threads starts (almost) simultaneously, the images are downloaded one by one, like in a single-threaded environment. Here is the threaded function: def updateIcon(self, iter, imageurl): req = urllib2.Request('http://site.com/' + imageurl) response = urllib2.urlopen(req) imgdata = response.read() gobject.idle_add(self.setIcon, iter, imgdata) Debugging my code I found that downloads seems to get stuck at "response = urllib2.urlopen(req)" line. What's the problem? It's because the threading module or urllib2? How I can fix that? Thank you in advance A: Consider using urllib3. It supports connection pooling and multiple concurrent requests via processes (not threads). It should solve this problem. Be careful to garbage collect connection pools if you contact many different sites, since each site gets its own pool. A: In my experience, multithreads of CPython seems to make better performance than those of sigle thread. Because CPython has thread implementation based on kernel thread. But the difference is little, because of GIL(Global Interpreter Lock). Substitute multiprocessing for multithreading. It's easy. Both have similar interface.
Multiple urllib2 connections
I want to download multiple images at the same time. For that I'm using threads, each one downloading an image, using urllib2 module. My problem is that even if threads starts (almost) simultaneously, the images are downloaded one by one, like in a single-threaded environment. Here is the threaded function: def updateIcon(self, iter, imageurl): req = urllib2.Request('http://site.com/' + imageurl) response = urllib2.urlopen(req) imgdata = response.read() gobject.idle_add(self.setIcon, iter, imgdata) Debugging my code I found that downloads seems to get stuck at "response = urllib2.urlopen(req)" line. What's the problem? It's because the threading module or urllib2? How I can fix that? Thank you in advance
[ "Consider using urllib3. It supports connection pooling and multiple concurrent requests via processes (not threads). It should solve this problem. Be careful to garbage collect connection pools if you contact many different sites, since each site gets its own pool.\n", "In my experience, multithreads of CPython ...
[ 3, 0 ]
[]
[]
[ "multithreading", "python", "urllib2" ]
stackoverflow_0004139988_multithreading_python_urllib2.txt
Q: How to implement server & multi-clients "communication"? What I aim to do is to fulfill a mutual communication between one server but multiple clients. Here is the Server part I wrote: Import subprocess, time, socket, fileinput s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host='' port = 2000 s.bind((host, port)) s.listen(2) # here 2 means the maximum number of clients that can connect to the server is 2 conn,addr = s.accept() for data in fileinput.input('some file I previously created') conn.send(data) conn.close() So, here pretty much is the client-server communication. (Only the Server part). The question is: This script can implement communication between one client and one server. How to fulfill communication between one server and multiple clients. Let's say I have 6 numbers in the file. I wish to transmit the first 3 to client-A, the 4th to client-B and the rest to client-C. How to make this happen? I appreciate your precious and experienced skills. A: Use Twisted.
How to implement server & multi-clients "communication"?
What I aim to do is to fulfill a mutual communication between one server but multiple clients. Here is the Server part I wrote: Import subprocess, time, socket, fileinput s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host='' port = 2000 s.bind((host, port)) s.listen(2) # here 2 means the maximum number of clients that can connect to the server is 2 conn,addr = s.accept() for data in fileinput.input('some file I previously created') conn.send(data) conn.close() So, here pretty much is the client-server communication. (Only the Server part). The question is: This script can implement communication between one client and one server. How to fulfill communication between one server and multiple clients. Let's say I have 6 numbers in the file. I wish to transmit the first 3 to client-A, the 4th to client-B and the rest to client-C. How to make this happen? I appreciate your precious and experienced skills.
[ "Use Twisted.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004140431_python.txt
Q: firefox can't establish connection with localhost while running a cherrypy tutorial example in Fedora core my configuration [global] server.socket_host = "0.0.0.0" server.socket_port = 8080 server.thread_pool = 10 server.environment = "production" server.showTracebacks = "True" server.logToScreen = "False" I have no access to "root" Please suggest me anythin A: Make your socket host address as "localhost" or correct ip address. [global] server.socket_host = "" server.socket_port = 8080 [Edit:] There seems to be a bug in cherrypy < 3.0 server.socket_host This setting binds CherryPy to a particular ip address. This isn't usually necessary, as CherryPy will listen for any incoming connections by default. The exception is when your application is running on a system which has both a IPv4 and IPv6 network stack. By default the CherryPy server will only listen on the IPv6 interfaces. Normally, to listen on all IPv4 interfaces, you would set server.socket_host = '0.0.0.0' but unfortunately, due to a bug in CherryPy <= 3.0, this causes an error on some systems. The workaround is to set server.socket_host to a specific interface address and run your application behind a reverse proxy that listens on all interfaces and forwards requests to your application.
firefox can't establish connection with localhost while running a cherrypy tutorial example in Fedora core
my configuration [global] server.socket_host = "0.0.0.0" server.socket_port = 8080 server.thread_pool = 10 server.environment = "production" server.showTracebacks = "True" server.logToScreen = "False" I have no access to "root" Please suggest me anythin
[ "Make your socket host address as \"localhost\" or correct ip address.\n[global]\nserver.socket_host = \"\"\nserver.socket_port = 8080\n\n[Edit:]\nThere seems to be a bug in cherrypy < 3.0\nserver.socket_host \n\nThis setting binds CherryPy to a particular ip address. This isn't usually necessary, as CherryPy will ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004140550_python.txt
Q: Does JQuery/Django have a way to build "click the text to edit"? A Flickr page displays the title and description of the photo. When I click on the description, it will turn it into a text-box, with a Save button. Then, I can edit what I want...and click "Save." It'll save it via AJAX. It doesn't go to a different page or anything...it just turns the current description into a wiki-like text box. A: jEditable http://www.appelsiini.net/projects/jeditable/default.html for demo
Does JQuery/Django have a way to build "click the text to edit"?
A Flickr page displays the title and description of the photo. When I click on the description, it will turn it into a text-box, with a Save button. Then, I can edit what I want...and click "Save." It'll save it via AJAX. It doesn't go to a different page or anything...it just turns the current description into a wiki-like text box.
[ "jEditable\nhttp://www.appelsiini.net/projects/jeditable/default.html for demo\n" ]
[ 4 ]
[]
[]
[ "django", "forms", "html", "javascript", "python" ]
stackoverflow_0004140634_django_forms_html_javascript_python.txt
Q: Shrink and merge PDFs in Python I'm trying to shrink and merge two A4 PDF pages into one A4 page so that if I had; _____ _____ | | | | | p1 | | p2 | | | | | |_____| |_____| I would get; _____ | p1 | |.....| | p2 | |_____| As a new PDF, with two A5 sized pages on that one page. Similar to how you might print two pages per page on paper. I've looked into pyPDF (http://pybrary.net/pyPdf/) ReportLab (http://www.reportlab.com) but I can't seem to find how to shrink and merge like this. Any hints? Thanks! A: pdfnup has this functionality (http://pypi.python.org/pypi/pdfnup)# e.g. from pyPdf import PdfFileWriter, PdfFileReader from pdfnup import generateNup output = PdfFileWriter() input1 = PdfFileReader(file("in.pdf", "rb")) page1 = input1.getPage(0) page2 = input1.getPage(1) output.addPage(page1) output.addPage(page2) outputStream = file("out.pdf", "wb") output.write(outputStream) outputStream.close() generateNup("out.pdf", 2) A: The way I would do it (not necessarily the best way, but using tools I have available) would be to use Ghostcript's pdf2ps to convert to PostScript, then append an N-up PostScript preamble (PS is a full programming language and you can redefine builtins like "showpage" to add N-up or posterization directly to a document) and then I'd convert back with ps2pdf. Offhand I'm not finding a published version of a PostScript N-up utility, but you can google several ones written in other languages that manipulate the PostScript document itself, such as those at http://www.tardis.ed.ac.uk/~ajcd/psutils/
Shrink and merge PDFs in Python
I'm trying to shrink and merge two A4 PDF pages into one A4 page so that if I had; _____ _____ | | | | | p1 | | p2 | | | | | |_____| |_____| I would get; _____ | p1 | |.....| | p2 | |_____| As a new PDF, with two A5 sized pages on that one page. Similar to how you might print two pages per page on paper. I've looked into pyPDF (http://pybrary.net/pyPdf/) ReportLab (http://www.reportlab.com) but I can't seem to find how to shrink and merge like this. Any hints? Thanks!
[ "pdfnup has this functionality (http://pypi.python.org/pypi/pdfnup)#\ne.g.\nfrom pyPdf import PdfFileWriter, PdfFileReader\nfrom pdfnup import generateNup\n\noutput = PdfFileWriter()\ninput1 = PdfFileReader(file(\"in.pdf\", \"rb\"))\n\npage1 = input1.getPage(0)\npage2 = input1.getPage(1)\n\noutput.addPage(page1)\no...
[ 4, 1 ]
[]
[]
[ "pdf", "pdf_generation", "python" ]
stackoverflow_0004140466_pdf_pdf_generation_python.txt
Q: Python Search Algebra Function I am trying to make a search function to work with algebra problems. I want something like Wolfram Alpha but I am building a python framework for it. It should be able to figure out multiple variables and equations on both sides of the equal sign. I have recently asked about a validator for the program so I need a loop that goes through a bunch of numbers and figures out what each of the variables equals. My problem is the decimals. I suggest using a search function. Here is the equation solver: def s_equation(a): left, right = a.split('=') return eval(left) == eval(right) Any help is helpful! A: The eval()s won't work, because left and right are strings, not expressions. Moreover, you'll have to do substantial validation to make what a user might input a valid Python expression. Consider a few values you might get: # The typical person's notation for x-squared isn't valid Python x^2 + x - 3 # 3x means 3 * x to us, but to python it means nothing 3x + 4 # Some people use % to represent division, but that's a modulo operator to Python 3 % 4x # Python doesn't understand the distributive property 3(4 - x) # People might use some functions in a way Python doesn't understand cos x # Square brackets are used synonymously with parentheses x[(x^2 - 5)(x^3 - 5x)] So, in short, you'll need some kind of engine to convert plain text equations into valid Python expressions. This is no easy task, but it can certainly be done. Although your project is very ambitious, I think it's a great way to use Python! If you come up with an intelligent way to convert equations as strings into valid Python, you should share it immediately because quite a few people in the scientific and math community could have use for that.
Python Search Algebra Function
I am trying to make a search function to work with algebra problems. I want something like Wolfram Alpha but I am building a python framework for it. It should be able to figure out multiple variables and equations on both sides of the equal sign. I have recently asked about a validator for the program so I need a loop that goes through a bunch of numbers and figures out what each of the variables equals. My problem is the decimals. I suggest using a search function. Here is the equation solver: def s_equation(a): left, right = a.split('=') return eval(left) == eval(right) Any help is helpful!
[ "The eval()s won't work, because left and right are strings, not expressions. Moreover, you'll have to do substantial validation to make what a user might input a valid Python expression. Consider a few values you might get:\n# The typical person's notation for x-squared isn't valid Python\nx^2 + x - 3\n# 3x means ...
[ 1 ]
[]
[]
[ "algebra", "function", "python", "search" ]
stackoverflow_0004140780_algebra_function_python_search.txt
Q: Python: Random combination from two files New to python, bear with me. I have two text files, each has a word on a line (some funny words). I want to create a third file which has the random combination of those. with a space between them. Example: File1: Smile Sad Noob Happy ... File2: Face Apple Orange ... File3: Smile Orange Sad Apple Noob Face ..... How can I Python this? Thanks! A: from __future__ import with_statement import random import os with open('File1', 'r') as f1: beginnings = [word.rstrip() for word in f1] with open('File2', 'r') as f2: endings = [word.rstrip() for word in f2] with open('File3', 'w') as f3: for beginning in beginnings: f3.write('%s %s' % (beginning, random.choice(endings))) f3.write(os.linesep) A: Start by parsing the input files, so you end up with a list of two lists, each containing the words in one if the files. We will also use the shuffle method in the random module to randomize them: from random import shuffle words = [] for filename in ['File1', 'File2']: with open(filename, 'r') as file: # Opening the file using the with statement will ensure that it is properly # closed when your done. words.append((line.strip() for line in file.readlines())) # The readlines method returns a list of the lines in the file shuffle(words[-1]) # Shuffle will randomize them # The -1 index refers to the last item (the one we just added) Next we have to write our list of output words to a file: with open('File3', 'w') as out_file: for pair in zip(words): # The zip method will take one element from each list and pair them up out_file.write(" ".join(pair) + "\n") # The join method will take the pair of words and return them as a string, # separated by a space. A: import random list1 = [ x.strip() for x in open('file1.txt', 'r').readlines()] list2 = [ x.strip() for x in open('file2.txt', 'r').readlines()] random.shuffle(list1) random.shuffle(list2) for word1, word2 in zip(list1, list2): print word1, word2 A: Try something like this: file1 = [] for line in open("file1.txt"): file1.append(line) #or just list(open("file1.txt")) ... file3 = open('file3.txt','w') file3.write(...) and work off that. Look at the random module and its functions. (http://docs.python.org/library/random.html) If you are new to Python, look at a tutorial like Dive into Python (http://diveintopython3.ep.io/), available online. A: you can do something like f = open(file,'r') data = [" "] while data[-1] != "": data += [f.readline() # do this a second time for the second file and then out = "" from random import randint for x in xrange(len(data)): y = randint(0, len(data) -1) if data[y] != 0: out += data[y] + "\n" data[y] = 0 f3 = open(third file,'w+b') f3.write(out) this is a terrible code, but it should work A: this is a quick try... import random f1 = [line.rstrip() for line in open('file1', 'r').readlines()] f2 = [line.rstrip() for line in open('file2', 'r').readlines()] random.shuffle(f1) random.shuffle(f2) out = zip(f1, f2) f3 = open('file3', 'w') for k, v in out: f3.write(k + ' ' + v + '\n')
Python: Random combination from two files
New to python, bear with me. I have two text files, each has a word on a line (some funny words). I want to create a third file which has the random combination of those. with a space between them. Example: File1: Smile Sad Noob Happy ... File2: Face Apple Orange ... File3: Smile Orange Sad Apple Noob Face ..... How can I Python this? Thanks!
[ "from __future__ import with_statement\nimport random\nimport os\n\nwith open('File1', 'r') as f1:\n beginnings = [word.rstrip() for word in f1]\n\nwith open('File2', 'r') as f2:\n endings = [word.rstrip() for word in f2]\n\nwith open('File3', 'w') as f3:\n for beginning in beginnings:\n f3.write('%...
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004140798_python.txt
Q: How do I convert GAE TimeProperty to integer? In this Python package there is this code: >>> dt = DateTime('Mar 9, 1997 13:45:00 US/Eastern') >>> dt.timeTime() 857933100.0 I would use this package but there is a warning: "Unless you need to communicate with Zope 2 APIs, you're probably better off using Python's bult-in datetime module." TimeProperty in GAE gives me something like this 02:37:31.797000 How do I convert it to a number as in the example so that I can add an integer to it and sort by the new value. I want to achieve some kind of weighed sort. Thanks. EDIT @Robert Kluin: Thanks; this works: >>> today = datetime.datetime.today().toordinal() >>> today 734086 >>> But I have a DateTime object that I am using in the query to sort; so this works: QUERY2 = Rep.all() QUERY2.filter("mAUTHOR =", user) QUERY2.order("-mDATE") RESULTS2 = QUERY2.fetch(10) But when I try this, it does not work: QUERY2 = Rep.all() QUERY2.filter("mAUTHOR =", user) QUERY2.order("-(datetime.datetime.mDATE.toordinal())") RESULTS2 = QUERY2.fetch(10) I get the error: PropertyError: Invalid property name '(datetime.datetime.mDATE.toordinal())' This is the value of mDATE as printed by the template: mDATE = 2010-11-10 05:38:55.340000 A: Check out the time module. import time value = time.time()
How do I convert GAE TimeProperty to integer?
In this Python package there is this code: >>> dt = DateTime('Mar 9, 1997 13:45:00 US/Eastern') >>> dt.timeTime() 857933100.0 I would use this package but there is a warning: "Unless you need to communicate with Zope 2 APIs, you're probably better off using Python's bult-in datetime module." TimeProperty in GAE gives me something like this 02:37:31.797000 How do I convert it to a number as in the example so that I can add an integer to it and sort by the new value. I want to achieve some kind of weighed sort. Thanks. EDIT @Robert Kluin: Thanks; this works: >>> today = datetime.datetime.today().toordinal() >>> today 734086 >>> But I have a DateTime object that I am using in the query to sort; so this works: QUERY2 = Rep.all() QUERY2.filter("mAUTHOR =", user) QUERY2.order("-mDATE") RESULTS2 = QUERY2.fetch(10) But when I try this, it does not work: QUERY2 = Rep.all() QUERY2.filter("mAUTHOR =", user) QUERY2.order("-(datetime.datetime.mDATE.toordinal())") RESULTS2 = QUERY2.fetch(10) I get the error: PropertyError: Invalid property name '(datetime.datetime.mDATE.toordinal())' This is the value of mDATE as printed by the template: mDATE = 2010-11-10 05:38:55.340000
[ "Check out the time module.\nimport time\nvalue = time.time()\n\n" ]
[ 1 ]
[]
[]
[ "datetime", "google_app_engine", "python" ]
stackoverflow_0004140944_datetime_google_app_engine_python.txt
Q: Tkinter: Listbox separators, disabled items, keyboard navigation? I'm studying the Tkinter Listbox widget and have been unable to find solutions for the following functionality: How can I create non-selectable horizontal separator items, eg. separators equivalent to the Tkinter Menu widget's .add_separator()? (Using chars like dashes and underscores looks awful). How can I disable a specific item? I tried using .itemconfig( index, state='disabled' ) without success. How can I enable keyboard navigation, eg. when a user's keyboard input automatically scrolls one forward to the closest item that begins with the text the user typed? Must I bind(<KeyPress>, ...) and manage this behavior myself? Would some of the above functionality be easier to implement using a Text widget or the ttk.Treeview widget? A: you cannot. The widget doesn't support that. you can't disable certain items, the widget doesn't support a state attribute. That being said, you can monitor the selection and do the appropriate thing if the user selects something that is disabled, and use the item foreground to denote disabled-ness. You will need to bind to keypress events and manage the behavior yourself. It's not particularly difficult, just a little tedious. the text widget might be your best bet, though you'll have to add bindings to mimic the default bindings of the listbox. Bottom line: Tkinter provides nothing that directly supports what you want to do, but the building blocks are all there. You'll just have to build it yourself.
Tkinter: Listbox separators, disabled items, keyboard navigation?
I'm studying the Tkinter Listbox widget and have been unable to find solutions for the following functionality: How can I create non-selectable horizontal separator items, eg. separators equivalent to the Tkinter Menu widget's .add_separator()? (Using chars like dashes and underscores looks awful). How can I disable a specific item? I tried using .itemconfig( index, state='disabled' ) without success. How can I enable keyboard navigation, eg. when a user's keyboard input automatically scrolls one forward to the closest item that begins with the text the user typed? Must I bind(<KeyPress>, ...) and manage this behavior myself? Would some of the above functionality be easier to implement using a Text widget or the ttk.Treeview widget?
[ "\nyou cannot. The widget doesn't support that.\nyou can't disable certain items, the widget doesn't support a state attribute. That being said, you can monitor the selection and do the appropriate thing if the user selects something that is disabled, and use the item foreground to denote disabled-ness.\nYou will n...
[ 5 ]
[]
[]
[ "listbox", "python", "tkinter", "ttk", "user_interface" ]
stackoverflow_0004140396_listbox_python_tkinter_ttk_user_interface.txt
Q: My script needs to run two loops at the same time to read IO data from two different sources. Is my threading correct? import threading import mynetworking def FirstNIC(): for addr in mynetworking.first.scan(): print addr def SecondNIC(): for addr in mynetworking.second.scan(): print addr first = threading.Thread(target=FirstNIC) second = threading.Thread(target=SecondNIC) first.start() second.start() That's the basic code structure I intend to you. The program will be running two while True loops to read data coming in over two different network sources. The script above needs to collect that data and log it. Will this code work? Is it any good? Should the threads return the addr for the main program to log? Or should I simply replace print addr with log(addr)? This is my first time with multithreading so I'm not entirely sure how this works... A: Your code is fine except that your print statments can collide because they could both write at once. Use Queue.queue for easy synchronization: import threading import mynetworking import Queue def FirstNIC(queue): for addr in mynetworking.first.scan(queue): queue.put(addr) def SecondNIC(queue): for addr in mynetworking.second.scan(): queue.put(addr) def logger(queue): while True: print queue.get() output_queue = Queue.queue() first = threading.Thread(target=FirstNIC, args=(output_queue,)) second = threading.Thread(target=SecondNIC, args=(output_queue,)) first.start() second.start() logger(output_queue)
My script needs to run two loops at the same time to read IO data from two different sources. Is my threading correct?
import threading import mynetworking def FirstNIC(): for addr in mynetworking.first.scan(): print addr def SecondNIC(): for addr in mynetworking.second.scan(): print addr first = threading.Thread(target=FirstNIC) second = threading.Thread(target=SecondNIC) first.start() second.start() That's the basic code structure I intend to you. The program will be running two while True loops to read data coming in over two different network sources. The script above needs to collect that data and log it. Will this code work? Is it any good? Should the threads return the addr for the main program to log? Or should I simply replace print addr with log(addr)? This is my first time with multithreading so I'm not entirely sure how this works...
[ "Your code is fine except that your print statments can collide because they could both write at once. Use Queue.queue for easy synchronization:\nimport threading\nimport mynetworking\nimport Queue\n\ndef FirstNIC(queue):\n for addr in mynetworking.first.scan(queue):\n queue.put(addr)\n\ndef SecondNIC(qu...
[ 1 ]
[]
[]
[ "asynchronous", "multithreading", "python" ]
stackoverflow_0004140928_asynchronous_multithreading_python.txt
Q: Temporary variables in Mathematica I have written a package for Mathematica called MathOO. In short, it allows you to use object orientation in Mathematica just like you do in Python. Please read the following article in Voofie/MathOO for details: MathOO: Adding Python style Object Orientation to Mathematica with MathOO (1.0 beta launch) [Alternative to Objectica] The problem I encountered is that, I would like to have garbage collector, so that user don't have to explicitly deleting the object after using it. For instance: NewClass[Object1] Object1.$init$[self_]:= Return[]; In the above two lines, I just defined Object1 to be a new class, and the constructor to be an empty function. If you are familiar with Python, you should see the similarity with __init__(). To instantiate an Object1, I do: object1 = new[Object1][] The output is: Out: object$13 Here, object$13 is an temporary variable. What I want is, when there are no references to this temporary variable, it should be deleted automatically. But it doesn't work as expected. I have identified the problem to be the following: In: y = Module[{x}, x[1] = 2; x] Out: x$117 In: FullDefinition[y] Out: y = x$117 Attributes[x$117] = {Temporary} x$117[1] = 2 Since y holds a reference of x$117, so x$117 is not removed yet. Now let's delete the reference by setting the value of y to 1: In: y = 1; However, x$117 is still here: In: Definition[x$117] Out: Attributes[x$117] = {Temporary} x$117[1] = 2 But I expected the variable to be removed since it is no longer referenced. From the manual of Mathematica, it said: Temporary symbols are removed if they are no longer referenced: So, is it a bug of Mathematica? Or is there any workaround methods? I am using Mathematica 7.0. Thank you very much. A: Mathematica really does garbage collects Temporary variables when they have no more references. That said, there's two reasons that your x$117 is not garbage collected. Remember that Module uses lexical scoping, so the module variables are only "local" in the sense that they are give a unique name "var$modnum" and the Temporary Attribute. Since you gave your x a DownValue, it must be cleared before x can be garbage collected. Your y was set to be the temporary variable x$... and the output was assigned to Out[]. So you also need to clear the history: Unprotect[In, Out]; Clear[In, Out]; Protect[In, Out];. Then your Module example seems to be properly garbage collected. When using your MathOO package (that I downloaded yesterday, but haven't played with yet) maybe you can just set the $HistoryLength to some finite number. And recommend that users suppress the output of instantiations object1 = new[Object1][]; A: Mathematica is a string rewriting system (at the bottom) (sort of) (not really) (but really) (ANYWAY...) The DownValue "x$117[1] = 2" is a string rewriting rule that it is not entirely inaccurate to imagine is an entry in an associative array. The array is named "x$117" and the entry is the pair {1,2}. As long as there is an entry in the array, the symbol "x$117" is referenced and will not be GCed by Mma. Your best bet is to Remove[] symbols when they are destructed or go out of scope. (Clear[] is insufficient since lingering attributes, messages, or defaults associated with symbols are not eliminated by Clear[] and so Mma will still hold live references to the symbol.)
Temporary variables in Mathematica
I have written a package for Mathematica called MathOO. In short, it allows you to use object orientation in Mathematica just like you do in Python. Please read the following article in Voofie/MathOO for details: MathOO: Adding Python style Object Orientation to Mathematica with MathOO (1.0 beta launch) [Alternative to Objectica] The problem I encountered is that, I would like to have garbage collector, so that user don't have to explicitly deleting the object after using it. For instance: NewClass[Object1] Object1.$init$[self_]:= Return[]; In the above two lines, I just defined Object1 to be a new class, and the constructor to be an empty function. If you are familiar with Python, you should see the similarity with __init__(). To instantiate an Object1, I do: object1 = new[Object1][] The output is: Out: object$13 Here, object$13 is an temporary variable. What I want is, when there are no references to this temporary variable, it should be deleted automatically. But it doesn't work as expected. I have identified the problem to be the following: In: y = Module[{x}, x[1] = 2; x] Out: x$117 In: FullDefinition[y] Out: y = x$117 Attributes[x$117] = {Temporary} x$117[1] = 2 Since y holds a reference of x$117, so x$117 is not removed yet. Now let's delete the reference by setting the value of y to 1: In: y = 1; However, x$117 is still here: In: Definition[x$117] Out: Attributes[x$117] = {Temporary} x$117[1] = 2 But I expected the variable to be removed since it is no longer referenced. From the manual of Mathematica, it said: Temporary symbols are removed if they are no longer referenced: So, is it a bug of Mathematica? Or is there any workaround methods? I am using Mathematica 7.0. Thank you very much.
[ "Mathematica really does garbage collects Temporary variables when they have no more references. That said, there's two reasons that your x$117 is not garbage collected.\n\nRemember that Module uses lexical scoping, so the module variables are only \"local\" in the sense that they are give a unique name \"var$modnu...
[ 2, 1 ]
[]
[]
[ "oop", "python", "wolfram_mathematica" ]
stackoverflow_0004114136_oop_python_wolfram_mathematica.txt
Q: What is a simple way to extract the list of URLs on a webpage using python? I want to create a simple web crawler for fun. I need the web crawler to get a list of all links on one page. Does the python library have any built in functions that would make this any easier? Thanks any knowledge appreciated. A: This is actually very simple with BeautifulSoup. from BeautifulSoup import BeautifulSoup [element['href'] for element in BeautifulSoup(document_contents).findAll('a', href=True)] # [u'http://example.com/', u'/example', ...] One last thing: you can use urlparse.urljoin to make all URLs absolute. If you need the link text, you can use something like element.contents[0]. And here's how you might tie it all together: import urllib2 import urlparse from BeautifulSoup import BeautifulSoup def get_all_link_targets(url): return [urlparse.urljoin(url, tag['href']) for tag in BeautifulSoup(urllib2.urlopen(url)).findAll('a', href=True)] A: There's an article on using HTMLParser to get URLs from <a> tags on a webpage. The code is this: from HTMLParser import HTMLParser from urllib2 import urlopen class Spider(HTMLParser): def __init__(self, url): HTMLParser.__init__(self) req = urlopen(url) self.feed(req.read()) def handle_starttag(self, tag, attrs): if tag == 'a' and attrs: print "Found link => %s" % attrs[0][1] Spider('http://www.python.org') If you ran that script, you'd get output like this: rafe@linux-7o1q:~> python crawler.py Found link => / Found link => #left-hand-navigation Found link => #content-body Found link => /search Found link => /about/ Found link => /news/ Found link => /doc/ Found link => /download/ Found link => /community/ Found link => /psf/ Found link => /dev/ Found link => /about/help/ Found link => http://pypi.python.org/pypi Found link => /download/releases/2.7/ Found link => http://docs.python.org/ Found link => /ftp/python/2.7/python-2.7.msi Found link => /ftp/python/2.7/Python-2.7.tar.bz2 Found link => /download/releases/3.1.2/ Found link => http://docs.python.org/3.1/ Found link => /ftp/python/3.1.2/python-3.1.2.msi Found link => /ftp/python/3.1.2/Python-3.1.2.tar.bz2 Found link => /community/jobs/ Found link => /community/merchandise/ Found link => margin-top:1.5em Found link => margin-top:1.5em Found link => margin-top:1.5em Found link => color:#D58228; margin-top:1.5em Found link => /psf/donations/ Found link => http://wiki.python.org/moin/Languages Found link => http://wiki.python.org/moin/Languages Found link => http://www.google.com/calendar/ical/b6v58qvojllt0i6ql654r1vh00%40group.calendar.google.com/public/basic.ics Found link => http://wiki.python.org/moin/Python2orPython3 Found link => http://pypi.python.org/pypi Found link => /3kpoll Found link => /about/success/usa/ Found link => reference Found link => reference Found link => reference Found link => reference Found link => reference Found link => reference Found link => /about/quotes Found link => http://wiki.python.org/moin/WebProgramming Found link => http://wiki.python.org/moin/CgiScripts Found link => http://www.zope.org/ Found link => http://www.djangoproject.com/ Found link => http://www.turbogears.org/ Found link => http://wiki.python.org/moin/PythonXml Found link => http://wiki.python.org/moin/DatabaseProgramming/ Found link => http://www.egenix.com/files/python/mxODBC.html Found link => http://sourceforge.net/projects/mysql-python Found link => http://wiki.python.org/moin/GuiProgramming Found link => http://wiki.python.org/moin/WxPython Found link => http://wiki.python.org/moin/TkInter Found link => http://wiki.python.org/moin/PyGtk Found link => http://wiki.python.org/moin/PyQt Found link => http://wiki.python.org/moin/NumericAndScientific Found link => http://www.pasteur.fr/recherche/unites/sis/formation/python/index.html Found link => http://www.pentangle.net/python/handbook/ Found link => /community/sigs/current/edu-sig Found link => http://www.openbookproject.net/pybiblio/ Found link => http://osl.iu.edu/~lums/swc/ Found link => /about/apps Found link => http://docs.python.org/howto/sockets.html Found link => http://twistedmatrix.com/trac/ Found link => /about/apps Found link => http://buildbot.net/trac Found link => http://www.edgewall.com/trac/ Found link => http://roundup.sourceforge.net/ Found link => http://wiki.python.org/moin/IntegratedDevelopmentEnvironments Found link => /about/apps Found link => http://www.pygame.org/news.html Found link => http://www.alobbs.com/pykyra Found link => http://www.vrplumber.com/py3d.py Found link => /about/apps Found link => reference external Found link => reference external Found link => reference external Found link => reference external Found link => reference external Found link => reference external Found link => reference external Found link => reference external Found link => reference external Found link => reference external Found link => reference external Found link => reference external Found link => reference external Found link => /channews.rdf Found link => /about/website Found link => http://www.xs4all.com/ Found link => http://www.timparkin.co.uk/ Found link => /psf/ Found link => /about/legal You can use regex then to distinguish between absolute and relative URLs. A: Solution done using libxml. import urllib import libxml2 parse_opts = libxml2.HTML_PARSE_RECOVER + \ libxml2.HTML_PARSE_NOERROR + \ libxml2.HTML_PARSE_NOWARNING doc = libxml2.htmlReadDoc(urllib.urlopen(url).read(), '', None, parse_opts) print [ i.getContent() for i in doc.xpathNewContext().xpathEval("//a/@href") ]
What is a simple way to extract the list of URLs on a webpage using python?
I want to create a simple web crawler for fun. I need the web crawler to get a list of all links on one page. Does the python library have any built in functions that would make this any easier? Thanks any knowledge appreciated.
[ "This is actually very simple with BeautifulSoup.\nfrom BeautifulSoup import BeautifulSoup\n\n[element['href'] for element in BeautifulSoup(document_contents).findAll('a', href=True)]\n\n# [u'http://example.com/', u'/example', ...]\n\nOne last thing: you can use urlparse.urljoin to make all URLs absolute. If you ne...
[ 7, 0, 0 ]
[]
[]
[ "python", "web_applications" ]
stackoverflow_0004139989_python_web_applications.txt
Q: Python API for Amazon EC2 that supports files The command line tool ec2-run-instances takes a -f parameter to pass a file to the instance at run time. Are there any Python APIs for EC2 that do the equivalent? I'm looking to customize a Wowza Media Server, which requires passing in a file when booting up a new image. A: You can either use boto. Then you can possibly code a small script to open a file first and read it's contents and pass it as user-data. Or try http://github.com/fschulze/mr.awsome
Python API for Amazon EC2 that supports files
The command line tool ec2-run-instances takes a -f parameter to pass a file to the instance at run time. Are there any Python APIs for EC2 that do the equivalent? I'm looking to customize a Wowza Media Server, which requires passing in a file when booting up a new image.
[ "You can either use boto. Then you can possibly code a small script to open a file first and read it's contents and pass it as user-data. \nOr try http://github.com/fschulze/mr.awsome\n" ]
[ 1 ]
[]
[]
[ "amazon_ec2", "api", "python" ]
stackoverflow_0004140640_amazon_ec2_api_python.txt
Q: json.dumps throws UnicodeDecodeError I had unknown encoding in a MS ACCESS data table because the text inputs originated by people copying and pasting from Word documents. So when I attempted: final_data_to_write = json.dumps(list_of_text_lines) The error output was: "UnicodeDecodeError: 'utf8' codec can't decode byte 0xe1 in position 5: unexpected end of data" A: You need to find out what character encoding is used in your database. Then you need to tell JSON encoder to use that encoding to properly interpret strings. final_data_to_write = json.dumps(myDict, encoding="XXX") Default encoding assumed by json module is UTF-8. A: The conversion from Access to Excel should have preserved your data as Unicode. If all the Unicode text is encodable in your "ANSI code page" (probably cp1252, but don't guess), then you won't have mangled anything by doing Excel "save-as-CSV" --- if not, you'd get ? characters replacing the non-encodable characters. These wouldn't cause your current problem. Things to do: (1) Find out what is your "ANSI code page": On my machine: command_prompt>\python27\python -c"import locale;print locale.setlocale(locale.LC_ALL,'')" English_Australia.1252 So mine is cp1252. (2) Try json.dumps(myDict, encoding='cpXXXX') (3) If that fails, you need to look at your data and your CSV-to-JSON code to see if you are mangling something somewhere. Insert some debugging code to output the line numbers of any lines that contain any non-ASCII characters -- the test for that is any(c >= '\x80' for c in line) -- and look at those lines in a text editor and check if they make sense in your environment. A: Loop over the text lines and encode each one as follows: row1 = unicode( list_of_text_line[j] , errors='ignore')
json.dumps throws UnicodeDecodeError
I had unknown encoding in a MS ACCESS data table because the text inputs originated by people copying and pasting from Word documents. So when I attempted: final_data_to_write = json.dumps(list_of_text_lines) The error output was: "UnicodeDecodeError: 'utf8' codec can't decode byte 0xe1 in position 5: unexpected end of data"
[ "You need to find out what character encoding is used in your database. Then you need to tell JSON encoder to use that encoding to properly interpret strings.\nfinal_data_to_write = json.dumps(myDict, encoding=\"XXX\")\n\nDefault encoding assumed by json module is UTF-8.\n", "The conversion from Access to Excel s...
[ 3, 2, 2 ]
[]
[]
[ "json", "python" ]
stackoverflow_0004140869_json_python.txt
Q: Pylons config has a different content in websetup.py In my pylons application I want to add some data on setup. ( a user) To secure passwords in the database i've hashed the passwords with a salt, this salt is stored in the configuration file. If I want to get the saltkey from configuration I do this (shortened example): from pylons import config saltkey = config.get("saltkey") If this code is placed in for example a model, it returns the saltkey. In the User-model this code is used to create a hash with the salt. However if I want to create an instance of this model in "websetup.py" the config has a different contents and it cannot retrieve the saltkey (resulting in an error) def setup_app(command, conf, vars): load_environment(conf.global_conf, conf.local_conf) Base.metadata.create_all(bind=Session.bind) user = User('admin', 'password123', 'test@test.com') Session.add(user) Session.commit() My question is: Why has the config a different content? And how do I fix this problem without an ugly hack? A: You can access your config file in this step. The from pylons import config method is best suited to doing so in the context of a WSGI request. However, you're not dealing with a WSGI request, so it's unavailable. Fortunately, you have a very easy way of accessing config during websetup.py's operation. The setup_app() function already consumes the config file, and Paster has already parsed it and turned it into a dictionary for you. You can access your config file as the conf.local_conf dictionary, and that will make the data you want available. With all of that said - you should not store the salt in your config.ini file, that's a bad idea and you should avoid wheel-reinvention like that.
Pylons config has a different content in websetup.py
In my pylons application I want to add some data on setup. ( a user) To secure passwords in the database i've hashed the passwords with a salt, this salt is stored in the configuration file. If I want to get the saltkey from configuration I do this (shortened example): from pylons import config saltkey = config.get("saltkey") If this code is placed in for example a model, it returns the saltkey. In the User-model this code is used to create a hash with the salt. However if I want to create an instance of this model in "websetup.py" the config has a different contents and it cannot retrieve the saltkey (resulting in an error) def setup_app(command, conf, vars): load_environment(conf.global_conf, conf.local_conf) Base.metadata.create_all(bind=Session.bind) user = User('admin', 'password123', 'test@test.com') Session.add(user) Session.commit() My question is: Why has the config a different content? And how do I fix this problem without an ugly hack?
[ "You can access your config file in this step. The from pylons import config method is best suited to doing so in the context of a WSGI request. However, you're not dealing with a WSGI request, so it's unavailable. Fortunately, you have a very easy way of accessing config during websetup.py's operation. The set...
[ 0 ]
[]
[]
[ "pylons", "python", "sqlalchemy" ]
stackoverflow_0004126000_pylons_python_sqlalchemy.txt
Q: Java setRequestHeader in Python What is the equivalent of this java statement in python? post.setRequestHeader("Cookie", jSessionID); I'm very confused as to whether this is really a cookie or just POST data with a key of 'Cookie' I have urllib2 and cookielib imported, and am confused. I'm also trying to send a file along with the url request, but that is another topic. A: Try something like this: sock = httplib.HTTPConnection('server.com', 80) data = "op=a_login_attempt" headers = { "Host":"server.com", "Content-Type":"application/x-www-form-urlencoded; charset=UTF=8", "Referer":"server2.com", "Cookie":"session=12345678",} sock.request("POST", '/login.php', data, headers) As you can see "Cookie" is just a key and value in the headers, which get sent along with the data using the request() method. Hope this answers your question. A: I would recommend pycurl
Java setRequestHeader in Python
What is the equivalent of this java statement in python? post.setRequestHeader("Cookie", jSessionID); I'm very confused as to whether this is really a cookie or just POST data with a key of 'Cookie' I have urllib2 and cookielib imported, and am confused. I'm also trying to send a file along with the url request, but that is another topic.
[ "Try something like this:\nsock = httplib.HTTPConnection('server.com', 80)\ndata = \"op=a_login_attempt\"\nheaders = { \"Host\":\"server.com\",\n \"Content-Type\":\"application/x-www-form-urlencoded; charset=UTF=8\",\n \"Referer\":\"server2.com\",\n \"Cookie\":\"session=12345678\",}...
[ 2, 0 ]
[]
[]
[ "http_headers", "java", "python" ]
stackoverflow_0004142253_http_headers_java_python.txt
Q: Why tuple is being used in string format I came across code like print "Users connected: %d" % (userCount, ) I was wondering, is there any reason of not writing them in print "Users connected: %d" % userCount They seem having the same output A: The code without an explicid tuple may bite you if your variable contains a tuple. >>> nums = (1, 2, 3, 4) >>> print "debug: %r" % (nums, ) debug: (1, 2, 3, 4) >>> print "debug: %r" % nums Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: not all arguments converted during string formatting So always using a tuple in format string syntax is a part of defensive coding. A: They end being the exact same thing if you have a single variable for substitution. From the docs: Given format % values (in your case format = "Users connected: %d", and values = userCount) If format requires a single argument, values may be a single non-tuple object Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary) A: in this case yes as only item is passed. If you need to pass multiple items a tuple is needed print 'There are %d user connected %s' % (userCount, 'today') A: Yes they have, but parenthesis is used to group variables in a such condition print "Hi there. I am %s and i am %d years old"%(name, age) So its the basic usage, with one or more variables...
Why tuple is being used in string format
I came across code like print "Users connected: %d" % (userCount, ) I was wondering, is there any reason of not writing them in print "Users connected: %d" % userCount They seem having the same output
[ "The code without an explicid tuple may bite you if your variable contains a tuple.\n>>> nums = (1, 2, 3, 4)\n>>> print \"debug: %r\" % (nums, )\ndebug: (1, 2, 3, 4)\n>>> print \"debug: %r\" % nums\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: not all arguments converted d...
[ 14, 0, 0, 0 ]
[ "They have the same output but the code looks different. Every software developer has developed a \"style\" over the years based on the kind of errors they make. If you tend to forget the comma in a single-element tuple or if you write code for different versions of Python or you just want to make your life easier ...
[ -1 ]
[ "python", "syntax" ]
stackoverflow_0004142243_python_syntax.txt
Q: Handling multiple end-users using threading in python I have an upload page in django powered site. The end-users upload the documents from that page. The back end processing of that uploaded document can take several minutes. How do i handle multiple end-users' request in the back end? I have thought of using thread for each end-user's request. However, i am finding it difficult in coding that how do i create a new thread as soon as some user uploads a document. A sample example or demo would be highly appreciated. Thanking you in advance!!! A: The other way to start a thread is to give your callable to the Thread constructor, like this: from threading import Thread processing_thread = Thread(target=your_heavy_lifting_function_name) processing_thread.start() A: Without more information its hard to say what exactly, but threads sound like a reasonable idea. To create a thread in python, you do the following: from threading import Thread class Worker(Thread): def __init__(self): Thread.__init__(self) #Runs the thread's constructor #Method that is run when the new thread starts def run(self): #Whatever data processing you have to do can go here while True: print "Hello from Worker" w = Worker() w.start() #Starts a new thread which executes the object's run function
Handling multiple end-users using threading in python
I have an upload page in django powered site. The end-users upload the documents from that page. The back end processing of that uploaded document can take several minutes. How do i handle multiple end-users' request in the back end? I have thought of using thread for each end-user's request. However, i am finding it difficult in coding that how do i create a new thread as soon as some user uploads a document. A sample example or demo would be highly appreciated. Thanking you in advance!!!
[ "The other way to start a thread is to give your callable to the Thread constructor, like this:\nfrom threading import Thread\n\nprocessing_thread = Thread(target=your_heavy_lifting_function_name)\nprocessing_thread.start()\n\n", "Without more information its hard to say what exactly, but threads sound like a rea...
[ 2, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0004142206_multithreading_python.txt
Q: lxml.html search and replace I need your help or suggestion, whatever. I start reading some books about python just because of this problem I have :) But I see it will takes long time for me to learn the whole language. I also skimmed and searched through lxml.html documentation but still I can figure out how to do this what I want. I created two html files for sample, to explain what is my problem. You can see those pieces of code here: http://pzt.me/ltbj There is also a screenshot with differences so that is even easier to see what's going on. If somebody tried to do something like this before or if you have an idea how could I do this please let me know. Thank you. Best, Jozsef OK here is the code: ~~~~~~~~~~~ This: ~~~~~~~~~~~ New Document <body> <h2><a name="2" class="class1">2</a></h2> <a href="#top" class="class2">^ top ^</a> <p><span class="class3">20</span>Sed imperdiet, lacus eu consectetur tempus, tellus metus vestibulum tortor, nec tincidunt nisl enim non tortor. <span class="class3">21</span>Nam in aliquam magna. Maecenas hendrerit fringilla dui facilisis aliquet. Phasellus neque justo, aliquet non pellentesque vel, dictum non libero. Phasellus vel nulla mi, id molestie purus. Suspendisse orci ante, imperdiet at tempus id, pulvinar eu mi. Aliquam erat volutpat. <span class="class3">22</span>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Pellentesque pretium, ligula tristique porta fringilla, mauris lectus gravida nibh, consectetur ornare lacus tellus quis sem. <span class="class3">23</span>Curabitur nibh dui, feugiat sed luctus sed, laoreet sed tortor.</p> <p><span class="class3">24</span>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. <span class="class3">25</span>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</p> <p><span class="class3">26</span>Sed imperdiet, lacus eu consectetur tempus, "tellus metus vestibulum tortor, nec tincidunt nisl enim non tortor."</p> <p><span class="class3">27</span></p> <p>Nunc volutpat lacus;</p> <p>Etiam sit amet dapibus;</p> <p>Nunc consequat mauris.</p> <p><span class="class3">15</span>Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc volutpat lacus a lacus dignissim sed iaculis metus consectetur. <span class="class3">17</span>Nunc consequat mauris nec ligula ullamcorper ut iaculis nibh sodales. "Nulla tincidunt lorem eu odio laoreet facilisis." <span class="class3">18</span>Aliquam erat volutpat. Curabitur sagittis, mauris quis laoreet consectetur, erat urna tincidunt augue, ut eleifend felis mi quis felis. <span class="class3">19</span>Vivamus a elit risus, consequat sagittis ligula. Nunc ut vestibulum ipsum. Curabitur at sapien vitae est egestas aliquam. <span class="class3">20</span> Donec porttitor, ligula vel venenatis posuere, purus nunc adipiscing ante, id pellentesque turpis nulla eu magna. <span class="class3">21</span>Praesent gravida, eros ut scelerisque commodo, magna quam volutpat elit, a aliquet neque ligula a mauris. <span class="class3">22</span>Curabitur nibh dui, feugiat sed luctus sed, laoreet sed tortor. <span class="class3">23</span>Lorem ipsum dolor sit:</p> <p>Pellentesque pretium, ligula tristique</p> <p>felis viverra;</p> <p>justo lobortis ut "l"</p> <p>unc ut consectetur fermentum.</p> <p><span class="class3">14</span>Proin et tellus felis:</p> <p>Suspendisse potenti,</p> <p>enim non tortor</p> <p>Donec porttitor.</p> <p>Morbi eleifend fermentum</p> <p>Aliquam id ante.</p> <p><span class="class3">15</span></p> <p>Curabitur nibh dui, feugiat sed luctus sed, laoreet sed tortor,</p> <p>etiam ullamcorper.</p> <p>vivamus interdum nulla,</p> <p>odio laoreet facilisis.</p> <p><span class="class3">20</span>Suspendisse potenti. Nam in aliquam magna. Maecenas hendrerit fringilla dui facilisis aliquet. <span class="class3">21</span>Suspendisse potenti. Nam in aliquam magna. Maecenas hendrerit fringilla dui facilisis aliquet. </p> </body> ~~~~~~~~~~~~~~~~~~~~~ To become this: ~~~~~~~~~~~~~~~~~~~~~ New Document <body> <h2><a name="2" class="class1">2</a></h2> <a href="#top" class="class2">^ top ^</a> <p><span class="class3">20</span>Sed imperdiet, lacus eu consectetur tempus, tellus metus vestibulum tortor, nec tincidunt nisl enim non tortor. <span class="class3">21</span>Nam in aliquam magna. Maecenas hendrerit fringilla dui facilisis aliquet. Phasellus neque justo, aliquet non pellentesque vel, dictum non libero. Phasellus vel nulla mi, id molestie purus. Suspendisse orci ante, imperdiet at tempus id, pulvinar eu mi. Aliquam erat volutpat. <span class="class3">22</span>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Pellentesque pretium, ligula tristique porta fringilla, mauris lectus gravida nibh, consectetur ornare lacus tellus quis sem. <span class="class3">23</span>Curabitur nibh dui, feugiat sed luctus sed, laoreet sed tortor.</p> <p><span class="class3">24</span>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. <span class="class3">25</span>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</p> <p><span class="class3">26</span>Sed imperdiet, lacus eu consectetur tempus, "tellus metus vestibulum tortor, nec tincidunt nisl enim non tortor."</p> <p><span class="class3">27</span><br /> Nunc volutpat lacus;<br /> Etiam sit amet dapibus;<br /> Nunc consequat mauris.</p> <p><span class="class3">15</span>Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc volutpat lacus a lacus dignissim sed iaculis metus consectetur. <span class="class3">17</span>Nunc consequat mauris nec ligula ullamcorper ut iaculis nibh sodales. "Nulla tincidunt lorem eu odio laoreet facilisis." <span class="class3">18</span>Aliquam erat volutpat. Curabitur sagittis, mauris quis laoreet consectetur, erat urna tincidunt augue, ut eleifend felis mi quis felis. <span class="class3">19</span>Vivamus a elit risus, consequat sagittis ligula. Nunc ut vestibulum ipsum. Curabitur at sapien vitae est egestas aliquam. <span class="class3">20</span> Donec porttitor, ligula vel venenatis posuere, purus nunc adipiscing ante, id pellentesque turpis nulla eu magna. <span class="class3">21</span>Praesent gravida, eros ut scelerisque commodo, magna quam volutpat elit, a aliquet neque ligula a mauris. <span class="class3">22</span>Curabitur nibh dui, feugiat sed luctus sed, laoreet sed tortor. <span class="class3">23</span>Lorem ipsum dolor sit:<br /> Pellentesque pretium, ligula tristique<br /> felis viverra;<br /> justo lobortis ut "l"<br /> unc ut consectetur fermentum.</p> <p><span class="class3">14</span>Proin et tellus felis:<br /> Suspendisse potenti,<br /> enim non tortor<br /> Donec porttitor.<br /> Morbi eleifend fermentum<br /> Aliquam id ante.</p> <p><span class="class3">15</span><br /> Curabitur nibh dui, feugiat sed luctus sed, laoreet sed tortor,<br /> etiam ullamcorper.<br /> vivamus interdum nulla,<br /> odio laoreet facilisis.</p> <p><span class="class3">20</span>Suspendisse potenti. Nam in aliquam magna. Maecenas hendrerit fringilla dui facilisis aliquet. <span class="class3">21</span>Suspendisse potenti. Nam in aliquam magna. Maecenas hendrerit fringilla dui facilisis aliquet. </p> </body> Can't include the image. sorry. you must to see the link on top if you want to see the image. Thanks. A: Use BeautifulSoup to parse the document and recreate it after processing it. It is the easiest thing to do. I wouldn't use lxml for what you are trying to do. http://www.crummy.com/software/BeautifulSoup/documentation.html Look at example here on how tags are added and removed: Extract all <script> tags in an HTML page and append to the bottom of the document https://stackoverflow.com/questions/tagged/beautifulsoup A: If you're really that short on time you may be able to accomplish your task after reading chapter 8 of Dive Into Python ( http://diveintopython.net/html_processing/index.html ). Alas, I strongly suggest that you start from the very beginning of the book. Regular expressions (chapter 7 same book) may also be of great help. I have not quite understood what you're trying to accomplish though. Replace <p></p> tags with <br/>? Anyway look into smgllib and re modules.
lxml.html search and replace
I need your help or suggestion, whatever. I start reading some books about python just because of this problem I have :) But I see it will takes long time for me to learn the whole language. I also skimmed and searched through lxml.html documentation but still I can figure out how to do this what I want. I created two html files for sample, to explain what is my problem. You can see those pieces of code here: http://pzt.me/ltbj There is also a screenshot with differences so that is even easier to see what's going on. If somebody tried to do something like this before or if you have an idea how could I do this please let me know. Thank you. Best, Jozsef OK here is the code: ~~~~~~~~~~~ This: ~~~~~~~~~~~ New Document <body> <h2><a name="2" class="class1">2</a></h2> <a href="#top" class="class2">^ top ^</a> <p><span class="class3">20</span>Sed imperdiet, lacus eu consectetur tempus, tellus metus vestibulum tortor, nec tincidunt nisl enim non tortor. <span class="class3">21</span>Nam in aliquam magna. Maecenas hendrerit fringilla dui facilisis aliquet. Phasellus neque justo, aliquet non pellentesque vel, dictum non libero. Phasellus vel nulla mi, id molestie purus. Suspendisse orci ante, imperdiet at tempus id, pulvinar eu mi. Aliquam erat volutpat. <span class="class3">22</span>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Pellentesque pretium, ligula tristique porta fringilla, mauris lectus gravida nibh, consectetur ornare lacus tellus quis sem. <span class="class3">23</span>Curabitur nibh dui, feugiat sed luctus sed, laoreet sed tortor.</p> <p><span class="class3">24</span>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. <span class="class3">25</span>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</p> <p><span class="class3">26</span>Sed imperdiet, lacus eu consectetur tempus, "tellus metus vestibulum tortor, nec tincidunt nisl enim non tortor."</p> <p><span class="class3">27</span></p> <p>Nunc volutpat lacus;</p> <p>Etiam sit amet dapibus;</p> <p>Nunc consequat mauris.</p> <p><span class="class3">15</span>Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc volutpat lacus a lacus dignissim sed iaculis metus consectetur. <span class="class3">17</span>Nunc consequat mauris nec ligula ullamcorper ut iaculis nibh sodales. "Nulla tincidunt lorem eu odio laoreet facilisis." <span class="class3">18</span>Aliquam erat volutpat. Curabitur sagittis, mauris quis laoreet consectetur, erat urna tincidunt augue, ut eleifend felis mi quis felis. <span class="class3">19</span>Vivamus a elit risus, consequat sagittis ligula. Nunc ut vestibulum ipsum. Curabitur at sapien vitae est egestas aliquam. <span class="class3">20</span> Donec porttitor, ligula vel venenatis posuere, purus nunc adipiscing ante, id pellentesque turpis nulla eu magna. <span class="class3">21</span>Praesent gravida, eros ut scelerisque commodo, magna quam volutpat elit, a aliquet neque ligula a mauris. <span class="class3">22</span>Curabitur nibh dui, feugiat sed luctus sed, laoreet sed tortor. <span class="class3">23</span>Lorem ipsum dolor sit:</p> <p>Pellentesque pretium, ligula tristique</p> <p>felis viverra;</p> <p>justo lobortis ut "l"</p> <p>unc ut consectetur fermentum.</p> <p><span class="class3">14</span>Proin et tellus felis:</p> <p>Suspendisse potenti,</p> <p>enim non tortor</p> <p>Donec porttitor.</p> <p>Morbi eleifend fermentum</p> <p>Aliquam id ante.</p> <p><span class="class3">15</span></p> <p>Curabitur nibh dui, feugiat sed luctus sed, laoreet sed tortor,</p> <p>etiam ullamcorper.</p> <p>vivamus interdum nulla,</p> <p>odio laoreet facilisis.</p> <p><span class="class3">20</span>Suspendisse potenti. Nam in aliquam magna. Maecenas hendrerit fringilla dui facilisis aliquet. <span class="class3">21</span>Suspendisse potenti. Nam in aliquam magna. Maecenas hendrerit fringilla dui facilisis aliquet. </p> </body> ~~~~~~~~~~~~~~~~~~~~~ To become this: ~~~~~~~~~~~~~~~~~~~~~ New Document <body> <h2><a name="2" class="class1">2</a></h2> <a href="#top" class="class2">^ top ^</a> <p><span class="class3">20</span>Sed imperdiet, lacus eu consectetur tempus, tellus metus vestibulum tortor, nec tincidunt nisl enim non tortor. <span class="class3">21</span>Nam in aliquam magna. Maecenas hendrerit fringilla dui facilisis aliquet. Phasellus neque justo, aliquet non pellentesque vel, dictum non libero. Phasellus vel nulla mi, id molestie purus. Suspendisse orci ante, imperdiet at tempus id, pulvinar eu mi. Aliquam erat volutpat. <span class="class3">22</span>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Pellentesque pretium, ligula tristique porta fringilla, mauris lectus gravida nibh, consectetur ornare lacus tellus quis sem. <span class="class3">23</span>Curabitur nibh dui, feugiat sed luctus sed, laoreet sed tortor.</p> <p><span class="class3">24</span>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. <span class="class3">25</span>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</p> <p><span class="class3">26</span>Sed imperdiet, lacus eu consectetur tempus, "tellus metus vestibulum tortor, nec tincidunt nisl enim non tortor."</p> <p><span class="class3">27</span><br /> Nunc volutpat lacus;<br /> Etiam sit amet dapibus;<br /> Nunc consequat mauris.</p> <p><span class="class3">15</span>Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc volutpat lacus a lacus dignissim sed iaculis metus consectetur. <span class="class3">17</span>Nunc consequat mauris nec ligula ullamcorper ut iaculis nibh sodales. "Nulla tincidunt lorem eu odio laoreet facilisis." <span class="class3">18</span>Aliquam erat volutpat. Curabitur sagittis, mauris quis laoreet consectetur, erat urna tincidunt augue, ut eleifend felis mi quis felis. <span class="class3">19</span>Vivamus a elit risus, consequat sagittis ligula. Nunc ut vestibulum ipsum. Curabitur at sapien vitae est egestas aliquam. <span class="class3">20</span> Donec porttitor, ligula vel venenatis posuere, purus nunc adipiscing ante, id pellentesque turpis nulla eu magna. <span class="class3">21</span>Praesent gravida, eros ut scelerisque commodo, magna quam volutpat elit, a aliquet neque ligula a mauris. <span class="class3">22</span>Curabitur nibh dui, feugiat sed luctus sed, laoreet sed tortor. <span class="class3">23</span>Lorem ipsum dolor sit:<br /> Pellentesque pretium, ligula tristique<br /> felis viverra;<br /> justo lobortis ut "l"<br /> unc ut consectetur fermentum.</p> <p><span class="class3">14</span>Proin et tellus felis:<br /> Suspendisse potenti,<br /> enim non tortor<br /> Donec porttitor.<br /> Morbi eleifend fermentum<br /> Aliquam id ante.</p> <p><span class="class3">15</span><br /> Curabitur nibh dui, feugiat sed luctus sed, laoreet sed tortor,<br /> etiam ullamcorper.<br /> vivamus interdum nulla,<br /> odio laoreet facilisis.</p> <p><span class="class3">20</span>Suspendisse potenti. Nam in aliquam magna. Maecenas hendrerit fringilla dui facilisis aliquet. <span class="class3">21</span>Suspendisse potenti. Nam in aliquam magna. Maecenas hendrerit fringilla dui facilisis aliquet. </p> </body> Can't include the image. sorry. you must to see the link on top if you want to see the image. Thanks.
[ "Use BeautifulSoup to parse the document and recreate it after processing it. It is the easiest thing to do. I wouldn't use lxml for what you are trying to do.\n\nhttp://www.crummy.com/software/BeautifulSoup/documentation.html\n\nLook at example here on how tags are added and removed:\n\nExtract all <script> tags i...
[ 2, 1 ]
[]
[]
[ "html", "lxml", "python" ]
stackoverflow_0004141764_html_lxml_python.txt
Q: pyparsing, forward, and recursion I'm using pyparsing to parse vcd (value change dump) files. Essentially, I want to read in the files, parse it into an internal dictionary, and manipulate the values. Without going into details on the structure, my problem occurs with identifying nested categories. In vcd files, you have 'scopes' which include wires and possibly some deeper (nested) scopes. Think of them like levels. So in my file, I have: $scope module toplevel $end $scope module midlevel $end $var wire a $end $var wire b $end $upscope $end $var wire c $end $var wire d $end $var wire e $end $scope module extralevel $end $var wire f $end $var wire g $end $upscope $end $var wire h $end $var wire i $end $upscope $end So 'toplevel' encompasses everything (a - i), 'midlevel' has (a - b), 'extralevel' has (f - g), etc. Here is my code (snippet) for parsing this section: scope_header = Group(Literal('$scope') + Word(alphas) + Word(alphas) + \ Literal('$end')) wire_map = Group(Literal('$var') + Literal('wire') + Word(alphas) + \ Literal('$end')) scope_footer = Group(Literal('$upscope') + Literal('$end')) scope = Forward() scope << (scope_header + ZeroOrMore(wire_map) + ZeroOrMore(scope) + \ ZeroOrMore(wire_map) + scope_footer) Now, what I thought happens is that as it hits each scope, it would keep track of each 'level' and I would end up with a structure containing nested scopes. However, it errors out on $scope module extralevel $end saying it expects '$upscope'. So I know I'm not using the recursion correctly. Can someone help me out? Let me know if I need to provide more info. Thanks!!!! A: According to your definition, a scope cannot contain another scope, followed by some maps, followed by another scope. If the parser has a debug mode where it prints its parse tree, you will be able to see this immediately. But in short, you're saying there are zero or more maps, followed by zero or more scopes, followed by zero or more maps, so if there is a scope, followed by a map, you have already passed the scope field, so any more scopes are invalid. If the language used by pyparsing supports "or" you could use: scope << (scope_header + ZeroOrMore((wire_map | scope)) + scope_footer) A: Please choose @ZackBloom's answer as the correct one, he intuited it right off, without even knowing pyparsing's syntax. Just a few comments/suggestions on your grammar: With the answer posted above, you can visualize the nesting using pprint and pyparsing's asList() method on ParseResults: res = scope.parseString(vcd) from pprint import pprint pprint(res.asList()) Giving: [[['$scope', 'module', 'toplevel', '$end'], [['$scope', 'module', 'midlevel', '$end'], ['$var', 'wire', 'a', '$end'], ['$var', 'wire', 'b', '$end'], ['$upscope', '$end']], ['$var', 'wire', 'c', '$end'], ['$var', 'wire', 'd', '$end'], ['$var', 'wire', 'e', '$end'], [['$scope', 'module', 'extralevel', '$end'], ['$var', 'wire', 'f', '$end'], ['$var', 'wire', 'g', '$end'], ['$upscope', '$end']], ['$var', 'wire', 'h', '$end'], ['$var', 'wire', 'i', '$end'], ['$upscope', '$end']]] So now you have nicely structured results. But you can clean things up a bit. For one thing, now that you have structure, you don't really need all those $scope, $end, etc. tokens. You can certainly just step over them as you navigate through the parsed results, but you can also have pyparsing just drop them from the parsed output (since the results are now structured, you're not really losing anything). Change you parser definitions to: SCOPE, VAR, UPSCOPE, END = map(Suppress, "$scope $var $upscope $end".split()) MODULE, WIRE = map(Literal, "module wire".split()) scope_header = Group(SCOPE + MODULE + Word(alphas) + END) wire_map = Group(VAR + WIRE + Word(alphas) + END) scope_footer = (UPSCOPE + END) (No need to group scope_footer - everything in that expression is suppressed, so Group would just give you an empty list.) And now you can see more clearly the really important bits: [[['module', 'toplevel'], [['module', 'midlevel'], ['wire', 'a'], ['wire', 'b']], ['wire', 'c'], ['wire', 'd'], ['wire', 'e'], [['module', 'extralevel'], ['wire', 'f'], ['wire', 'g']], ['wire', 'h'], ['wire', 'i']]] At the risk of too much grouping, I would suggest also Grouping the content of your scope expression, like this: scope << Group(scope_header + Group(ZeroOrMore((wire_map | scope))) + scope_footer) which gives these results: [[['module', 'toplevel'], [[['module', 'midlevel'], [['wire', 'a'], ['wire', 'b']]], ['wire', 'c'], ['wire', 'd'], ['wire', 'e'], [['module', 'extralevel'], [['wire', 'f'], ['wire', 'g']]], ['wire', 'h'], ['wire', 'i']]]] Now every scope result has 2 predictable elements: the module header, and a list of wires or subscopes. This predictability will make it a lot easier to write the recursive code that will navigate the results: res = scope.parseString(vcd) def dumpScope(parsedTokens, indent=''): module,contents = parsedTokens print indent + '- ' + module[1] for item in contents: if item[0]=='wire': print indent + ' wire: ' + item[1] else: dumpScope(item, indent+' ') dumpScope(res[0]) which comes out looking like: - toplevel - midlevel wire: a wire: b wire: c wire: d wire: e - extralevel wire: f wire: g wire: h wire: i Good first question, welcome to SO and pyparsing!
pyparsing, forward, and recursion
I'm using pyparsing to parse vcd (value change dump) files. Essentially, I want to read in the files, parse it into an internal dictionary, and manipulate the values. Without going into details on the structure, my problem occurs with identifying nested categories. In vcd files, you have 'scopes' which include wires and possibly some deeper (nested) scopes. Think of them like levels. So in my file, I have: $scope module toplevel $end $scope module midlevel $end $var wire a $end $var wire b $end $upscope $end $var wire c $end $var wire d $end $var wire e $end $scope module extralevel $end $var wire f $end $var wire g $end $upscope $end $var wire h $end $var wire i $end $upscope $end So 'toplevel' encompasses everything (a - i), 'midlevel' has (a - b), 'extralevel' has (f - g), etc. Here is my code (snippet) for parsing this section: scope_header = Group(Literal('$scope') + Word(alphas) + Word(alphas) + \ Literal('$end')) wire_map = Group(Literal('$var') + Literal('wire') + Word(alphas) + \ Literal('$end')) scope_footer = Group(Literal('$upscope') + Literal('$end')) scope = Forward() scope << (scope_header + ZeroOrMore(wire_map) + ZeroOrMore(scope) + \ ZeroOrMore(wire_map) + scope_footer) Now, what I thought happens is that as it hits each scope, it would keep track of each 'level' and I would end up with a structure containing nested scopes. However, it errors out on $scope module extralevel $end saying it expects '$upscope'. So I know I'm not using the recursion correctly. Can someone help me out? Let me know if I need to provide more info. Thanks!!!!
[ "According to your definition, a scope cannot contain another scope, followed by some maps, followed by another scope.\nIf the parser has a debug mode where it prints its parse tree, you will be able to see this immediately. But in short, you're saying there are zero or more maps, followed by zero or more scopes, ...
[ 9, 6 ]
[]
[]
[ "forward", "pyparsing", "python", "recursion" ]
stackoverflow_0004140884_forward_pyparsing_python_recursion.txt
Q: Using Python's PIL, how do I enhance the contrast/saturation of an image? Just a simple contrast and saturation enhancement. Nothing fancy. A: Since PIL is dead for the most part. Install the Pillow fork instead, sudo pip install pillow, and use its ImageEnhance module http://pillow.readthedocs.org/en/3.0.x/reference/ImageEnhance.html >>> from PIL import Image, ImageEnhance >>> image = Image.open('downloads/jcfeb2011.jpg') >>> contrast = ImageEnhance.Contrast(image) >>> image.show() >>> contrast.enhance(2).show()
Using Python's PIL, how do I enhance the contrast/saturation of an image?
Just a simple contrast and saturation enhancement. Nothing fancy.
[ "Since PIL is dead for the most part. Install the Pillow fork instead, sudo pip install pillow, and use its ImageEnhance module http://pillow.readthedocs.org/en/3.0.x/reference/ImageEnhance.html\n>>> from PIL import Image, ImageEnhance\n>>> image = Image.open('downloads/jcfeb2011.jpg')\n>>> contrast = ImageEnhance....
[ 28 ]
[]
[]
[ "algorithm", "image", "python", "python_imaging_library" ]
stackoverflow_0004142687_algorithm_image_python_python_imaging_library.txt
Q: Python class changer I need class runtime class declaration from database. Some class need override field and redeclaration. models.py class Staff(object): name = StringField( verbose_name = "Full name") age = IntegerField( verbose_name = "Age") utils.py def class_changer(class_path, field_key, new_Field): pass ?????? >>> class_changer("models.Staff", "gender", BooleanField()) # Add new field to Staff >>> class_changer("models.Country", "name", StringField()) # Add new class with name field >>> class_changer("models.Staff", "country", ForeignKey("Country")) # Add new field to Staff result is class Staff(object): name = StringField( verbose_name = "Full name") age = IntegerField( verbose_name = "Age") gender = BooleanField() country = ForeignKey("Country") class Country(object): name = StringField() How to implement class_changer? A: you need better architecture for this, but as a starting solution you may try this, In [12]: class a1(object): ...: pass In [13]: def class_changer(cls_path, attr, val): ....: try: ....: obj = eval(cls_path) ....: setattr(obj, attr, val) ....: except: ....: raise ....: In [14]: def getGender(self): ...: return True In [15]: class_changer('a1','getGender', getGender) In [16]: a1().getGender() Out[16]: True A: First adding new attributes to a class: >>> class_changer("models.Staff", "gender", BooleanField()) # Add new field to Staff >>> class_changer("models.Staff", "country", ForeignKey("Country")) # Add new field to Staff For these two, just go ahead and set Staff directly: models.Staff.gender = BooleanField() models.Staff.country = ForeignKey("Country") Or to make it generic: def add_to_class(cls, name, attr): setattr(cls, name, attr) add_to_class(models.Staff, "gender", BooleanField()) add_to_class(models.Staff, "country", ForeignKey("Country")) Second, creating a new class: >>> class_changer("models.Country", "name", StringField()) # Add new class with name field You can create a class in a function and then assign it to a module: def new_class(mod, name): class New(object): pass setattr(mod, name, New) new_class(test, "Country") add_to_class(test, "Country", StringField()) I'm not sure you'd want to combine new_class and add_to_class, but I suppose you could do: def create_if_needed_and_add_to_class(mod, clsname, attrname, value): if clsname not in dir(mod): new_class(mod, clsname) add_to_class(mod, attrname, value) and then finally for your class_changer: def class_changer(mod_clsname_string, attrname, value): modname, clsname = '.'.split(mod_clsname_string) create_if_needed_and_add_to_class(globals()[modname], clsname, attrname, value) Edit: fixed class_changer to use locals() for module name lookup, since it is a string and not a module. Edit: oops, it should be globals().
Python class changer
I need class runtime class declaration from database. Some class need override field and redeclaration. models.py class Staff(object): name = StringField( verbose_name = "Full name") age = IntegerField( verbose_name = "Age") utils.py def class_changer(class_path, field_key, new_Field): pass ?????? >>> class_changer("models.Staff", "gender", BooleanField()) # Add new field to Staff >>> class_changer("models.Country", "name", StringField()) # Add new class with name field >>> class_changer("models.Staff", "country", ForeignKey("Country")) # Add new field to Staff result is class Staff(object): name = StringField( verbose_name = "Full name") age = IntegerField( verbose_name = "Age") gender = BooleanField() country = ForeignKey("Country") class Country(object): name = StringField() How to implement class_changer?
[ "you need better architecture for this, but as a starting solution you may try this,\nIn [12]: class a1(object):\n ...: pass\n\nIn [13]: def class_changer(cls_path, attr, val):\n ....: try:\n ....: obj = eval(cls_path)\n ....: setattr(obj, attr, val)\n ....: except:\n ....: ...
[ 4, 1 ]
[]
[]
[ "architecture", "coding_style", "metaprogramming", "python" ]
stackoverflow_0004142681_architecture_coding_style_metaprogramming_python.txt
Q: Python properties also as class properties I have a set of classes which can contain an optional name attribute. The reason is that the classes will get a default name if the attribute is set, but individual classes can still have a custom name if needed. What I want is to be able to get the name attribute from both the class (without any class instance) and from instances of a class. class NameMixin(object): def _get_name(self): if getattr(self, '_name', ''): return self._name else: return self.__class__.__name__ def _set_name(self, name): self._name = name name = property(_get_name, _set_name) class A(NameMixin): name = 'Class A' class B(NameMixin): pass Here, the class A customizes the name, while class B does not. >>> a = A() >>> a.name 'Class A' >>> A.name 'Class A' As seen, this works as it should >>> b = B() >>> b.name 'B' >>> B.name <property object at 0x7fd50a38c578> This does not work as I want! Getting the name from a specific instance works as it should, but attempting to get the name from the class returns a property object. Is it possible to get the name directly from a class without jumping through hoops with the property object (which I really can't check for in the place where I need the class-attribute anyway.) A: class NameMixinMeta(type): def _get_name(self): return getattr(self, '_name', self.__name__) def _set_name(self, name): self._name = name name = property(_get_name, _set_name) class NameMixin(object): __metaclass__ = NameMixinMeta def _get_name(self): return getattr(self, '_name', self.__class__.__name__) def _set_name(self, name): self._name = name name = property(_get_name, _set_name) class A(NameMixin): _name = 'Class A' class B(NameMixin): pass A: I am not sure if your NameMixin class is at work here. In the first case, name is a class property and can be accessed just like you say. >>> class A(): ... name = 'Class A' ... >>> >>> a = A() >>> a.name 'Class A' >>> A.name 'Class A' >>> In the second case the NameMixin class has the effect of returning the property as you suggested.
Python properties also as class properties
I have a set of classes which can contain an optional name attribute. The reason is that the classes will get a default name if the attribute is set, but individual classes can still have a custom name if needed. What I want is to be able to get the name attribute from both the class (without any class instance) and from instances of a class. class NameMixin(object): def _get_name(self): if getattr(self, '_name', ''): return self._name else: return self.__class__.__name__ def _set_name(self, name): self._name = name name = property(_get_name, _set_name) class A(NameMixin): name = 'Class A' class B(NameMixin): pass Here, the class A customizes the name, while class B does not. >>> a = A() >>> a.name 'Class A' >>> A.name 'Class A' As seen, this works as it should >>> b = B() >>> b.name 'B' >>> B.name <property object at 0x7fd50a38c578> This does not work as I want! Getting the name from a specific instance works as it should, but attempting to get the name from the class returns a property object. Is it possible to get the name directly from a class without jumping through hoops with the property object (which I really can't check for in the place where I need the class-attribute anyway.)
[ "class NameMixinMeta(type):\n def _get_name(self):\n return getattr(self, '_name', self.__name__)\n\n def _set_name(self, name):\n self._name = name\n\n name = property(_get_name, _set_name)\n\nclass NameMixin(object):\n __metaclass__ = NameMixinMeta\n def _get_name(self):\n retu...
[ 1, 0 ]
[]
[]
[ "properties", "python" ]
stackoverflow_0004143002_properties_python.txt
Q: Python: split by (different) n spaces I have lines like this: 2 20 164 "guid" Some name^7 0 ip.a.dd.res:port -21630 25000 6 30 139 "guid" Other name^7 0 ip.a.dd.res:port 932 25000 I would like to split this, but the problem is that there is different number of spaces between this "words"... How can I do this? A: Python's split function doesn't care about the number of spaces: >>> ' 2 20 164 "guid" Some name^7 0 ip.a.dd.res:port -21630 25000'.split() ['2', '20', '164', '"guid"', 'Some', 'name^7', '0', 'ip.a.dd.res:port', '-21630', '25000'] A: Have you tried split()? It will "compress" spaces, so after split you will get: '2', '20', '164', '"guid'" etc. A: >>> l = "1 2 4 'ds' 5 66" >>> l "1 2 4 'ds' 5 66" >>> l.split(' ') ['1', '', '', '2', '', '', '4', "'ds'", '5', '', '66'] >>> [x for x in l.split()] ['1', '2', '4', "'ds'", '5', '66'] A: Just use split() function. The delimiter is \s+ that is any kind and any number of space
Python: split by (different) n spaces
I have lines like this: 2 20 164 "guid" Some name^7 0 ip.a.dd.res:port -21630 25000 6 30 139 "guid" Other name^7 0 ip.a.dd.res:port 932 25000 I would like to split this, but the problem is that there is different number of spaces between this "words"... How can I do this?
[ "Python's split function doesn't care about the number of spaces:\n>>> ' 2 20 164 \"guid\" Some name^7 0 ip.a.dd.res:port -21630 25000'.split()\n['2', '20', '164', '\"guid\"', 'Some', 'name^7', '0', 'ip.a.dd.res:port', '-21630', '25000']\n\n", "Have you tried split()? It will \"compress\" space...
[ 7, 1, 0, 0 ]
[]
[]
[ "python", "split" ]
stackoverflow_0004143531_python_split.txt
Q: Emacs on Mac for Python - python-mode keeps using the default Python version how do I change the version of Python that emacs uses in the python-mode to the latest version that I just installed ? I tried setting the PATH in my init.el file to the path where the latest version of python resides but its not working. A: Set the variable python-python-command. This can be done via customize: M-x customize-option RET python-python-command RET Change the value to point to the appropriate binary. A: PATH is only searched when a program is launched via the shell. For programs that are launched directly by Emacs (for example, via call-process), it's the exec-path variable that is searched.
Emacs on Mac for Python - python-mode keeps using the default Python version
how do I change the version of Python that emacs uses in the python-mode to the latest version that I just installed ? I tried setting the PATH in my init.el file to the path where the latest version of python resides but its not working.
[ "Set the variable python-python-command. This can be done via customize:\n\nM-x customize-option RET python-python-command RET\nChange the value to point to the appropriate binary.\n\n", "PATH is only searched when a program is launched via the shell.\nFor programs that are launched directly by Emacs (for example...
[ 1, 0 ]
[]
[]
[ "emacs", "python" ]
stackoverflow_0004140943_emacs_python.txt
Q: Make Python aritmetic operations Possible Duplicate: python limiting floats to two decimal points If I make this: 12.45-12 in Python the answer I get is: 0.44999999999999929 I do I do it to make it: 0.45? BTW I did remember to do: 12.45-12.0 But no result. A: This is a result of the fact that many decimals cannot be exactly represented in binary. For example, 0.25 can: it's 0.01 (0*1, 0*1/2, 1*1/4). 0.1 can't (0.0001100110011...), just like you can't write 1/3 as a complete decimal (0.3333333333...). If you do print(12.45-12) you get 0.45 because print only displays the first significant digits. See the Python docs for an excellent summary. If you do care about decimal values being exact (for example to avoid a Superman III scenario in a financial institution), look at the Decimal module. A: It's perfectly OK, but you need to google (and search around on StackOverflow) for "IEEE 754". EDIT: Take a look e.g. here: Inaccurate Logarithm in Python or here: Another floating point question A: Also in Python 2.4 up, check out the decimal module if you need more accuracy.
Make Python aritmetic operations
Possible Duplicate: python limiting floats to two decimal points If I make this: 12.45-12 in Python the answer I get is: 0.44999999999999929 I do I do it to make it: 0.45? BTW I did remember to do: 12.45-12.0 But no result.
[ "This is a result of the fact that many decimals cannot be exactly represented in binary.\nFor example, 0.25 can: it's 0.01 (0*1, 0*1/2, 1*1/4). 0.1 can't (0.0001100110011...), just like you can't write 1/3 as a complete decimal (0.3333333333...).\nIf you do\nprint(12.45-12)\n\nyou get\n0.45\n\nbecause print only d...
[ 5, 2, 2 ]
[]
[]
[ "floating_point", "python" ]
stackoverflow_0004143709_floating_point_python.txt
Q: Filter the particular dictionary d = {'id': 'ccccc', 'school': [{'s_id': '12', 'city': 'xxx'}, {'s_id': '11', 'city':'yy'}]} I want to filter it using s_id. Suppose if some one want to filter the s_id = 11 it should return {'s_id': '11', 'city':'yy'}. Please answer using the filter keyword. A: Just use python built-in filter function : >>> filter(lambda d:d['s_id']=='11',d['school']) [{'s_id': '11', 'city': 'yy'}] as a bonus, if you want to sort by 's_id' you can do: >>> for school in sorted(d['school'],key=lambda d:d['s_id']): ... print school ... {'s_id': '11', 'city': 'yy'} {'s_id': '12', 'city': 'xxx'} A: >>> s_id=11 >>> [i for i in d['school'] if i['s_id'] == str(s_id)] [{'s_id': '11', 'city': 'yy'}] A: Here is is using filter and partial functions. #!/usr/bin/env python from functools import partial d = {'id': 'ccccc','school': [{'s_id': '12', 'city': 'xxx'}, {'s_id': '11', 'city':'yy'}]} def myfilter(school, s_id): return school['s_id'] == str(s_id) f = partial(myfilter, s_id = 11) print filter(f, d['school'])
Filter the particular dictionary
d = {'id': 'ccccc', 'school': [{'s_id': '12', 'city': 'xxx'}, {'s_id': '11', 'city':'yy'}]} I want to filter it using s_id. Suppose if some one want to filter the s_id = 11 it should return {'s_id': '11', 'city':'yy'}. Please answer using the filter keyword.
[ "Just use python built-in filter function :\n>>> filter(lambda d:d['s_id']=='11',d['school'])\n[{'s_id': '11', 'city': 'yy'}]\n\nas a bonus, if you want to sort by 's_id'\nyou can do:\n>>> for school in sorted(d['school'],key=lambda d:d['s_id']):\n... print school\n... \n{'s_id': '11', 'city': 'yy'}\n{'s_id': '...
[ 2, 0, 0 ]
[]
[]
[ "dictionary", "filter", "python" ]
stackoverflow_0004143705_dictionary_filter_python.txt
Q: Does on-the-fly list creation and return in a function create a memory leak in Python? If I create a list in a python function and return it to the caller, how does garbage collection work on that list? Do I have to do anything to keep a memory leak from occurring? For example: #!/usr/bin/python import random class Example: def f1(self): list = [] len = random.randint(0, 30) for i in range (0, len): list.append(random.randint(0, 65536)) return list random.seed(None) e = Example() while (1): l = e.f1() Will this cause a memory leak? Does the 'list' in f1() have an appropriate reference count at all times? Does the caller of f1() have to do anything to keep a memory leak from occurring? Should the caller do a del() on the list or something? A: There's no memory leak here. The list assigned to l is the same list that is generated in the function. Python passes objects, not references or values. Python keeps track of the references to that list: on each iteration of the while loop, a new list is created and assigned to l. This causes the previous one to no longer have any references, so it will be deleted. A: in python it's all automatic...most of time you don't have to worry about garbage collections... in this case, the func create a list and returns it. then you assign it to l. once you assign a value to a non-empty var, the first value it's simply throw out, there is no memory leaks, you dont' have to use del.. it's, cool, isn't it? :)
Does on-the-fly list creation and return in a function create a memory leak in Python?
If I create a list in a python function and return it to the caller, how does garbage collection work on that list? Do I have to do anything to keep a memory leak from occurring? For example: #!/usr/bin/python import random class Example: def f1(self): list = [] len = random.randint(0, 30) for i in range (0, len): list.append(random.randint(0, 65536)) return list random.seed(None) e = Example() while (1): l = e.f1() Will this cause a memory leak? Does the 'list' in f1() have an appropriate reference count at all times? Does the caller of f1() have to do anything to keep a memory leak from occurring? Should the caller do a del() on the list or something?
[ "There's no memory leak here. The list assigned to l is the same list that is generated in the function. Python passes objects, not references or values.\nPython keeps track of the references to that list: on each iteration of the while loop, a new list is created and assigned to l. This causes the previous one to ...
[ 6, 2 ]
[]
[]
[ "garbage_collection", "memory_leaks", "python" ]
stackoverflow_0004143967_garbage_collection_memory_leaks_python.txt
Q: In Python can one implement mixin behavior without using inheritance? Is there a reasonable way in Python to implement mixin behavior similar to that found in Ruby -- that is, without using inheritance? class Mixin(object): def b(self): print "b()" def c(self): print "c()" class Foo(object): # Somehow mix in the behavior of the Mixin class, # so that all of the methods below will run and # the issubclass() test will be False. def a(self): print "a()" f = Foo() f.a() f.b() f.c() print issubclass(Foo, Mixin) I had a vague idea to do this with a class decorator, but my attempts led to confusion. Most of my searches on the topic have led in the direction of using inheritance (or in more complex scenarios, multiple inheritance) to achieve mixin behavior. A: def mixer(*args): """Decorator for mixing mixins""" def inner(cls): for a,k in ((a,k) for a in args for k,v in vars(a).items() if callable(v)): setattr(cls, k, getattr(a, k).im_func) return cls return inner class Mixin(object): def b(self): print "b()" def c(self): print "c()" class Mixin2(object): def d(self): print "d()" def e(self): print "e()" @mixer(Mixin, Mixin2) class Foo(object): # Somehow mix in the behavior of the Mixin class, # so that all of the methods below will run and # the issubclass() test will be False. def a(self): print "a()" f = Foo() f.a() f.b() f.c() f.d() f.e() print issubclass(Foo, Mixin) output: a() b() c() d() e() False A: You can add the methods as functions: Foo.b = Mixin.b.im_func Foo.c = Mixin.c.im_func A: EDIT: Fixed what could (and probably should) be construed as a bug. Now it builds a new dict and then updates that from the class's dict. This prevents mixins from overwriting methods that are defined directly on the class. The code is still untested but should work. I'm busy ATM so I'll test it later. It worked fine except for a syntax error. In retrospect, I decided that I don't like it (even after my further improvements) and much prefer my other solution even if it is more complicated. The test code for that one applies here as well but I wont duplicate it. You could use a metaclass factory: import inspect def add_mixins(*mixins): Dummy = type('Dummy', mixins, {}) d = {} for mixin in reversed(inspect.getmro(Dummy)): d.update(mixin.__dict__) class WithMixins(type): def __new__(meta, classname, bases, classdict): d.update(classdict) return super(WithMixins, meta).__new__(meta, classname, bases, d) return WithMixins then use it like: class Foo(object): __metaclass__ = add_mixins(Mixin1, Mixin2) # rest of the stuff A: I am not that familiar with Python, but from what I know about Python metaprogramming, you could actually do it pretty much the same way it is done in Ruby. In Ruby, a module basically consists of two things: a pointer to a method dictionary and a pointer to a constant dictionary. A class consists of three things: a pointer to a method dictionary, a pointer to a constant dictionary and a pointer to the superclass. When you mix in a module M into a class C, the following happens: an anonymous class α is created (this is called an include class) α's method dictionary and constant dictionary pointers are set equal to M's α's superclass pointer is set equal to C's C's superclass pointer is set to α In other words: a fake class which shares its behavior with the mixin is injected into the inheritance hierarchy. So, Ruby actually does use inheritance for mixin composition. I left out a couple of subleties above: first off, the module doesn't actually get inserted as C's superclass, it gets inserted as C's superclasses' (which is C's singleton class) superclass. And secondly, if the mixin itself has mixed in other mixins, then those also get wrapped into fake classes which get inserted directly above α, and this process is applied recursively, in case the mixed in mixins in turn have mixins. Basically, the whole mixin hierarchy gets flattened into a straight line and spliced into the inheritance chain. AFAIK, Python actually allows you to change a class's superclass(es) after the fact (something which Ruby does not allow you to do), and it also gives you access to a class's dict (again, something that is impossible in Ruby), so you should be able to implement this yourself. A: This one is based on the way it's done in ruby as explained by Jörg W Mittag. All of the wall of code after if __name__=='__main__' is test/demo code. There's actually only 13 lines of real code to it. import inspect def add_mixins(*mixins): Dummy = type('Dummy', mixins, {}) d = {} # Now get all the class attributes. Use reversed so that conflicts # are resolved with the proper priority. This rules out the possibility # of the mixins calling methods from their base classes that get overridden # using super but is necessary for the subclass check to fail. If that wasn't a # requirement, we would just use Dummy above (or use MI directly and # forget all the metaclass stuff). for base in reversed(inspect.getmro(Dummy)): d.update(base.__dict__) # Create the mixin class. This should be equivalent to creating the # anonymous class in Ruby. Mixin = type('Mixin', (object,), d) class WithMixins(type): def __new__(meta, classname, bases, classdict): # The check below prevents an inheritance cycle from forming which # leads to a TypeError when trying to inherit from the resulting # class. if not any(issubclass(base, Mixin) for base in bases): # This should be the the equivalent of setting the superclass # pointers in Ruby. bases = (Mixin,) + bases return super(WithMixins, meta).__new__(meta, classname, bases, classdict) return WithMixins if __name__ == '__main__': class Mixin1(object): def b(self): print "b()" def c(self): print "c()" class Mixin2(object): def d(self): print "d()" def e(self): print "e()" class Mixin3Base(object): def f(self): print "f()" class Mixin3(Mixin3Base): pass class Foo(object): __metaclass__ = add_mixins(Mixin1, Mixin2, Mixin3) def a(self): print "a()" class Bar(Foo): def f(self): print "Bar.f()" def test_class(cls): print "Testing {0}".format(cls.__name__) f = cls() f.a() f.b() f.c() f.d() f.e() f.f() print (issubclass(cls, Mixin1) or issubclass(cls, Mixin2) or issubclass(cls, Mixin3)) test_class(Foo) test_class(Bar) A: You could decorate the classes __getattr__ to check in the mixin. The problem is that all methods of the mixin would always require an object the type of the mixin as their first parameter, so you would have to decorate __init__ as well to create a mixin-object. I believe you could achieve this using a class decorator. A: from functools import partial class Mixin(object): @staticmethod def b(self): print "b()" @staticmethod def c(self): print "c()" class Foo(object): def __init__(self, mixin_cls): self.delegate_cls = mixin_cls def __getattr__(self, attr): if hasattr(self.delegate_cls, attr): return partial(getattr(self.delegate_cls, attr), self) def a(self): print "a()" f = Foo(Mixin) f.a() f.b() f.c() print issubclass(Foo, Mixin) This basically uses the Mixin class as a container to hold ad-hoc functions (not methods) that behave like methods by taking an object instance (self) as the first argument. __getattr__ will redirect missing calls to these methods-alike functions. This passes your simple tests as shown below. But I cannot guarantee it will do all the things you want. Make more thorough test to make sure. $ python mixin.py a() b() c() False A: Composition? It seems like that would be the simplest way to handle this: either wrap your object in a decorator or just import the methods as an object into your class definition itself. This is what I usually do: put the methods that I want to share between classes in a file and then import the file. If I want to override some behavior I import a modified file with the same method names as the same object name. It's a little sloppy, but it works. For example, if I want the init_covers behavior from this file (bedg.py) import cove as cov def init_covers(n): n.covers.append(cov.Cover((set([n.id])))) id_list = [] for a in n.neighbors: id_list.append(a.id) n.covers.append(cov.Cover((set(id_list)))) def update_degree(n): for a in n.covers: a.degree = 0 for b in n.covers: if a != b: a.degree += len(a.node_list.intersection(b.node_list)) In my bar class file I would do: import bedg as foo and then if I want to change my foo behaviors in another class that inherited bar, I write import bild as foo Like I say, it is sloppy.
In Python can one implement mixin behavior without using inheritance?
Is there a reasonable way in Python to implement mixin behavior similar to that found in Ruby -- that is, without using inheritance? class Mixin(object): def b(self): print "b()" def c(self): print "c()" class Foo(object): # Somehow mix in the behavior of the Mixin class, # so that all of the methods below will run and # the issubclass() test will be False. def a(self): print "a()" f = Foo() f.a() f.b() f.c() print issubclass(Foo, Mixin) I had a vague idea to do this with a class decorator, but my attempts led to confusion. Most of my searches on the topic have led in the direction of using inheritance (or in more complex scenarios, multiple inheritance) to achieve mixin behavior.
[ "def mixer(*args):\n \"\"\"Decorator for mixing mixins\"\"\"\n def inner(cls):\n for a,k in ((a,k) for a in args for k,v in vars(a).items() if callable(v)):\n setattr(cls, k, getattr(a, k).im_func)\n return cls\n return inner\n\nclass Mixin(object):\n def b(self): print \"b()\"\...
[ 9, 4, 3, 3, 3, 0, 0, 0 ]
[]
[]
[ "inheritance", "mixins", "python", "ruby" ]
stackoverflow_0004139508_inheritance_mixins_python_ruby.txt
Q: django-paypal IPN doesn't work I'm using django-paypal as a payment solution inside my django application. I'm trying to implement a IPN handler. What happens when I receive an IPN message at my IPN-handling URL the django server crashes: Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 281, in run self.finish_response() File "/usr/local/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 321, in finish_response self.write(data) File "/usr/local/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 417, in write self._write(data) File "/usr/lib/python2.6/socket.py", line 300, in write self.flush() File "/usr/lib/python2.6/socket.py", line 286, in flush self._sock.sendall(buffer) error: [Errno 104] Connection reset by peer My payments applications urls.py looks like this: urlpatterns = patterns('mysite.payment.views', (r'^thank_you/', 'thank_you'), (r'^canceled/', 'canceled'), (r'^paypal-ipn/', include('paypal.standard.ipn.urls')) ) To me the error message is pretty useless. Would be great if someone could help me. A: I admit I'm an idiot :) You don't need ssl for this. But what you need is to do a syncdb before you are able to use it,... God sometimes it is so easy that you just don't see it. A: Can you monitor precisely the packet that paypal is sending your server using tcpdump or wireshark? It looks like they may be terminating the connection early, but it's hard to tell much without a longer traceback and/or a packet dump. Edit: I had forgotten about the https messages. Paypal probably requires HTTPS for those callbacks. The dev server won't support that, so unfortunately you will probably need to flesh out your server configuration before you can test that functionality.
django-paypal IPN doesn't work
I'm using django-paypal as a payment solution inside my django application. I'm trying to implement a IPN handler. What happens when I receive an IPN message at my IPN-handling URL the django server crashes: Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 281, in run self.finish_response() File "/usr/local/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 321, in finish_response self.write(data) File "/usr/local/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 417, in write self._write(data) File "/usr/lib/python2.6/socket.py", line 300, in write self.flush() File "/usr/lib/python2.6/socket.py", line 286, in flush self._sock.sendall(buffer) error: [Errno 104] Connection reset by peer My payments applications urls.py looks like this: urlpatterns = patterns('mysite.payment.views', (r'^thank_you/', 'thank_you'), (r'^canceled/', 'canceled'), (r'^paypal-ipn/', include('paypal.standard.ipn.urls')) ) To me the error message is pretty useless. Would be great if someone could help me.
[ "I admit I'm an idiot :)\nYou don't need ssl for this. But what you need is to do a syncdb before you are able to use it,...\nGod sometimes it is so easy that you just don't see it.\n", "Can you monitor precisely the packet that paypal is sending your server using tcpdump or wireshark? It looks like they may be t...
[ 5, 0 ]
[]
[]
[ "django", "django_paypal", "paypal", "python" ]
stackoverflow_0004133988_django_django_paypal_paypal_python.txt
Q: Vertical code block delimiters in eclipse Is it possible to enable vertical bars delimiting code blocks in eclipse ? A: If you are referencing to bug 84878 about "Draw vertical lines in control flow statements", then no, it isn't possible yet. In order to help reading complex algorithm, one could imagine having some graphical connections in between constructs (remember when we learned algorithmic at school). if (...) { | if (...) { | | | } } else { | | } I would imagine a thin line directly in the code, anchored on left side of control flow keyword, and t would only look nice if correctly indented
Vertical code block delimiters in eclipse
Is it possible to enable vertical bars delimiting code blocks in eclipse ?
[ "If you are referencing to bug 84878 about \"Draw vertical lines in control flow statements\", then no, it isn't possible yet.\n\nIn order to help reading complex algorithm, one could imagine having some graphical connections in between constructs (remember when we learned algorithmic at school).\n\nif (...) {\n| ...
[ 1 ]
[]
[]
[ "eclipse", "python" ]
stackoverflow_0004143737_eclipse_python.txt
Q: Python to C# conversion In python i'm creating .an file using commandStr="dpan.exe -np -Lwork_%s.lib -Owork_%s.lib %s %s.an" %( option1, option2, Sourcefile, Destination file) os.system( commandStr ) This will create the .an file (Destination file) from Sourcefile. Now i'm converting this line of code from Python to C# So how do i do this in C#. How to run the commandStr in C# Please help me to do this. A: You could use the Process.Start method: Process.Start( "dpan.exe", string.Format( "-np -Lwork_{0}.lib -Owork_{1}.lib \"{2}\" \"{3}.an\"", option1, option2, sourceFile, destinationFile ) ); A: The equivalent of os.system is System.Diagnostics.Process.Start in C#.
Python to C# conversion
In python i'm creating .an file using commandStr="dpan.exe -np -Lwork_%s.lib -Owork_%s.lib %s %s.an" %( option1, option2, Sourcefile, Destination file) os.system( commandStr ) This will create the .an file (Destination file) from Sourcefile. Now i'm converting this line of code from Python to C# So how do i do this in C#. How to run the commandStr in C# Please help me to do this.
[ "You could use the Process.Start method:\nProcess.Start(\n \"dpan.exe\", \n string.Format(\n \"-np -Lwork_{0}.lib -Owork_{1}.lib \\\"{2}\\\" \\\"{3}.an\\\"\", \n option1, option2, sourceFile, destinationFile\n )\n);\n\n", "The equivalent of os.system is System.Diagnostics.Process.Start in C...
[ 4, 2 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0004144649_c#_python.txt
Q: What's the fix for module _mysql: This Python has API version 1012, module _mysql has version 1013 If I try to use the shell I get this API conflict. /home/username/.python-eggs/MySQL_python-1.2.3c1-py2.6-linux-i686.egg-tmp/_mysql.so:6: RuntimeWarning: Python C API version mismatch for module _mysql: This Python has API version 1012, module _mysql has version 1013. I'm running: Python 2.6 MySQL Server version: 5.0.77 MySQL_python-1.2.3c1 I tried unsuccessfully to update to a new version of MySQL-python. easy_install-2.6 -d ~/lib/python2.6 MySQL-python Searching for MySQL-python Best match: MySQL-python 1.2.3c1 Processing MySQL_python-1.2.3c1-py2.6-linux-i686.egg MySQL-python 1.2.3c1 is already the active version in easy-install.pth Using /home/username/lib/python2.6/MySQL_python-1.2.3c1-py2.6-linux-i686.egg Processing dependencies for MySQL-python Finished processing dependencies for MySQL-python How do I correct this error? A: The error message means the _mysql module, part of MySQLdb, was built for a newer version of Python than it's being loaded into. API version 1013 is the one used by Python 2.5 and 2.6, and 1012 is the one used by Python 2.4. You don't say how you're using MySQLdb, but apparently it's being imported by Python 2.4.
What's the fix for module _mysql: This Python has API version 1012, module _mysql has version 1013
If I try to use the shell I get this API conflict. /home/username/.python-eggs/MySQL_python-1.2.3c1-py2.6-linux-i686.egg-tmp/_mysql.so:6: RuntimeWarning: Python C API version mismatch for module _mysql: This Python has API version 1012, module _mysql has version 1013. I'm running: Python 2.6 MySQL Server version: 5.0.77 MySQL_python-1.2.3c1 I tried unsuccessfully to update to a new version of MySQL-python. easy_install-2.6 -d ~/lib/python2.6 MySQL-python Searching for MySQL-python Best match: MySQL-python 1.2.3c1 Processing MySQL_python-1.2.3c1-py2.6-linux-i686.egg MySQL-python 1.2.3c1 is already the active version in easy-install.pth Using /home/username/lib/python2.6/MySQL_python-1.2.3c1-py2.6-linux-i686.egg Processing dependencies for MySQL-python Finished processing dependencies for MySQL-python How do I correct this error?
[ "The error message means the _mysql module, part of MySQLdb, was built for a newer version of Python than it's being loaded into. API version 1013 is the one used by Python 2.5 and 2.6, and 1012 is the one used by Python 2.4. You don't say how you're using MySQLdb, but apparently it's being imported by Python 2.4.\...
[ 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0004138414_mysql_python.txt
Q: Python: Execute scp, stdin for password not working I'm trying the following from subprocess import Popen, PIPE Popen(["scp", "-B","user@url:file", "."], stdin=PIPE, shell=False).communicate(input="password") But I still get the password promt, and no password is sent. I know I can use scp with keys, but this is not what I need. Any help? A: scp interacts with the terminal directly, rather than reading from STDIN, You can't pass the password via a pipe, it security matter for scp and it's the same for sftp, ssh. you can try it in you terminal like this (and it will not work): echo "password" | scp me@localhost:test . A: As others have said, scp (and ssh) read the password directly from the console instead of stdin, so using subprocess to send the password will not work. You can use pexpect instead - see the docs and numerous examples for how to do this.
Python: Execute scp, stdin for password not working
I'm trying the following from subprocess import Popen, PIPE Popen(["scp", "-B","user@url:file", "."], stdin=PIPE, shell=False).communicate(input="password") But I still get the password promt, and no password is sent. I know I can use scp with keys, but this is not what I need. Any help?
[ "scp interacts with the terminal directly, rather than reading from STDIN, You can't pass the password via a pipe, it security matter for scp and it's the same for sftp, ssh.\nyou can try it in you terminal like this (and it will not work):\necho \"password\" | scp me@localhost:test .\n\n", "As others have said, ...
[ 2, 1 ]
[]
[]
[ "passwords", "popen", "python", "scp", "stdin" ]
stackoverflow_0004144134_passwords_popen_python_scp_stdin.txt
Q: How to have data structure with both tuple and dictionary characteristic By refering code at http://initd.org/psycopg/docs/extras.html#dictionary-like-cursor >>> rec['data'] "abc'def" >>> rec[2] "abc'def" I was wondering how they manage to make a data structure having both tuple and dictionary characteristic? A: In Python the [] lookups are handled by the __getitem__ magic method; in other words, when you index a custom class Python will call instance.__getitem__(...) and return you the value. This lets you do e.g. >>> class Foo: ... def __getitem__(self, value): ... return value ... >>> foo = Foo() >>> foo["1"] '1' >>> foo[0] 0 There are several natural ways of maintaining the actual data structure; probably the easiest is to maintain both a dict and a list and index into one of them depending on the type of the key. Notice that this is unnatural; you would expect a dict-like object to treat 0 as a key. it might be worth writing a different method e.g. index to handle the indexing. You may also wish to implement the __setitem__ and __contains__ methods. A: Here's a modified version of demas's answer that (I think) will preserve ordering (but will not be efficient): class TupleDict(collections.OrderedDict): def __getitem__(self, key): if isinstance(key, int): return list(self.values())[key] return super(TupleDict, self).__getitem__(key) A: Read the code. Thats my best suggestion. For example: class cursor(_2cursor): """psycopg 1.1.x cursor. Note that this cursor implements the exact procedure used by psycopg 1 to build dictionaries out of result rows. The DictCursor in the psycopg.extras modules implements a much better and faster algorithm. """ def __build_dict(self, row): res = {} for i in range(len(self.description)): res[self.description[i][0]] = row[i] return res ..... And where it is coming from .. class connection(_2connection): """psycopg 1.1.x connection.""" def cursor(self): """cursor() -> new psycopg 1.1.x compatible cursor object""" return _2connection.cursor(self, cursor_factory=cursor) A: After reading Glenn Maynard's comment on the answer that caused me to delete this one, I've decided to resurrect it. This uses a normal list to store the indices and so will have the same O(1) access. Here's my take on it. Error handling could probably be improved but I didn't want to clutter up the code too much. I don't know how the original code handled it but why not go ahead and handle slices as well. We can only handle slice assignment for slices that don't create new keys (that is, that don't change the count of items) but we can handle arbitrary slice lookups. Note that it also effectively disallows integer keys. Here's a small demo of it in action. class IndexedDict(object): def __init__(self, *args, **kwargs): d = dict(*args, **kwargs) self._keys = d.keys() # list(d.keys()) in python 3.1 self._d = d def __getitem__(self, item): if isinstance(item, int): key = self._keys[item] return self._d[key] elif isinstance(item, slice): keys = self._keys[item] return tuple(self._d[key] for key in keys) else: return self._d[key] def __setitem__(self, item, value): if isinstance(item, int): key = self._keys[item] self._d[key] = value elif isinstance(item, slice): # we only handle slices that don't require the creation of # new keys. keys = self._keys[item] if not len(keys) == len(value): raise ValueError("Complain here") for key, v in zip(keys, value): self._d[key] = v else: self._d[item] = value if item not in self._keys: # This is the only form that can create a new element self._keys.append(item) def __delitem__(self, item): if isinstance(item, int): key = self._keys[item] del self._keys[item] del self._d[key] elif isinstance(item, slice): keys = self._keys[item] del self._keys[item] for key in keys: del self._d[key] else: del self._d[item] self._keys.remove(item) def __contains__(self, item): if isinstance(item, int): return i < len(self._keys) else: return i in self._d # Just for debugging. Not intended as part of API. def assertions(self): assert len(self._d) == len(self._keys) assert set(self._d.keys()) == set(self._keys) There's still some stuff to implement. keys, items, iteritems, update, etc. but they shouldn't be too hard. Just work with self._keys and use list comps and generator expressions. for example, iteritems is just (self._d[key] for key in self._keys) For update, I would just make sure you're dealing with a dictlike object and then update self._keys as self._keys += [key for key in other.keys() if key not in self._keys]. I might go so far as to define __add__ in essentially the same way. A: A dictionary can map any python type against any other python type, so it's simple to retrieve a value where the key is an integer. v = {} v[0] = 'a' v[1] = 'b' v['abc'] = 'def' >>> v[0] 'a' A: Something like that: class d(dict): def __getitem__(self, key): if str(key).isdigit(): return self.values()[key] else: return super(d, self).get(key) cls = d() cls["one"] = 1 print cls["one"] print cls[0]
How to have data structure with both tuple and dictionary characteristic
By refering code at http://initd.org/psycopg/docs/extras.html#dictionary-like-cursor >>> rec['data'] "abc'def" >>> rec[2] "abc'def" I was wondering how they manage to make a data structure having both tuple and dictionary characteristic?
[ "In Python the [] lookups are handled by the __getitem__ magic method; in other words, when you index a custom class Python will call instance.__getitem__(...) and return you the value. This lets you do e.g.\n>>> class Foo:\n... def __getitem__(self, value):\n... return value\n...\n>>> foo = Foo()\n...
[ 5, 2, 1, 1, 0, 0 ]
[]
[]
[ "psycopg2", "python" ]
stackoverflow_0004142406_psycopg2_python.txt
Q: Extract lines below category and stop when another category is reached Let's suppose I have a text file of movie genres with my favorite movies under each genre. [category] Horror: Movie Movie Movie [category] Comedy: Movie [category] Action: Movie Movie How would I create a function that extracts and packages all the movie titles below a certain [category] * into an array without spilling over into another category? A: You could parse the file line-by-line this way: import collections result=collections.defaultdict(list) with open('data') as f: genre='unknown' for line in f: line=line.strip() if line.startswith('[category]'): genre=line.replace('[category]','',1) elif line: result[genre].append(line) for key in result: print('{k} {m}'.format(k=key,m=list(result[key]))) yields Action: ['1. Movie', '2. Movie'] Comedy: ['1. Movie'] Horror: ['1. Movie', '2. Movie', '3. Movie'] A: Already given others' advice for your text file format, I'm just stepping in giving another suggestion... If rewriting your file is possible, an easy solution could be to change it to ConfigParser-readable (and writable) file: [Horror] 1: Movie 2: Movie 3: Movie [Comedy] 1: Movie [Action] 1: Movie 2: Movie A: Use a negative lookahead: \[category\](?:(?!\[category\]).)* will match one entire category (if the regex is compiled using the re.DOTALL option). You can grab the category and the contents separately by using \[category\]\s*([^\r\n]*)\r?\n((?:(?!\[category\]).)*) After a match, mymatch.group(1) will contain the category, and mymatch.group(2) will contain the movie titles. Example in Python 3.1 (using your string as mymovies): >>> import re >>> myregex = re.compile(r"\[category\]\s*([^\r\n]*)\r?\n((?:(?!\[category\]).)*)", re.DOTALL) >>> for mymatch in myregex.finditer(mymovies): ... print("Category: {}".format(mymatch.group(1))) ... for movie in mymatch.group(2).split("\n"): ... if movie.strip(): ... print("contains: {}".format(movie.strip())) ... Category: Horror: contains: 1. Movie contains: 2. Movie contains: 3. Movie Category: Comedy: contains: 1. Movie Category: Action: contains: 1. Movie contains: 2. Movie >>> A: import re re_cat = re.compile("\[category\] (.*):") categories = {} category = None for line in open("movies.txt", "r").read().split("\n"): line = line.strip() if not line: continue if re_cat.match(line): category = re_cat.sub("\\1", line) if not category in categories: categories[category] = [] continue categories[category].append(line) print categories Makes the following dictionary: { 'Action': ['Movie', 'Movie'], 'Horror': ['Movie', 'Movie', 'Movie'], 'Comedy': ['Movie'] } We use the same regular expression for matching and stripping out the category name, so it's efficient to compile it with re.compile. We have a running category variable which changes whenever a new category is parsed. Any line that doesn't define a new category gets added to the categories dictionary under the appropriate key. Categories defined for the first time create a list under the right dictionary key, but categories can also be listed multiple times and everything will end up under the right key. Any movies listed before a category is defined will be in the dictionary under the None key.
Extract lines below category and stop when another category is reached
Let's suppose I have a text file of movie genres with my favorite movies under each genre. [category] Horror: Movie Movie Movie [category] Comedy: Movie [category] Action: Movie Movie How would I create a function that extracts and packages all the movie titles below a certain [category] * into an array without spilling over into another category?
[ "You could parse the file line-by-line this way:\nimport collections\n\nresult=collections.defaultdict(list)\nwith open('data') as f:\n genre='unknown'\n for line in f:\n line=line.strip()\n if line.startswith('[category]'):\n genre=line.replace('[category]','',1)\n elif line:\...
[ 2, 2, 1, 0 ]
[]
[]
[ "python", "text_extraction" ]
stackoverflow_0004145053_python_text_extraction.txt
Q: calling cmd from python windows error 2 I am tring to call the cmd command "move" from python. cmd1 = ["move", spath , npath] startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(cmd1, startupinfo=startupinfo) While the comammand works in the cmd. I can move files. With this python code i get: WindowsError: [Error 2] The system cannot find the file specified Spath and npath, are absolute paths to folders, so being in another directory should not matter. [edit] Responding to Tim's answear: The how do i move a folder? A: move is built-in into the cmd shell, so it's not a file command that you can call this way. You could use shutil.move(), but this "forgets" all alternate data stream, ACLs etc. A: try to use cmd1 = ["cmd", "/c", "move", spath, npath]
calling cmd from python windows error 2
I am tring to call the cmd command "move" from python. cmd1 = ["move", spath , npath] startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(cmd1, startupinfo=startupinfo) While the comammand works in the cmd. I can move files. With this python code i get: WindowsError: [Error 2] The system cannot find the file specified Spath and npath, are absolute paths to folders, so being in another directory should not matter. [edit] Responding to Tim's answear: The how do i move a folder?
[ "move is built-in into the cmd shell, so it's not a file command that you can call this way.\nYou could use shutil.move(), but this \"forgets\" all alternate data stream, ACLs etc.\n", "try to use cmd1 = [\"cmd\", \"/c\", \"move\", spath, npath]\n" ]
[ 3, 2 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0004145331_python_windows.txt
Q: Cron Syntax, MAC OS X Quick Summary of Issue I would to run a python script every minute of everyday. I would like cron to run the following 2 commands (in this order) every minute: cd ~/desktop/WebProgramming python MyPythonScript.py Is it possible for cron to run 2 commands? More Detailed Explanation I am having difficulty running a python script in the cron scheduler for mac. Essentially, I would like to run the script every minute, here is my Cron syntax: * * * * * python ~/desktop/WebProgramming/MyPythonFile.py MyPythonFile uses severals of the files in the WebProgrammingFolder--when I first navigate to the directory (cd ~/desktop/WebProgramming/) and manually run the script, the program runs fine. However, I get an error when I try to run it on cron, saying that "No File is In the Directory" referring to the code within MyPythonFile that refers to the other files in the folder. Therefore, I would like cron to navigate to this directory, and then execute the command the run the file. A: The proper fix would be to make MyPythonFile.py look in the appropriate directory for its files. If you don't want to do that (...), then: * * * * * cd ~/desktop/WebProgramming ; python MyPythonScript.py A: ... (cd ~/desktop/WebProgramming/ && python ...) A: Try and specify absolute paths to scripts when using cron
Cron Syntax, MAC OS X
Quick Summary of Issue I would to run a python script every minute of everyday. I would like cron to run the following 2 commands (in this order) every minute: cd ~/desktop/WebProgramming python MyPythonScript.py Is it possible for cron to run 2 commands? More Detailed Explanation I am having difficulty running a python script in the cron scheduler for mac. Essentially, I would like to run the script every minute, here is my Cron syntax: * * * * * python ~/desktop/WebProgramming/MyPythonFile.py MyPythonFile uses severals of the files in the WebProgrammingFolder--when I first navigate to the directory (cd ~/desktop/WebProgramming/) and manually run the script, the program runs fine. However, I get an error when I try to run it on cron, saying that "No File is In the Directory" referring to the code within MyPythonFile that refers to the other files in the folder. Therefore, I would like cron to navigate to this directory, and then execute the command the run the file.
[ "The proper fix would be to make MyPythonFile.py look in the appropriate directory for its files.\nIf you don't want to do that (...), then:\n* * * * * cd ~/desktop/WebProgramming ; python MyPythonScript.py\n\n", "... (cd ~/desktop/WebProgramming/ && python ...)\n", "Try and specify absolute paths to scripts wh...
[ 6, 1, 0 ]
[]
[]
[ "cron", "python" ]
stackoverflow_0004145387_cron_python.txt
Q: Python + QT, Windows Forms or Swing for a cross-platform application? I'd like to develop a small/medium-size cross-platform application (including GUI). My background: mostly web applications with MVC architectures, both Python (Pylons + SqlAlchemy) and Java (know the language well, but don't like it that much). I also know some C#. So far, I have no GUI programming experience (neither Windows Forms, Swing nor QT). I plan to use SQLite for data storage: It seems to be a nice cross-platform solution and has some powerful features (e.g. full text search, which SQL Server Compact lacks). I have done some research and these are my favorite options: 1) QT, Python (PyQT or PySide), and SQLAlchemy pros: Python the language open source is strong in the Python world (lots of libraries and users) SQLAlchemy: A fantastic way to interact with a DB and incredibly well documented! cons: compilation, distribution and deployment more difficult? no QT experience QT Designer not as nice as the Visual Studio Winforms designer 2) .NET/Mono, Windows Forms, C#, (Fluent) NHibernate, System.Data.SQLite pros: C# (I like it, especially compared to Java and would like to get more experience in it) The Winforms GUI designer in Visual Studio seems really slick IntelliSense ClickOnce Deployment(?) Windows Forms look and feel good on Windows cons: (Fluent) NHibernate far less documented than SQLAlchemy; also annoying: Fluent docs refer to NHibernate docs which refer to Hibernate (aargh!). But plain NHibernate + XML does not look very comfortable. Windows Forms will not look + behave native on Linux/Mac OS (correct?) fewer open source libraries in the .NET world, fewer OSS users, less documentation in general no WinForms and NHibernate experience 3) JVM, Java + Jython, Swing, SQLAlchemy (I'm emotionally biased against this one, but listed for completeness sake) pros: JVM/Swing work well as cross-platform basis Jython SQLAlchemy lots of open source libraries cons: Swing seems ugly and difficult to layout lacks a good GUI designer Guessing that I won't be able to avoid Java for UI stuff Not sure how stable the Jython/Java integration is (Options that I have ruled out... just to avoid discussion on these): - wxWidgets/wxPython (now that QT is LGPLed) - GTK/PyGTK The look and feel of the final application is very important to me. The above technology stacks are very different (PyQT, .NET WinForms, JVM Swing) and require some time to get proficient, so: Which alternative would you recommend and why? A: I'm a Python guy and use PyQt myself, and I can wholly recommend it. Concerning your cons: compilation, distribution and deployment more difficult? No, not really. For many projects, a full setup.py for e.g. cx_Freeze can be less than 30 lines that rarely need to change (most import dependencies are detected automatically, only need to specify the few modules that are not recognized), and then python setup.py will build a standalone executable. Then you can distribute it just like e.g. a C++ .exe. no QT experience I didn't have notable GUI experience either when I started out with Qt (only a bit of fiddling with Tkinter), but I grew to love Qt. Most of the time, all widgets work seamlessly and do what they're supposed to do - and there's a lot of them for many purposes. You name it, there's probably a widget that does it, and doesn't annoy the user by being half-assed. All the nice things we've been spoiled with are there. Qt is huge, but the PyQt documentation answer most question with reasonable search effort. And if all else fails and you know a bit of C++, you can also look at Qt resources. QT Designer not as nice as the Visual Studio Winforms designer I don't know the VS Winforms designer, but I must admit that the Qt Designer is lacking. I ended up making a sketch of the UI in the designer, generating the code, cleaning that up and taking care all remaining details by hand. It works out okay so far, but my projects are rather small. PS: (now that QT is LGPLed) PyQt is still GPL only. PySide is LGPL, yes, but it's not that mature, if that's a concern. The project website states that "starting development on PySide should be pretty safe now" though.
Python + QT, Windows Forms or Swing for a cross-platform application?
I'd like to develop a small/medium-size cross-platform application (including GUI). My background: mostly web applications with MVC architectures, both Python (Pylons + SqlAlchemy) and Java (know the language well, but don't like it that much). I also know some C#. So far, I have no GUI programming experience (neither Windows Forms, Swing nor QT). I plan to use SQLite for data storage: It seems to be a nice cross-platform solution and has some powerful features (e.g. full text search, which SQL Server Compact lacks). I have done some research and these are my favorite options: 1) QT, Python (PyQT or PySide), and SQLAlchemy pros: Python the language open source is strong in the Python world (lots of libraries and users) SQLAlchemy: A fantastic way to interact with a DB and incredibly well documented! cons: compilation, distribution and deployment more difficult? no QT experience QT Designer not as nice as the Visual Studio Winforms designer 2) .NET/Mono, Windows Forms, C#, (Fluent) NHibernate, System.Data.SQLite pros: C# (I like it, especially compared to Java and would like to get more experience in it) The Winforms GUI designer in Visual Studio seems really slick IntelliSense ClickOnce Deployment(?) Windows Forms look and feel good on Windows cons: (Fluent) NHibernate far less documented than SQLAlchemy; also annoying: Fluent docs refer to NHibernate docs which refer to Hibernate (aargh!). But plain NHibernate + XML does not look very comfortable. Windows Forms will not look + behave native on Linux/Mac OS (correct?) fewer open source libraries in the .NET world, fewer OSS users, less documentation in general no WinForms and NHibernate experience 3) JVM, Java + Jython, Swing, SQLAlchemy (I'm emotionally biased against this one, but listed for completeness sake) pros: JVM/Swing work well as cross-platform basis Jython SQLAlchemy lots of open source libraries cons: Swing seems ugly and difficult to layout lacks a good GUI designer Guessing that I won't be able to avoid Java for UI stuff Not sure how stable the Jython/Java integration is (Options that I have ruled out... just to avoid discussion on these): - wxWidgets/wxPython (now that QT is LGPLed) - GTK/PyGTK The look and feel of the final application is very important to me. The above technology stacks are very different (PyQT, .NET WinForms, JVM Swing) and require some time to get proficient, so: Which alternative would you recommend and why?
[ "I'm a Python guy and use PyQt myself, and I can wholly recommend it. Concerning your cons:\n\ncompilation, distribution and deployment more difficult?\n\nNo, not really. For many projects, a full setup.py for e.g. cx_Freeze can be less than 30 lines that rarely need to change (most import dependencies are detected...
[ 5 ]
[]
[]
[ "c#", "cross_platform", "java", "python", "user_interface" ]
stackoverflow_0004145350_c#_cross_platform_java_python_user_interface.txt
Q: /etc/init.d sh script I'm new to python. I want to create controlled script executed from /etc/init.d command like /etc/init.d something start/stop/restart Any advise appreciated. A: See this post on how to write a script to place in your /etc/init.d directory. The only difference is you must change the hash-bang line to point to python, and not bash: #!/usr/bin/python def myfunc(): print 'myfunct()' if __name__ == '__main__': print 'running python script' myfunc() And make the file executable chmod +x myscript A: If you're looking for a module for constructing daemons. I've used this: https://gist.github.com/slor/5946334 A: Pardus initialization (http://www.pardus.org.tr/eng/projects/comar/SpeedingUpLinuxWithPardus.html) is based on python and in theory you can even start system with windows executable (through Wine of course). You can see a sample initialisation script there doing almost same thing with shell script but in a pythonic way.
/etc/init.d sh script
I'm new to python. I want to create controlled script executed from /etc/init.d command like /etc/init.d something start/stop/restart Any advise appreciated.
[ "See this post on how to write a script to place in your /etc/init.d directory. The only difference is you must change the hash-bang line to point to python, and not bash:\n#!/usr/bin/python\ndef myfunc():\n print 'myfunct()'\n\nif __name__ == '__main__':\n print 'running python script'\n myfunc()\n\nAnd m...
[ 3, 1, 1 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0004145282_linux_python.txt
Q: How to use .pem file with Python M2Crypto To generate an RSA key pair I used openssl: openssl genrsa -out my_key.private.pem 1024 openssl rsa -in my_key.private.pem -pubout -out my_key.public.pem Now I want to use this my_key.public.pem file in a function of another .py file: import M2Crypto from M2Crypto import RSA,SSL def encrypt(): pk = open( 'my_key.public.pem', 'rb' ).read() rsa = M2Crypto.RSA.load_pub_key(pk) print rsa; Am I doing it right? Both files are in same directory, but this function is not giving any output. A: According to the documentation the load_pub_key expects a file name as input. It returns a M2Crypto.RSA.RSA_pub object, which doesn't make sense to print. What exactly are trying to achieve? A: Try this: RSA.load_key('mykey.pem')
How to use .pem file with Python M2Crypto
To generate an RSA key pair I used openssl: openssl genrsa -out my_key.private.pem 1024 openssl rsa -in my_key.private.pem -pubout -out my_key.public.pem Now I want to use this my_key.public.pem file in a function of another .py file: import M2Crypto from M2Crypto import RSA,SSL def encrypt(): pk = open( 'my_key.public.pem', 'rb' ).read() rsa = M2Crypto.RSA.load_pub_key(pk) print rsa; Am I doing it right? Both files are in same directory, but this function is not giving any output.
[ "According to the documentation the load_pub_key expects a file name as input. It returns a M2Crypto.RSA.RSA_pub object, which doesn't make sense to print. What exactly are trying to achieve?\n", "Try this:\nRSA.load_key('mykey.pem')\n\n" ]
[ 4, 0 ]
[]
[]
[ "m2crypto", "pem", "python" ]
stackoverflow_0001176055_m2crypto_pem_python.txt
Q: In Python, how can you respond to method calls that don't exist on an object? Possible Duplicate: Dynamic Finders and Method Missing in Python I know you can do this in Ruby, but how would it be done in Python? So basically you could maybe to a regex on the method call that didn't exist, and create 'syntactic sugar'. A: Define __getattr__. But that still won't make s./.*/ valid syntax, if that's what you have in mind. Python's syntax is nowhere as bendable as Ruby's. A: You can override __getattribute__ on an object to handle requests for attributes that do not exist. This only works for new-style classes. If you have old-style classes, you can use delnans answer.
In Python, how can you respond to method calls that don't exist on an object?
Possible Duplicate: Dynamic Finders and Method Missing in Python I know you can do this in Ruby, but how would it be done in Python? So basically you could maybe to a regex on the method call that didn't exist, and create 'syntactic sugar'.
[ "Define __getattr__.\nBut that still won't make s./.*/ valid syntax, if that's what you have in mind. Python's syntax is nowhere as bendable as Ruby's.\n", "You can override __getattribute__ on an object to handle requests for attributes that do not exist. This only works for new-style classes. If you have old-st...
[ 2, 1 ]
[]
[]
[ "metaprogramming", "python" ]
stackoverflow_0004145844_metaprogramming_python.txt
Q: Best way to python table? Any thoughts on the best way to implement a table (i.e. a small relational database) in python without using any external databases extra modules and when the sqlite3 module is broken or missing. user:~ $ python3 >>> import sqlite3 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/bns/rma/local/python/lib/python3.1/sqlite3/__init__.py", line 24, in <module> from sqlite3.dbapi2 import * File "/bns/rma/local/python/lib/python3.1/sqlite3/dbapi2.py", line 27, in <module> from _sqlite3 import * ImportError: No module named _sqlite3 >>> ^D user:~ $ python2.7 Python 2.7 (r27:82500, Jul 28 2010, 11:39:31) [GCC 3.4.3 (csl-sol210-3_4-branch+sol_rpath)] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/dcottr/local/lib/python2.7/sqlite3/__init__.py", line 24, in <module> from dbapi2 import * File "/home/dcottr/local/lib/python2.7/sqlite3/dbapi2.py", line 27, in <module> from _sqlite3 import * ImportError: No module named _sqlite3 >>> A: Use sqlite3. It comes with python, you don't need external databases or extra modules. It can create the whole database on memory. You don't need extra files on disk if you don't want to. It's lightning fast. It can do modern queries on the tables, like JOINs There's no reason to not use it. It will be faster and more complete than any solution you roll up on your own. A: You can basically represent a tables as a list of lists/tuples. Then you can have dict to represent indexes. Will you do queries in the table or just "have" it represented? What do you need this for? A: Since Version 2.5 python supports Sqlite. It is very lightweight and not external.
Best way to python table?
Any thoughts on the best way to implement a table (i.e. a small relational database) in python without using any external databases extra modules and when the sqlite3 module is broken or missing. user:~ $ python3 >>> import sqlite3 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/bns/rma/local/python/lib/python3.1/sqlite3/__init__.py", line 24, in <module> from sqlite3.dbapi2 import * File "/bns/rma/local/python/lib/python3.1/sqlite3/dbapi2.py", line 27, in <module> from _sqlite3 import * ImportError: No module named _sqlite3 >>> ^D user:~ $ python2.7 Python 2.7 (r27:82500, Jul 28 2010, 11:39:31) [GCC 3.4.3 (csl-sol210-3_4-branch+sol_rpath)] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/dcottr/local/lib/python2.7/sqlite3/__init__.py", line 24, in <module> from dbapi2 import * File "/home/dcottr/local/lib/python2.7/sqlite3/dbapi2.py", line 27, in <module> from _sqlite3 import * ImportError: No module named _sqlite3 >>>
[ "Use sqlite3.\n\nIt comes with python, you don't need\nexternal databases or extra modules.\nIt can create the whole database on\nmemory. You don't need extra files on\ndisk if you don't want to.\nIt's lightning fast.\nIt can do modern queries on the\ntables, like JOINs\n\nThere's no reason to not use it. It will b...
[ 14, 4, 2 ]
[]
[]
[ "database", "python" ]
stackoverflow_0004146254_database_python.txt
Q: __getattr__ doesn't work with __enter__ -> AttributeError I would like to use with on an object that uses __getattr__ to redirect calls. Howerver, this does not seem to work with the method __enter__ Please consider the following, simplified code to reproduce the error: class EnterTest(object): def myenter(self): pass def __exit__(self, type, value, traceback): pass def __getattr__(self, name): if name == '__enter__': return self.myenter enter_obj = EnterTest() print getattr(enter_obj, '__enter__') with enter_obj: pass Output: <bound method EnterTest.myenter of <__main__.EnterTest object at 0x00000000021432E8>> Traceback (most recent call last): File "test.py", line 14, in <module> with enter_obj: AttributeError: __enter__ Why doesn't it fall back to __getattr__ since __enter__ does not exist on the object? Of course, I could make it work if I just create an __enter__ method and redirect from there instead, but I'm wondering why it doesn't work otherwise. My python version is the following: C:\Python27\python27.exe 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] A: According to upstream, this working was a bug in 2.6 which was "fixed" in 2.7. The short answer is that methods like __enter__ are looked up on the class, not on the object. The documentation for this obscure behavior is at http://docs.python.org/reference/datamodel#specialnames: x[i] is roughly equivalent to ... type(x).__getitem__(x, i) for new-style classes. You can see this behavior with other special methods: class foo(object): def __iadd__(self, i): print i a = foo() a += 1 class foo2(object): def __getattr__(self, key): print key raise AttributeError b = foo2() b += 1 class foo3(object): pass def func(self, i): print i c = foo3() c.__iadd__ = func c += 1 The first works; the second two don't. Python 2.6 didn't conform to this behavior for __enter__ and __exit__, but 2.7 does. http://bugs.python.org/issue9259 That said, it's painfully inconsistent that these methods can't be handled dynamically like any other attributes can. Similarly, you can't instrument accesses to these methods with __getattribute__ like you can any other method. I can't find any intrinsic design logic to this. Python is normally very consistent, and this is a fairly unpleasant wart. A: Which version of python do you use? It seems to be an old bug. Look at this. Your code works with Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12) with fixed def __exit__(self, *args):.
__getattr__ doesn't work with __enter__ -> AttributeError
I would like to use with on an object that uses __getattr__ to redirect calls. Howerver, this does not seem to work with the method __enter__ Please consider the following, simplified code to reproduce the error: class EnterTest(object): def myenter(self): pass def __exit__(self, type, value, traceback): pass def __getattr__(self, name): if name == '__enter__': return self.myenter enter_obj = EnterTest() print getattr(enter_obj, '__enter__') with enter_obj: pass Output: <bound method EnterTest.myenter of <__main__.EnterTest object at 0x00000000021432E8>> Traceback (most recent call last): File "test.py", line 14, in <module> with enter_obj: AttributeError: __enter__ Why doesn't it fall back to __getattr__ since __enter__ does not exist on the object? Of course, I could make it work if I just create an __enter__ method and redirect from there instead, but I'm wondering why it doesn't work otherwise. My python version is the following: C:\Python27\python27.exe 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)]
[ "According to upstream, this working was a bug in 2.6 which was \"fixed\" in 2.7. The short answer is that methods like __enter__ are looked up on the class, not on the object.\nThe documentation for this obscure behavior is at http://docs.python.org/reference/datamodel#specialnames: x[i] is roughly equivalent to ...
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004146095_python.txt
Q: Scatter plot with a huge amount of data I would like to use Matplotlib to generate a scatter plot with a huge amount of data (about 3 million points). Actually I've 3 vectors with the same dimension and I use to plot in the following way. import matplotlib.pyplot as plt import numpy as np from numpy import * from matplotlib import rc import pylab from pylab import * fig = plt.figure() fig.subplots_adjust(bottom=0.2) ax = fig.add_subplot(111) plt.scatter(delta,vf,c=dS,alpha=0.7,cmap=cm.Paired) Nothing special actually. But it takes too long to generate it actually (I'm working on my MacBook Pro 4 GB RAM with Python 2.7 and Matplotlib 1.0). Is there any way to improve the speed? A: Unless your graphic is huge, many of those 3 million points are going to overlap. (A 400x600 image only has 240K dots...) So the easiest thing to do would be to take a sample of say, 1000 points, from your data: import random delta_sample=random.sample(delta,1000) and just plot that. For example: import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np import random fig = plt.figure() fig.subplots_adjust(bottom=0.2) ax = fig.add_subplot(111) N=3*10**6 delta=np.random.normal(size=N) vf=np.random.normal(size=N) dS=np.random.normal(size=N) idx=random.sample(range(N),1000) plt.scatter(delta[idx],vf[idx],c=dS[idx],alpha=0.7,cmap=cm.Paired) plt.show() Or, if you need to pay more attention to outliers, then perhaps you could bin your data using np.histogram, and then compose a delta_sample which has representatives from each bin. Unfortunately, when using np.histogram I don't think there is any easy way to associate bins with individual data points. A simple, but approximate solution is to use the location of a point in or on the bin edge itself as a proxy for the points in it: xedges=np.linspace(-10,10,100) yedges=np.linspace(-10,10,100) zedges=np.linspace(-10,10,10) hist,edges=np.histogramdd((delta,vf,dS), (xedges,yedges,zedges)) xidx,yidx,zidx=np.where(hist>0) plt.scatter(xedges[xidx],yedges[yidx],c=zedges[zidx],alpha=0.7,cmap=cm.Paired) plt.show() A: What about trying pyplot.hexbin? It generates a sort of heatmap based on point density in a set number of bins. A: You could take the heatmap approach shown here. In this example the color represents the quantity of data in the bin, not the median value of the dS array, but that should be easy to change. More later if you are interested.
Scatter plot with a huge amount of data
I would like to use Matplotlib to generate a scatter plot with a huge amount of data (about 3 million points). Actually I've 3 vectors with the same dimension and I use to plot in the following way. import matplotlib.pyplot as plt import numpy as np from numpy import * from matplotlib import rc import pylab from pylab import * fig = plt.figure() fig.subplots_adjust(bottom=0.2) ax = fig.add_subplot(111) plt.scatter(delta,vf,c=dS,alpha=0.7,cmap=cm.Paired) Nothing special actually. But it takes too long to generate it actually (I'm working on my MacBook Pro 4 GB RAM with Python 2.7 and Matplotlib 1.0). Is there any way to improve the speed?
[ "Unless your graphic is huge, many of those 3 million points are going to overlap.\n(A 400x600 image only has 240K dots...)\nSo the easiest thing to do would be to take a sample of say, 1000 points, from your data:\nimport random\ndelta_sample=random.sample(delta,1000)\n\nand just plot that.\nFor example:\nimport m...
[ 29, 11, 9 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0004082298_matplotlib_numpy_python.txt
Q: Python Combinatorics, part 2 This is a follow-up question to Combinatorics in Python I have a tree or directed acyclic graph if you will with a structure as: Where r are root nodes, p are parent nodes, c are child nodes and b are hypothetical branches. The root nodes are not directly linked to the parent nodes, it is only a reference. I am intressted in finding all the combinations of branches under the constraints: A child can be shared by any number of parent nodes given that these parent nodes do not share root node. A valid combination should not be a subset of another combination In this example only two valid combinations are possible under the constraints: combo[0] = [b[0], b[1], b[2], b[3]] combo[1] = [b[0], b[1], b[2], b[4]] The data structure is such as b is a list of branch objects, which have properties r, c and p, e.g.: b[3].r = 1 b[3].p = 3 b[3].c = 2 A: This problem can be solved in Python easily and elegantly, because there is a module called "itertools". Lets say we have objects of type HypotheticalBranch, which have attributes r, p and c. Just as you described it in your post: class HypotheticalBranch(object): def __init__(self, r, p, c): self.r=r self.p=p self.c=c def __repr__(self): return "HypotheticalBranch(%d,%d,%d)" % (self.r,self.p,self.c) Your set of hypothetical branches is thus b=[ HypotheticalBranch(0,0,0), HypotheticalBranch(0,1,1), HypotheticalBranch(1,2,1), HypotheticalBranch(1,3,2), HypotheticalBranch(1,4,2) ] The magical function that returns a list of all possible branch combos could be written like so: import collections, itertools def get_combos(branches): rc=collections.defaultdict(list) for b in branches: rc[b.r,b.c].append(b) return itertools.product(*rc.values()) To be precise, this function returns an iterator. Get the list by iterating over it. These four lines of code will print out all possible combos: for combo in get_combos(b): print "Combo:" for branch in combo: print " %r" % (branch,) The output of this programme is: Combo: HypotheticalBranch(0,1,1) HypotheticalBranch(1,3,2) HypotheticalBranch(0,0,0) HypotheticalBranch(1,2,1) Combo: HypotheticalBranch(0,1,1) HypotheticalBranch(1,4,2) HypotheticalBranch(0,0,0) HypotheticalBranch(1,2,1) ...which is just what you wanted. So what does the script do? It creates a list of all hypothetical branches for each combination (root node, child node). And then it yields the product of these lists, i.e. all possible combinations of one item from each of the lists. I hope I got what you actually wanted. A: You second constraint means you want maximal combinations, i.e. all the combinations with the length equal to the largest combination. I would approach this by first traversing the "b" structure and creating a structure, named "c", to store all branches coming to each child node and categorized by the root node that comes to it. Then to construct combinations for output, for each child you can include one entry from each root set that is not empty. The order (execution time) of the algorithm will be the order of the output, which is the best you can get. For example, your "c" structure, will look like: c[i][j] = [b_k0, ...] --> means c_i has b_k0, ... as branches that connect to root r_j) For the example you provided: c[0][0] = [0] c[0][1] = [] c[1][0] = [1] c[1][1] = [2] c[2][0] = [] c[2][1] = [3, 4] It should be fairly easy to code it using this approach. You just need to iterate over all branches "b" and fill the data structure for "c". Then write a small recursive function that goes through all items inside "c". Here is the code (I entered your sample data at the top for testing sake): class Branch: def __init__(self, r, p, c): self.r = r self.p = p self.c = c b = [ Branch(0, 0, 0), Branch(0, 1, 1), Branch(1, 2, 1), Branch(1, 3, 2), Branch(1, 4, 2) ] total_b = 5 # Number of branches total_c = 3 # Number of child nodes total_r = 2 # Number of roots c = [] for i in range(total_c): c.append([]) for j in range(total_r): c[i].append([]) for k in range(total_b): c[b[k].c][b[k].r].append(k) combos = [] def list_combos(n_c, n_r, curr): if n_c == total_c: combos.append(curr) elif n_r == total_r: list_combos(n_c+1, 0, curr) elif c[n_c][n_r]: for k in c[n_c][n_r]: list_combos(n_c, n_r+1, curr + [b[k]]) else: list_combos(n_c, n_r+1, curr) list_combos(0, 0, []) print combos A: There are really two problems here: firstly, you need to work out the algorithm that you will use to solve this problem and secondly, you need to implement it (in Python). Algorithm I shall assume you want a maximal collection of branches; that is, once to which you can't add any more branches. If you don't, you can consider all subsets of a maximal collection. Therefore, for a child node we want to take as many branches as possible, subject to the constraint that no two parent nodes share a root. In other words, from each child you may have at most one edge in the neighbourhood of each root node. This seems to suggest that you want to iterate first over the children, then over the (neighbourhoods of the) root nodes, and finally over the edges between these. This concept gives the following pseudocode: for each child node: for each root node: remember each permissible edge find all combinations of permissible edges Code >>> import networkx as nx >>> import itertools >>> >>> G = nx.DiGraph() >>> G.add_nodes_from(["r0", "r1", "p0", "p1", "p2", "p3", "p4", "c0", "c1", "c2"]) >>> G.add_edges_from([("r0", "p0"), ("r0", "p1"), ("r1", "p2"), ("r1", "p3"), ... ("r1", "p4"), ("p0", "c0"), ("p1", "c1"), ("p2", "c1"), ... ("p3", "c2"), ("p4", "c2")]) >>> >>> combs = set() >>> leaves = [node for node in G if not G.out_degree(node)] >>> roots = [node for node in G if not G.in_degree(node)] >>> for leaf in leaves: ... for root in roots: ... possibilities = tuple(edge for edge in G.in_edges_iter(leaf) ... if G.has_edge(root, edge[0])) ... if possibilities: combs.add(possibilities) ... >>> combs set([(('p1', 'c1'),), (('p2', 'c1'),), (('p3', 'c2'), ('p4', 'c2')), (('p0', 'c0'),)]) >>> print list(itertools.product(*combs)) [(('p1', 'c1'), ('p2', 'c1'), ('p3', 'c2'), ('p0', 'c0')), (('p1', 'c1'), ('p2', 'c1'), ('p4', 'c2'), ('p0', 'c0'))] The above seems to work, although I haven't tested it. A: For each child c, with hypothetical parents p(c), with roots r(p(c)), choose exactly one parent p from p(c) for each root r in r(p(c)) (such that r is the root of p) and include b in the combination where b connects p to c (assuming there is only one such b, meaning it's not a multigraph). The number of combinations will be the product of the numbers of parents by which each child is hypothetically connected to each root. In other words, the size of the set of combinations will be equal to the product of the hypothetical connections of all child-root pairs. In your example all such child-root pairs have only one path, except r1-c2, which has two paths, thus the size of the set of combinations is two. This satisfies the constraint of no combination being a subset of another because by choosing exactly one parent for each root of each child, we maximize the number connections. Subsequently adding any edge b would cause its root to be connected to its child twice, which is not allowed. And since we are choosing exactly one, all combinations will be exactly the same length. Implementing this choice recursively will yield the desired combinations.
Python Combinatorics, part 2
This is a follow-up question to Combinatorics in Python I have a tree or directed acyclic graph if you will with a structure as: Where r are root nodes, p are parent nodes, c are child nodes and b are hypothetical branches. The root nodes are not directly linked to the parent nodes, it is only a reference. I am intressted in finding all the combinations of branches under the constraints: A child can be shared by any number of parent nodes given that these parent nodes do not share root node. A valid combination should not be a subset of another combination In this example only two valid combinations are possible under the constraints: combo[0] = [b[0], b[1], b[2], b[3]] combo[1] = [b[0], b[1], b[2], b[4]] The data structure is such as b is a list of branch objects, which have properties r, c and p, e.g.: b[3].r = 1 b[3].p = 3 b[3].c = 2
[ "This problem can be solved in Python easily and elegantly, because there is a module called \"itertools\".\nLets say we have objects of type HypotheticalBranch, which have attributes r, p and c. Just as you described it in your post:\nclass HypotheticalBranch(object):\n def __init__(self, r, p, c):\n self.r=r\...
[ 3, 1, 1, 0 ]
[]
[]
[ "combinatorics", "python" ]
stackoverflow_0004145873_combinatorics_python.txt
Q: How can I use Boost::Python to add a method to an exported class without modifying the base class? I have a class in C++ that I can't modify. However, that class holds an std::list<> of items that I need to be able to access in a Python extension. Since Boost::Python doesn't seem to have a built-in conversion between an std::list and a Python list, I was hoping to be able to write a method in C++ that could do this conversion for me and later, when I am mapping the C++ classes to Python classes, I could attach this method. I would prefer if I could just call the method like baseClassInstance.get_std_list_of_items_as_python_list() A: To answer the question in a more general way, you can attach any c++ function that has the right signature to the python export in the class_ declaration. assume a class foo: struct foo { //class stuff here } You can define a free function that takes a reference to foo as the first argument: int do_things_to_a_foo(foo& self, int a, std::string b, other_type c) { //Do things to self } And export it just like a member of foo: class_<foo>("foo") ... .def("do_things_to_a_foo", &do_things_to_a_foo) ... ; A: Boost provides a helper to wrap iterators which is documented here: http://www.boost.org/doc/libs/1_42_0/libs/python/doc/v2/iterator.html The example hear the end of that page worked for me, you just need to explicitly create the conversion, for example: class_<std::list<Item> >("ItemList") .def("__iter__", iterator<std::list<Item> >()); To modify the C++ class without changing it, I am in the habit of creating a thin wrapper that subclasses the real class. This makes a nice place to separate out all the crud that makes my C++ objects feel comfortable from Python. class Py_BaseClass : public BaseClass { public: std::list<Item> & py_get_items(); }
How can I use Boost::Python to add a method to an exported class without modifying the base class?
I have a class in C++ that I can't modify. However, that class holds an std::list<> of items that I need to be able to access in a Python extension. Since Boost::Python doesn't seem to have a built-in conversion between an std::list and a Python list, I was hoping to be able to write a method in C++ that could do this conversion for me and later, when I am mapping the C++ classes to Python classes, I could attach this method. I would prefer if I could just call the method like baseClassInstance.get_std_list_of_items_as_python_list()
[ "To answer the question in a more general way, you can attach any c++ function that has the right signature to the python export in the class_ declaration. \nassume a class foo:\nstruct foo\n{\n //class stuff here\n}\n\nYou can define a free function that takes a reference to foo as the first argument:\nint do_t...
[ 3, 1 ]
[]
[]
[ "boost_python", "c++", "python" ]
stackoverflow_0002348960_boost_python_c++_python.txt
Q: How do I insert a SuperColumn with python/thrift? Using the python/thrift interface I am trying to insert a SuperColumn just like the Comments example in WTF is a Supercolumn.. I've gotten as far as to create the SuperColumn and figured out that I should use batch_mutate to insert it. But I don't know how to create the Mutation and set the key and SuperColumn type keyspace = "Keyspace1" col1 = Column(name = "commenter", value = "J Doe", timestamp = time.time()) col2 = Column(name = "email", value = "jdoe@example.com", timestamp = time.time()) sc = SuperColumn(name = str(uuid.uuidl()), [col1, col2]) # i am guessing the missing code goes here mutation = Mutation(column_or_supercolumn = sc?) client.batch_mutate(keyspace, mutation, ConsistencyLevel.ZERO) A: I would use pycassa or something to make life easier, but something like: keyspace = "Keyspace1" tableName = "Super1" key = "jdoe" col1 = Column(name = "commenter", value = "J Doe", timestamp = time.time()) col2 = Column(name = "email", value = "jdoe@example.com", timestamp = time.time()) newData = [Mutation(ColumnOrSuperColumn(None, SuperColumn(str(uuid.uuidl()), [col1, col2])))] dataMap = {key : {tableName : newData}} client.batch_mutate(keyspace=keyspace, mutation_map=dataMap, consistency_level=ConsistencyLevel.ZERO)
How do I insert a SuperColumn with python/thrift?
Using the python/thrift interface I am trying to insert a SuperColumn just like the Comments example in WTF is a Supercolumn.. I've gotten as far as to create the SuperColumn and figured out that I should use batch_mutate to insert it. But I don't know how to create the Mutation and set the key and SuperColumn type keyspace = "Keyspace1" col1 = Column(name = "commenter", value = "J Doe", timestamp = time.time()) col2 = Column(name = "email", value = "jdoe@example.com", timestamp = time.time()) sc = SuperColumn(name = str(uuid.uuidl()), [col1, col2]) # i am guessing the missing code goes here mutation = Mutation(column_or_supercolumn = sc?) client.batch_mutate(keyspace, mutation, ConsistencyLevel.ZERO)
[ "I would use pycassa or something to make life easier, but something like:\nkeyspace = \"Keyspace1\"\ntableName = \"Super1\"\nkey = \"jdoe\"\ncol1 = Column(name = \"commenter\", value = \"J Doe\", timestamp = time.time())\ncol2 = Column(name = \"email\", value = \"jdoe@example.com\", timestamp = time.time())\n\nnew...
[ 0 ]
[]
[]
[ "cassandra", "python", "thrift" ]
stackoverflow_0004145831_cassandra_python_thrift.txt
Q: Removing clients from the reactor in Twisted I have a simple TCP client which is connected to twisted using: reactor.connectTCP(host, port, SomeClientFactory()) The program is able to receive a HUP signal to trigger a reload. I'd like to basically: Remove the old clients Reload config Create new clients based upon new config However, I can't seem to find a way to acheive the first of these points. Any tips? Thanks A: IReactorTCP.connectTCP returns an IConnector provider. As you can see on the definition of the IConnector interface, the disconnect method will do something like what you want. You can also use the protocol instance's transport attribute's loseConnection method, of course. The latter would be more suitable if there's any kind of cleanup you want the protocol to do before actually disconnecting, since you could put that work and a call to loseConnection at the end of a method like shutdown or quit or cleanup on the protocol class and then just call that.
Removing clients from the reactor in Twisted
I have a simple TCP client which is connected to twisted using: reactor.connectTCP(host, port, SomeClientFactory()) The program is able to receive a HUP signal to trigger a reload. I'd like to basically: Remove the old clients Reload config Create new clients based upon new config However, I can't seem to find a way to acheive the first of these points. Any tips? Thanks
[ "IReactorTCP.connectTCP returns an IConnector provider. As you can see on the definition of the IConnector interface, the disconnect method will do something like what you want. You can also use the protocol instance's transport attribute's loseConnection method, of course. The latter would be more suitable if t...
[ 2 ]
[]
[]
[ "python", "tcp", "twisted" ]
stackoverflow_0004146379_python_tcp_twisted.txt
Q: Uniqueness of global Python objects void in sub-interpreters? I have a question about inner-workings of Python sub-interpreter initialization (from Python/C API) and Python id() function. More precisely, about handling of global module objects in a WSGI Python containers (like uWSGI used with nginx and mod_wsgi on Apache). The following code works as expected (isolated) in both of the mentioned environments, but I can not explain to my self why the id() function always returns the same value per variable, regardless of the process/sub-interpreter in which it is executed. from __future__ import print_function import os, sys def log(*msg): print(">>>", *msg, file=sys.stderr) class A: def __init__(self, x): self.x = x def __str__(self): return self.x def set(self, x): self.x = x a = A("one") log("class instantiated.") def application(environ, start_response): output = "pid = %d\n" % os.getpid() output += "id(A) = %d\n" % id(A) output += "id(a) = %d\n" % id(a) output += "str(a) = %s\n\n" % a a.set("two") status = "200 OK" response_headers = [ ('Content-type', 'text/plain'), ('Content-Length', str(len(output))) ] start_response(status, response_headers) return [output] I have tested this code in uWSGI with one master process and 2 workers; and in mod_wsgi using a deamon mode with two processes and one thread per process. The typical output is: pid = 15278 id(A) = 139748093678128 id(a) = 139748093962360 str(a) = one on first load, then: pid = 15282 id(A) = 139748093678128 id(a) = 139748093962360 str(a) = one on second, and then pid = 15278 | pid = 15282 id(A) = 139748093678128 id(a) = 139748093962360 str(a) = two on every other. As you can see, id() (memory location) of both the class and the class instance remains the same in both processes (first/second load above), while at the same time class instances live in a separate context (otherwise the second request would show "two" instead of "one")! I suspect the answer might be hinted by Python docs: id(object): Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. But if that indeed is the reason, I'm troubled by the next statement that claims the id() value is object's address! While I appreciate the fact this could very well be just a Python/C API "clever" feature that solves (or rather fixes) a problem of caching object references (pointers) in 3rd party extension modules, I still find this behavior to be inconsistent with... well, common sense. Could someone please explain this? I've also noticed mod_wsgi imports the module in each process (i.e. twice), while uWSGI is importing the module only once for both processes. Since the uWSGI master process does the importing, I suppose it seeds the children with copies of that context. Both workers work independently afterwards (deep copy?), while at the same time using the same object addresses, seemingly. (Also, a worker gets reinitialized to the original context upon reload.) I apologize for such a long post, but I wanted to give enough details. Thank you! A: It's not entirely clear what you're asking; I'd give a more concise answer if the question was more specific. First, the id of an object is, in fact--at least in CPython--its address in memory. That's perfectly normal: two objects in the same process at the same time can't share an address, and an object's address never changes in CPython, so the address works neatly as an id. I don't know how this violates common sense. Next, note that a backend process may be spawned in two very distinct ways: A generic WSGI backend handler will fork processes, and then each of the processes will start a backend. This is simple and language-agnostic, but wastes a lot of memory and wastes time loading the backend code repeatedly. A more advanced backend will load the Python code once, and then fork copies of the server after it's loaded. This causes the code to be loaded only once, which is much faster and reduces memory waste significantly. This is how production-quality WSGI servers work. However, the end result in both of these cases is identical: separate, forked processes. So, why are you ending up with the same IDs? That depends on which of the above methods is in use. With a generic WSGI handler, it's happening simply because each process is doing essentially the same thing. So long as processes are doing the same thing, they'll tend to end up with the same IDs; at some point they'll diverge and this will no longer happen. With a pre-loading backend, it's happening because this initial code happens only once, before the server forks, so it's guaranteed to have the same ID. However, either way, once the fork happens they're separate objects, in separate contexts. There's no significance to objects in separate processes having the same ID. A: This is simple to explain by way of a demonstration. You see, when uwsgi creates a new process, it forks the interpreter. Now, forks have interesting memory properties: import os, time if os.fork() == 0: print "child first " + str(hex(id(os))) time.sleep(2) os.attr = 'test' print "child second " + str(hex(id(os))) else: time.sleep(1) print "parent first " + str(hex(id(os))) time.sleep(2) print "parent second " + str(hex(id(os))) print os.attr Output: child first 0xb782414cL parent first 0xb782414cL child second 0xb782414cL parent second 0xb782414cL Traceback (most recent call last): File "test.py", line 13, in <module> print os.attr AttributeError: 'module' object has no attribute 'attr' Although the objects seem to reside at the same memory addr, they are different objects, but this is not python, but the os. edit: I suspect the reason that mod_wsgi imports twice is that it creates further processes via calling python rather than forking. uwsgi's approach is better because it can use less memory. fork's page sharing is COW (copy on write).
Uniqueness of global Python objects void in sub-interpreters?
I have a question about inner-workings of Python sub-interpreter initialization (from Python/C API) and Python id() function. More precisely, about handling of global module objects in a WSGI Python containers (like uWSGI used with nginx and mod_wsgi on Apache). The following code works as expected (isolated) in both of the mentioned environments, but I can not explain to my self why the id() function always returns the same value per variable, regardless of the process/sub-interpreter in which it is executed. from __future__ import print_function import os, sys def log(*msg): print(">>>", *msg, file=sys.stderr) class A: def __init__(self, x): self.x = x def __str__(self): return self.x def set(self, x): self.x = x a = A("one") log("class instantiated.") def application(environ, start_response): output = "pid = %d\n" % os.getpid() output += "id(A) = %d\n" % id(A) output += "id(a) = %d\n" % id(a) output += "str(a) = %s\n\n" % a a.set("two") status = "200 OK" response_headers = [ ('Content-type', 'text/plain'), ('Content-Length', str(len(output))) ] start_response(status, response_headers) return [output] I have tested this code in uWSGI with one master process and 2 workers; and in mod_wsgi using a deamon mode with two processes and one thread per process. The typical output is: pid = 15278 id(A) = 139748093678128 id(a) = 139748093962360 str(a) = one on first load, then: pid = 15282 id(A) = 139748093678128 id(a) = 139748093962360 str(a) = one on second, and then pid = 15278 | pid = 15282 id(A) = 139748093678128 id(a) = 139748093962360 str(a) = two on every other. As you can see, id() (memory location) of both the class and the class instance remains the same in both processes (first/second load above), while at the same time class instances live in a separate context (otherwise the second request would show "two" instead of "one")! I suspect the answer might be hinted by Python docs: id(object): Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. But if that indeed is the reason, I'm troubled by the next statement that claims the id() value is object's address! While I appreciate the fact this could very well be just a Python/C API "clever" feature that solves (or rather fixes) a problem of caching object references (pointers) in 3rd party extension modules, I still find this behavior to be inconsistent with... well, common sense. Could someone please explain this? I've also noticed mod_wsgi imports the module in each process (i.e. twice), while uWSGI is importing the module only once for both processes. Since the uWSGI master process does the importing, I suppose it seeds the children with copies of that context. Both workers work independently afterwards (deep copy?), while at the same time using the same object addresses, seemingly. (Also, a worker gets reinitialized to the original context upon reload.) I apologize for such a long post, but I wanted to give enough details. Thank you!
[ "It's not entirely clear what you're asking; I'd give a more concise answer if the question was more specific.\nFirst, the id of an object is, in fact--at least in CPython--its address in memory. That's perfectly normal: two objects in the same process at the same time can't share an address, and an object's addre...
[ 2, 2 ]
[]
[]
[ "mod_wsgi", "python", "uwsgi" ]
stackoverflow_0004146630_mod_wsgi_python_uwsgi.txt
Q: How can I handle attributes in python? I have to create a function, printObjects(attribute, option), which must print the objects based on a certain attribute. The attribute can take ints or strings as input. The option attribute is optional. How do I implement this for my class? A: I assume you want something like this, or perhaps it will be helpful at least: def printObject(obj, attributes=()): for a in attributes: print getattr(obj, a)
How can I handle attributes in python?
I have to create a function, printObjects(attribute, option), which must print the objects based on a certain attribute. The attribute can take ints or strings as input. The option attribute is optional. How do I implement this for my class?
[ "I assume you want something like this, or perhaps it will be helpful at least:\n\ndef printObject(obj, attributes=()):\n for a in attributes:\n print getattr(obj, a)\n\n" ]
[ 1 ]
[]
[]
[ "arguments", "python" ]
stackoverflow_0004147202_arguments_python.txt
Q: Django Text Markup Editors Can you suggest some good django-specific text-markup editors? A: As for WYSIWYG in-page editor, there are not too many alternatives: wymeditor (used by djangocms), tinymce, ckeditor. I prefer tinymce because there is an easy integration with django-filebrowser. btw you can find better answers than mine in SO: https://stackoverflow.com/search?q=django+wysiwyg A: If you've got the RAM: Eclipse with Pydev and Django Editor NetBeans 7, which is due out 2010 Q4 (see django and netbeans? for more info) A bit lighter: Wing JetBrains PyCharm (Guido's favorite, but at $100 for the personal edition and no free major upgrades, it's a bit steep) Lightest: Most Linux distros' text editors (I know that KWrite, Kate, and gedit all have syntax highlighting for Django templates
Django Text Markup Editors
Can you suggest some good django-specific text-markup editors?
[ "As for WYSIWYG in-page editor, there are not too many alternatives: wymeditor (used by djangocms), tinymce, ckeditor. I prefer tinymce because there is an easy integration with django-filebrowser.\nbtw you can find better answers than mine in SO:\nhttps://stackoverflow.com/search?q=django+wysiwyg\n", "If you've ...
[ 2, 0 ]
[]
[]
[ "django", "markup", "markup_extensions", "python", "semantic_markup" ]
stackoverflow_0004141220_django_markup_markup_extensions_python_semantic_markup.txt
Q: What's the right way for a Python/Twisted program to validate an SSL certificate under Windows? Is there a way for a Python/Twisted program to cleanly make use of the list of root certificates that Internet Explorer uses to validate an SSL connection to an HTTPS server? The answers provided to Validate SSL certificates with Python are very helpful but the example code gets the root certificates by reading the Unix specific directory /etc/ssl/certs/*.pem and it's not clear to me what the Windows equivalent of this would be. A: The Windows equivalent is "copy /etc/ssl/certs/*.pem from your Linux machine". Mac and Windows have different native APIs for getting at their respective certificate stores, which Twisted doesn't directly support. They don't use OpenSSL certificates natively, and they certainly don't put things in as straightforward a layout as 'directory of PEM files'. If you can export your trust roots as PEMs, you could then ask Twisted (well, really, OpenSSL via PyOpenSSL) to verify it that way. I am abstractly interested in doing this in a super-portable way, but I've never actually tried it. Here are some links to get you started: SecureTransport reference, Microsoft Cryptography Functions. In the SecureTransport reference, the documentation points out that SSLGetTrustedRoots is deprecated but doesn't mention the alternative SSLCopyTrustedRoots which isn't. That's probably the API you want to start with on a Mac (via PyObjC). On Windows, I'm really not sure, except somewhere in that pile of functions there's probably one that does what you would like, and maybe you can call it with ctypes :).
What's the right way for a Python/Twisted program to validate an SSL certificate under Windows?
Is there a way for a Python/Twisted program to cleanly make use of the list of root certificates that Internet Explorer uses to validate an SSL connection to an HTTPS server? The answers provided to Validate SSL certificates with Python are very helpful but the example code gets the root certificates by reading the Unix specific directory /etc/ssl/certs/*.pem and it's not clear to me what the Windows equivalent of this would be.
[ "The Windows equivalent is \"copy /etc/ssl/certs/*.pem from your Linux machine\". Mac and Windows have different native APIs for getting at their respective certificate stores, which Twisted doesn't directly support. They don't use OpenSSL certificates natively, and they certainly don't put things in as straightf...
[ 3 ]
[]
[]
[ "python", "ssl", "twisted", "windows" ]
stackoverflow_0004145123_python_ssl_twisted_windows.txt
Q: Silent Installer - to install scripting langues from winform Application I am developing Winform application, using C# on .NET 4.0, which need to install scripting langue(s) based on the user selection. What is the best way to detect if a particular scripting environment/Engine for a given langue(Ruby, python, Perl, etc) is installed on client machine and silently install it if not already installed. A: Though I agree with idea that a truly "silent" install might not be desirable for the users, there are many different installer packages that support silent installation. This page actually has a good breakdown of the various installers and the command arguments needed to do unattended and silent installations. I am more familiar with MSI and it has lots of options. So if you go this route, you'd fire up a Process (uh, Task I guess in C# 4) and run an installer.
Silent Installer - to install scripting langues from winform Application
I am developing Winform application, using C# on .NET 4.0, which need to install scripting langue(s) based on the user selection. What is the best way to detect if a particular scripting environment/Engine for a given langue(Ruby, python, Perl, etc) is installed on client machine and silently install it if not already installed.
[ "Though I agree with idea that a truly \"silent\" install might not be desirable for the users, there are many different installer packages that support silent installation.\nThis page actually has a good breakdown of the various installers and the command arguments needed to do unattended and silent installations....
[ 1 ]
[]
[]
[ "c#", "python", "ruby", "silent_installer", "winforms" ]
stackoverflow_0004146953_c#_python_ruby_silent_installer_winforms.txt
Q: Python Class Inheritance issue I'm playing with Python Class inheritance and ran into a problem where the inherited __init__ is not being executed if called from the sub-class (code below) the result I get from Active Python is: >>> start Tom Sneed Sue Ann Traceback (most recent call last): File "C:\Python26\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 312, <br>in RunScript exec codeObject in __main__.__dict__ File "C:\temp\classtest.py", line 22, in <module> print y.get_emp() File "C:\temp\classtest.py", line 16, in get_emp return self.FirstName + ' ' + 'abc' AttributeError: Employee instance has no attribute 'FirstName' Here's the code class Person(): AnotherName = 'Sue Ann' def __init__(self): self.FirstName = 'Tom' self.LastName = 'Sneed' def get_name(self): return self.FirstName + ' ' + self.LastName class Employee(Person): def __init__(self): self.empnum = 'abc123' def get_emp(self): print self.AnotherName return self.FirstName + ' ' + 'abc' x = Person() y = Employee() print 'start' print x.get_name() print y.get_emp() A: Three things: You need to explicitly call the constructor. It isn't called for you automatically like in C++ Use a new-style class inherited from object With a new-style class, use the super() method available This will look like: class Person(object): AnotherName = 'Sue Ann' def __init__(self): super(Person, self).__init__() self.FirstName = 'Tom' self.LastName = 'Sneed' def get_name(self): return self.FirstName + ' ' + self.LastName class Employee(Person): def __init__(self): super(Employee, self).__init__() self.empnum = 'abc123' def get_emp(self): print self.AnotherName return self.FirstName + ' ' + 'abc' Using super is recommended as it will also deal correctly with calling constructors only once in multiple inheritance cases (as long as each class in the inheritance graph also uses super). It's also one less place you need to change code if/when you change what a class is inherited from (for example, you factor out a base-class and change the derivation and don't need to worry about your classes calling the wrong parent constructors). Also on the MI front, you only need one super call to correctly call all the base-class constructors. A: You should explicitely call the superclass' init function: class Employee(Person): def __init__(self): Person.__init__(self) self.empnum = "abc123" A: Employee has to explicitly invoke the parent's __init__ (not init): class Employee(Person): def __init__(self): Person.__init__(self) self.empnum = 'abc123' A: Instead of super(class, instance) pattern why not just use super(instance) as the class is always instance.__class__? Are there specific cases where it would not be instance.__class__?
Python Class Inheritance issue
I'm playing with Python Class inheritance and ran into a problem where the inherited __init__ is not being executed if called from the sub-class (code below) the result I get from Active Python is: >>> start Tom Sneed Sue Ann Traceback (most recent call last): File "C:\Python26\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 312, <br>in RunScript exec codeObject in __main__.__dict__ File "C:\temp\classtest.py", line 22, in <module> print y.get_emp() File "C:\temp\classtest.py", line 16, in get_emp return self.FirstName + ' ' + 'abc' AttributeError: Employee instance has no attribute 'FirstName' Here's the code class Person(): AnotherName = 'Sue Ann' def __init__(self): self.FirstName = 'Tom' self.LastName = 'Sneed' def get_name(self): return self.FirstName + ' ' + self.LastName class Employee(Person): def __init__(self): self.empnum = 'abc123' def get_emp(self): print self.AnotherName return self.FirstName + ' ' + 'abc' x = Person() y = Employee() print 'start' print x.get_name() print y.get_emp()
[ "Three things:\n\nYou need to explicitly call the constructor. It isn't called for you automatically like in C++\nUse a new-style class inherited from object\nWith a new-style class, use the super() method available\n\nThis will look like:\nclass Person(object):\n AnotherName = 'Sue Ann'\n def __init__(self):...
[ 25, 9, 5, 2 ]
[]
[]
[ "class", "inheritance", "python" ]
stackoverflow_0000927985_class_inheritance_python.txt
Q: Proxying with django and gunicorn I have a django application that i serve using gunicorn. I do that by using the method prescribed on the gunicorn site - embedding gunicorn into my django application. I'm trying to set up a proxy into my application so that when you go to "http://mysite.com/proxy/" it does proxy you to "http://mysite.com:8100". I know i can do that with apache and other webservers. For some reasons i would prefer to do it directly with gunicorn/django. One of theses reasons is keeping everything in the same place. My question is, what is the best way to do that ? Also is it a terrible idea altogether ? Thanks. A: You should deploy some proxy application into your gunicorn installation, such as WSGIProxy. A: I've written dj-revproxy for easy integration of a proxy in django. Bonus point it's using restkit which use the gunicorn HTTP engine. (I'm one of the gunicorn authors). More info here: https://github.com/benoitc/dj-revproxy
Proxying with django and gunicorn
I have a django application that i serve using gunicorn. I do that by using the method prescribed on the gunicorn site - embedding gunicorn into my django application. I'm trying to set up a proxy into my application so that when you go to "http://mysite.com/proxy/" it does proxy you to "http://mysite.com:8100". I know i can do that with apache and other webservers. For some reasons i would prefer to do it directly with gunicorn/django. One of theses reasons is keeping everything in the same place. My question is, what is the best way to do that ? Also is it a terrible idea altogether ? Thanks.
[ "You should deploy some proxy application into your gunicorn installation, such as WSGIProxy.\n", "I've written dj-revproxy for easy integration of a proxy in django. Bonus point it's using restkit which use the gunicorn HTTP engine. (I'm one of the gunicorn authors). More info here:\nhttps://github.com/benoitc/d...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004065437_django_python.txt
Q: Spurious failures in django.contrib.messages.tests when running manage.py test I've recently added authentication (via django.contrib.auth of course) to my application, along with appropriate "signin"/"signup" links to my base.html. The problem comes when I run manage.py tests, and I get 4 failures, all from django.contrib.messages.tests: ERROR: test_middleware_disabled_anon_user (django.contrib.messages.tests.cookie.CookieTest) ERROR: test_middleware_disabled_anon_user (django.contrib.messages.tests.fallback.FallbackTest) ERROR: test_middleware_disabled_anon_user (django.contrib.messages.tests.user_messages.LegacyFallbackTest) ERROR: test_middleware_disabled_anon_user (django.contrib.messages.tests.session.SessionTest) All with the same failure: TemplateSyntaxError: Caught NoReverseMatch while rendering: Reverse for 'django.contrib.auth.views.login' with arguments '()' and keyword arguments '{}' not found. In manage.py shell this works: >>> from django.core.urlresolvers import reverse >>> reverse('django.contrib.auth.views.login') '/signin/' However this doesn't: >>> reverse('django.contrib.auth.views.login', (), {}) Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/dave/Dropbox/Projects/statbooks.co.uk/lib/python2.6/site-packages/django/core/urlresolvers.py", line 350, in reverse *args, **kwargs))) File "/Users/dave/Dropbox/Projects/statbooks.co.uk/lib/python2.6/site-packages/django/core/urlresolvers.py", line 296, in reverse "arguments '%s' not found." % (lookup_view_s, args, kwargs)) NoReverseMatch: Reverse for 'django.contrib.auth.views.login' with arguments '()' and keyword arguments '{}' not found. Commenting out the {% url %} tags from my base.html make the tests pass. What's causing this? A: There are several suggestions for workarounds in this Django ticket and links therein: http://code.djangoproject.com/ticket/11077 The one I like is this: http://groups.google.com/group/django-developers/msg/ec7508651e9e9fb8. To summarize, it divides up built-in tests and app tests, then overrides manage.py test to run just app tests. None of these suggestions fixes the underlying problem (that all unit tests should be able to run even if base templates use the {% url %} tag).
Spurious failures in django.contrib.messages.tests when running manage.py test
I've recently added authentication (via django.contrib.auth of course) to my application, along with appropriate "signin"/"signup" links to my base.html. The problem comes when I run manage.py tests, and I get 4 failures, all from django.contrib.messages.tests: ERROR: test_middleware_disabled_anon_user (django.contrib.messages.tests.cookie.CookieTest) ERROR: test_middleware_disabled_anon_user (django.contrib.messages.tests.fallback.FallbackTest) ERROR: test_middleware_disabled_anon_user (django.contrib.messages.tests.user_messages.LegacyFallbackTest) ERROR: test_middleware_disabled_anon_user (django.contrib.messages.tests.session.SessionTest) All with the same failure: TemplateSyntaxError: Caught NoReverseMatch while rendering: Reverse for 'django.contrib.auth.views.login' with arguments '()' and keyword arguments '{}' not found. In manage.py shell this works: >>> from django.core.urlresolvers import reverse >>> reverse('django.contrib.auth.views.login') '/signin/' However this doesn't: >>> reverse('django.contrib.auth.views.login', (), {}) Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/dave/Dropbox/Projects/statbooks.co.uk/lib/python2.6/site-packages/django/core/urlresolvers.py", line 350, in reverse *args, **kwargs))) File "/Users/dave/Dropbox/Projects/statbooks.co.uk/lib/python2.6/site-packages/django/core/urlresolvers.py", line 296, in reverse "arguments '%s' not found." % (lookup_view_s, args, kwargs)) NoReverseMatch: Reverse for 'django.contrib.auth.views.login' with arguments '()' and keyword arguments '{}' not found. Commenting out the {% url %} tags from my base.html make the tests pass. What's causing this?
[ "There are several suggestions for workarounds in this Django ticket and links therein: http://code.djangoproject.com/ticket/11077 The one I like is this: http://groups.google.com/group/django-developers/msg/ec7508651e9e9fb8. To summarize, it divides up built-in tests and app tests, then overrides manage.py test to...
[ 3 ]
[]
[]
[ "django", "django_contrib", "python" ]
stackoverflow_0003424710_django_django_contrib_python.txt
Q: Macintosh Python: 64-bit vs 32-bit problems I'm trying to sort through a whole host of problems arising from upgrading my macintosh to 10.6. Most of the tools I need work, but a couple (scipy, wxpython) do not, and give error messages that are highly suggestive of my messing up something with 64-bit and 32-bit binaries. I'm currently running Python 2.7. I don't know whether it is a 32-bit or a 64-bit version. How do I tell? What I'm most concerned about is that I have some bizarre mixture of 32-bit and 64-bit, and that I should scrap everything and reinstall. If I do this, and I want to avoid as many build problems as possible, do I (1) install the 32-bit version, (2) install the 64-bit version and make sure everything I build is 64-bit enabled, or (3) something else. I've tried without luck to find web pages regarding this, since other people must have stumbled over these issue, but I apologize if I'm rehashing old issues here. I've also tried very hard not to type the offensive statement "I don't care about 32-bit vs 64-bit, I just want Python to work", but, in effect, that's what I'm asking here. Heaps of gratitude to whomever can help me sort through this, and apologies if I'm just being dense. A: I also had major problems upgrading, so you are not alone, only a bit late. To figure out what kind of binary you have, the file command is your friend: $ file /usr/local/bin/python /usr/local/bin/python: Mach-O universal binary with 2 architectures /usr/local/bin/python (for architecture i386): Mach-O executable i386 /usr/local/bin/python (for architecture x86_64): Mach-O 64-bit executable x86_64 You may also be advised to use MacPorts or (even better) HomeBrew. If you are already using MacPorts and nothing works anymore, you may even want to uninstall it and start from scratch with Homebrew. It gets you quickly to a point where hell is less hot. After that you only need to figure out how to compile that important esoteric library to the right architecture. A: For wxPython, try using this shebang as the first line of your script: #!/usr/bin/arch -arch i386 python2.7 Or running from the command line with arch -arch i386 python2.7 yourScript.py Basically, your python executable should include both 32-bit and 64-bit versions, and the 'arch' command tells the system which one to run with.
Macintosh Python: 64-bit vs 32-bit problems
I'm trying to sort through a whole host of problems arising from upgrading my macintosh to 10.6. Most of the tools I need work, but a couple (scipy, wxpython) do not, and give error messages that are highly suggestive of my messing up something with 64-bit and 32-bit binaries. I'm currently running Python 2.7. I don't know whether it is a 32-bit or a 64-bit version. How do I tell? What I'm most concerned about is that I have some bizarre mixture of 32-bit and 64-bit, and that I should scrap everything and reinstall. If I do this, and I want to avoid as many build problems as possible, do I (1) install the 32-bit version, (2) install the 64-bit version and make sure everything I build is 64-bit enabled, or (3) something else. I've tried without luck to find web pages regarding this, since other people must have stumbled over these issue, but I apologize if I'm rehashing old issues here. I've also tried very hard not to type the offensive statement "I don't care about 32-bit vs 64-bit, I just want Python to work", but, in effect, that's what I'm asking here. Heaps of gratitude to whomever can help me sort through this, and apologies if I'm just being dense.
[ "I also had major problems upgrading, so you are not alone, only a bit late.\nTo figure out what kind of binary you have, the file command is your friend:\n$ file /usr/local/bin/python\n/usr/local/bin/python: Mach-O universal binary with 2 architectures\n/usr/local/bin/python (for architecture i386): Mach-O execut...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004146317_python.txt
Q: write sql results to XML using python using SQL server 2005+ for over a year now, I've been running a query to return all users from the database for whom i'd like generate a report for. at the end of the query, I've added for xml auto The result of this is a link to a file where the xml lives (one row, one column). I then take this file and pass it through some xslt and am left with the final xml that a java program I created nearly two years ago can parse. What i'd like to do is skip the whole middle part and simply automate this all with python. Run the query, put the results into xml format and then either use the xslt or simply format the xml that's returned into the format that I need for the application. I've searched far and wide on the internet but I'm afraid I'm not sure enough of the technologies available to find just what I'm looking for. Any help in directing me to an answer would be greatly appreciated. A: PyODBC to talk to MS SQL Server, libxml2 to handle the XSLT, and subprocess to run your Java program.
write sql results to XML using python
using SQL server 2005+ for over a year now, I've been running a query to return all users from the database for whom i'd like generate a report for. at the end of the query, I've added for xml auto The result of this is a link to a file where the xml lives (one row, one column). I then take this file and pass it through some xslt and am left with the final xml that a java program I created nearly two years ago can parse. What i'd like to do is skip the whole middle part and simply automate this all with python. Run the query, put the results into xml format and then either use the xslt or simply format the xml that's returned into the format that I need for the application. I've searched far and wide on the internet but I'm afraid I'm not sure enough of the technologies available to find just what I'm looking for. Any help in directing me to an answer would be greatly appreciated.
[ "PyODBC to talk to MS SQL Server, libxml2 to handle the XSLT, and subprocess to run your Java program.\n" ]
[ 2 ]
[]
[]
[ "python", "sql_server_2005", "xml" ]
stackoverflow_0004147865_python_sql_server_2005_xml.txt
Q: is there a more efficient way to write results from a query in python? This is effectively how i'm using _mssql. Everything works fine, even after i use fetch_array(). The problem is, when I iterate through fetch_array(), it takes over ten minutes for 6K rows to be written to the body of an email. This just isn't acceptable. Is there a better way for me to do this? EDIT: haven't figured out the best way to copy python code here but here is the crappily formatted code used. code for writing the email body: results=mssql.fetch_array() mssql.close() resultTuple = results[0] if resultTuple[1] == 0: emailBody = 'Zero Rows returned' if test or resultTuple[1] != 0: i = 0 columnTuples = resultTuple[0] listOfRows = resultTuple[2] columns = [] emailBody = '' if test: print 'looping results' while i < len(columnTuples): columns.append(columnTuples[i][0]) emailBody = emailBody + columns[i].center(20) + '\t' i = i + 1 emailBody = emailBody + '\n' for rowTuple in listOfRows: #row loop for x in range(0, len(rowTuple)): #field loop emailBody = emailBody + str(rowTuple[x]).center(20) + '\t' if test: print x emailBody = emailBody + '\n' A: Could you show us some code of iterating through the results and creating an email? If I had to make a wild guess, I would say you are probably violating this idiom: "Build strings as a list and use ''.join at the end." If you keep adding to a string as you go you create a new (and progressively larger) string on each iteration, which runs in quadratic time. (Turned this comment into an answer at the request of the OP. Will edit to more complete answer as needed.) Edit: Ok, my guess was correct. You'll want something like this: email_lines = [] for row in result: line = do_something_with(row) email_lines.append(line) email_body = '\n'.join*(email_lines)
is there a more efficient way to write results from a query in python?
This is effectively how i'm using _mssql. Everything works fine, even after i use fetch_array(). The problem is, when I iterate through fetch_array(), it takes over ten minutes for 6K rows to be written to the body of an email. This just isn't acceptable. Is there a better way for me to do this? EDIT: haven't figured out the best way to copy python code here but here is the crappily formatted code used. code for writing the email body: results=mssql.fetch_array() mssql.close() resultTuple = results[0] if resultTuple[1] == 0: emailBody = 'Zero Rows returned' if test or resultTuple[1] != 0: i = 0 columnTuples = resultTuple[0] listOfRows = resultTuple[2] columns = [] emailBody = '' if test: print 'looping results' while i < len(columnTuples): columns.append(columnTuples[i][0]) emailBody = emailBody + columns[i].center(20) + '\t' i = i + 1 emailBody = emailBody + '\n' for rowTuple in listOfRows: #row loop for x in range(0, len(rowTuple)): #field loop emailBody = emailBody + str(rowTuple[x]).center(20) + '\t' if test: print x emailBody = emailBody + '\n'
[ "Could you show us some code of iterating through the results and creating an email? If I had to make a wild guess, I would say you are probably violating this idiom: \"Build strings as a list and use ''.join at the end.\" If you keep adding to a string as you go you create a new (and progressively larger) string o...
[ 1 ]
[]
[]
[ "python", "sql_server_2005" ]
stackoverflow_0004147901_python_sql_server_2005.txt
Q: Using python to generate XML from SQL tables I have some XML as follows: <dd> <persson> <name>sam</name> <tel>9748</tel> </persson> <cat> <name>frank</name> </cat> </dd> I parsed it into two SQL tables, one for the tags and one for the pcdata. The start and stop columns represent the position the tag appears at and ends. Tags: start | stop | tag -------+------+-------- 3 | 5 | name 6 | 8 | tel 2 | 9 | persson 11 | 13 | name 10 | 14 | cat 1 | 15 | dd (6 rows) Pcdata: pos | pcdata -----+-------- 4 | sam 7 | 9748 12 | frank (3 rows) Now i'd like to parse this database back into XML in the original form. I want to write a function that takes both tables and writes the XML out in a file. I'm using python and psycopg2 to do this. A: H'mmm having decoded your "columns": <dd><persson><name>sam</name><tel>9748</tel></persson> 1 2 3 4 5 6 7 8 9 <cat><name>frank</name></cat></dd> 10 11 12 13 14 15 I have some questions for you: How did you do that? Why did you do that? Exactly what do you want to achieve? Note that your question title is rather misleading -- "SQL tables" are merely where you have parked your peculiar representation of the data. Here's some pseudocode to do what you want to do: pieces = [] result = cursor.execute("select * from tags;") for start, step, tag in result: pieces.append((start, "<" + tag + ">")) pieces.append((stop, "</" + tag + ">")) result = cursor.execute("select * from pcdata;") for pos, pcdata in result: pieces.append((pos, pcdata)) pieces.sort() xml_stream = "".join(piece[1] for piece in pieces) your_file_object.write(xml_stream) In answer to the question about whether the above would put the "positions" in the output stream: No it won't; the following snippet shows it working. The positions are used only to get the soup sorted into the correct order. In the "join", piece[0] refers to the position, but it isn't used, only piece[1] which is the required text. >>> pieces [(3, '<name>'), (4, 'sam'), (5, '</name>')] >>> ''.join(piece[1] for piece in pieces) '<name>sam</name>' Relenting on the SQL comment-question: Although shown with SQLite, this is bog-standard SQL. If your database doesn't grok || as the concatenation operator, try +. Question that you forgot to ask: "How do I get a <?xml blah-blah ?> thingie up the front?". Answer: See below. console-prompt>sqlite3 SQLite version 3.6.14 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> create table tags (start int, stop int, tag text); sqlite> insert into tags values(3,5,'name'); sqlite> insert into tags values(6,8,'tel'); sqlite> insert into tags values(2,9,'persson'); sqlite> insert into tags values(11,13,'name'); sqlite> insert into tags values(10,14,'cat'); sqlite> insert into tags values(1,15,'dd'); sqlite> create table pcdata (pos int, pcdata text); sqlite> insert into pcdata values(4,'sam'); sqlite> insert into pcdata values(7,'9748'); sqlite> insert into pcdata values(12,'frank'); sqlite> select datum from ( ...> select 0 as posn, '<?xml version="1.0" encoding="UTF-8"?>' as datum ...> union ...> select start as posn, '<' || tag || '>' as datum from tags ...> union ...> select stop as posn, '</' || tag || '>' as datum from tags ...> union ...> select pos as posn, pcdata as datum from pcdata ...> ) ...> order by posn; <?xml version="1.0" encoding="UTF-8"?> <dd> <persson> <name> sam </name> <tel> 9748 </tel> </persson> <cat> <name> frank </name> </cat> </dd> sqlite> A: The simple answer is don't. If you are using Postgres 8.3 or above, build the XML using SQL. It will be much easier. http://www.postgresql.org/docs/current/static/functions-xml.html A: First off, if Postgres includes mechanisms to create XML for you, use them. Second off, don't use string manipulation to create XML unless you really know what you're doing. And even then, don't. Just concatenating string values from your database will produce poorly-formed XML if any column contains an ampersand, for instance. Unless you will be processing too much data to fit in memory, use John Machin's approach to parse the data into elements and lxml.etree to create the actual XML elements.
Using python to generate XML from SQL tables
I have some XML as follows: <dd> <persson> <name>sam</name> <tel>9748</tel> </persson> <cat> <name>frank</name> </cat> </dd> I parsed it into two SQL tables, one for the tags and one for the pcdata. The start and stop columns represent the position the tag appears at and ends. Tags: start | stop | tag -------+------+-------- 3 | 5 | name 6 | 8 | tel 2 | 9 | persson 11 | 13 | name 10 | 14 | cat 1 | 15 | dd (6 rows) Pcdata: pos | pcdata -----+-------- 4 | sam 7 | 9748 12 | frank (3 rows) Now i'd like to parse this database back into XML in the original form. I want to write a function that takes both tables and writes the XML out in a file. I'm using python and psycopg2 to do this.
[ "H'mmm having decoded your \"columns\":\n<dd><persson><name>sam</name><tel>9748</tel></persson>\n1 2 3 4 5 6 7 8 9 \n<cat><name>frank</name></cat></dd>\n10 11 12 13 14 15\n\nI have some questions for you: How did you do that? Why did you do that? Exactly ...
[ 3, 1, 1 ]
[]
[]
[ "postgresql", "python", "sql", "xml" ]
stackoverflow_0004139959_postgresql_python_sql_xml.txt