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: My implementation of Bresenham's algorithm fails for lines at certain angles I've written an implementation of Bresenham's algorithm in Python (following the Wikipedia article), and it works correctly except for lines at certain angles. All lines that should extend between 45 and 90 degrees, or between 135 and 270 degrees, will instead extend along the line y = x. Here's my code: def bresenham(origin, dest): # debug code print origin print dest # end debug code x0 = origin[0]; y0 = origin[1] x1 = dest[0]; y1 = dest[1] steep = abs(y1 - y0) > abs(x1 - x0) backward = x0 > x1 if steep: x0, y0 = y0, x0 x1, y1 = y1, x1 if backward: x0, x1 = x1, x0 y0, y1 = y1, y0 dx = x1 - x0 dy = abs(y1 - y0) error = dx / 2 y = y0 if y0 < y1: ystep = 1 else: ystep = -1 result = [] #if x0 > x1: xstep = -1 #else: xstep = 1 # debug code print "x0 = %d" % (x0) print "x1 = %d" % (x1) print "y0 = %d" % (y0) print "y1 = %d" % (y1) for x in range(x0, x1): if steep: result.append((y,x)) else: result.append((x,y)) error -= dy if error < 0: y += ystep error += dx # ensure the line extends from the starting point to the destination # and not vice-versa if backward: result.reverse() print result return result Anyone see what I'm screwing up? EDIT: I added some printing code to the function. (0,0) is at the top left of the display. My test framework is pretty simple. It's a standalone function, so I just pass two points to it: origin = (416, 384) dest = (440, 347) bresenham(origin, dest) (416, 384) (440, 347) x0 = 384 x1 = 347 y0 = 416 y1 = 440 [] A: I don't know why you're using an xstep variable. You don't really need one with the algorithm you're using. @Gabe: xstep is needed because without it, if x0 > x1, then the for loop will terminate immediately, as the default step for a Python for loop is 1. The reason you don't need an xstep variable is because, if it's going backwards, the coordinates were already switched (in the if backward: conditional at the beginning) so that the end-point is now the start-point and vice-versa, such that we now are still going left-to-right. You just need this: result = [] for x in range(x0, x1): if steep: result.append((y, x)) else: result.append((x, y)) error -= dy if error < 0: y += ystep error += dx return result If you want the list of coordinates in order from start to end-point, then you can do the check at the end: if backward: return result.reverse() else: return result EDIT: The problem is that the backward boolean is being evaluated before it needs to be. If the steep conditional executes, then the values change, but by then your backward conditional is different. To fix this, instead of using a backward boolean, make it an explicit expression: if x0 > x1: # swapping here Then again, since you end up using the boolean later on, you could just define it before the conditional: backward = x0 > x1 if backward: A: The problem is that you are computing x0 > x1 before you swap x and y. Instead of: backward = x0 > x1 if steep: x0, y0 = y0, x0 x1, y1 = y1, x1 if backward: x0, x1 = x1, x0 y0, y1 = y1, y0 You should have: if steep: x0, y0 = y0, x0 x1, y1 = y1, x1 backward = x0 > x1 if backward: x0, x1 = x1, x0 y0, y1 = y1, y0
My implementation of Bresenham's algorithm fails for lines at certain angles
I've written an implementation of Bresenham's algorithm in Python (following the Wikipedia article), and it works correctly except for lines at certain angles. All lines that should extend between 45 and 90 degrees, or between 135 and 270 degrees, will instead extend along the line y = x. Here's my code: def bresenham(origin, dest): # debug code print origin print dest # end debug code x0 = origin[0]; y0 = origin[1] x1 = dest[0]; y1 = dest[1] steep = abs(y1 - y0) > abs(x1 - x0) backward = x0 > x1 if steep: x0, y0 = y0, x0 x1, y1 = y1, x1 if backward: x0, x1 = x1, x0 y0, y1 = y1, y0 dx = x1 - x0 dy = abs(y1 - y0) error = dx / 2 y = y0 if y0 < y1: ystep = 1 else: ystep = -1 result = [] #if x0 > x1: xstep = -1 #else: xstep = 1 # debug code print "x0 = %d" % (x0) print "x1 = %d" % (x1) print "y0 = %d" % (y0) print "y1 = %d" % (y1) for x in range(x0, x1): if steep: result.append((y,x)) else: result.append((x,y)) error -= dy if error < 0: y += ystep error += dx # ensure the line extends from the starting point to the destination # and not vice-versa if backward: result.reverse() print result return result Anyone see what I'm screwing up? EDIT: I added some printing code to the function. (0,0) is at the top left of the display. My test framework is pretty simple. It's a standalone function, so I just pass two points to it: origin = (416, 384) dest = (440, 347) bresenham(origin, dest) (416, 384) (440, 347) x0 = 384 x1 = 347 y0 = 416 y1 = 440 []
[ "I don't know why you're using an xstep variable. You don't really need one with the algorithm you're using.\n\n@Gabe: xstep is needed because without it, if x0 > x1, then the for loop will terminate immediately, as the default step for a Python for loop is 1.\n\nThe reason you don't need an xstep variable is becau...
[ 4, 4 ]
[]
[]
[ "bresenham", "python" ]
stackoverflow_0003713821_bresenham_python.txt
Q: Handling file reading and multiple values to a key in dictionary How can I code to read the first line from a file and put it as a key value of a dictionary and keep reading next values in a iterative manner and put them as the values to the particular key they fall into in the file. Like example: Item Quality Cost Place Ball 1 $12 TX Umbrella 5 $35 NY sweater 89 $100 LA So here, the representation is my file. When I read, I want the dictionary to be created as in the things in bold go as keys and when i keep reading lines below that, I would have them going as multiple values in the respective keys. thanks A: Looks like you are describing a csv file with a space delimiter. Something like this should work (from the Python help). >>> import csv >>> spamReader = csv.reader(open('eggs.csv', 'rb'), delimiter=' ', quotechar='|') >>> for row in spamReader: ... print ', '.join(row) Spam, Spam, Spam, Spam, Spam, Baked Beans Spam, Lovely Spam, Wonderful Spam In fact, the csv.DictReader would be better in order to have each row as a dictionary with keys defined by the first row. I am assuming that there is a newline inserted after each group of values. Edit: Using the example above, we get: In [1]: import csv In [2]: f = csv.DictReader(open('test.txt', 'r'), delimiter = ' ', skipinitialspace = True) In [3]: for row in f: print row {'Item': 'Ball', 'Cost': '$12', 'Quality': '1', 'Place': 'TX'} {'Item': 'Umbrella', 'Cost': '$35', 'Quality': '5', 'Place': 'NY'} {'Item': 'sweater', 'Cost': '$100', 'Quality': '89', 'Place': 'LA'} Passing the parameter skipinitialspace = True to the DictReader is needed to be able to get rid of multiple spaces without creating spurious entries in each row. A: You can't have "multiple values" for a given key, but you can of course have one value per key that's a list. For example (Python 2.6 or better -- simply because I use the next function for generality rather than methods such as readline, but you can of course tweak that!): def makedictwithlists(f): keys = next(f).split() d = {} for k in keys: d[k] = [] for line in f: for k, v in zip(keys, line.split()): d[k].append(v) return d
Handling file reading and multiple values to a key in dictionary
How can I code to read the first line from a file and put it as a key value of a dictionary and keep reading next values in a iterative manner and put them as the values to the particular key they fall into in the file. Like example: Item Quality Cost Place Ball 1 $12 TX Umbrella 5 $35 NY sweater 89 $100 LA So here, the representation is my file. When I read, I want the dictionary to be created as in the things in bold go as keys and when i keep reading lines below that, I would have them going as multiple values in the respective keys. thanks
[ "Looks like you are describing a csv file with a space delimiter. Something like this should work (from the Python help).\n>>> import csv\n>>> spamReader = csv.reader(open('eggs.csv', 'rb'), delimiter=' ', quotechar='|')\n>>> for row in spamReader:\n... print ', '.join(row)\nSpam, Spam, Spam, Spam, Spam, Baked ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003714067_python.txt
Q: Two Tkinter Images I have written a simple GUI in Python using the Tkinter library. This GUI has to display 2 images, one on top and one on the bottom. When I place the two images on the window, there seems to be a white line between the two. How to I place them so this doesn't show up? I am programming on Windows 7 with Python 2.6 A: I set border=0 and it seemed to eliminate the gap between the two stacked images. panel1 = Label(root, border=0, image=p) panel2 = Label(root, border=0, image=p)
Two Tkinter Images
I have written a simple GUI in Python using the Tkinter library. This GUI has to display 2 images, one on top and one on the bottom. When I place the two images on the window, there seems to be a white line between the two. How to I place them so this doesn't show up? I am programming on Windows 7 with Python 2.6
[ "I set border=0 and it seemed to eliminate the gap between the two stacked images.\n\npanel1 = Label(root, border=0, image=p)\npanel2 = Label(root, border=0, image=p)\n\n" ]
[ 1 ]
[]
[]
[ "image", "python", "tkinter", "user_interface", "windows_7" ]
stackoverflow_0003713499_image_python_tkinter_user_interface_windows_7.txt
Q: Python: spawn or thread for long running background process? I am planning to make a long running background process with Python but I am still unsure whether to use os.spawnle or thread. I've only read about it therefore I have not much experience with either spawn or thread. Is there any rule of thumb when to use which? Thanks heaps A: Be sure that you take the Global Interpreter Lock into account. If the long running process is CPU intensive, you should probably make it an independent process. If on the other hand, it's going to spend a lot of time blocking, then the GIL isn't really that big of a deal and you should be fine to make it a thread. Also, if you don't need something in particular that os.spawnle provides, consider using the multiprocessing package from the standard library. It provides an interface similar to that of the threading package and is altogether easier to use than mucking around with manually spawning and tracking processes. A: The obvious difference is that os.spawnle is used to start another process running a different program, whereas a thread would be executing code that's part of the same program. In fact, if your background process is some other program that already exists, then os.spawnle (or some other means of creating a separate process) is your only option; two threads in a program have to be running the same program. If you wondering whether you should structure your own code to be run as separate processes or as separate threads, then take a look at some of the process v. thread questions like this one to decide which better fits what you're trying to do. In particular, consider what resources the processes/threads will need to share, what they will communicate with each other, and how robust each needs to be -- a thread that crashes will bring the rest of the process down with it, for example.
Python: spawn or thread for long running background process?
I am planning to make a long running background process with Python but I am still unsure whether to use os.spawnle or thread. I've only read about it therefore I have not much experience with either spawn or thread. Is there any rule of thumb when to use which? Thanks heaps
[ "Be sure that you take the Global Interpreter Lock into account. If the long running process is CPU intensive, you should probably make it an independent process. If on the other hand, it's going to spend a lot of time blocking, then the GIL isn't really that big of a deal and you should be fine to make it a thread...
[ 4, 2 ]
[]
[]
[ "background_process", "python", "spawn" ]
stackoverflow_0003713429_background_process_python_spawn.txt
Q: What to use for Python string.find? The documentation for Python 2.7 lists string.find as a deprecated function but does not (unlike atoi and atol) provide an alternative. I'm coding in 2.7 at the moment so I'm happy to use it but I would like to know: what is it going to be replaced with? is that usable in 2.7 (if so, I'll use it now so as to avoid recoding later)? A: A lot of methods in string have been replaced by the str class. Here is str.find. A: Almost the entire string module has been moved to the str type as method functions. Why are you using the string module, when almost everything you need is already part of the string type? http://docs.python.org/library/stdtypes.html#str.find The string type -- and it's methods -- is not deprecated. Indeed, it will me morphed to include Unicode in Python 3.
What to use for Python string.find?
The documentation for Python 2.7 lists string.find as a deprecated function but does not (unlike atoi and atol) provide an alternative. I'm coding in 2.7 at the moment so I'm happy to use it but I would like to know: what is it going to be replaced with? is that usable in 2.7 (if so, I'll use it now so as to avoid recoding later)?
[ "A lot of methods in string have been replaced by the str class. Here is str.find.\n", "Almost the entire string module has been moved to the str type as method functions.\nWhy are you using the string module, when almost everything you need is already part of the string type?\nhttp://docs.python.org/library/std...
[ 6, 6 ]
[]
[]
[ "deprecated", "find", "python", "string" ]
stackoverflow_0003714276_deprecated_find_python_string.txt
Q: How to inspect mystery deserialized object in Python I'm trying to load JSON back into an object. The "loads" method seems to work without error, but the object doesn't seem to have the properties I expect. How can I go about examining/inspecting the object that I have (this is web-based code). results = {"Subscriber": {"firstname": "Neal", "lastname": "Walters"}} subscriber = json.loads(results) for item in inspect.getmembers(subscriber): self.response.out.write("<BR>Item") for subitem in item: self.response.out.write("<BR>&nbsp;SubItem=" + subitem) The attempt above returned this: Item SubItem=__class__ I don't think it matters, but for context: The JSON is actually coming from a urlfetch in Google App Engine to a rest web service created using this utility: http://code.google.com/p/appengine-rest-server. The data is being retrieved from a datastore with this definition: class Subscriber(db.Model): firstname = db.StringProperty() lastname = db.StringProperty() Thanks, Neal Update #1: Basically I'm trying to deserialize JSON back into an object. In theory it was serialized from an object, and I want to now get it back into an object. Maybe the better question is how to do that? Update #2: I was trying to abstract a complex program down to a few lines of code, so I made a few mistakes in "pseudo-coding" it for purposes of posting here. Here's a better code sample, now take out of website where I can run on PC. results = '{"Subscriber": {"firstname": "Neal", "lastname": "Walters"}}' subscriber = json.loads(results) for key, value in subscriber.items(): print " %s: %s" %(key, value) The above runs, what it displays doesn't look any more structured than the JSON string itself. It displays this: Subscriber: {u'lastname': u'Walters', u'firstname': u'Neal'} I have more of a Microsoft background, so when I hear serialize/deserialize, I think going from an object to a string, and from a string back to an object. So if I serialize to JSON, and then deserialize, what do I get, a dictionary, a list, or an object? Actually, I'm getting the JSON from a REST webmethod, that is on my behalf serializing my object for me. Ideally I want a subscriber object that matches my Subscriber class above, and ideally, I don't want to write one-off custom code (i.e. code that would be specific to "Subscriber"), because I would like to do the same thing with dozens of other classes. If I have to write some custom code, I will need to do it generically so it will work with any class. Update #3: This is to explain more of why I think this is a needed tool. I'm writing a huge app, probably on Google App Engine (GAE). We are leaning toward a REST architecture for several reasons, but one is that our web GUI should access the data store via a REST web layer. (I'm a lot more used to SOAP, so switching to REST is a small challenge in itself). So one of the classic ways of getting and update data is through a business or data tier. By using the REST utility mention above, I have the choice of XML or JSON. I'm hoping to do a small working prototype of both before we develop the huge app). Then, suppose we have a successful app, and GAE doubles it prices. Then we can rewrite just the data tier, and take our Python/Django user tier (web code), and run it on Amazon or somewhere else. If I'm going to do all that, why would I want everything to be dictionary objects. Wouldn't I want the power of full-blown class structure? One of the next tricks is sort of an object relational mapping (ORM) so that we don't necessarily expose our exact data tables, but more of a logical layer. We also want to expose a RESTful API to paying users, who might be using any language. For them, they can use XML or JSON, and they wouldn't use the serialize routine discussed here. A: json only encodes strings, floats, integers, javascript objects (python dicts) and lists. You have to create a function to turn the returned dictionary into a class and then pass it to a json.loads using the object_hook keyword argument along with the json string. Heres some code that fleshes it out: import json class Subscriber(object): firstname = None lastname = None class Post(object): author = None title = None def decode_from_dict(cls,vals): obj = cls() for key, val in vals.items(): setattr(obj, key, val) return obj SERIALIZABLE_CLASSES = {'Subscriber': Subscriber, 'Post': Post} def decode_object(d): for field in d: if field in SERIALIZABLE_CLASSES: cls = SERIALIZABLE_CLASSES[field] return decode_from_dict(cls, d[field]) return d results = '''[{"Subscriber": {"firstname": "Neal", "lastname": "Walters"}}, {"Post": {"author": {"Subscriber": {"firstname": "Neal", "lastname": "Walters"}}}, "title": "Decoding JSON Objects"}]''' result = json.loads(results, object_hook=decode_object) print result print result[1].author This will handle any class that can be instantiated without arguments to the constructor and for which setattr will work. Also, this uses json. I have no experience with simplejson so YMMV but I hear that they are identical. Note that although the values for the two subscriber objects are identical, the resulting objects are not. This could be fixed by memoizing the decode_from_dict class. A: results in your snippet is a dict, not a string, so the json.loads would raise an exception. If that is fixed, each subitem in the inner loop is then a tuple, so trying to add it to a string as you are doing would raise another exception. I guess you've simplified your code, but the two type errors should already show that you simplified it too much (and incorrectly). Why not use an (equally simplified) working snippet, and the actual string you want to json.loads instead of one that can't possibly reproduce your problem? That course of action would make it much easier to help you. Beyyond peering at the actual string, and showing some obvious information such as type(subscriber), it's hard to offer much more help based on that clearly-broken code and such insufficient information:-(. Edit: in "update2", the OP says It displays this: Subscriber: {u'lastname': u'Walters', u'firstname': u'Neal'} ...and what else could it possibly display, pray?! You're printing the key as string, then the value as string -- the key is a string, and the value is another dict, so of course it's "stringified" (and all strings in JSON are Unicode -- just like in C# or Java, and you say you come from a MSFT background, so why does this surprise you at all?!). str(somedict), identically to repr(somedict), shows the repr of keys and values (with braces around it all and colons and commas as appropriate separators). JSON, a completely language-independent serialization format though originally centered on Javascript, has absolutely no idea of what classes (if any) you expect to see instances of (of course it doesn't, and it's just absurd to think it possibly could: how could it possibly be language-independent if it hard-coded the very concept of "class", a concept which so many languages, including Javascript, don't even have?!) -- so it uses (in Python terms) strings, numbers, lists, and dicts (four very basic data types that any semi-decent modern language can be expected to have, at least in some library if not embedded in the language proper!). When you json.loads a string, you'll always get some nested combination of the four datatypes above (all strings will be unicode and all numbers will be floats, BTW;-). If you have no idea (and don't want to encode by some arbitrary convention or other) what class's instances are being serialized, but absolutely must have class instances back (not just dicts etc) when you deserialize, JSON per se can't help you -- that metainformation cannot possibly be present in the JSON-serialized string itself. If you're OK with the four fundamental types, and just want to see some printed results that you consider "prettier" than the default Python string printing of the fundamental types in question, you'll have to code your own recursive pretty-printing function depending on your subjective definition of "pretty" (I doubt you'd like Python's own pprint standard library module any more than you like your current results;-). A: My guess is that loads is returning a dictionary. To iterate over its content, use something like: for key, value in subscriber.items(): self.response.out.write("%s: %s" %(key, value))
How to inspect mystery deserialized object in Python
I'm trying to load JSON back into an object. The "loads" method seems to work without error, but the object doesn't seem to have the properties I expect. How can I go about examining/inspecting the object that I have (this is web-based code). results = {"Subscriber": {"firstname": "Neal", "lastname": "Walters"}} subscriber = json.loads(results) for item in inspect.getmembers(subscriber): self.response.out.write("<BR>Item") for subitem in item: self.response.out.write("<BR>&nbsp;SubItem=" + subitem) The attempt above returned this: Item SubItem=__class__ I don't think it matters, but for context: The JSON is actually coming from a urlfetch in Google App Engine to a rest web service created using this utility: http://code.google.com/p/appengine-rest-server. The data is being retrieved from a datastore with this definition: class Subscriber(db.Model): firstname = db.StringProperty() lastname = db.StringProperty() Thanks, Neal Update #1: Basically I'm trying to deserialize JSON back into an object. In theory it was serialized from an object, and I want to now get it back into an object. Maybe the better question is how to do that? Update #2: I was trying to abstract a complex program down to a few lines of code, so I made a few mistakes in "pseudo-coding" it for purposes of posting here. Here's a better code sample, now take out of website where I can run on PC. results = '{"Subscriber": {"firstname": "Neal", "lastname": "Walters"}}' subscriber = json.loads(results) for key, value in subscriber.items(): print " %s: %s" %(key, value) The above runs, what it displays doesn't look any more structured than the JSON string itself. It displays this: Subscriber: {u'lastname': u'Walters', u'firstname': u'Neal'} I have more of a Microsoft background, so when I hear serialize/deserialize, I think going from an object to a string, and from a string back to an object. So if I serialize to JSON, and then deserialize, what do I get, a dictionary, a list, or an object? Actually, I'm getting the JSON from a REST webmethod, that is on my behalf serializing my object for me. Ideally I want a subscriber object that matches my Subscriber class above, and ideally, I don't want to write one-off custom code (i.e. code that would be specific to "Subscriber"), because I would like to do the same thing with dozens of other classes. If I have to write some custom code, I will need to do it generically so it will work with any class. Update #3: This is to explain more of why I think this is a needed tool. I'm writing a huge app, probably on Google App Engine (GAE). We are leaning toward a REST architecture for several reasons, but one is that our web GUI should access the data store via a REST web layer. (I'm a lot more used to SOAP, so switching to REST is a small challenge in itself). So one of the classic ways of getting and update data is through a business or data tier. By using the REST utility mention above, I have the choice of XML or JSON. I'm hoping to do a small working prototype of both before we develop the huge app). Then, suppose we have a successful app, and GAE doubles it prices. Then we can rewrite just the data tier, and take our Python/Django user tier (web code), and run it on Amazon or somewhere else. If I'm going to do all that, why would I want everything to be dictionary objects. Wouldn't I want the power of full-blown class structure? One of the next tricks is sort of an object relational mapping (ORM) so that we don't necessarily expose our exact data tables, but more of a logical layer. We also want to expose a RESTful API to paying users, who might be using any language. For them, they can use XML or JSON, and they wouldn't use the serialize routine discussed here.
[ "json only encodes strings, floats, integers, javascript objects (python dicts) and lists.\nYou have to create a function to turn the returned dictionary into a class and then pass it to a json.loads using the object_hook keyword argument along with the json string. Heres some code that fleshes it out:\nimport json...
[ 4, 3, 0 ]
[]
[]
[ "google_app_engine", "inspection", "json", "python" ]
stackoverflow_0003706208_google_app_engine_inspection_json_python.txt
Q: Python, trying to instantiate class imported using __import__, getting ''module' object is not callable' I've been researching how to do this and I can't figure out what I am doing wrong, I want to use import to import a class and then instantiate it and am doing it as so: the class, from a file called "action_1", I have already imported / appended the path to this) class Action_1 (): def __init__ (self): pass how I am trying to import then instantiate it imprtd_class = __import__('action_1', globals(), locals(), ['Action_1'], -1) #instantiate the imported class: inst_imprtd_class = imprtd_class() >>>> 'module' object is not callable A: __import__ returns the module, not anything specified in the fromlist. Check out the __import__ docs and see the example below. >>> a1module = __import__('action_1', fromlist=['Action_1']) >>> action1 = a1module.Action_1() >>> print action1 <action_1.Action_1 instance at 0xb77b8a0c> Note, the fromlist is not required in the above case, but if the action_1 module was within a package (e.g. mystuff.action_1) it is required. See the __import__ docs for more info.
Python, trying to instantiate class imported using __import__, getting ''module' object is not callable'
I've been researching how to do this and I can't figure out what I am doing wrong, I want to use import to import a class and then instantiate it and am doing it as so: the class, from a file called "action_1", I have already imported / appended the path to this) class Action_1 (): def __init__ (self): pass how I am trying to import then instantiate it imprtd_class = __import__('action_1', globals(), locals(), ['Action_1'], -1) #instantiate the imported class: inst_imprtd_class = imprtd_class() >>>> 'module' object is not callable
[ "__import__ returns the module, not anything specified in the fromlist. Check out the __import__ docs and see the example below.\n>>> a1module = __import__('action_1', fromlist=['Action_1'])\n>>> action1 = a1module.Action_1()\n>>> print action1\n<action_1.Action_1 instance at 0xb77b8a0c>\n\nNote, the fromlist is no...
[ 2 ]
[]
[]
[ "class", "dynamic", "import", "python" ]
stackoverflow_0003714573_class_dynamic_import_python.txt
Q: can a django application be run using paster? can a django application be run using paster? Or is it pylons specific? A: It's pylons specific. There was a Django Paste project, but I'm not sure if it's active or how much progress was ever made.
can a django application be run using paster?
can a django application be run using paster? Or is it pylons specific?
[ "It's pylons specific. There was a Django Paste project, but I'm not sure if it's active or how much progress was ever made.\n" ]
[ 1 ]
[]
[]
[ "django", "pylons", "python" ]
stackoverflow_0003714373_django_pylons_python.txt
Q: which language (python/perl/tcl) on linux doesn't need to install the third-party libs? When deploy java app on linux, we don't need to install anything, all third-party libs are jar files and we only update classpath in script file. But java needs jre which is quite large. So is there any other language supported by linux can do that? By default our server only support perl/python/tcl, no gcc available, sigh. A: Perl 5 has PAR and PAR::Packer. PAR is conceptually similar to a JAR file (it is a zip file of one or more modules). PAR::Packer takes it one step further: it bundles every you need to run a program into one executable file. PAR::Packer executables don't even need Perl 5 installed on the target system. A: perl, python and tcl can run 3rd party libs without installing them pick which ever you are most comfortable with tcl has starkits and starpacks perl is covered in another answer python appears to have eggs and freeze (and py2exe for windows) A: Tcl applications can be wrapped into a single-file executable with all dependencies included. I have used these for several applications. You can produce single-file executables for Linux, Windows and OSX. From http://www.equi4.com/starkit/ : A Starkit is a wrapping mechanism for delivering an application in a self-contained, installation-free, and highly portable way. The name comes from being based on a StandAlone Runtime, called Tclkit. A Starkit creates the illusion of a "file system in a file" - on the outside, it's a single file, yet the application code continues to see a complete directory of scripts, extensions, packages, images, and whatever other files it needs. Starkits can be multi-platform. And they can be written to, due to the underlying Metakit database. A: On Linux you should use the distribution's native package format (DEB, RPM, …) to deploy applications. The package managers included in the distributions can handle dependencies automatically. Apart from that, I think Perl is the only language that is available in most Linux systems out of the box. Python is very popular, too, but probably not as ubiquitous. A: Stumbled upon this yesterday: http://code.activestate.com/recipes/497000-build-a-compressed-self-extracting-executable-scri/ The page shows how to turn a zip file containing python scripts into an executable very easily.
which language (python/perl/tcl) on linux doesn't need to install the third-party libs?
When deploy java app on linux, we don't need to install anything, all third-party libs are jar files and we only update classpath in script file. But java needs jre which is quite large. So is there any other language supported by linux can do that? By default our server only support perl/python/tcl, no gcc available, sigh.
[ "Perl 5 has PAR and PAR::Packer. PAR is conceptually similar to a JAR file (it is a zip file of one or more modules). PAR::Packer takes it one step further: it bundles every you need to run a program into one executable file. PAR::Packer executables don't even need Perl 5 installed on the target system.\n", "p...
[ 10, 4, 3, 2, 0 ]
[]
[]
[ "java", "linux", "perl", "python", "tcl" ]
stackoverflow_0003675659_java_linux_perl_python_tcl.txt
Q: Is there a way to compare two lists of dicts in python efficiently? I have two lists of dictionaries. The first list contains sphere definitions in terms of x, y, z, radius. The second list contains various points in space as x, y, z. These lists are both very long, so iterating over each list and comparing against all values is inefficient. I've been trying the map and reduce terms, but both of them take only 1 term in the filtering function. What I'm using is the following: for curNode in nodeList: for i in sphereList: tmpRad = findRadius(i, curNode) if float(tmpRad) <= float(i['radius']): print "Remove node", curNode['num'] nodeRemovalList.append(curNode['num']) break where i is the current sphere (x, y, z, rad) and curNode is the node (num, x, y, z). For large lists, this becomes very inefficient. I'd like to filter out nodes which fall within the radius of any sphere. A: try this: def in_sphere(node): return any(float(findRadius(sphere, node)) <= float(sphere['radius']) for sphere in sphereList) nodeRemovalList = filter(in_sphere, nodeList) This will run much faster than the code that you have displayed. this is assuming that you actually want the nodeRemovalList and that it isn't just an intermediate step. If it's just an intermediate step, return not any( and the result of `filter will be the set you want. Also, why isn't sphere['radius'] already a float? this would speed things up a little on a really huge list. A: You may want to look into something like spatial octrees to reduce the number of spheres you have to check each point against. A: Are you trying to detect which points fall within a sphere. Using matrix based approach in numpy may be easier since you can do a 3d distance vector for all points efficiently, let p = point (x1,y1,z1). Let A be arrays of sphere centres then distance vector arrays can be computer and compared against radius arrays in numpy. You will find matrix operations faster than iterations.
Is there a way to compare two lists of dicts in python efficiently?
I have two lists of dictionaries. The first list contains sphere definitions in terms of x, y, z, radius. The second list contains various points in space as x, y, z. These lists are both very long, so iterating over each list and comparing against all values is inefficient. I've been trying the map and reduce terms, but both of them take only 1 term in the filtering function. What I'm using is the following: for curNode in nodeList: for i in sphereList: tmpRad = findRadius(i, curNode) if float(tmpRad) <= float(i['radius']): print "Remove node", curNode['num'] nodeRemovalList.append(curNode['num']) break where i is the current sphere (x, y, z, rad) and curNode is the node (num, x, y, z). For large lists, this becomes very inefficient. I'd like to filter out nodes which fall within the radius of any sphere.
[ "try this:\ndef in_sphere(node):\n return any(float(findRadius(sphere, node)) <= float(sphere['radius']) \n for sphere in sphereList)\n\nnodeRemovalList = filter(in_sphere, nodeList)\n\nThis will run much faster than the code that you have displayed.\nthis is assuming that you actually want the nod...
[ 4, 3, 2 ]
[]
[]
[ "compare", "filter", "list", "performance", "python" ]
stackoverflow_0003715039_compare_filter_list_performance_python.txt
Q: Can stuck Python threads hinder other threads if there are no shared resources? I am considering utilizing Python to call various dlls that will perform things like accessing the LAN (on Windows) or making HTTP requests. These dlls might be poorly written and get stuck. My first question is, whether isolating these dll calls in Python threads will guarantee that the main Python thread will not get stuck? My second question is whether Python can kill a thread if the DLL gets stuck in an infinite loop? I know that I could solve this by launching the dlls in its own processes, but I would prefer to only have a single process. I could use the latest versions of Python. A: Your main thread will still be responsive if another thread is issuing a blocking call. Still, terminating a thread is never really clean and might leave a mess around. See the MSDN documentation for TerminateThread for that matter. With the introduction of the subprocess module, what are your concerns when it comes to using multiple processes?
Can stuck Python threads hinder other threads if there are no shared resources?
I am considering utilizing Python to call various dlls that will perform things like accessing the LAN (on Windows) or making HTTP requests. These dlls might be poorly written and get stuck. My first question is, whether isolating these dll calls in Python threads will guarantee that the main Python thread will not get stuck? My second question is whether Python can kill a thread if the DLL gets stuck in an infinite loop? I know that I could solve this by launching the dlls in its own processes, but I would prefer to only have a single process. I could use the latest versions of Python.
[ "Your main thread will still be responsive if another thread is issuing a blocking call. Still, terminating a thread is never really clean and might leave a mess around. See the MSDN documentation for TerminateThread for that matter.\nWith the introduction of the subprocess module, what are your concerns when it co...
[ 1 ]
[]
[]
[ "multithreading", "python", "python_3.x", "python_multithreading" ]
stackoverflow_0003716027_multithreading_python_python_3.x_python_multithreading.txt
Q: wxPython: Assigning text labels to ticks on a slider A wxPython program that I'm writing uses two sliders as part of the GUI. These sliders represent a three state switch with the states "On Full", "On Medium" and "Off". I'd like to be able to assign these labels to the ticks on the slider. Is there a way of doing this without having to subclass or position separate static text controls? Thanks, Spry A: Not built in. You'd have to create your own.
wxPython: Assigning text labels to ticks on a slider
A wxPython program that I'm writing uses two sliders as part of the GUI. These sliders represent a three state switch with the states "On Full", "On Medium" and "Off". I'd like to be able to assign these labels to the ticks on the slider. Is there a way of doing this without having to subclass or position separate static text controls? Thanks, Spry
[ "Not built in. You'd have to create your own.\n" ]
[ 1 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0003715317_python_user_interface_wxpython.txt
Q: Is python's shutil.move() atomic on linux? I am wondering whether python's shutil.move is atomic on linux ? Is the behavior different if the source and destination files are on two different partitions or is it same as when they are present on the same partition ? I am more concerned to know whether the shutil.move is atomic if the source and destination files are on the same partition ! A: It is not atomic if the files are on different filsystems. In that case, python opens the source and destination file, loops on reading from the source and writing to the desination and finally unlinks the source file. If the source and destination file are on the same file system, python uses the rename() C call, which is atomic.
Is python's shutil.move() atomic on linux?
I am wondering whether python's shutil.move is atomic on linux ? Is the behavior different if the source and destination files are on two different partitions or is it same as when they are present on the same partition ? I am more concerned to know whether the shutil.move is atomic if the source and destination files are on the same partition !
[ "It is not atomic if the files are on different filsystems. In that case, python opens the source and destination file, loops on reading from the source and writing to the desination and finally unlinks the source file.\nIf the source and destination file are on the same file system, python uses the rename() C cal...
[ 22 ]
[]
[]
[ "atomic", "file", "python", "unix" ]
stackoverflow_0003716325_atomic_file_python_unix.txt
Q: gtk: indicate a button should be pressed What's the best way to indicate on a GTK interface that a button should be pressed / to "highlight" the button? The use case is that I have a set of checkboxes representing various settings, but for them to take effect, they must be submitted to a server. I want to indicate that the currently checked settings have not been sent to the server, by, for example, highlighting the Submit button to be red. I tried messing with the button style to change its color conditionally, but I ran into problems there. A: Perhaps you could disable the button (so that it "greyed out") until all the checkboxes have been set or whatever... This is quite a common approach. A: You could set the button's label to be bold when there are changes to be submitted: button.get_child().set_markup('<b>Submit</b>')
gtk: indicate a button should be pressed
What's the best way to indicate on a GTK interface that a button should be pressed / to "highlight" the button? The use case is that I have a set of checkboxes representing various settings, but for them to take effect, they must be submitted to a server. I want to indicate that the currently checked settings have not been sent to the server, by, for example, highlighting the Submit button to be red. I tried messing with the button style to change its color conditionally, but I ran into problems there.
[ "Perhaps you could disable the button (so that it \"greyed out\") until all the checkboxes have been set or whatever... This is quite a common approach.\n", "You could set the button's label to be bold when there are changes to be submitted:\nbutton.get_child().set_markup('<b>Submit</b>')\n\n" ]
[ 4, 1 ]
[]
[]
[ "coding_style", "gtk", "python", "user_interface" ]
stackoverflow_0003711300_coding_style_gtk_python_user_interface.txt
Q: Python: safe to read values from an object in a thread? I have a Python/wxPython program where the GUI is the main thread and I use another thread to load data from a file. Sometimes the files are big and slow to load so I use a wxPulse dialog to indicate progress. As I load the file, I count the number of lines that have been read in the counting thread, and I display this count in the wxPulse dialog in the main thread. I get the count in the main thread by reading the same variable that is being written to by the loading thread. Is this "thread safe"? Could this somehow cause problems? I've been doing it for awhile and it has been fine so far. PS. I know I could use a queue to transfer the count, but I'm lazy and don't want to if I don't have to. A: Generally as long as... You only have one thread writing to it, and... It's not important that the count be kept precisely in sync with the displayed value... it's fine. A: In normal python this will be safe as all access to variables are protected by the GIL(Global Interpreter Lock) this means that all access to a variable are syncronised so only one thread can do this at a time. The only issue is as @Eloff noted if you need to read more than one value and need them to be consistent - you will need to design in some control of access in this case. A: This is fine because you have only one writer thread. Read only operations are always thread-safe. The exception to this arises when you are reading more than one related value and expecting some form of consistency between them. Since writes can happen at any time, reads of multiple values may not be consistent and indeed may not even have any sensible program state at all. In this case, locks are used to make the multiple reads appear to happen as a single atomic operation exclusive to any writes. A: It's quite safe. When the count increases from n to n+1 the "n+1 object" is created and then count is switched from referring to the "n object" to the new "n+1 object". There is no stage that count is referring to something other than the "n object" or the "n+1 object" A: It's safe only because it's not especially critical. Weird things like the value not updating when it should won't matter. It is very hard to get a definitive answer on what happens when you pretend a single int that's being read and written to is "atomic", as it depends on the exact architecture and a bunch of other things. But it won't do anything worse than give the wrong number sometimes, so go ahead... or use a queue. :)
Python: safe to read values from an object in a thread?
I have a Python/wxPython program where the GUI is the main thread and I use another thread to load data from a file. Sometimes the files are big and slow to load so I use a wxPulse dialog to indicate progress. As I load the file, I count the number of lines that have been read in the counting thread, and I display this count in the wxPulse dialog in the main thread. I get the count in the main thread by reading the same variable that is being written to by the loading thread. Is this "thread safe"? Could this somehow cause problems? I've been doing it for awhile and it has been fine so far. PS. I know I could use a queue to transfer the count, but I'm lazy and don't want to if I don't have to.
[ "Generally as long as...\n\nYou only have one thread writing to it, and...\nIt's not important that the count be kept precisely in sync with the displayed value...\n\nit's fine.\n", "In normal python this will be safe as all access to variables are protected by the GIL(Global Interpreter Lock) this means that all...
[ 8, 3, 2, 1, 0 ]
[]
[]
[ "python", "thread_safety" ]
stackoverflow_0003714613_python_thread_safety.txt
Q: python bitwise operation hi i am new in python just started learning with python i got a task in which i need to store "1" byte of integer into different bits just like RGB the value are store in that can any one would write a small program for me and explain that ,please i need a help Thankyou A: I'll assume this question is legitimate and appropriate for the forum.. # To Encode: r = 1 g = 2 b = 3 rgb = r << 16 | g << 8 | b #To extract: r = (rgb >> 16) & 0xFF g = (rgb >> 8) & 0xFF b = rgb & 0xFF A: To convert a number to a list of it's binary digits: list(bin(number))[2:]
python bitwise operation
hi i am new in python just started learning with python i got a task in which i need to store "1" byte of integer into different bits just like RGB the value are store in that can any one would write a small program for me and explain that ,please i need a help Thankyou
[ "I'll assume this question is legitimate and appropriate for the forum..\n# To Encode:\nr = 1\ng = 2\nb = 3\n\nrgb = r << 16 | g << 8 | b\n\n#To extract:\nr = (rgb >> 16) & 0xFF\ng = (rgb >> 8) & 0xFF\nb = rgb & 0xFF\n\n", "To convert a number to a list of it's binary digits: list(bin(number))[2:]\n" ]
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003711762_python.txt
Q: GtkExpander style widget in wxWidgets? I'm looking for a widget along the lines of GtkExpander, but for wxWidgets. Can't seem to find anything obvious in the documentation. Custom widgets (non-GPL) from somewhere else would be fine, but they need to work on Windows (i.e. without GTK). Practically (if it makes any difference) this is primarily for wxPython, on Windows and hopefully Linux. A: Damn, I'm stupid. If you've got here because you're stupid too, check out wxCollapsiblePane.
GtkExpander style widget in wxWidgets?
I'm looking for a widget along the lines of GtkExpander, but for wxWidgets. Can't seem to find anything obvious in the documentation. Custom widgets (non-GPL) from somewhere else would be fine, but they need to work on Windows (i.e. without GTK). Practically (if it makes any difference) this is primarily for wxPython, on Windows and hopefully Linux.
[ "Damn, I'm stupid. If you've got here because you're stupid too, check out wxCollapsiblePane.\n" ]
[ 3 ]
[]
[]
[ "gtk", "python", "windows", "wxpython", "wxwidgets" ]
stackoverflow_0003716997_gtk_python_windows_wxpython_wxwidgets.txt
Q: Sentence Splitter testing file I am looking for a testing file for my Sentence Splitter Application, and i hope the file can cover as many cases as possible. Thanks! A: Read the documentation for Lingua::Sentence. It names the corpus it uses, and also related sentence splitting modules. Peruse the test files.
Sentence Splitter testing file
I am looking for a testing file for my Sentence Splitter Application, and i hope the file can cover as many cases as possible. Thanks!
[ "Read the documentation for Lingua::Sentence. It names the corpus it uses, and also related sentence splitting modules. Peruse the test files.\n" ]
[ 6 ]
[]
[]
[ "java", "perl", "python" ]
stackoverflow_0003717171_java_perl_python.txt
Q: Color handling in Python For my clustering gui, I am currently using random colors for the clusters, since I won't know before hand how many clusters I will end up with. In Python, this looks like: import random def randomColor(): return (random.random(),random.random(),random.random()) However, when I update things, the colors change. So what I would favor is to have a function which has an input argument I such as def nonrandomColor(i): ... return color would always return the same color for the same I, while keeping the ability to generate arbitrarily many colors. Answer does not have to be formulated in Python, it's more the general layout I'm interested in. A: One way is to use caching. Use a defaultdict: >>> import random >>> def randomColor(): ... return (random.random(),random.random(),random.random()) ... >>> from collections import defaultdict >>> colors = defaultdict(randomColor) >>> colors[3] (0.10726172906719755, 0.97327604757295705, 0.58935794305308264) >>> colors[1] (0.48991106537516382, 0.77039712435566876, 0.73707003166893892) >>> colors[3] (0.10726172906719755, 0.97327604757295705, 0.58935794305308264) A: Just set the seed of the random generator to the index, this might be cheaper than storing the colors. random.seed(i) Note that this will make random numbers way less random than before. If that is a problem, e.g. if your application uses random numbers elsewhere, you might want to look into the caching options suggested by other answers. A: You want to store the colors in a dictionary or a list: colors = {} # int -> color def nonrandomColor(i): if i not in colors: colors[i] = randomColor() return colors[i] A: If you want repeatable non colliding colors then you could use something like the function below. It sections the number into 1, 10, 100 and then uses them as the RGB parts of the color. def color(i): r = i % 10 g = (i//10) % 10 b = (i//100) % 10 return(r*25, g*25, b*25) For example: color(1) == (25,0,0) color(10) == (0,25,0) color(999) = (225,225,255)
Color handling in Python
For my clustering gui, I am currently using random colors for the clusters, since I won't know before hand how many clusters I will end up with. In Python, this looks like: import random def randomColor(): return (random.random(),random.random(),random.random()) However, when I update things, the colors change. So what I would favor is to have a function which has an input argument I such as def nonrandomColor(i): ... return color would always return the same color for the same I, while keeping the ability to generate arbitrarily many colors. Answer does not have to be formulated in Python, it's more the general layout I'm interested in.
[ "One way is to use caching. Use a defaultdict:\n>>> import random\n>>> def randomColor():\n... return (random.random(),random.random(),random.random())\n... \n>>> from collections import defaultdict\n>>> colors = defaultdict(randomColor)\n>>> colors[3]\n(0.10726172906719755, 0.97327604757295705, 0.58935794305308...
[ 6, 2, 1, 1 ]
[ "You can use i to seed the random number generator. So, as long as the seed remains the same, you get the same value.\n>>> import random\n>>> random.seed(12)\n>>> random.randint(0,255), random.randint(0,255), random.randint(0,255)\n(121, 168, 170)\n>>> random.seed(12)\n>>> random.randint(0,255), random.randint(0,25...
[ -1 ]
[ "colors", "python" ]
stackoverflow_0003717354_colors_python.txt
Q: Python Twisted framework HTTP client I want to write a simple SSL HTTP client in Python and have heard about the Twisted framework. I need to be able to authenticate with a REST service - so I was thinking I'd just POST a user name and password to the target server. Assuming authentication is successful, the client will receive a cookie. Will an HTTP client built on Twisted automatically resend the cookie header for each subsequent request, or do I need to do something special? I've never used Twisted before. Thanks A: Will an HTTP client built on Twisted automatically resend the cookie header for each subsequent request, or do I need to do something special? "an HTTP client built on Twisted" will do anything it is built to do - just like, presumably any X built on any Y will do whatever it was built to do. :) So I might suggest that this isn't the question you really care about the answer to. Since Twisted 11.1.0, twisted.web.client.CookieAgent accepts a cookieJar argument which does two things: it defines the cookies which are available to be sent with the requests it stores new cookies received from servers in responses The soon-to-be-deprecated twisted.web.client.getPage accepts a cookies argument behaves similarly. So if you use CookieAgent then the cookie will be persisted and sent with subsequent requests, providing the authentication behavior you're after. You could also do something with getPage but given its impending doom you probably shouldn't.
Python Twisted framework HTTP client
I want to write a simple SSL HTTP client in Python and have heard about the Twisted framework. I need to be able to authenticate with a REST service - so I was thinking I'd just POST a user name and password to the target server. Assuming authentication is successful, the client will receive a cookie. Will an HTTP client built on Twisted automatically resend the cookie header for each subsequent request, or do I need to do something special? I've never used Twisted before. Thanks
[ "\nWill an HTTP client built on Twisted automatically resend the cookie header for each subsequent request, or do I need to do something special?\n\n\"an HTTP client built on Twisted\" will do anything it is built to do - just like, presumably any X built on any Y will do whatever it was built to do. :) So I might...
[ 4 ]
[]
[]
[ "python", "twisted", "twisted.web" ]
stackoverflow_0003716647_python_twisted_twisted.web.txt
Q: Which exception App Engine raises when a task nears the 30 second limit? From Task Queue Python API Overview: If your task's execution nears the 30 second limit, App Engine will raise an exception which you may catch and then quickly save your work or log process. Which exception is that? A: The exception is google.appengine.runtime.DeadlineExceededError, the same was with normal web requests. A task running from the queue behaves identically to an ordinary web request, except that the Taskqueue API will reschedule a task that exits with a non-200 response.
Which exception App Engine raises when a task nears the 30 second limit?
From Task Queue Python API Overview: If your task's execution nears the 30 second limit, App Engine will raise an exception which you may catch and then quickly save your work or log process. Which exception is that?
[ "The exception is google.appengine.runtime.DeadlineExceededError, the same was with normal web requests. A task running from the queue behaves identically to an ordinary web request, except that the Taskqueue API will reschedule a task that exits with a non-200 response.\n" ]
[ 5 ]
[]
[]
[ "exception", "google_app_engine", "python", "task", "task_queue" ]
stackoverflow_0003717466_exception_google_app_engine_python_task_task_queue.txt
Q: Google App Engine to Twisted I was about to migrate the GAE-OpenSocial project to Twisted Matrix and Nevow. I am very new to Nevow templating and couldn't find good documentation other than given in Divmod's Nevow Project page. Is there any books relating to Nevow? I am having trouble serving static files in Nevow. For app engine its easy to define static files in app.yaml. But here I can't find a suitable way. Please help. A: There is a large collection of examples in Nevow's source directory, Nevow/examples/. These are all runnable examples. You can start a server which will serve an index page for them like so: exarkun@boson:~/Projects/Divmod/trunk/Nevow/examples$ twistd -ny examples.tac ... [-] Log opened. ... [-] twistd 10.1.0+r30002 (/usr/bin/python 2.6.4) starting up. ... [-] reactor class: twisted.internet.selectreactor.SelectReactor. ... [-] nevow.appserver.NevowSite starting on 8080 ... [-] Starting factory <nevow.appserver.NevowSite instance at 0x94cc8ec> Visit http://localhost:8080/ and you'll see a list of the examples and links to see their source or actually visit them and see their output. For the particular case of static files, the answer is pretty simple, simply serve up a nevow.static.File or a twisted.web.static.File somewhere.
Google App Engine to Twisted
I was about to migrate the GAE-OpenSocial project to Twisted Matrix and Nevow. I am very new to Nevow templating and couldn't find good documentation other than given in Divmod's Nevow Project page. Is there any books relating to Nevow? I am having trouble serving static files in Nevow. For app engine its easy to define static files in app.yaml. But here I can't find a suitable way. Please help.
[ "There is a large collection of examples in Nevow's source directory, Nevow/examples/. These are all runnable examples. You can start a server which will serve an index page for them like so:\nexarkun@boson:~/Projects/Divmod/trunk/Nevow/examples$ twistd -ny examples.tac\n... [-] Log opened.\n... [-] twistd 10.1.0...
[ 3 ]
[]
[]
[ "google_app_engine", "nevow", "python", "templates", "twisted" ]
stackoverflow_0003715639_google_app_engine_nevow_python_templates_twisted.txt
Q: Python installation i have a machine with two users accounts. i installed python in the first account without any problem but when am gone to install into the second account it cause the following error checking for C compiler default output file name... configure: error: C compiler cannot create executables caused when execute the following command: ./configure --prefix="/home/df/python5" i don't why ? could anyone help me Thanks in Advance A: When you execute ./configure in what folder you are (absolute path) ? Check if this folder and sub-folders are read-writable for your "second" user account. Seems you have no write access ... Anyway, why do you want to install the same python two times ? A: Take a look at the contents of config.log, it lists what commands the configure script is trying to execute in order to find out where your C compiler is and what parameters it supports. Search for the error message in the log file, scroll a few lines up and you should see what commands were executed that led to this error message. Maybe it helps you figure out why the script is not able to find a suitable C compiler. For instance, this is the line I see in a config.log file on my computer corresponding to the test that failed for you: configure:2827: checking for C compiler default output file name configure:2854: gcc conftest.c >&5 configure:2857: $? = 0 configure:2895: result: a.out For the record, $? = 0 means that the command was executed successfully.
Python installation
i have a machine with two users accounts. i installed python in the first account without any problem but when am gone to install into the second account it cause the following error checking for C compiler default output file name... configure: error: C compiler cannot create executables caused when execute the following command: ./configure --prefix="/home/df/python5" i don't why ? could anyone help me Thanks in Advance
[ "When you execute ./configure in what folder you are (absolute path) ?\nCheck if this folder and sub-folders are read-writable for your \"second\" user account.\nSeems you have no write access ...\nAnyway, why do you want to install the same python two times ?\n", "Take a look at the contents of config.log, it li...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003717544_python.txt
Q: Is it possible to code images into a python script? Instead of using directories to reference an image, is it possible to code an image into the program directly? A: You can use the base64 module to embed data into your programs. From the base64 documentation: >>> import base64 >>> encoded = base64.b64encode('data to be encoded') >>> encoded 'ZGF0YSB0byBiZSBlbmNvZGVk' >>> data = base64.b64decode(encoded) >>> data 'data to be encoded' Using this ability you can base64 encode an image and embed the resulting string in your program. To get the original image data you would pass that string to base64.b64decode. A: Try img2py script. It's included as part of wxpython (google to see if you can dl seperately). img2py.py -- Convert an image to PNG format and embed it in a Python module with appropriate code so it can be loaded into a program at runtime. The benefit is that since it is Python source code it can be delivered as a .pyc or 'compiled' into the program using freeze, py2exe, etc. Usage: img2py.py [options] image_file python_file A: There is no need to base64 encode the string, just paste it's repr into the code A: If you mean, storing the bytes that represent the image in the program code itself, you could do it by base64 encoding the image file, and setting a variable to that string. You could also declare a byte array, where the contents of the array are the bytes that represent the image. In both cases, if you want to operate on the image, you may need to decode the value that you have included in your source code. Warning: you may be treading on a performance minefield here. A better way might be to store the image/s in the directory structure of your module, and the loading it on demand (even caching it). You could write a generalized method/function that loads the right image based on some identifier which maps to the particular image file name that is part and parcel of your module.
Is it possible to code images into a python script?
Instead of using directories to reference an image, is it possible to code an image into the program directly?
[ "You can use the base64 module to embed data into your programs. From the base64 documentation: \n>>> import base64\n>>> encoded = base64.b64encode('data to be encoded')\n>>> encoded\n'ZGF0YSB0byBiZSBlbmNvZGVk' \n>>> data = base64.b64decode(encoded)\n>>> data\n'data to be encoded'\n\nUsing this ability you can base...
[ 9, 5, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003715244_python.txt
Q: Selenium-rc: How do you use CaptureNetworkTraffic in python I've found many tutorials for selenium in java in which you first start selenium using s.start("captureNetworkTraffic=True"), but in python start() does not take any arguments. How do you pass this argument? Or don't you need it in python? A: I changed the start in selenium.py: def start(self, captureNetworkTraffic=False): l = [self.browserStartCommand, self.browserURL, self.extensionJs] if captureNetworkTraffic: l.append("captureNetworkTraffic=true") result = self.get_string("getNewBrowserSession", l) The you do: sel = selenium.selenium('localhost', 4444, '*firefox', 'http://www.google.com') sel.start(True) sel.open('') print sel.captureNetworkTraffic('json') and it works like a charm A: Start the browser in "proxy-injection mode" (note *pifirefox instead of *firefox). Then you can call the captureNetworkTraffic method. import selenium import time sel=selenium.selenium("localhost",4444,"*pifirefox","http://www.google.com/webhp") sel.start() time.sleep(1) print(sel.captureNetworkTraffic('json')) I learned the *pifirefox "trick" here.
Selenium-rc: How do you use CaptureNetworkTraffic in python
I've found many tutorials for selenium in java in which you first start selenium using s.start("captureNetworkTraffic=True"), but in python start() does not take any arguments. How do you pass this argument? Or don't you need it in python?
[ "I changed the start in selenium.py:\ndef start(self, captureNetworkTraffic=False):\n l = [self.browserStartCommand, self.browserURL, self.extensionJs]\n if captureNetworkTraffic:\n l.append(\"captureNetworkTraffic=true\")\n result = self.get_string(\"getNewBrowserSession\", l)\n\nThe you do:\nsel =...
[ 5, 1 ]
[]
[]
[ "python", "selenium_rc" ]
stackoverflow_0003712278_python_selenium_rc.txt
Q: problem with python print function I am trying to this function: def sleep(sec): for i in range(sec): print(".", end=" "); time.sleep(1); the problem is that it waits for the for loop to finish then it prints everything. If I use the normal print with \n in the end everything works as it should. But with the end=" " it does not. A: The stdout is line buffered. You need to flush the output manually. import sys def sleep(sec): for i in range(sec): print(".", end=" ") sys.stdout.flush() time.sleep(1)
problem with python print function
I am trying to this function: def sleep(sec): for i in range(sec): print(".", end=" "); time.sleep(1); the problem is that it waits for the for loop to finish then it prints everything. If I use the normal print with \n in the end everything works as it should. But with the end=" " it does not.
[ "The stdout is line buffered. You need to flush the output manually.\nimport sys\n\ndef sleep(sec):\n for i in range(sec):\n print(\".\", end=\" \")\n sys.stdout.flush()\n time.sleep(1)\n\n" ]
[ 5 ]
[]
[]
[ "printing", "python", "python_3.x" ]
stackoverflow_0003718082_printing_python_python_3.x.txt
Q: Memory error (MemoryError) when creating a boolean NumPy array (Python) I'm using NumPy with Python 2.6.2. I'm trying to create a small (length 3), simple boolean array. The following gives me a MemoryError, which I think it ought not to. import numpy as np cond = np.fromiter((x in [2] for x in [0, 1, 2]), dtype = np.bool) The error it gives me is: MemoryError: cannot allocate array memory However, the following method of obtaining a list (as opposed to an ndarray) works fine (without using numpy): cond = list((x in [2] for x in [0, 1, 2])) Have I done anything wrong in the Numpy code? My feeling is that it ought to work. A: You should not get any error. With Python 2.6.5 or Python 2.7, and Numpy 1.5.0, I don't get any error. I therefore think that updating your software could very well solve the problem that you observe. A: I can reproduce the problem with numpy 1.1 (but not with anything newer). Obviously, upgrading to a more recent version of numpy is your best bet. Nonetheless, it seems to be related to using np.bool as the dtype when count=-1 (the default: Read all items in the iterator, instead of a set number). A quick workaround is just to create it as an int array and then convert it to a boolean array: cond = np.fromiter((x in [2] for x in [0, 1, 2]), dtype=np.int).astype(np.bool) An alternative is to convert it to a list, and then set count to the length of the list (or just use np.asarray on the list): items = list((x in [2] for x in [0, 1, 2])) cond = np.fromiter(items, dtype=np.bool, count=len(items)) Obviously, both of these are suboptimal, but if you can't upgrade to a more recent version of numpy, they will work.
Memory error (MemoryError) when creating a boolean NumPy array (Python)
I'm using NumPy with Python 2.6.2. I'm trying to create a small (length 3), simple boolean array. The following gives me a MemoryError, which I think it ought not to. import numpy as np cond = np.fromiter((x in [2] for x in [0, 1, 2]), dtype = np.bool) The error it gives me is: MemoryError: cannot allocate array memory However, the following method of obtaining a list (as opposed to an ndarray) works fine (without using numpy): cond = list((x in [2] for x in [0, 1, 2])) Have I done anything wrong in the Numpy code? My feeling is that it ought to work.
[ "You should not get any error.\nWith Python 2.6.5 or Python 2.7, and Numpy 1.5.0, I don't get any error. I therefore think that updating your software could very well solve the problem that you observe.\n", "I can reproduce the problem with numpy 1.1 (but not with anything newer). Obviously, upgrading to a more...
[ 1, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0003717418_numpy_python.txt
Q: Getting tests to parallelize using nose in python I have a directory with lots of .py files (say test_1.py, test_2.py and so on) Each one of them is written properly to be used with nose. So when I run nosetests script, it finds all the tests in all the .py files and executes them. I now want to parallelize them so that all the tests in all .py files are treated as being parallelizable and delegated to worker processes. It seems that by default, doing : nosetests --processes=2 introduces no parallelism at all and all tests across all .py files still run in just one process I tried putting a _multiprocess_can_split_ = True in each of the .py files but that makes no difference Thanks for any inputs! A: It seems that nose, actually the multiprocess plugin, will make test run in parallel. The caveat is that the way it works, you can end up not executing test on multiple processes. The plugin creates a test queue, spawns multiple processes and then each process consumes the queue concurrently. There is no test dispatch for each process thus if your test are executing very fast, they could end up being executed in the same process. The following example displays this beaviour: File test1.py import os import unittest class testProcess2(unittest.TestCase): def test_Dummy2(self): self.assertEqual(0, os.getpid()) File test2.py import os import unittest class testProcess2(unittest.TestCase): def test_Dummy2(self): self.assertEqual(0, os.getpid()) Running nosetests --processes=2 outputs (notice the identical process id) FF ====================================================================== FAIL: test_Dummy2 (test1.testProcess2) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\temp\test1.py", line 7, in test_Dummy2 self.assertEqual(0, os.getpid()) AssertionError: 0 != 94048 ====================================================================== FAIL: test_Dummy1 (test2.testProcess1) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\temp\test2.py", line 8, in test_Dummy1 self.assertEqual(0, os.getpid()) AssertionError: 0 != 94048 ---------------------------------------------------------------------- Ran 2 tests in 0.579s FAILED (failures=2) Now if we add a sleep in one of the test import os import unittest import time class testProcess2(unittest.TestCase): def test_Dummy2(self): time.sleep(1) self.assertEqual(0, os.getpid()) We get (notice the different process id) FF ====================================================================== FAIL: test_Dummy1 (test2.testProcess1) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\temp\test2.py", line 8, in test_Dummy1 self.assertEqual(0, os.getpid()) AssertionError: 0 != 80404 ====================================================================== FAIL: test_Dummy2 (test1.testProcess2) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\temp\test1.py", line 10, in test_Dummy2 self.assertEqual(0, os.getpid()) AssertionError: 0 != 92744 ---------------------------------------------------------------------- Ran 2 tests in 1.422s FAILED (failures=2)
Getting tests to parallelize using nose in python
I have a directory with lots of .py files (say test_1.py, test_2.py and so on) Each one of them is written properly to be used with nose. So when I run nosetests script, it finds all the tests in all the .py files and executes them. I now want to parallelize them so that all the tests in all .py files are treated as being parallelizable and delegated to worker processes. It seems that by default, doing : nosetests --processes=2 introduces no parallelism at all and all tests across all .py files still run in just one process I tried putting a _multiprocess_can_split_ = True in each of the .py files but that makes no difference Thanks for any inputs!
[ "It seems that nose, actually the multiprocess plugin, will make test run in parallel. The caveat is that the way it works, you can end up not executing test on multiple processes. The plugin creates a test queue, spawns multiple processes and then each process consumes the queue concurrently. There is no test disp...
[ 12 ]
[]
[]
[ "nose", "nosetests", "python" ]
stackoverflow_0003111915_nose_nosetests_python.txt
Q: Is there a better/more pythonified way to do this? I've been teaching myself Python at my new job, and really enjoying the language. I've written a short class to do some basic data manipulation, and I'm pretty confident about it. But old habits from my structured/modular programming days are hard to break, and I know there must be a better way to write this. So, I was wondering if anyone would like to take a look at the following, and suggest some possible improvements, or put me on to a resource that could help me discover those for myself. A quick note: The RandomItems root class was written by someone else, and I'm still wrapping my head around the itertools library. Also, this isn't the entire module - just the class I'm working on, and it's prerequisites. What do you think? import itertools import urllib2 import random import string class RandomItems(object): """This is the root class for the randomizer subclasses. These are used to generate arbitrary content for each of the fields in a csv file data row. The purpose is to automatically generate content that can be used as functional testing fixture data. """ def __iter__(self): while True: yield self.next() def slice(self, times): return itertools.islice(self, times) class RandomWords(RandomItems): """Obtain a list of random real words from the internet, place them in an iterable list object, and provide a method for retrieving a subset of length 1-n, of random words from the root list. """ def __init__(self): urls = [ "http://dictionary-thesaurus.com/wordlists/Nouns%285,449%29.txt", "http://dictionary-thesaurus.com/wordlists/Verbs%284,874%29.txt", "http://dictionary-thesaurus.com/wordlists/Adjectives%2850%29.txt", "http://dictionary-thesaurus.com/wordlists/Adjectives%28929%29.txt", "http://dictionary-thesaurus.com/wordlists/DescriptiveActionWords%2835%29.txt", "http://dictionary-thesaurus.com/wordlists/WordsThatDescribe%2886%29.txt", "http://dictionary-thesaurus.com/wordlists/DescriptiveWords%2886%29.txt", "http://dictionary-thesaurus.com/wordlists/WordsFunToUse%28100%29.txt", "http://dictionary-thesaurus.com/wordlists/Materials%2847%29.txt", "http://dictionary-thesaurus.com/wordlists/NewsSubjects%28197%29.txt", "http://dictionary-thesaurus.com/wordlists/Skills%28341%29.txt", "http://dictionary-thesaurus.com/wordlists/TechnicalManualWords%281495%29.txt", "http://dictionary-thesaurus.com/wordlists/GRE_WordList%281264%29.txt" ] self._words = [] for url in urls: urlresp = urllib2.urlopen(urllib2.Request(url)) self._words.extend([word for word in urlresp.read().split("\r\n")]) self._words = list(set(self._words)) # Removes duplicates self._words.sort() # sorts the list def next(self): """Return a single random word from the list """ return random.choice(self._words) def get(self): """Return the entire list, if needed. """ return self._words def wordcount(self): """Return the total number of words in the list """ return len(self._words) def sublist(self,size=3): """Return a random segment of _size_ length. The default is 3 words. """ segment = [] for i in range(size): segment.append(self.next()) #printable = " ".join(segment) return segment def random_name(self): """Return a string-formatted list of 3 random words. """ words = self.sublist() return "%s %s %s" % (words[0], words[1], words[2]) def main(): """Just to see it work... """ wl = RandomWords() print wl.wordcount() print wl.next() print wl.sublist() print 'Three Word Name = %s' % wl.random_name() #print wl.get() if __name__ == "__main__": main() A: Here are my five cents: Constructor should be called __init__. You could abolish some code by using random.sample, it does what your next() and sublist() does but it's prepackaged. Override __iter__ (define the method in your class) and you can get rid of RandomIter. You can read more about at it in the docs (note Py3K, some stuff may not be relevant for lower version). You could use yield for this which as you may or may not know creates a generator, thus wasting little to no memory. random_name could use str.join instead. Note that you may need to convert the values if they are not guaranteed to be strings. This can be done through [str(x) for x in iterable] or in-built map. A: First knee-jerk reaction: I would offload your hard-coded URLs into a constructor parameter passed to the class and perhaps read from configuration somewhere; this will allow for easier change without necessitating a redeploy. The drawback of this is that consumers of the class have to know where those URLs are stored... so you could create a companion class whose only job is to know what the URLs are (i.e. in configuration, or even hard-coded) and how to get them. You could allow the consumer of your class to provide the URLs, or if they are not provided, the class could hit up the companion class for the URLs.
Is there a better/more pythonified way to do this?
I've been teaching myself Python at my new job, and really enjoying the language. I've written a short class to do some basic data manipulation, and I'm pretty confident about it. But old habits from my structured/modular programming days are hard to break, and I know there must be a better way to write this. So, I was wondering if anyone would like to take a look at the following, and suggest some possible improvements, or put me on to a resource that could help me discover those for myself. A quick note: The RandomItems root class was written by someone else, and I'm still wrapping my head around the itertools library. Also, this isn't the entire module - just the class I'm working on, and it's prerequisites. What do you think? import itertools import urllib2 import random import string class RandomItems(object): """This is the root class for the randomizer subclasses. These are used to generate arbitrary content for each of the fields in a csv file data row. The purpose is to automatically generate content that can be used as functional testing fixture data. """ def __iter__(self): while True: yield self.next() def slice(self, times): return itertools.islice(self, times) class RandomWords(RandomItems): """Obtain a list of random real words from the internet, place them in an iterable list object, and provide a method for retrieving a subset of length 1-n, of random words from the root list. """ def __init__(self): urls = [ "http://dictionary-thesaurus.com/wordlists/Nouns%285,449%29.txt", "http://dictionary-thesaurus.com/wordlists/Verbs%284,874%29.txt", "http://dictionary-thesaurus.com/wordlists/Adjectives%2850%29.txt", "http://dictionary-thesaurus.com/wordlists/Adjectives%28929%29.txt", "http://dictionary-thesaurus.com/wordlists/DescriptiveActionWords%2835%29.txt", "http://dictionary-thesaurus.com/wordlists/WordsThatDescribe%2886%29.txt", "http://dictionary-thesaurus.com/wordlists/DescriptiveWords%2886%29.txt", "http://dictionary-thesaurus.com/wordlists/WordsFunToUse%28100%29.txt", "http://dictionary-thesaurus.com/wordlists/Materials%2847%29.txt", "http://dictionary-thesaurus.com/wordlists/NewsSubjects%28197%29.txt", "http://dictionary-thesaurus.com/wordlists/Skills%28341%29.txt", "http://dictionary-thesaurus.com/wordlists/TechnicalManualWords%281495%29.txt", "http://dictionary-thesaurus.com/wordlists/GRE_WordList%281264%29.txt" ] self._words = [] for url in urls: urlresp = urllib2.urlopen(urllib2.Request(url)) self._words.extend([word for word in urlresp.read().split("\r\n")]) self._words = list(set(self._words)) # Removes duplicates self._words.sort() # sorts the list def next(self): """Return a single random word from the list """ return random.choice(self._words) def get(self): """Return the entire list, if needed. """ return self._words def wordcount(self): """Return the total number of words in the list """ return len(self._words) def sublist(self,size=3): """Return a random segment of _size_ length. The default is 3 words. """ segment = [] for i in range(size): segment.append(self.next()) #printable = " ".join(segment) return segment def random_name(self): """Return a string-formatted list of 3 random words. """ words = self.sublist() return "%s %s %s" % (words[0], words[1], words[2]) def main(): """Just to see it work... """ wl = RandomWords() print wl.wordcount() print wl.next() print wl.sublist() print 'Three Word Name = %s' % wl.random_name() #print wl.get() if __name__ == "__main__": main()
[ "Here are my five cents:\n\nConstructor should be called __init__.\nYou could abolish some code by using random.sample, it does what your next() and sublist() does but it's prepackaged.\nOverride __iter__ (define the method in your class) and you can get rid of RandomIter. You can read more about at it in the docs ...
[ 6, 5 ]
[]
[]
[ "optimization", "python", "random", "string" ]
stackoverflow_0003718284_optimization_python_random_string.txt
Q: Multi-panel time series of lines and filled contours using matplotlib? If I wanted to make a combined image like the one shown below (original source here), could you point me to the matplotlib objects do I need to assemble? I've been trying to work with AxesImage objects and I've also downloaded SciKits Timeseries - but do I need this, or can is it as easy to use strptime, mktime, and strftime from the time module and roll my own custom axes? Thanks ~ A: You shouldn't need any custom axes. The Timeseries Scikit is great, but you don't need it at all to work with dates in matplotlib... You'll probably want to use the various functions in matplotlib.dates, plot_date to plot your values, imshow (and/or pcolor in some cases) to plot your specgrams of various sorts, and matplotlib.mlab.specgram to compute them. For your subplots, you'll want to use the sharex kwarg when creating them, so that they all share the same x-axis. To disable the x-axis labels on some axes when using sharing an x-axis between the plots, you'll need to use something like matplotlib.pyplot.setp(ax1.get_xticklabels(), visible=False). (It's a slightly crude hack, but it's the only way to only display x-axis labels on the bottom subplot when sharing the same x-axis between all subplots) To adjust the spacing between subplots, see subplots_adjust. Hope all that makes some sense... I'll add a quick example of using all of that when I have time later today... Edit: So here's a rough example of the idea. Some things (e.g. multicolored axis labels) shown in your example are rather difficult to do in matplotlib. (Not impossible, but I've skipped them here...) import datetime import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib import mlab from mpl_toolkits.axes_grid1 import make_axes_locatable def main(): #-- Make a series of dates start = datetime.datetime(2010,9,15,8,0) end = datetime.datetime(2010,9,15,18,0) delta = datetime.timedelta(seconds=1) # Note: "time" is now an array of floats, where 1.0 corresponds # to one day, and 0.0 corresponds to 1900 (I think...) # It's _not_ an array of datetime objects! time = mpl.dates.drange(start, end, delta) num = time.size #-- Generate some data x = brownian_noise(num) y = brownian_noise(num) z = brownian_noise(num) plot(x, y, z, time) plt.show() def plot(x, y, z, time): fig = plt.figure() #-- Panel 1 ax1 = fig.add_subplot(311) im, cbar = specgram(x, time, ax1, fig) ax1.set_ylabel('X Freq. (Hz)') ax1.set_title('Fake Analysis of Something') #-- Panel 2 ax2 = fig.add_subplot(312, sharex=ax1) im, cbar = specgram(y, time, ax2, fig) ax2.set_ylabel('Y Freq. (Hz)') #-- Panel 3 ax3 = fig.add_subplot(313, sharex=ax1) # Plot the 3 source datasets xline = ax3.plot_date(time, x, 'r-') yline = ax3.plot_date(time, y, 'b-') zline = ax3.plot_date(time, z, 'g-') ax3.set_ylabel(r'Units $(\mu \phi)$') # Make an invisible spacer... cax = make_legend_axes(ax3) plt.setp(cax, visible=False) # Make a legend ax3.legend((xline, yline, zline), ('X', 'Y', 'Z'), loc='center left', bbox_to_anchor=(1.0, 0.5), frameon=False) # Set the labels to be rotated at 20 deg and aligned left to use less space plt.setp(ax3.get_xticklabels(), rotation=-20, horizontalalignment='left') # Remove space between subplots plt.subplots_adjust(hspace=0.0) def specgram(x, time, ax, fig): """Make and plot a log-scaled spectrogram""" dt = np.diff(time)[0] # In days... fs = dt * (3600 * 24) # Samples per second spec_img, freq, _ = mlab.specgram(x, Fs=fs, noverlap=200) t = np.linspace(time.min(), time.max(), spec_img.shape[1]) # Log scaling for amplitude values spec_img = np.log10(spec_img) # Log scaling for frequency values (y-axis) ax.set_yscale('log') # Plot amplitudes im = ax.pcolormesh(t, freq, spec_img) # Add the colorbar in a seperate axis cax = make_legend_axes(ax) cbar = fig.colorbar(im, cax=cax, format=r'$10^{%0.1f}$') cbar.set_label('Amplitude', rotation=-90) ax.set_ylim([freq[1], freq.max()]) # Hide x-axis tick labels plt.setp(ax.get_xticklabels(), visible=False) return im, cbar def make_legend_axes(ax): divider = make_axes_locatable(ax) legend_ax = divider.append_axes('right', 0.4, pad=0.2) return legend_ax def brownian_noise(num): x = np.random.random(num) - 0.5 x = np.cumsum(x) return x if __name__ == '__main__': main()
Multi-panel time series of lines and filled contours using matplotlib?
If I wanted to make a combined image like the one shown below (original source here), could you point me to the matplotlib objects do I need to assemble? I've been trying to work with AxesImage objects and I've also downloaded SciKits Timeseries - but do I need this, or can is it as easy to use strptime, mktime, and strftime from the time module and roll my own custom axes? Thanks ~
[ "You shouldn't need any custom axes. The Timeseries Scikit is great, but you don't need it at all to work with dates in matplotlib...\nYou'll probably want to use the various functions in matplotlib.dates, plot_date to plot your values, imshow (and/or pcolor in some cases) to plot your specgrams of various sorts, ...
[ 11 ]
[]
[]
[ "matplotlib", "python", "scipy" ]
stackoverflow_0003716528_matplotlib_python_scipy.txt
Q: Accessing and manipulating the values ( in list form) of a dictionary I have a dictionary with keys and a list attached as value to each key. I have to traverse list value attached to each key and segregate them into two different lists with '0' and '1' ( as '0' and '1' are the values in the list) also with the count of '0' , '1' and the total. Please let me know how should i go abut doing this. Thanks A: #to loop through a dictionary total_0 = 0 list_0 =[] total_1 = 0 list_1 = [] somedict = {'key1':[1,1,1,0,1,0]} for key,value in somedict.items(): # now loop through each list of your dict, since value keep your list for item in value: if item == 1: total_1 += 1 list_1.append(item) else : total_0 += 1 list_0.append(item) Thats an example, if you explain it with detail, i will try to help you more (: A: The problem is abundantly under-specified (are the two different lists supposed to be mutually exclusive? What happens if a key has a list with both 0 and 1, or neither? Etc). But if for example there is no mutual exclusion constraint, the counts must count each 0 or 1 repeatedly if it occurs repeatedly, and many other guesses about conditions you just don't mention at all...: def weird_op(d): keysw0 = [] keysw1 = [] count0s = count1s = 0 for k, v in d.iteritems(): n0 = v.count('0') n1 = v.count('1') if n0: keysw0.append(k) if n1: keysw1.append(k) count0s += n0 count1s += n1 return keysw0, keysw1, count0s, count1s I've omitted the "also the total" part of your request because, for that one, the lack of specs borders on the nightmare -- total of WHAT?! Keys, items in the lists, angels dancing on the point of a pin...?! And since you very specifically mention that the lists' items are strings (you do use quotes around them, which must mean strings -- right...?) how the flip do you propose to "total" them?! If you can clarify the specs (especially that weird "total" one!) no doubt better approaches can be found, but this is the boundary to which my mind-reading patented crystal ball can push. BTW, as part of the specs, some examples of input dict-of-lists and expected results for each would really really help.
Accessing and manipulating the values ( in list form) of a dictionary
I have a dictionary with keys and a list attached as value to each key. I have to traverse list value attached to each key and segregate them into two different lists with '0' and '1' ( as '0' and '1' are the values in the list) also with the count of '0' , '1' and the total. Please let me know how should i go abut doing this. Thanks
[ "#to loop through a dictionary\ntotal_0 = 0\nlist_0 =[]\ntotal_1 = 0\nlist_1 = []\nsomedict = {'key1':[1,1,1,0,1,0]}\nfor key,value in somedict.items():\n # now loop through each list of your dict, since value keep your list\n for item in value:\n if item == 1: \n total_1 += 1\n l...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003718622_python.txt
Q: Python set error reporting level like in PHP How can I set error reporting and warning outputs in Python like in PHP error_reporting(E_LEVEL)? A: A vaguely related option might be the setting of level in the logging module of the Python standard library, and I quote from Python's docs: import logging LOG_FILENAME = 'example.log' logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) logging.debug('This message should go to the log file') That level= determines which logging messages are emitted and which ones are filtered. However this only applies to errors (and other messages) emitted through logging module functions, not to (e.g) tracebacks resulting from exceptions; if you want to control the latter (what kinds of message come out when the process dies by propagating an exception), you can build something based on sys.excepthook, but your degrees of freedom will still be somewhat limited (in particular, after the reporting -- abundant or scarce as it may be -- the process will exit if an exception has propagated to that point).
Python set error reporting level like in PHP
How can I set error reporting and warning outputs in Python like in PHP error_reporting(E_LEVEL)?
[ "A vaguely related option might be the setting of level in the logging module of the Python standard library, and I quote from Python's docs:\nimport logging\nLOG_FILENAME = 'example.log'\nlogging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)\n\nlogging.debug('This message should go to the log file')\n\nTh...
[ 1 ]
[]
[]
[ "php", "python", "warnings" ]
stackoverflow_0003718630_php_python_warnings.txt
Q: How do I convert this C code into Python? I am trying to convert this C code I have into a python script so it's readily accessible by more people, but I am having problems understanding this one snippet. int i, t; for (i = 0; i < N; i++) { t = (int)(T*drand48()); z[i] = t; Nwt[w[i]][t]++; Ndt[d[i]][t]++; Nt[t]++; } N is a value (sum of one column from an array. Elemental corrected me). T is just a numerical value. z, w, and d are memory allocations created from the N array. They were created with this method. w = ivec(N); d = ivec(N); z = ivec(N); int *ivec(int n) // { int *x = (int*)calloc(n,sizeof(int)); assert(x); return x; } Nwt & Ndt are both arrays too, with each element being a memory allocation? (Not sure). At least, each one of them was created by using the following method, passing in two different int's. Nwt = dmat(W,T); Ndt = dmat(D,T); double **dmat(int nr, int nc) // { int N = nr*nc; double *tmp = (double*) calloc(N,sizeof(double)); double **x = (double**)calloc(nr,sizeof(double*)); int r; assert(tmp); assert(x); for (r = 0; r < nr; r++) x[r] = tmp + nc*r; return x; } So looking at the first loop I posted, what are the following lines doing? I would like to accomplish the same thing in python, but since no memory allocation is needed, not sure what those three lines do, or how I would duplicate it in python. Nwt[w[i]][t]++; Ndt[d[i]][t]++; Nt[t]++; This is what I have so far: for i in range(self.N): t = self.T * random.random() self.z[i] = t //** INCORRECT BELOW ** //self.Nwt[self.N[i]] = t + 1 //self.Ndt[i] = t + 1 //self.Nt[t + 1] += 1 A: A suggestion for the Python part of things is to use numpy arrays to represent the matrices (and possibly the arrays too). But to be honest, you should not be concerned with that right now. That C-code looks ugly. Apart from that, different languages use different approaches to achieve the same thing. That is what makes such conversions hard. Try to get an understanding of the algorithm it implements (supposing that is what it does) and write that down in a language-agnostic way. Then think how you would implement that in Python. A: Nwt and Ndt are 2-dimensional arrays. These lines: Nwt[w[i]][t]++; Ndt[d[i]][t]++; Increment by 1 the value at one of the locations in each of the arrays. If you think of the addressing as array[column][row], then the column is chosen based on the value in some other one-dimensional array w and d (respectively) for the index i. t seems to be some random index. You don't show what dmat function is doing, so hard to break that one down. (Can't help you on the Python side, hopefully this helps clarify the C) A: Okay you seem to have a few ideas wrong. N is the size of the array. dmat returns a matrix like thing which is represented by nr row(s) - where each row is an 'array' of nc doubles ivec returns an 'array' of n integer elements. So w[] and d[] represent indexes to the array of doubles. The loop that you are having trouble with is used to increment certain elements of the matrices. One index appears pre-stored in the w and d arrays and the other generated randomly I suspect - with out knowing what the intent of the code is it is a bit difficult to understand the semantics. Specifically it might help to know: Nwt[x][y]++ means increment (add 1) the matrix element at row x col y Also must mention that this C code is ugly - no useful naming and no comments, fearless use C's nastiest syntax, really difficult to follow. A: In your translation, the first thing I would worry about is making sensical variable names, particularly for those arrays. Regardless, much of that translates directly. Nwt and Ndt are 2D arrays, Nt is a one dimensional array. It looks like you're looping over all the 'columns' in the z array, and generating a random number for each one. Then you increment whichever column was picked in Nwt (row w[i]), Ndt (row d[i]) and Nt. The actual random value is stashed in z. #Literal translation for i in range(N): t = Random.randint(0,T) #Not sure on this... but it seems likely. z[i] = t Nwt[w[i]][t] += 1 Ndt[d[i]][t] += 1 Nt[t] += 1 #In place of w= ivec(N); w = [0]*N d = [0]*N z = [0]*N #In place of Nwt = dmat(W,T) Nwt = [[0.0] * T] * W Ndt = [[0.0] * T] * D EDIT: corrected w/d/z initialization from "n" to "N" Note that there are still some things wrong here, since it looks like N must equal W, and D... so tread carefully.
How do I convert this C code into Python?
I am trying to convert this C code I have into a python script so it's readily accessible by more people, but I am having problems understanding this one snippet. int i, t; for (i = 0; i < N; i++) { t = (int)(T*drand48()); z[i] = t; Nwt[w[i]][t]++; Ndt[d[i]][t]++; Nt[t]++; } N is a value (sum of one column from an array. Elemental corrected me). T is just a numerical value. z, w, and d are memory allocations created from the N array. They were created with this method. w = ivec(N); d = ivec(N); z = ivec(N); int *ivec(int n) // { int *x = (int*)calloc(n,sizeof(int)); assert(x); return x; } Nwt & Ndt are both arrays too, with each element being a memory allocation? (Not sure). At least, each one of them was created by using the following method, passing in two different int's. Nwt = dmat(W,T); Ndt = dmat(D,T); double **dmat(int nr, int nc) // { int N = nr*nc; double *tmp = (double*) calloc(N,sizeof(double)); double **x = (double**)calloc(nr,sizeof(double*)); int r; assert(tmp); assert(x); for (r = 0; r < nr; r++) x[r] = tmp + nc*r; return x; } So looking at the first loop I posted, what are the following lines doing? I would like to accomplish the same thing in python, but since no memory allocation is needed, not sure what those three lines do, or how I would duplicate it in python. Nwt[w[i]][t]++; Ndt[d[i]][t]++; Nt[t]++; This is what I have so far: for i in range(self.N): t = self.T * random.random() self.z[i] = t //** INCORRECT BELOW ** //self.Nwt[self.N[i]] = t + 1 //self.Ndt[i] = t + 1 //self.Nt[t + 1] += 1
[ "A suggestion for the Python part of things is to use numpy arrays to represent the matrices (and possibly the arrays too). But to be honest, you should not be concerned with that right now. That C-code looks ugly. Apart from that, different languages use different approaches to achieve the same thing. That is what...
[ 2, 1, 1, 1 ]
[]
[]
[ "c", "python" ]
stackoverflow_0003718768_c_python.txt
Q: PyQt ListView with groups How can i create connection groups inside a QListView with PyQt. The group name should not be selectable. Example: http://www.shrani.si/f/T/bB/gSpSsYt/connectionlist.jpg :) A: There are basically two approaches: add items that are the "section headings" that can be set disabled (see setFlags), or use a QTreeView.
PyQt ListView with groups
How can i create connection groups inside a QListView with PyQt. The group name should not be selectable. Example: http://www.shrani.si/f/T/bB/gSpSsYt/connectionlist.jpg :)
[ "There are basically two approaches: add items that are the \"section headings\" that can be set disabled (see setFlags), or use a QTreeView.\n" ]
[ 3 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0003717109_pyqt_python_qt.txt
Q: Modifying Python code to use SSL for a REST call I have Python code to call a REST service that is something like this: import urllib import urllib2 username = 'foo' password = 'bar' passwordManager = urllib2.HTTPPasswordMgrWithDefaultRealm() passwordManager .add_password(None, MY_APP_PATH, username, password) authHandler = urllib2.HTTPBasicAuthHandler(passwordManager) opener = urllib2.build_opener(authHandler) urllib2.install_opener(opener) params= { "param1" : param1, "param2" : param2, "param3" : param3 } xmlResults = urllib2.urlopen(MY_APP_PATH, urllib.urlencode(params)).read() results = MyResponseParser.parse(xmlResults) MY_APP_PATH is currently an HTTP url. I would like to change it to use SSL ("HTTPS"). How would I go about changing this code to use https in the simplest way possible? A: Unfortunately, urllib2 and httplib, at least up to Python 2.7 don't do any certificate verification for when using HTTPS. The result is that you're exchanging information with a server you haven't necessarily identified (it's a bit like exchanging a secret with someone whose identity you haven't verified): this defeats the security purpose of HTTPS. See this quote from httplib (in Python 2.7): Note: This does not do any certificate verification. (This is independent of httplib.HTTPSConnection being able to send a client-certificate: that's what its key and cert parameters are for.) There are ways around this, for example: http://thejosephturner.com/blog/post/https-certificate-verification-in-python-with-urllib2/ http://code.google.com/p/python-httpclient/ (not using urllib2, so possibly not the shortest way for you) A: Just using HTTPS:// instead of HTTP:// in the URL you are calling should work, at least if you are trying to reach a known/verified server. If necessary, you can use your client-side SSL certificate to secure the API transaction: mykey = '/path/to/ssl_key_file' mycert = '/path/to/ssl_cert_file' opener = urllib2.build_opener(HTTPSClientAuthHandler(mykey, mycert)) opener.add_handler(urllib2.HTTPBasicAuthHandler()) # add HTTP Basic Authentication information... opener.add_password(user=settings.USER_ID, passwd=settings.PASSWD)
Modifying Python code to use SSL for a REST call
I have Python code to call a REST service that is something like this: import urllib import urllib2 username = 'foo' password = 'bar' passwordManager = urllib2.HTTPPasswordMgrWithDefaultRealm() passwordManager .add_password(None, MY_APP_PATH, username, password) authHandler = urllib2.HTTPBasicAuthHandler(passwordManager) opener = urllib2.build_opener(authHandler) urllib2.install_opener(opener) params= { "param1" : param1, "param2" : param2, "param3" : param3 } xmlResults = urllib2.urlopen(MY_APP_PATH, urllib.urlencode(params)).read() results = MyResponseParser.parse(xmlResults) MY_APP_PATH is currently an HTTP url. I would like to change it to use SSL ("HTTPS"). How would I go about changing this code to use https in the simplest way possible?
[ "Unfortunately, urllib2 and httplib, at least up to Python 2.7 don't do any certificate verification for when using HTTPS. The result is that you're exchanging information with a server you haven't necessarily identified (it's a bit like exchanging a secret with someone whose identity you haven't verified): this de...
[ 3, 1 ]
[]
[]
[ "python", "rest", "ssl" ]
stackoverflow_0003704405_python_rest_ssl.txt
Q: TypeError uploading image file to Amazon S3 in Django using BOTO Library I am a total beginner to programming and Django so I'd appreciate help that beginner can get his head round! I was following a tutorial to show how to upload images to an Amazon S3 account with the Boto library but I think it is for an older version of Django (I'm on 1.1.2 and Python 2.65) and something has changed. I get an error: Exception Type: TypeError Exception Value: 'InMemoryUploadedFile' object is unsubscriptable My code is: Models.py: from django.db import models from django.contrib.auth.models import User from django import forms from datetime import datetime class PhotoUrl(models.Model): url = models.CharField(max_length=128) uploaded = models.DateTimeField() def save(self): self.uploaded = datetime.now() models.Model.save(self) views.py: import mimetypes from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.core.urlresolvers import reverse from django import forms from django.conf import settings from boto.s3.connection import S3Connection from boto.s3.key import Key def awsdemo(request): def store_in_s3(filename, content): conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) b = conn.create_bucket('almacmillan-hark') mime = mimetypes.guess_type(filename)[0] k = Key(b) k.key = filename k.set_metadata("Content-Type", mime) k.set_contents_from_strong(content) k.set_acl("public-read") photos = PhotoUrl.objects.all().order_by("-uploaded") if not request.method == "POST": f = UploadForm() return render_to_response('awsdemo.html', {'form':f, 'photos':photos}) f = UploadForm(request.POST, request.FILES) if not f.is_valid(): return render_to_response('awsdemo.html', {'form':f, 'photos':photos}) file = request.FILES['file'] filename = file.name content = file['content'] store_in_s3(filename, content) p = PhotoUrl(url="http://almacmillan-hark.s3.amazonaws.com/" + filename) p.save() photos = PhotoUrl.objects.all().order_by("-uploaded") return render_to_response('awsdemo.html', {'form':f, 'photos':photos}) urls.py: (r'^awsdemo/$', 'harkproject.s3app.views.awsdemo'), awsdemo.html: <div class="form"> <strong>{{form.file.label}}</strong> <form method="POST" action ="." enctype="multipart/form-data"> {{form.file}}<br/> <input type="submit" value="Upload"> </form> </div> I'd really appreciate help. I hope I have provided enough code. Kind regards AL A: I think your problem is this line: content = file['content'] From the Django docs: Each value in FILES is an UploadedFile object containing the following attributes: read(num_bytes=None) -- Read a number of bytes from the file. name -- The name of the uploaded file. size -- The size, in bytes, of the uploaded file. chunks(chunk_size=None) -- A generator that yields sequential chunks of data. Try this instead: content = file.read() A: Have you tried Django Storages? That way you only have to specify a storage backend (s3boto in this case) either as the default storage backend, or supply it as an argument to a FileField or ImageField class.
TypeError uploading image file to Amazon S3 in Django using BOTO Library
I am a total beginner to programming and Django so I'd appreciate help that beginner can get his head round! I was following a tutorial to show how to upload images to an Amazon S3 account with the Boto library but I think it is for an older version of Django (I'm on 1.1.2 and Python 2.65) and something has changed. I get an error: Exception Type: TypeError Exception Value: 'InMemoryUploadedFile' object is unsubscriptable My code is: Models.py: from django.db import models from django.contrib.auth.models import User from django import forms from datetime import datetime class PhotoUrl(models.Model): url = models.CharField(max_length=128) uploaded = models.DateTimeField() def save(self): self.uploaded = datetime.now() models.Model.save(self) views.py: import mimetypes from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.core.urlresolvers import reverse from django import forms from django.conf import settings from boto.s3.connection import S3Connection from boto.s3.key import Key def awsdemo(request): def store_in_s3(filename, content): conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) b = conn.create_bucket('almacmillan-hark') mime = mimetypes.guess_type(filename)[0] k = Key(b) k.key = filename k.set_metadata("Content-Type", mime) k.set_contents_from_strong(content) k.set_acl("public-read") photos = PhotoUrl.objects.all().order_by("-uploaded") if not request.method == "POST": f = UploadForm() return render_to_response('awsdemo.html', {'form':f, 'photos':photos}) f = UploadForm(request.POST, request.FILES) if not f.is_valid(): return render_to_response('awsdemo.html', {'form':f, 'photos':photos}) file = request.FILES['file'] filename = file.name content = file['content'] store_in_s3(filename, content) p = PhotoUrl(url="http://almacmillan-hark.s3.amazonaws.com/" + filename) p.save() photos = PhotoUrl.objects.all().order_by("-uploaded") return render_to_response('awsdemo.html', {'form':f, 'photos':photos}) urls.py: (r'^awsdemo/$', 'harkproject.s3app.views.awsdemo'), awsdemo.html: <div class="form"> <strong>{{form.file.label}}</strong> <form method="POST" action ="." enctype="multipart/form-data"> {{form.file}}<br/> <input type="submit" value="Upload"> </form> </div> I'd really appreciate help. I hope I have provided enough code. Kind regards AL
[ "I think your problem is this line:\ncontent = file['content']\n\nFrom the Django docs:\n\nEach value in FILES is an UploadedFile object containing the following attributes:\n\nread(num_bytes=None) -- Read a number of bytes from the file.\nname -- The name of the uploaded file.\nsize -- The size, in bytes, of the u...
[ 7, 0 ]
[]
[]
[ "amazon_s3", "boto", "django", "file_upload", "python" ]
stackoverflow_0003414778_amazon_s3_boto_django_file_upload_python.txt
Q: Need to remove duplicates from a list of dictionaries and alter data for the remaining duplicate (python) Consider this short python list of dictionaries (first dictionary item is a string, second item is a Widget object): raw_results = [{'src': 'tag', 'widget': <Widget: to complete a form today>}, # dupe 1a {'src': 'tag', 'widget': <Widget: a newspaper>}, # dupe 2a {'src': 'zip', 'widget': <Widget: to complete a form today>}, # dupe 1b {'src': 'zip', 'widget': <Widget: the new Jack Johnson album>}, {'src': 'zip', 'widget': <Widget: a newspaper>}, # dupe 2b {'src': 'zip', 'widget': <Widget: premium dog food >}] I want to go through that list and remove the duplicates, which this SO question answered for me: Remove duplicates in a list while keeping its order (Python) known_widgets= set() processed_results = [] for x in raw_results: widget = x['widget'] if widget in known_widgets: continue else: processed_results.append(x) known_widgets.add(widget) However, after I remove the duplicate row (e.g. dupe 1b), I want to change the remaining duplicate's (e.g. dupe 1a) "src" data. I would like to append the removed duplicates "src" to the original. This is what I'd like to end up with: processed_results = [{'src': 'tag-zip', 'widget': <Widget: to complete a form today>}, # dupe 1a {'src': 'tag-zip', 'widget': <Widget: a newspaper>}, # dupe 2a {'src': 'zip', 'widget': <Widget: the new Jack Johnson album>}, {'src': 'zip', 'widget': <Widget: premium dog food >}] I'm sure this is easy to do, but my head is spinning after too much coffee and many hours circling this problem. I'd love and really appreciate the help of an expert. Thank you! A: def find_widget(widget, L): for i, v in enumerate(L): if v[widget] == widget: return i known_widgets= set() processed_results = [] for x in raw_results: widget = x['widget'] if widget in known_widgets: processed_widgets[find_widget(widget, processed_results)]['src'] += '-%s' % x['tag'] continue else: processed_results.append(x) known_widgets.add(widget) Could probably be done better (as this is two passes for each duplicate widget). A: Assuming you want to have a list of widgets keyed on the repeated src values, this is what you want: class Widget(object): def __init__(self, desc): self.desc = desc def __str__(self): return "Widget(%s)" % self.desc raw_results = [ {'src':'tag-zip', 'widget':Widget('to complete a form today')}, {'src':'tag-zip', 'widget':Widget('a newspaper')}, {'src':'zip', 'widget':Widget('the new Jack Johnson album')}, {'src':'zip', 'widget':Widget('premium dog food')} ] from collections import defaultdict known_widgets = defaultdict(list) for x in raw_results: k, v = x['src'], x['widget'] known_widgets[k].append(v) for k, v in known_widgets.iteritems(): print "%s: %s" % (k, ",".join(str(w) for w in v)) And if you want the duplicate widget5s eliminated, do this: class Widget(object): def __init__(self, desc): self.desc = desc def __str__(self): return "Widget(%s)" % self.desc def __hash__(self): return hash(self.desc) def __cmp__(self, other): return cmp(self.desc, other.desc) raw_results = [ {'src':'tag-zip', 'widget':Widget('to complete a form today')}, {'src':'tag-zip', 'widget':Widget('a newspaper')}, {'src':'zip', 'widget':Widget('the new Jack Johnson album')}, {'src':'zip', 'widget':Widget('premium dog food')}, {'src':'tag-zip', 'widget':Widget('to complete a form today')}, {'src':'tag-zip', 'widget':Widget('a newspaper')}, {'src':'zip', 'widget':Widget('the new Jack Johnson album')}, {'src':'zip', 'widget':Widget('premium dog food')}, ] from collections import defaultdict known_widgets = defaultdict(set) for x in raw_results: k, v = x['src'], x['widget'] known_widgets[k].add(v) for k, v in known_widgets.iteritems(): print "%s: %s" % (k, ",".join(str(w) for w in v))
Need to remove duplicates from a list of dictionaries and alter data for the remaining duplicate (python)
Consider this short python list of dictionaries (first dictionary item is a string, second item is a Widget object): raw_results = [{'src': 'tag', 'widget': <Widget: to complete a form today>}, # dupe 1a {'src': 'tag', 'widget': <Widget: a newspaper>}, # dupe 2a {'src': 'zip', 'widget': <Widget: to complete a form today>}, # dupe 1b {'src': 'zip', 'widget': <Widget: the new Jack Johnson album>}, {'src': 'zip', 'widget': <Widget: a newspaper>}, # dupe 2b {'src': 'zip', 'widget': <Widget: premium dog food >}] I want to go through that list and remove the duplicates, which this SO question answered for me: Remove duplicates in a list while keeping its order (Python) known_widgets= set() processed_results = [] for x in raw_results: widget = x['widget'] if widget in known_widgets: continue else: processed_results.append(x) known_widgets.add(widget) However, after I remove the duplicate row (e.g. dupe 1b), I want to change the remaining duplicate's (e.g. dupe 1a) "src" data. I would like to append the removed duplicates "src" to the original. This is what I'd like to end up with: processed_results = [{'src': 'tag-zip', 'widget': <Widget: to complete a form today>}, # dupe 1a {'src': 'tag-zip', 'widget': <Widget: a newspaper>}, # dupe 2a {'src': 'zip', 'widget': <Widget: the new Jack Johnson album>}, {'src': 'zip', 'widget': <Widget: premium dog food >}] I'm sure this is easy to do, but my head is spinning after too much coffee and many hours circling this problem. I'd love and really appreciate the help of an expert. Thank you!
[ "def find_widget(widget, L):\n for i, v in enumerate(L):\n if v[widget] == widget:\n return i\n\nknown_widgets= set()\nprocessed_results = []\n\nfor x in raw_results:\n widget = x['widget']\n if widget in known_widgets:\n processed_widgets[find_widget(widget, processed_results)]['src']...
[ 2, 1 ]
[]
[]
[ "dictionary", "duplicates", "list", "python" ]
stackoverflow_0003704674_dictionary_duplicates_list_python.txt
Q: How to search for most recent excel files in remore directories in PYTHON? This is the code that lists all the subdirectories from FTP server. How do I search for the most recent Excel files sitting in these multiple Subdirectories directory? As shown in the results, I want to go through all the ls**** subdirectories and notify me if there is an Excel file with today's date. Thanks in advance! from ftplib import FTP def handleDownload(block): file.write(block) print ".", ftp = FTP('connect to host,'name', 'dflt port') directory = 'Dir_name' ftp.cwd(directory) data = [] ftp.dir(data.append) ftpContentList = ftp.retrlines('LIST') # list directory contents Results: drwxrwx--- 4 17610000 smartfile 4096 Jul 21 19:31 ls0125 drwxrwx--- 4 17610000 smartfile 4096 Jul 19 20:34 ls0146 drwxrwx--- 4 17610000 smartfile 4096 Jul 21 19:31 ls0265 drwxrwx--- 4 17610000 smartfile 4096 Jul 19 20:34 ls0368 A: You're going to want to register a callback function in ftp.retlines like so def callback(line): try: #only use this code if you'll be dealing with that FTP server alone #look into dateutil module which parses dates with more flexibility when = datetime.strptime(re.search('[A-z]{3}\s+\d{1,2}\s\d{1,2}:\d{2}', line).group(0), "%b %d %H:%M") today = datetime.today() if when.day == today.day and when.month == today.month: pass #perform your magic here except: print "failed to parse" return ftp.retrlines('LIST', callback)
How to search for most recent excel files in remore directories in PYTHON?
This is the code that lists all the subdirectories from FTP server. How do I search for the most recent Excel files sitting in these multiple Subdirectories directory? As shown in the results, I want to go through all the ls**** subdirectories and notify me if there is an Excel file with today's date. Thanks in advance! from ftplib import FTP def handleDownload(block): file.write(block) print ".", ftp = FTP('connect to host,'name', 'dflt port') directory = 'Dir_name' ftp.cwd(directory) data = [] ftp.dir(data.append) ftpContentList = ftp.retrlines('LIST') # list directory contents Results: drwxrwx--- 4 17610000 smartfile 4096 Jul 21 19:31 ls0125 drwxrwx--- 4 17610000 smartfile 4096 Jul 19 20:34 ls0146 drwxrwx--- 4 17610000 smartfile 4096 Jul 21 19:31 ls0265 drwxrwx--- 4 17610000 smartfile 4096 Jul 19 20:34 ls0368
[ "You're going to want to register a callback function in ftp.retlines like so\ndef callback(line):\n try:\n #only use this code if you'll be dealing with that FTP server alone\n #look into dateutil module which parses dates with more flexibility\n when = datetime.strptime(re.search('[A-z]{3}...
[ 1 ]
[]
[]
[ "ftp", "ftplib", "python" ]
stackoverflow_0003719885_ftp_ftplib_python.txt
Q: python: Is there a stronger version of json other than the built in one I use the built in json for python 2.6. I'm having tons of trouble parsing jsons like this: { name: 'some name' value: 'some value' } I found two reasons - ' doesn't work. You need " the keys of the dictionary need to be strings. I.e "name"/"value" Am I missing something? Is there a way to parse this kind of dictionary using the json package? Is there any other python package that can parse this? Thanks A: I think that what you want is not a "stronger" parser but a broken parser that will parse broken code. See the standard specifically, The keys of an object are defined to be strings Strings are defined to be "" or "chars" where chars has the pretty much obvious meaning There's someplace on the internet where you can watch Douglass Crockford make semi-witty remarks about why this is the case. It has to do with compatibility with non-javascript languages though. Specifically, you could not have {name :'some name', value: 'some value'} as a dict in python unless name and some value where preexisting, hashable variables; Broken parsers in general are bad. Just look at the mess that broken HTML parsers in browsers have created where any idiot can make a web site. That dude that wrote all those RFC's had it wrong: It's better to be strict in what you emit and what you accept. A: The problem is not with the Python module, the problem is with your string, which could be whatever you say, but not JSON, so it cannot be parsed by a JSON parser. If it were JSON it would look like: {"name":"some name", "value":"some value"} So, it is not a problem with the Python module. It is like asking for a "stronger python compiler" because C-Python cannot parse: using json json.loads(my_string) Obviously the first line is simply not Python, so we cannot ask Python to interpret it. Now if you want to parse that string I recommend that you either: make it a JSON string OR use Pyparsing for writing a quick and dirty parser (I guarantee it will work great in less than, say, 50 lines). Cheers, Juan. A: There are: simplejson, which is "is the externally maintained development version of the json library included with Python 2.6 and Python 3.0, but maintains backwards compatibility with Python 2.5." cjson (Not sure if they'll parse broken JSON.)
python: Is there a stronger version of json other than the built in one
I use the built in json for python 2.6. I'm having tons of trouble parsing jsons like this: { name: 'some name' value: 'some value' } I found two reasons - ' doesn't work. You need " the keys of the dictionary need to be strings. I.e "name"/"value" Am I missing something? Is there a way to parse this kind of dictionary using the json package? Is there any other python package that can parse this? Thanks
[ "I think that what you want is not a \"stronger\" parser but a broken parser that will parse broken code. See the standard\nspecifically,\n\nThe keys of an object are defined to be strings\nStrings are defined to be \"\" or \"chars\" where chars has the pretty much obvious meaning\n\nThere's someplace on the intern...
[ 4, 2, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0003720428_json_python.txt
Q: Numpy Modular arithmetic How can I define in numpy a matrix that uses operations modulo 2? For example: 0 0 1 0 1 0 1 1 + 0 1 = 1 0 Thanks! A: This operation is called "xor". >>> import numpy >>> x = numpy.array([[0,0],[1,1]]) >>> y = numpy.array([[1,0],[0,1]]) >>> x ^ y array([[1, 0], [1, 0]]) BTW, (element-wise) multiplication modulo 2 can be done with "and". >>> x & y array([[0, 0], [0, 1]]) A: You could subclass numpy.ndarray and override the __add__ method, but I think it would be far simpler to just be explicit. For example: import numpy as np x = np.array([[0,0],[1,1]]) y = np.array([[1,0],[0,1]]) print (x + y) % 2 Which yields: array([[1, 0], [1, 0]])
Numpy Modular arithmetic
How can I define in numpy a matrix that uses operations modulo 2? For example: 0 0 1 0 1 0 1 1 + 0 1 = 1 0 Thanks!
[ "This operation is called \"xor\".\n>>> import numpy\n>>> x = numpy.array([[0,0],[1,1]])\n>>> y = numpy.array([[1,0],[0,1]])\n>>> x ^ y\narray([[1, 0],\n [1, 0]])\n\nBTW, (element-wise) multiplication modulo 2 can be done with \"and\".\n>>> x & y\narray([[0, 0],\n [0, 1]])\n\n", "You could subclass nu...
[ 9, 2 ]
[]
[]
[ "math", "modular", "numpy", "python" ]
stackoverflow_0003719957_math_modular_numpy_python.txt
Q: Server Costs for a Computing-Intense Application? I have a scientific application that I built in Python (the application's 'critical areas' are optimized with Cython, for increased speed). Every instance of the application is given a text file (with parameters) an an input. The application reads the parameters from the text file and, using data that is stored in the hard drive, runs and outputs the results of the calculations back into the hard drive. Every instance requires about 600MB of memory over the course of its operation. Currently, I am running the app on my laptop (Intel Core 2 Duo, T7500, @2.2Ghz, 2GB RAM). Every 'instance run' on my laptop takes about 3 hours to complete. Due to the needs of the project, there is a need for me to run 10000 instances. Obviously, it would take forever to do so on my laptop, hence the need for more computing power. Knowing that every such an instance is independent from another, what would be the cost of a server that can run say 10 instances at the same time (I am on a budget...)? Can you recommend on a configuration? Currently, I am using Windows XP but ideally, I would be happy to have the server installed with unix (ubuntu). A: You can spin up Amazon EC2 standard instances (1.7GB / 1 slow core) for $0.085 per hour, or 23GB / 8core "cluster compute" instances for $1.60 an hour. "One EC2 Compute Unit equals 1.0-1.2 GHz 2007 Xeon processor." According to the tool, 10,000 "High-CPU Medium" instances with 5 EC2 Compute Units and 1.7GB each, for 3 hours, is $5100. This doesn't include the cost of getting your source data in and results out. You can also bid on idle server time. The current "spot" price is about 1/3 the "on-demand" price, and fluctuates with demand. If you put in a low bid, your job may be interrupted by demand. It is interesting to compare the cost of electricity for running your server/cooling with the cost of an Amazon instance. Commerical electricity rates are about 7.5¢/kWh here.. A: http://calculator.s3.amazonaws.com/calc5.html It'd probably cost you about 15 dollars and you cut run it on a massive cluster of computers if the problem is easily parallelized.
Server Costs for a Computing-Intense Application?
I have a scientific application that I built in Python (the application's 'critical areas' are optimized with Cython, for increased speed). Every instance of the application is given a text file (with parameters) an an input. The application reads the parameters from the text file and, using data that is stored in the hard drive, runs and outputs the results of the calculations back into the hard drive. Every instance requires about 600MB of memory over the course of its operation. Currently, I am running the app on my laptop (Intel Core 2 Duo, T7500, @2.2Ghz, 2GB RAM). Every 'instance run' on my laptop takes about 3 hours to complete. Due to the needs of the project, there is a need for me to run 10000 instances. Obviously, it would take forever to do so on my laptop, hence the need for more computing power. Knowing that every such an instance is independent from another, what would be the cost of a server that can run say 10 instances at the same time (I am on a budget...)? Can you recommend on a configuration? Currently, I am using Windows XP but ideally, I would be happy to have the server installed with unix (ubuntu).
[ "You can spin up Amazon EC2 standard instances (1.7GB / 1 slow core) for $0.085 per hour, or 23GB / 8core \"cluster compute\" instances for $1.60 an hour. \n\"One EC2 Compute Unit equals 1.0-1.2 GHz 2007 Xeon processor.\"\nAccording to the tool, 10,000 \"High-CPU Medium\" instances with 5 EC2 Compute Units and 1.7G...
[ 1, 0 ]
[]
[]
[ "cython", "python", "server_hardware", "ubuntu" ]
stackoverflow_0003720667_cython_python_server_hardware_ubuntu.txt
Q: How to plot a figure of my purpose in python? in python, I would like to use: from pylab import * Then use plot provided in this module. However, the curves I plot were not what I want: Say two lists: x = [1, 2, 3, 4] y = [1.4, 5.6, 6, 3.5] and I am after a plot method that can plot the following chart: Plot a line that joins the points: (1, 0) and (1, 1.4) Plot a line that joins the points: (2, 0) and (2, 5.6) Plot a line that joins the points: (3, 0) and (3, 6) Plot a line that joins the points: (4, 0) and (4, 3.5) ... i.e.: it should plot a spectra like graphs, such as plot(x, type='h') in R. I suppose the plot method I use just joins all the points by lines. So, for my purpose, which methods to choose please? thanks!! A: Maybe you want just vertical lines? You could use vlines(x, [0], y). See this example You could also have a look at this page (screenshots) to help you select the right function. A: Do you mean a bar chart? If so, just use the bar function: bar(x, y)
How to plot a figure of my purpose in python?
in python, I would like to use: from pylab import * Then use plot provided in this module. However, the curves I plot were not what I want: Say two lists: x = [1, 2, 3, 4] y = [1.4, 5.6, 6, 3.5] and I am after a plot method that can plot the following chart: Plot a line that joins the points: (1, 0) and (1, 1.4) Plot a line that joins the points: (2, 0) and (2, 5.6) Plot a line that joins the points: (3, 0) and (3, 6) Plot a line that joins the points: (4, 0) and (4, 3.5) ... i.e.: it should plot a spectra like graphs, such as plot(x, type='h') in R. I suppose the plot method I use just joins all the points by lines. So, for my purpose, which methods to choose please? thanks!!
[ "Maybe you want just vertical lines? You could use vlines(x, [0], y). See this example\nYou could also have a look at this page (screenshots) to help you select the right function.\n", "Do you mean a bar chart? If so, just use the bar function:\nbar(x, y)\n\n" ]
[ 4, 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003720499_matplotlib_python.txt
Q: Applying conditions to dictionary key values while traversing through them The Dictionary is as given below: goodDay= {'Class':[1,1,0,0,0,1,0,1,0,1], 'Grade':[1,0,0,1,0,1,0,1,0,1]} I want to code this way that i should get the count of "1" and also "0" in Class when my grade has value "1" and also vice versa i.e. when my grade has value "0". So i will have to traverse through the list values for both and Class and Grade and then may be put this condition while segregating. Please help. Thanks A: This counts the number of cs (classes) which are 1 when g (grades) is 1: In [5]: sum(c for c,g in zip(goodDay['Class'],goodDay['Grade']) if g) Out[5]: 4 And this gives the number of gs that are 1 when c is 1: In [6]: sum(g for c,g in zip(goodDay['Class'],goodDay['Grade']) if c) Out[6]: 4
Applying conditions to dictionary key values while traversing through them
The Dictionary is as given below: goodDay= {'Class':[1,1,0,0,0,1,0,1,0,1], 'Grade':[1,0,0,1,0,1,0,1,0,1]} I want to code this way that i should get the count of "1" and also "0" in Class when my grade has value "1" and also vice versa i.e. when my grade has value "0". So i will have to traverse through the list values for both and Class and Grade and then may be put this condition while segregating. Please help. Thanks
[ "This counts the number of cs (classes) which are 1 when g (grades) is 1:\nIn [5]: sum(c for c,g in zip(goodDay['Class'],goodDay['Grade']) if g)\nOut[5]: 4\n\nAnd this gives the number of gs that are 1 when c is 1:\nIn [6]: sum(g for c,g in zip(goodDay['Class'],goodDay['Grade']) if c)\nOut[6]: 4\n\n" ]
[ 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003720802_dictionary_python.txt
Q: App Engine Bulk Loader Performance I am using the App Engine Bulk loader (Python Runtime) to bulk upload entities to the data store. The data that i am uploading is stored in a proprietary format, so i have implemented by own connector (registerd it in bulkload_config.py) to convert it to the intermediate python dictionary. import google.appengine.ext.bulkload import connector_interface class MyCustomConnector(connector_interface.ConnectorInterface): .... #Overridden method def generate_import_record(self, filename, bulkload_state=None): .... yeild my_custom_dict To convert this neutral python dictionary to a datastore Entity, i use a custom post import function that i have defined in my YAML. def feature_post_import(input_dict, entity_instance, bulkload_state): .... return [all_entities_to_put] Note: I am not using entity_instance, bulkload_state in my feature_post_import function. I am just creating new data store entities (based on my input_dict), and returning them. Now, everything works great. However, the process of bulk loading data seems to take way too much time. For e.g. a GB (~ 1,000,000 entities) of data takes ~ 20 hours. How can I improve the performance of the bulk load process. Am i missing something? Some of the parameters that i use with appcfg.py are (10 threads with a batch size of 10 entities per thread). Linked a Google App Engine Python group post: http://groups.google.com/group/google-appengine-python/browse_thread/thread/4c8def071a86c840 Update: To test the performance of the Bulk Load process, I loaded entities of a 'Test' Kind. Even though this entity has a very simple FloatProperty, it still took me the same amount of time to bulk load those entities. I am still going to try to vary the bulk loader parameters, rps_limit, bandwidth_limit and http_limit, to see if i can get any more throughput. A: There is parameter called rps_limit that determines the number of entities to upload per second. This was the major bottleneck. The default value for this is 20. Also increase the bandwidth_limit to something reasonable. I increased rps_limit to 500 and everything improved. I achieved 5.5 - 6 seconds per 1000 entities which is a major improvement from 50 seconds per 1000 entities.
App Engine Bulk Loader Performance
I am using the App Engine Bulk loader (Python Runtime) to bulk upload entities to the data store. The data that i am uploading is stored in a proprietary format, so i have implemented by own connector (registerd it in bulkload_config.py) to convert it to the intermediate python dictionary. import google.appengine.ext.bulkload import connector_interface class MyCustomConnector(connector_interface.ConnectorInterface): .... #Overridden method def generate_import_record(self, filename, bulkload_state=None): .... yeild my_custom_dict To convert this neutral python dictionary to a datastore Entity, i use a custom post import function that i have defined in my YAML. def feature_post_import(input_dict, entity_instance, bulkload_state): .... return [all_entities_to_put] Note: I am not using entity_instance, bulkload_state in my feature_post_import function. I am just creating new data store entities (based on my input_dict), and returning them. Now, everything works great. However, the process of bulk loading data seems to take way too much time. For e.g. a GB (~ 1,000,000 entities) of data takes ~ 20 hours. How can I improve the performance of the bulk load process. Am i missing something? Some of the parameters that i use with appcfg.py are (10 threads with a batch size of 10 entities per thread). Linked a Google App Engine Python group post: http://groups.google.com/group/google-appengine-python/browse_thread/thread/4c8def071a86c840 Update: To test the performance of the Bulk Load process, I loaded entities of a 'Test' Kind. Even though this entity has a very simple FloatProperty, it still took me the same amount of time to bulk load those entities. I am still going to try to vary the bulk loader parameters, rps_limit, bandwidth_limit and http_limit, to see if i can get any more throughput.
[ "There is parameter called rps_limit that determines the number of entities to upload per second. This was the major bottleneck. The default value for this is 20. \nAlso increase the bandwidth_limit to something reasonable. \nI increased rps_limit to 500 and everything improved. I achieved 5.5 - 6 seconds per 1000 ...
[ 4 ]
[]
[]
[ "bulk_load", "bulkloader", "google_app_engine", "performance", "python" ]
stackoverflow_0003670941_bulk_load_bulkloader_google_app_engine_performance_python.txt
Q: win32: moving mouse with SetCursorPos vs. mouse_event Is there any difference between moving the mouse in windows using the following two techniques? win32api.SetCursorPos((x,y)) vs: nx = x*65535/win32api.GetSystemMetrics(0) ny = y*65535/win32api.GetSystemMetrics(1) win32api.mouse_event(win32con.MOUSEEVENTF_ABSOLUTE|win32con.MOUSEEVENTF_MOVE,nx,ny) Does anything happen differently in the way Windows processes the movements? A: I believe that mouse_event works by inserting the events into the mouse input stream where as SetCursorPos just moves the cursor around the screen. I don't believe that SetCursorPos generates any input events either (though I may be wrong). The practical implications are that when you use SetCursorPos, it just moves the cursor around. Where as when you use mouse_event, it inserts the events in the input stream which will in turn generate input events for any programs that are listening. This has implications with programs that listen for lower level mouse events rather than just cursor clicks; games for instance. Also, if you're using mouse_event to move the cursor around and have cursor/pointer acceleration on, than the resulting mouse motion should be subject to whatever acceleration curves windows is using.
win32: moving mouse with SetCursorPos vs. mouse_event
Is there any difference between moving the mouse in windows using the following two techniques? win32api.SetCursorPos((x,y)) vs: nx = x*65535/win32api.GetSystemMetrics(0) ny = y*65535/win32api.GetSystemMetrics(1) win32api.mouse_event(win32con.MOUSEEVENTF_ABSOLUTE|win32con.MOUSEEVENTF_MOVE,nx,ny) Does anything happen differently in the way Windows processes the movements?
[ "I believe that mouse_event works by inserting the events into the mouse input stream where as SetCursorPos just moves the cursor around the screen. I don't believe that SetCursorPos generates any input events either (though I may be wrong).\nThe practical implications are that when you use SetCursorPos, it just mo...
[ 5 ]
[]
[]
[ "automation", "input", "python", "winapi" ]
stackoverflow_0003720938_automation_input_python_winapi.txt
Q: Example use of assert in Python? I've read about when to use assert vs. exceptions, but I'm still not "getting it". It seems like whenever I think I'm in a situation where I should use assert, later on in development I find that I'm "looking before I leap" to make sure the assert doesn't fail when I call the function. Since there's another Python idiom about preferring to use try-except, I generally end up ditching the assert and throwing an exception instead. I have yet to find a place where it seems right to use an assert. Can anyone come up with some good examples? A: A good guideline is using assert when its triggering means a bug in your code. When your code assumes something and acts upon the assumption, it's recommended to protect this assumption with an assert. This assert failing means your assumption isn't correct, which means your code isn't correct. A: tend to use assert to check for things that should never happen. sort of like a sanity check. Another thing to realize is that asserts are removed when optimized: The current code generator emits no code for an assert statement when optimization is requested at compile time. A: Generelly, assert is there to verify an assumption you have about your code, i.e. at that point in time, either the assert succeeds, or your implementation is somehow buggy. An exception is acutally expecting an error to happen and "embracing" it, i.e. allowing you to handle it. A: A good example is checking the arguments of a function for consistency: def f(probability_vector, positive_number): assert sum(probability_vector) == 1., "probability vectors have to sum to 1" assert positive_number >= 0., "positive_number should be positive" # body of function goes here
Example use of assert in Python?
I've read about when to use assert vs. exceptions, but I'm still not "getting it". It seems like whenever I think I'm in a situation where I should use assert, later on in development I find that I'm "looking before I leap" to make sure the assert doesn't fail when I call the function. Since there's another Python idiom about preferring to use try-except, I generally end up ditching the assert and throwing an exception instead. I have yet to find a place where it seems right to use an assert. Can anyone come up with some good examples?
[ "A good guideline is using assert when its triggering means a bug in your code. When your code assumes something and acts upon the assumption, it's recommended to protect this assumption with an assert. This assert failing means your assumption isn't correct, which means your code isn't correct.\n", "tend to use ...
[ 23, 16, 3, 3 ]
[]
[]
[ "assert", "exception", "python" ]
stackoverflow_0003721126_assert_exception_python.txt
Q: win32: simulate a click without simulating mouse movement? I'm trying to simulate a mouse click on a window. I currently have success doing this as follows (I'm using Python, but it should apply to general win32): win32api.SetCursorPos((x,y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0) This works fine. However, if the click happens while I'm moving the mouse manually, the cursor position gets thrown off. Is there any way to send a click directly to a given (x,y) coordinate without moving the mouse there? I've tried something like the following with not much luck: nx = x*65535/win32api.GetSystemMetrics(0) ny = y*65535/win32api.GetSystemMetrics(1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN | \ win32con.MOUSEEVENTF_ABSOLUTE,nx,ny) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP | \ win32con.MOUSEEVENTF_ABSOLUTE,nx,ny) A: Try WindowFromPoint() function: POINT pt; pt.x = 30; // This is your click coordinates pt.y = 30; HWND hWnd = WindowFromPoint(pt); LPARAM lParam = MAKELPARAM(pt.x, pt.y); PostMessage(hWnd, WM_RBUTTONDOWN, MK_RBUTTON, lParam); PostMessage(hWnd, WM_RBUTTONUP, MK_RBUTTON, lParam); A: This doesn't answer the question, but it does solve my problem: win32api.ClipCursor((x-1,y-1,x+1,y+1)) win32api.SetCursorPos((x,y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN| \ win32con.MOUSEEVENTF_ABSOLUTE,0,0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP| \ win32con.MOUSEEVENTF_ABSOLUTE,0,0) win32api.ClipCursor((0,0,0,0)) The result is that any movements I'm making won't interfere with the click. The downside is that my actual movement will be messed up, so I'm still open to suggestions.
win32: simulate a click without simulating mouse movement?
I'm trying to simulate a mouse click on a window. I currently have success doing this as follows (I'm using Python, but it should apply to general win32): win32api.SetCursorPos((x,y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0) This works fine. However, if the click happens while I'm moving the mouse manually, the cursor position gets thrown off. Is there any way to send a click directly to a given (x,y) coordinate without moving the mouse there? I've tried something like the following with not much luck: nx = x*65535/win32api.GetSystemMetrics(0) ny = y*65535/win32api.GetSystemMetrics(1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN | \ win32con.MOUSEEVENTF_ABSOLUTE,nx,ny) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP | \ win32con.MOUSEEVENTF_ABSOLUTE,nx,ny)
[ "Try WindowFromPoint() function:\nPOINT pt;\n pt.x = 30; // This is your click coordinates\n pt.y = 30;\n\nHWND hWnd = WindowFromPoint(pt);\nLPARAM lParam = MAKELPARAM(pt.x, pt.y);\nPostMessage(hWnd, WM_RBUTTONDOWN, MK_RBUTTON, lParam);\nPostMessage(hWnd, WM_RBUTTONUP, MK_RBUTTON, lParam);\n\n", "This doesn...
[ 11, 4 ]
[]
[]
[ "automation", "input", "mouse", "python", "winapi" ]
stackoverflow_0003720968_automation_input_mouse_python_winapi.txt
Q: How to authenticate the administrator username in Windows I want to authenticate the administrator username's password. The administrator username is not a domain account but a local system account. I am trying to do this in Python, but any code even if it is .NET, VC++ would be fine. Thanks A: You can either LogonUser (and be sure to CloseHandle after) or call NetUserChangePassword (with old and new passwords the same). Anything in .NET or Python will likely wrap LogonUser.
How to authenticate the administrator username in Windows
I want to authenticate the administrator username's password. The administrator username is not a domain account but a local system account. I am trying to do this in Python, but any code even if it is .NET, VC++ would be fine. Thanks
[ "You can either LogonUser (and be sure to CloseHandle after) or call NetUserChangePassword (with old and new passwords the same). Anything in .NET or Python will likely wrap LogonUser.\n" ]
[ 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0003721178_python_windows.txt
Q: Python 3.1 image library So, is there an image processing library for Python 3.x? There is Python Imaging Library (PIL) but the last supported Python version is 2.7 ("A version for 3.X will be released later.") A: PyQt provides image processing functionality and is available for Python 3, if you can live with a dependency of that size and with such license restrictions.
Python 3.1 image library
So, is there an image processing library for Python 3.x? There is Python Imaging Library (PIL) but the last supported Python version is 2.7 ("A version for 3.X will be released later.")
[ "PyQt provides image processing functionality and is available for Python 3, if you can live with a dependency of that size and with such license restrictions.\n" ]
[ 3 ]
[]
[]
[ "image", "image_processing", "python" ]
stackoverflow_0003721329_image_image_processing_python.txt
Q: Readable convention for unpacking single value tuple There are some related questions about unpacking single-value tuples, but I'd like to know if there is a preferred method in terms of readability for sharing and maintaining code. I'm finding these to be a source of confusion or misreading among colleagues when they involve a long function chain such as an ORM query. Is there some convention for this similar to the pep8 guidelines? If not, which is the clearest, most readable way to do it? Below are the ways I've tried, and my thoughts on them. Two common methods that are neat but easy to miss: value, = long().chained().expression().that().returns().tuple() value = long().chained().expression().that().returns().tuple()[0] A function would be explicit, but non-standard: value = unpack_tuple(long().chained().expression().that().returns().tuple()) Maybe always commenting would be the most clear? # unpack single-value tuple value, = long().chained().expression().that().returns().tuple() A: How about using explicit parenthesis to indicate that you are unpacking a tuple? (value, ) = long().chained().expression().that().returns().tuple() After all explicit is better than implicit.
Readable convention for unpacking single value tuple
There are some related questions about unpacking single-value tuples, but I'd like to know if there is a preferred method in terms of readability for sharing and maintaining code. I'm finding these to be a source of confusion or misreading among colleagues when they involve a long function chain such as an ORM query. Is there some convention for this similar to the pep8 guidelines? If not, which is the clearest, most readable way to do it? Below are the ways I've tried, and my thoughts on them. Two common methods that are neat but easy to miss: value, = long().chained().expression().that().returns().tuple() value = long().chained().expression().that().returns().tuple()[0] A function would be explicit, but non-standard: value = unpack_tuple(long().chained().expression().that().returns().tuple()) Maybe always commenting would be the most clear? # unpack single-value tuple value, = long().chained().expression().that().returns().tuple()
[ "How about using explicit parenthesis to indicate that you are unpacking a tuple? \n(value, ) = long().chained().expression().that().returns().tuple()\n\nAfter all explicit is better than implicit. \n" ]
[ 22 ]
[]
[]
[ "coding_style", "python", "tuples" ]
stackoverflow_0003721477_coding_style_python_tuples.txt
Q: twisted: how to communicate elegantly between reactor code and threaded code? I have a client connected to a server using twisted. The client has a thread which might potentially be doing things in the background. When the reactor is shutting down, I have to: 1) check if the thread is doing things 2) stop it if it is What's an elegant way to do this? The best I can do is some confused thing like: def cleanup(self): isWorkingDF = defer.Deferred() doneDF = defer.Deferred() def checkIsWorking(): res = self.stuff.isWorking() #blocking call reactor.callFromThread(isWorkingDF.callback, res) def shutdownOrNot(isWorking): if isWorking: #shutdown necessary, shutdown is also a blocking call def shutdown(): self.stuff.shutdown() reactor.callFromThread(doneDF, None) reactor.callInThread(shutdown) else: doneDF.callback(None) #no shutdown needed isWorkingDF.addCallback(shutdownOrNot) reactor.callInThread(checkIsWorking) return doneDF First we check if it's working at all. The result of that callback goes into rescallback which either shuts down or doesn't, and then fires the doneDF, which twisted waits for until closing. Pretty messed up eh! Is there a better way? Maybe a related question is, is there a more elegant way to chain callbacks to each other? I could see myself needing to do more cleanup code after this is done, so then I'd have to make a different done deferred, and have the current doneDF fire a callback which does stuff then calls that done deferred.. A: Ah the real answer is to use the defer.inlineCallbacks decorator. The above code now becomes: @defer.inlineCallbacks def procShutdownStuff(self): isWorking = yield deferToThread(self.stuff.isWorking) if isWorking: yield deferToThread(self.stuff.shutdown) def cleanup(self): return self.procShutdownStuff() A: You can simplify this somewhat by using deferToThread instead of the callInThread/callFromThread pairs: from twisted.internet.threads import deferToThread def cleanup(self): isWorkingDF = deferToThread(self.stuff.isWorking) def shutdownOrNot(isWorking): if isWorking: #shutdown necessary, shutdown is also a blocking call return deferToThread(self.stuff.shutdown) isWorkingDF.addCallback(shutdownOrNot) return isWorkingDF deferToThread is basically just a nice wrapper around the same threading logic you had implemented twice in your version of the function. A: If the program is terminating after you shut down the reactor you could make the thread a daemon thread. This will automatically exit when all the non-daemon threads terminate. Just set daemon = True on the thread object before you call start(). If this is not viable, e.g. the thread has to do resource cleanup before it exits then you could communicate between the reactor and the thread with a Queue. Push work to be done onto a Queue object and have the thread pull it off and do it. Have a special "FINISH" token (or simply None) to indicate that the thread needs to terminate.
twisted: how to communicate elegantly between reactor code and threaded code?
I have a client connected to a server using twisted. The client has a thread which might potentially be doing things in the background. When the reactor is shutting down, I have to: 1) check if the thread is doing things 2) stop it if it is What's an elegant way to do this? The best I can do is some confused thing like: def cleanup(self): isWorkingDF = defer.Deferred() doneDF = defer.Deferred() def checkIsWorking(): res = self.stuff.isWorking() #blocking call reactor.callFromThread(isWorkingDF.callback, res) def shutdownOrNot(isWorking): if isWorking: #shutdown necessary, shutdown is also a blocking call def shutdown(): self.stuff.shutdown() reactor.callFromThread(doneDF, None) reactor.callInThread(shutdown) else: doneDF.callback(None) #no shutdown needed isWorkingDF.addCallback(shutdownOrNot) reactor.callInThread(checkIsWorking) return doneDF First we check if it's working at all. The result of that callback goes into rescallback which either shuts down or doesn't, and then fires the doneDF, which twisted waits for until closing. Pretty messed up eh! Is there a better way? Maybe a related question is, is there a more elegant way to chain callbacks to each other? I could see myself needing to do more cleanup code after this is done, so then I'd have to make a different done deferred, and have the current doneDF fire a callback which does stuff then calls that done deferred..
[ "Ah the real answer is to use the defer.inlineCallbacks decorator. The above code now becomes:\n@defer.inlineCallbacks\ndef procShutdownStuff(self):\n isWorking = yield deferToThread(self.stuff.isWorking)\n\n if isWorking:\n yield deferToThread(self.stuff.shutdown)\n\ndef cleanup(self):\n return sel...
[ 6, 5, 0 ]
[]
[]
[ "multithreading", "python", "shutdown", "twisted" ]
stackoverflow_0003462698_multithreading_python_shutdown_twisted.txt
Q: Easy way of overriding default methods in custom Python classes? I have a class called Cell: class Cell: def __init__(self, value, color, size): self._value = value self._color = color self._size = size # and other methods... Cell._value will store a string, integer, etc. (whatever I am using that object for). I want all default methods that would normally use the "value" of an object to use <Cell object>._value so that I can do: >>> c1 = Cell(7, "blue", (5,10)) >>> c2 = Cell(8, "red", (10, 12)) >>> print c1 + c2 15 >>> c3 = Cell(["ab", "cd"], "yellow", (50, 50)) >>> print len(c3), c3 2 ['ab', 'cd'] # etc. I could override all the default methods: class Cell: def __init__(self, value, color, size): # ... def __repr__(self): return repr(self._value) def __str__(self): return str(self._value) def __getitem__(self, key): return self._value[key] def __len__(self): return len(self._value) # etc. ...but is there an easier way? A: If I understand you correctly, you're looking for an easy way to delegate an object's method to a property of that object? You can avoid some of the repetitiveness by defining a decorator: def delegate(method, prop): def decorate(cls): setattr(cls, method, lambda self, *args, **kwargs: getattr(getattr(self, prop), method)(*args, **kwargs)) return cls return decorate You can then apply the decorator for each method you want delegated: @delegate('__len__', '_content') @delegate('__getitem__', '_content') class MyList(object): def __init__(self, content): self._content = content spam = MyList([1,2,3,4,5]) len(spam) # prints "5" spam[0] # prints "1" You could probably simplify it further by modifying the decorator to take multiple method names as argument. If you want your class to act as a full wrapper, you could probably override the class's __getattr__ method to check the wrapped object before failing. That would emulate the behaviour of subclasses without actual inheritance. A: You need to overload the __add__ method in order to get the c1 + c2 behavior you want. See here for info on what they all are.
Easy way of overriding default methods in custom Python classes?
I have a class called Cell: class Cell: def __init__(self, value, color, size): self._value = value self._color = color self._size = size # and other methods... Cell._value will store a string, integer, etc. (whatever I am using that object for). I want all default methods that would normally use the "value" of an object to use <Cell object>._value so that I can do: >>> c1 = Cell(7, "blue", (5,10)) >>> c2 = Cell(8, "red", (10, 12)) >>> print c1 + c2 15 >>> c3 = Cell(["ab", "cd"], "yellow", (50, 50)) >>> print len(c3), c3 2 ['ab', 'cd'] # etc. I could override all the default methods: class Cell: def __init__(self, value, color, size): # ... def __repr__(self): return repr(self._value) def __str__(self): return str(self._value) def __getitem__(self, key): return self._value[key] def __len__(self): return len(self._value) # etc. ...but is there an easier way?
[ "If I understand you correctly, you're looking for an easy way to delegate an object's method to a property of that object?\nYou can avoid some of the repetitiveness by defining a decorator:\ndef delegate(method, prop):\n def decorate(cls):\n setattr(cls, method,\n lambda self, *args, **kwargs:...
[ 13, 0 ]
[]
[]
[ "class", "methods", "overriding", "python" ]
stackoverflow_0003720717_class_methods_overriding_python.txt
Q: python import problem although there are many posts on the internet as well as some posts on stack overflow, I still want to ask about this nasty python "import" problem. OK. so, the open source code organization is usually like this: project/src/model.py; project/test/testmodel.py if I put the famous __init__.py in project directory and also in src/ and test/ subdirectories, and then put "from project.src import model" for the testmodel.py. it does not work! keep telling me that the Module named "project.src" is not found! how can I solve the problem without changing the code structure? A: You shoud not add the project directory to your pythonpath but it's parent, e.g. imagine the setup /home/user/develop/project/src/model You'd add /home/user/develop to PYTHONPATH If that still doesn't work, make sure you don't have a 'project.py' insite project/src/model. A: Make sure you have the parent directory of project/ on your pythonpath, rather than the project directory. If you add the project path itself, imports like import project.src will look for project/project/src. A: The directory where project is located is probably not in your python path. A: You can use a relative import (assuming Python 2.5+) from testmodel.py, like: from ..src import model However, this does not work if you're running testmodel.py as the main module.
python import problem
although there are many posts on the internet as well as some posts on stack overflow, I still want to ask about this nasty python "import" problem. OK. so, the open source code organization is usually like this: project/src/model.py; project/test/testmodel.py if I put the famous __init__.py in project directory and also in src/ and test/ subdirectories, and then put "from project.src import model" for the testmodel.py. it does not work! keep telling me that the Module named "project.src" is not found! how can I solve the problem without changing the code structure?
[ "You shoud not add the project directory to your pythonpath but it's parent, e.g. imagine the setup\n/home/user/develop/project/src/model\n\nYou'd add /home/user/develop to PYTHONPATH\nIf that still doesn't work, make sure you don't have a 'project.py' insite project/src/model. \n", "Make sure you have the parent...
[ 3, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003721415_python.txt
Q: Selenium issues with IE tests When I change mt test browser to IE using the following line of code: self.selenium = selenium("localhost", 4444, "*iexplore", "http://www.mydomain.net/") I get the following error: Exception: Failed to start new browser session: java.lang.RuntimeException: SystemRoot apparently not set! It works perfectly fine using firefox and Chrome. This is running on an Ubuntu server. A: How could the Selenium RC server (which is what I guess you are using) possibly start an IE instance on an Ubuntu machine?! IIRC all browser instances started by the Selenium RC server have to be local to the server. So if you want to test with IE, you have to run the SRC on a Windows box. Makes sense?!
Selenium issues with IE tests
When I change mt test browser to IE using the following line of code: self.selenium = selenium("localhost", 4444, "*iexplore", "http://www.mydomain.net/") I get the following error: Exception: Failed to start new browser session: java.lang.RuntimeException: SystemRoot apparently not set! It works perfectly fine using firefox and Chrome. This is running on an Ubuntu server.
[ "How could the Selenium RC server (which is what I guess you are using) possibly start an IE instance on an Ubuntu machine?! IIRC all browser instances started by the Selenium RC server have to be local to the server. So if you want to test with IE, you have to run the SRC on a Windows box. Makes sense?!\n" ]
[ 6 ]
[]
[]
[ "internet_explorer", "python", "selenium", "ubuntu" ]
stackoverflow_0003721451_internet_explorer_python_selenium_ubuntu.txt
Q: Parsing unicode attachment names on incoming mail to Google App Engine I have an app engine app that receives incoming mail with attachments. I check the attachment filename to make sure that the extension is correct. If the filename has umlauts or accented characters in it the encoding makes the filename unreadable to my methods, so I don't know how to check the file type. For example, if I send a file with name ZumBrückenwirtÜberGrünwaldZurück(2).gpx And then print out the attachment name like this: attachments = [message.attachments] attachmenttype = attachments[0][0][-4:].lower() logging.error("attachment name %s, %s" % (attachments[0][0], attachmenttype)) I get: attachment name =?ISO-8859-1?B?WnVtQnL8Y2tlbndpcnTcYmVyR3L8bndhbGRadXL8Y2soMikuZ3B4?=, b4?= A: That's an RFC2047 encoded-word. You can partially decode it with the email package, although it still needs stitching together afterwards: import email.header def parseHeader(h): return ''.join(s.decode(c or 'us-ascii') for s, c in email.header.decode_header(h)) >>> parseHeader('=?ISO-8859-1?B?WnVtQnL8Y2tlbndpcnTcYmVyR3L8bndhbGRadXL8Y2soMikuZ3B4?=') u'ZumBr\xfcckenwirt\xdcberGr\xfcnwaldZur\xfcck(2).gpx' It is, however, utterly incorrect to use an encoded-word in the filename="..." parameter for Content-Disposition in an attachment. RFC2047 explicitly states that an encoded-word cannot appear in a quoted paramter. Non-ASCII parameter values are supposed to be transferred using the rules of RFC2231, which look completely different (and very complicated). So according to the mail standard, you should treat this filename as literally being “=?ISO-8859-1?B?WnVtQnL8Y2tlbndpc...”. I believe it's MS Exchange that generates this nonsense. Try to keep this processing down to a minimum (eg. by only decoding when the string is wrapped in =?...?= which is pretty unlikely for a filename.
Parsing unicode attachment names on incoming mail to Google App Engine
I have an app engine app that receives incoming mail with attachments. I check the attachment filename to make sure that the extension is correct. If the filename has umlauts or accented characters in it the encoding makes the filename unreadable to my methods, so I don't know how to check the file type. For example, if I send a file with name ZumBrückenwirtÜberGrünwaldZurück(2).gpx And then print out the attachment name like this: attachments = [message.attachments] attachmenttype = attachments[0][0][-4:].lower() logging.error("attachment name %s, %s" % (attachments[0][0], attachmenttype)) I get: attachment name =?ISO-8859-1?B?WnVtQnL8Y2tlbndpcnTcYmVyR3L8bndhbGRadXL8Y2soMikuZ3B4?=, b4?=
[ "That's an RFC2047 encoded-word. You can partially decode it with the email package, although it still needs stitching together afterwards:\nimport email.header\ndef parseHeader(h):\n return ''.join(s.decode(c or 'us-ascii') for s, c in email.header.decode_header(h))\n\n>>> parseHeader('=?ISO-8859-1?B?WnVtQnL8Y2...
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003721528_google_app_engine_python.txt
Q: customize ticks for AxesImage? I have created an image plot with ax = imshow(). ax is an AxesImage object, but I can't seem to find the function or attribute I need to acess to customize the tick labels. The ordinary pyplots seem to have set_ticks and set_ticklabels methods, but these do not appear to be available for the AxesImage class. Any ideas? Thanks ~ A: For what it's worth, you're slightly misunderstanding what imshow() returns, and how matplotlib axes are structured in general... An AxesImage object is responsible for the image displayed (e.g. colormaps, data, etc), but not the axis that the image resides in. It has no control over things like ticks and tick labels. What you want to use is the current axis instance. You can access this with gca(), if you're using the pylab interface, or matplotlib.pyplot.gca if you're accessing things through pyplot. However, if you're using either one, there is an xticks() function to get/set the xtick labels and locations. For example (using pylab): import pylab pylab.figure() pylab.plot(range(10)) pylab.xticks([2,3,4], ['a','b','c']) pylab.show() Using a more object-oriented approach (on a random note, matplotlib's getters and setters get annoying quickly...): import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(1,1,1) # Or we could call plt.gca() later... im = ax.imshow(np.random.random((10,10))) ax.set_xticklabels(['a','b','c','d']) # Or we could use plt.xticks(...) Hope that clears things up a bit!
customize ticks for AxesImage?
I have created an image plot with ax = imshow(). ax is an AxesImage object, but I can't seem to find the function or attribute I need to acess to customize the tick labels. The ordinary pyplots seem to have set_ticks and set_ticklabels methods, but these do not appear to be available for the AxesImage class. Any ideas? Thanks ~
[ "For what it's worth, you're slightly misunderstanding what imshow() returns, and how matplotlib axes are structured in general... \nAn AxesImage object is responsible for the image displayed (e.g. colormaps, data, etc), but not the axis that the image resides in. It has no control over things like ticks and tick ...
[ 10 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003716339_matplotlib_python.txt
Q: What is the ruby equivalent of the python BeautifulSoup library? I'm looking for a forgiving HTML parser for scraping HTML and extracting data in Ruby. I've had success using BeautifulSoup for this - what is the ruby equivalent? A: Nokogiri Also see: Nokogiri vs Hpricot before making a choice. Nokogiri seems to outdo hpricot performance-wise (haven't benchmarked myself) and has a nice syntax IMO. A: There was a Rubyful Soup gem, which was a Ruby port of BeautifulSoup, but it's no longer maintained and their site now recommends hpricot.
What is the ruby equivalent of the python BeautifulSoup library?
I'm looking for a forgiving HTML parser for scraping HTML and extracting data in Ruby. I've had success using BeautifulSoup for this - what is the ruby equivalent?
[ "Nokogiri\nAlso see:\nNokogiri vs Hpricot before making a choice.\nNokogiri seems to outdo hpricot performance-wise (haven't benchmarked myself) and has a nice syntax IMO.\n", "There was a Rubyful Soup gem, which was a Ruby port of BeautifulSoup, but it's no longer maintained and their site now recommends hpricot...
[ 6, 0 ]
[]
[]
[ "beautifulsoup", "python", "ruby" ]
stackoverflow_0003722117_beautifulsoup_python_ruby.txt
Q: Strings in Python 3 I am programing VIX API from python 2.5, but now I want to port the code to python 3.2 This function opens the virtual machine: self.jobHandle = self.VixLib.vix.VixVM_Open(self.hostHandle, "C:\\MyVirtualMachine.vmx", None, None) Previusly this function is imported from Vix.dll with this code: vix.VixVM_Open.restype = VixHandle vix.VixVM_Open.argtypes = [VixHandle,c_char_p,POINTER(VixEventProc),c_void_p] In 2.5 this code is correct, but in 3.2 it returns ctypes.ArgumentError What can I do? A: Your second argument has to be encoded to a format that the VIX API will understand, since Python 3.x now creates all strings as Unicode. The simplest approach would be to modify your second argument to read: "C:\\MyVirtualMachine.vmx".encode('ascii','ignore') which should give you a variable of type bytes, which should be more palatable to VIX.
Strings in Python 3
I am programing VIX API from python 2.5, but now I want to port the code to python 3.2 This function opens the virtual machine: self.jobHandle = self.VixLib.vix.VixVM_Open(self.hostHandle, "C:\\MyVirtualMachine.vmx", None, None) Previusly this function is imported from Vix.dll with this code: vix.VixVM_Open.restype = VixHandle vix.VixVM_Open.argtypes = [VixHandle,c_char_p,POINTER(VixEventProc),c_void_p] In 2.5 this code is correct, but in 3.2 it returns ctypes.ArgumentError What can I do?
[ "Your second argument has to be encoded to a format that the VIX API will understand, since Python 3.x now creates all strings as Unicode. The simplest approach would be to modify your second argument to read:\n\"C:\\\\MyVirtualMachine.vmx\".encode('ascii','ignore')\n\nwhich should give you a variable of type byte...
[ 5 ]
[]
[]
[ "ctypes", "python", "python_3.x", "string", "unicode" ]
stackoverflow_0003721995_ctypes_python_python_3.x_string_unicode.txt
Q: How do I say "not" using a regex when extracting a group of text? I am trying to extract a section of text that looks something like this: Thing 2A blah blah Thing 2A blah blah Thing 3 Where the "3" above could actually be ANY single digit. The code I have that doesn't work is: ((Thing\s2A).+?(Thing\s\d)) Since the 3 could be any single digit, I cannot simply replace the "\d" with "3". I tried the following code, but it doesn't work either: ((Thing\s2A).+?(Thing\s\d[^A])) Please help! A: Is this what you're trying to do? ((Thing\s2A).+?(Thing\s[0-9])) Edit: Oh I get it, you want a digit not followed by an A. Use a forward lookahead ((Thing\s2A).+?(Thing\s[0-9](?!A)) That's assuming you want it not followed by an A. Replace the A with whatever you DON'T want to follow the digit ((Thing\s2A).+?(Thing\s[0-9](?![A-Za-Z])) Or if you know what you expect after the digit, you can add it. For example ((Thing\s2A).+?(Thing\s[0-9][\s$]) That will match Thing 3 followed by a space, tab, or a newline A: Do you mean this? (((Thing\s2A).+)?(Thing\s\d)) A: It is not very clear what you want exactly... The forward lookahead of @Falmarri might help. If you want the last Thing followed by a digit you could use ((Thing\s2A).+(Thing\s\d)) (removing the ? after the + indicates it uses the default 'greedy' matching and it will eat all till the last matching Thing foolowed by a digit) If the last thing is always the last on the line then this might help ((Thing\s2A).+(Thing\s\d))\s*$ The \s* is to throw away some remaining spaces at the end of the line.
How do I say "not" using a regex when extracting a group of text?
I am trying to extract a section of text that looks something like this: Thing 2A blah blah Thing 2A blah blah Thing 3 Where the "3" above could actually be ANY single digit. The code I have that doesn't work is: ((Thing\s2A).+?(Thing\s\d)) Since the 3 could be any single digit, I cannot simply replace the "\d" with "3". I tried the following code, but it doesn't work either: ((Thing\s2A).+?(Thing\s\d[^A])) Please help!
[ "Is this what you're trying to do?\n((Thing\\s2A).+?(Thing\\s[0-9]))\nEdit: Oh I get it, you want a digit not followed by an A. Use a forward lookahead\n((Thing\\s2A).+?(Thing\\s[0-9](?!A))\nThat's assuming you want it not followed by an A. Replace the A with whatever you DON'T want to follow the digit\n((Thing\\s2...
[ 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003722132_python_regex.txt
Q: complete beginner trying to create a flat file database in python trying to keep it stupidly simple. Is it a bad idea to move a txt file into and out of a python list? the txt files will probably get to about 2-5k entries. what is the preferred method to create a simple flat file databse? A: It might or might not be a bad idea. It depends on what you are trying to achieve, how much memory you have and how big those lines are on average. It also depends on what you are doing with that data. Maybe it is worth it to read and process file line by line? In any case, database assumes indexes, what are you going to do with a list of strings without an index? You cannot search it efficiently, for example. In any case, if you feel like you need a database, take a look at SQLite. It is a small embedded SQL server written in C with Python interface. It is stable and proven to work. For example, it is being used on iPhone in tons of applications. A: If you're looking for a very simple file database, maybe you should look at the shelve module. Example usage: import shelve with shelve.open("myfile") as mydb: mydb["0"] = "first value" mydb["1"] = "second value" # ...
complete beginner trying to create a flat file database in python
trying to keep it stupidly simple. Is it a bad idea to move a txt file into and out of a python list? the txt files will probably get to about 2-5k entries. what is the preferred method to create a simple flat file databse?
[ "It might or might not be a bad idea. It depends on what you are trying to achieve, how much memory you have and how big those lines are on average. It also depends on what you are doing with that data. Maybe it is worth it to read and process file line by line? In any case, database assumes indexes, what are you g...
[ 3, 0 ]
[]
[]
[ "flat_file", "python" ]
stackoverflow_0003722178_flat_file_python.txt
Q: Python ''.format(): "tuple index out of range"? Consider the following snippet: >>> def foo(port, out, udp=False, ipv6=False, data=''): ... if not data: ... data = 'foo {family} {:port} {direction}'.format( ... family=('ipv6' if ipv6 else 'ipv4'), ... port=port, ... direction=('out' if out else 'in')) ... return data ... >>> foo(12345, out=True) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 6, in foo IndexError: tuple index out of range As far as I know, the scoping of names look alright. What's with the cryptic error? A: Watch the colon. Move it from the front of the port area: Either data = 'foo {family} {port:} {direction}'.format( Or data = 'foo {family} :{port} {direction}'.format( The results of the two options are: >>> foo(12345, out=True) 'foo ipv4 12345 out' >>> foo(12345, out=True) 'foo ipv4 :12345 out' A: {:port} should be {port:}.
Python ''.format(): "tuple index out of range"?
Consider the following snippet: >>> def foo(port, out, udp=False, ipv6=False, data=''): ... if not data: ... data = 'foo {family} {:port} {direction}'.format( ... family=('ipv6' if ipv6 else 'ipv4'), ... port=port, ... direction=('out' if out else 'in')) ... return data ... >>> foo(12345, out=True) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 6, in foo IndexError: tuple index out of range As far as I know, the scoping of names look alright. What's with the cryptic error?
[ "Watch the colon. Move it from the front of the port area:\nEither\ndata = 'foo {family} {port:} {direction}'.format(\n\nOr\ndata = 'foo {family} :{port} {direction}'.format(\n\nThe results of the two options are:\n>>> foo(12345, out=True)\n'foo ipv4 12345 out'\n>>> foo(12345, out=True)\n'foo ipv4 :12345 out' \n...
[ 2, 0 ]
[]
[]
[ "formatting", "python", "string" ]
stackoverflow_0003722771_formatting_python_string.txt
Q: What is in your Python Interactive Startup Script? Are there any common timesavers that people put in Python Interactive Startup scripts? I made a dopey one to help me know where I am when I try to do relative file operations or imports, using a win32 module to change the name of the console window. import sys import os import win32api __title_prefix = 'Python %i.%i.%i %s %s' % (sys.version_info[0:4] + (sys.version_info[4] or "",)) def __my_chdir(path): __os_chdir(path) win32api.SetConsoleTitle(__title_prefix + " - " + os.getcwd()) # replace chdir func __os_chdir = os.chdir os.chdir = __my_chdir os.chdir(r'C:\Scripts') A: I also use see, an easier on the eye replacement for Python's dir. from see import see An example of use of see as opposed to dir follows: >>> k = {} >>> dir(k) ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__','__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] >>> see(k) [] in < <= == != > >= hash() help() iter() len() repr() str() .clear() .copy() .fromkeys() .get() .has_key() .items() .iteritems() .iterkeys() .itervalues() .keys() .pop() .popitem() .setdefault() .update() .values() A: # Add auto-completion and a stored history file of commands to your Python # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is # bound to the Esc key by default (you can change it - see readline docs). # # Store the file in ~/.pystartup, and set an environment variable to point # to it: "export PYTHONSTARTUP=/home/user/.pystartup" in bash. # # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the # full path to your home directory. import atexit import os import readline import rlcompleter readline.parse_and_bind("tab: complete") historyPath = os.path.expanduser("~/.history.py") def save_history(historyPath=historyPath): import readline readline.write_history_file(historyPath) if os.path.exists(historyPath): readline.read_history_file(historyPath) atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath A: History http://friendpaste.com/6Q6B7IcsQeAs3RKVJbsgHG Completion http://friendpaste.com/4mBdyrSUsEJZ0dssqjqkvQ Prompt History http://friendpaste.com/7l3KAmp42TDGeii5zd2DP
What is in your Python Interactive Startup Script?
Are there any common timesavers that people put in Python Interactive Startup scripts? I made a dopey one to help me know where I am when I try to do relative file operations or imports, using a win32 module to change the name of the console window. import sys import os import win32api __title_prefix = 'Python %i.%i.%i %s %s' % (sys.version_info[0:4] + (sys.version_info[4] or "",)) def __my_chdir(path): __os_chdir(path) win32api.SetConsoleTitle(__title_prefix + " - " + os.getcwd()) # replace chdir func __os_chdir = os.chdir os.chdir = __my_chdir os.chdir(r'C:\Scripts')
[ "I also use see, an easier on the eye replacement for Python's dir.\nfrom see import see\n\nAn example of use of see as opposed to dir follows:\n>>> k = {}\n>>> dir(k)\n['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__','__doc__',\n'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem_...
[ 5, 4, 1 ]
[]
[]
[ "interactive", "python", "startup" ]
stackoverflow_0003613418_interactive_python_startup.txt
Q: What is the escape character for % in python's string method I am trying to pass a string which has a '%' in it (its actually a sql query string). How do I pass the % (do I have to use a specific escape character? eg: compute_answertime("%how do I%") A: Use another % to escape it >>> compute_answertime("%%how do I%%") A: use %%.......... A: You can use: %%; DROP TABLE Students; -- Sorry, couldn't resist.
What is the escape character for % in python's string method
I am trying to pass a string which has a '%' in it (its actually a sql query string). How do I pass the % (do I have to use a specific escape character? eg: compute_answertime("%how do I%")
[ "Use another % to escape it\n>>> compute_answertime(\"%%how do I%%\")\n\n", "use %%..........\n", "You can use:\n%%; DROP TABLE Students; --\n\nSorry, couldn't resist.\n" ]
[ 4, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003718322_python.txt
Q: Pre declared dictionary size limit? I have a big dictionary i constantly reference in my code so i have it initialized at the top: import ... myDictionary = {'a':'avalue','b':'bvalue',...} code ... But when i try to get values, some of the keys are not found. It appears as though Python is chopping my dictionary due to a size limit. I tried searching google but couldn't find anything on this. I ended up dumping the key:value mappings into a separate file and wrote a function that would build the dictionary by reading in the file. It would be nice to know why this is happening... even better to find a cleaner way to still have my dictionary. EDIT: Dictionary has over 1,700 keys A: One thing you might want to look for is that the keys in your dictionary are not duplicates. For example, in the following code: >>> d = {'1': 'hello', '2': 'world', '1': 'new'} >>> d {'1': 'new', '2': 'world'} >>> because I used the key '1' twice, only the last one appeared and thus I was left with a dictionary of size 2 rather than 3. A: Python does not have a dictionary size limit. I've had dictionaries with well over 1 million keys. Could you post more of the code?
Pre declared dictionary size limit?
I have a big dictionary i constantly reference in my code so i have it initialized at the top: import ... myDictionary = {'a':'avalue','b':'bvalue',...} code ... But when i try to get values, some of the keys are not found. It appears as though Python is chopping my dictionary due to a size limit. I tried searching google but couldn't find anything on this. I ended up dumping the key:value mappings into a separate file and wrote a function that would build the dictionary by reading in the file. It would be nice to know why this is happening... even better to find a cleaner way to still have my dictionary. EDIT: Dictionary has over 1,700 keys
[ "One thing you might want to look for is that the keys in your dictionary are not duplicates. For example, in the following code:\n>>> d = {'1': 'hello', '2': 'world', '1': 'new'}\n>>> d\n{'1': 'new', '2': 'world'}\n>>> \n\nbecause I used the key '1' twice, only the last one appeared and thus I was left with a dict...
[ 4, 2 ]
[]
[]
[ "dictionary", "limit", "predefined_variables", "python", "size" ]
stackoverflow_0003722527_dictionary_limit_predefined_variables_python_size.txt
Q: Python char encoding I have the following code : msgtxt = "é" msg = MIMEText(msgtxt) msg.set_charset('ISO-8859-1') msg['Subject'] = "subject" msg['From'] = "from@mail.com" msg['To'] = "to@mail.com" serv.sendmail("from@mail.com","to@mail.com", msg.as_string()) The e-mail arrive with é as its body instead of the expected é I have tried : msgtxt = "é".encode("ISO-8859-1") msgtxt = u"é" msgtxt = unicode("é", "ISO-8859-1") all yield the same result. How to make this work? Any help is appreciated. Thanks in advance, J. A: msgtxt = "é" msg.set_charset('ISO-8859-1') Well, what's the encoding of the source file containing this code? If it's UTF-8, which is a good default choice, just writing the é will have given you the two-byte string '\xc3\xa9', which, when viewed as ISO-8859-1, looks like é. If you want to use non-ASCII byte string literals in your source file without having to worry about what encoding the text editor is saving it as, use a string literal escape: msgtxt = '\xE9' A: # coding: utf-8 (or whatever you want to save your source file in) msgtxt = u"é" msg = MIMEText(msgtxt,_charset='ISO-8859-1') Without the u the text will be in the source encoding. As a Unicode string, msgtxt will be encoded in the indicated character set.
Python char encoding
I have the following code : msgtxt = "é" msg = MIMEText(msgtxt) msg.set_charset('ISO-8859-1') msg['Subject'] = "subject" msg['From'] = "from@mail.com" msg['To'] = "to@mail.com" serv.sendmail("from@mail.com","to@mail.com", msg.as_string()) The e-mail arrive with é as its body instead of the expected é I have tried : msgtxt = "é".encode("ISO-8859-1") msgtxt = u"é" msgtxt = unicode("é", "ISO-8859-1") all yield the same result. How to make this work? Any help is appreciated. Thanks in advance, J.
[ "msgtxt = \"é\"\nmsg.set_charset('ISO-8859-1')\n\nWell, what's the encoding of the source file containing this code? If it's UTF-8, which is a good default choice, just writing the é will have given you the two-byte string '\\xc3\\xa9', which, when viewed as ISO-8859-1, looks like é.\nIf you want to use non-ASCII ...
[ 1, 0 ]
[]
[]
[ "encoding", "python", "smtplib" ]
stackoverflow_0003722075_encoding_python_smtplib.txt
Q: Is it safe to replace MacOS X default Python interpreter? I have the default Python 2.6.1 installed as /usr/bin/python and Python 3.1.2 installed in /usr/local/bin/python3.1. Considering that I use only 3.x syntax, is it safe to replace the default interpreter (2.6) with the 3.1 one (python-config included) using symlinks (and removing old Python binary)? Or is the system relying on the 2.x version for some purpose I don't know? A: If you're only using Python 3, start your scripts with: #! /usr/bin/env python3.1 And you'll be using the right version, without doinking the system about. edit: BTW this idea is suggested by the Python docs. Each script will be running the version of Python they depend on. Since Python 3 is not backward compatible, it seems dangerous to be replacing the Python executable with one that will break scripts other utilities may rely on. A: You can not safely replace the system supplied python. I cannot find a Mac-specific reference for you... but some recent Python versions are not backwards compatible... Many scripts made dependent on an older version of Python will not run on an upgraded python. OS X Comes with Python pre-installed because it has dependencies on it. Try using VirtualEnv instead. Update: Just came across python-select from macports which may solve your problem. A: Don't replace / remove any binaries unless you are in dire need for storage. In that case too, the mileage is very little in removing them. You can simply make 3.1 as default with : defaults write com.apple.versioner.python Version 3.1 There are other ways to ensure that you use 3.1 by default, I have not used them though. export VERSIONER_PYTHON_VERSION=3.1
Is it safe to replace MacOS X default Python interpreter?
I have the default Python 2.6.1 installed as /usr/bin/python and Python 3.1.2 installed in /usr/local/bin/python3.1. Considering that I use only 3.x syntax, is it safe to replace the default interpreter (2.6) with the 3.1 one (python-config included) using symlinks (and removing old Python binary)? Or is the system relying on the 2.x version for some purpose I don't know?
[ "If you're only using Python 3, start your scripts with:\n#! /usr/bin/env python3.1\n\nAnd you'll be using the right version, without doinking the system about.\nedit: BTW this idea is suggested by the Python docs. Each script will be running the version of Python they depend on. Since Python 3 is not backward comp...
[ 8, 2, 1 ]
[]
[]
[ "macos", "python", "python_2.x", "python_3.x" ]
stackoverflow_0003723183_macos_python_python_2.x_python_3.x.txt
Q: Python: compiling regexp problems I have a interesting problem. I have a list of lists, and I want all except the first element of each list compiled into a regular expression. And then put back into the list. The lists start as strings. The following code doesn't work. It doesn't raise an error, it just doesn't seem to do anything. I think I have identified the problem. (see below) Code: for i in range(len(groups)): for j in range(len(groups[i][1:])): groups[i][1:][j] = re.compile(groups[i][1:][j]) The problem as I see it is that, while list[1:] = [1,2,3] works, list[1:][1] = 2 does not work. What would an appropriate fix be? A: #!/usr/bin/env python import re lol = [ ["unix", ".*", "cool(, eh)?"], ["windows", "_*.*", "[wft]*"], ] # think of `il` as inner list and `ii` as inner item (if you need) ... print [ ii[:1] + map(re.compile, ii[1:]) for ii in [ il for il in lol ]] # ... or, since list comprehensions are preferred over `map` print [ ii[:1] + [re.compile(x) for x in ii[1:]] for ii in [ il for il in lol ]] Will yield: [['unix', <_sre.SRE_Pattern object at 0x100559b90>, <_sre.SRE_Pattern object at 0x10052b870>], ['windows', <_sre.SRE_Pattern object at 0x100590828>, <_sre.SRE_Pattern object at 0x10049b780>]] A: Why bother with slicing? Why not just do... for i in range(len(groups)): for j in range(1, len(groups[i])): groups[i][j] = re.compile(groups[i][j]) More detailed explanation of your problem: "Assigning to a slice" in Python doesn't actually create a slice - it just tells the original object to replace a certain range of elements, hence why for instance a[:2] = [1,2,3] works to replaces the first 3 elements of a list. If you actually create a slice, though, and then try to index into it (a la a[1:][0]), you're actually indexing into a slice object (and then modifying the slice object) rather than touching the original object. A: You should give a more detailed working example to investigate further. How ever, the problem that you are mentioning does not seem to be an issue. It does work. Unless, I have misunderstood something. >>> a=[1,2,3,4] >>> a[1:] [2, 3, 4] >>> a[1:][0] 2 >>> a[1:][1] 3
Python: compiling regexp problems
I have a interesting problem. I have a list of lists, and I want all except the first element of each list compiled into a regular expression. And then put back into the list. The lists start as strings. The following code doesn't work. It doesn't raise an error, it just doesn't seem to do anything. I think I have identified the problem. (see below) Code: for i in range(len(groups)): for j in range(len(groups[i][1:])): groups[i][1:][j] = re.compile(groups[i][1:][j]) The problem as I see it is that, while list[1:] = [1,2,3] works, list[1:][1] = 2 does not work. What would an appropriate fix be?
[ "#!/usr/bin/env python\n\nimport re\n\nlol = [\n [\"unix\", \".*\", \"cool(, eh)?\"],\n [\"windows\", \"_*.*\", \"[wft]*\"],\n]\n\n# think of `il` as inner list and `ii` as inner item (if you need) ...\nprint [ ii[:1] + map(re.compile, ii[1:]) for ii in [ il for il in lol ]]\n\n# ... or, since list comprehens...
[ 2, 1, 0 ]
[]
[]
[ "list", "python", "regex" ]
stackoverflow_0003723251_list_python_regex.txt
Q: Operating on a file's content despite a failure in the 'with' block I've just written a utility in Python to do something I need (irrelevant, but it's to generate a ctags-compatible tag file for an in-house DSL). Anyway- I'm opening and reading the file in the context of a with statement, and I'm curious, how do people tend to handle failures in that process? My solution is with open(filename, 'rt') as f: content = f.read() matches = re.findall(REGEX, content) if len(matches) > 0: # do more stuff... pass I put the match check outside of the with statement because I like having the file closed and done with. However, if content never gets built, this will fail. My solution was to initialize content to the empty string just above this bit of code, but the feeling I get is that I'd like the function just to end; an exception gets thrown out of the function or something. In this case, I could put the rest of the function into the with block but that broadens the scope of the open file. I can create content before the with block so that it exists in light of a failure. I'm curious, however, what other solutions do people like to see (assuming the question makes any sense in the first place)? I suppose I'd sorta like something like this: with open(filename, 'rt') as f: content = f.read() else: content = '' matches = re.findall(REGEX, content) I will accept the idea that I just need to deal with it and leave the file open for the rest of the function if that's the general consensus. :) A: What I would do is as you said: content = '' with open(filename, 'rt') as f: content = f.read() matches = re.findall(REGEX, content) as the cost for regexing and checking matches would be negligable for an empty string. However, closing the file immediately isn't that important as long as it is closed in the end, assuming that you don't reuse it.
Operating on a file's content despite a failure in the 'with' block
I've just written a utility in Python to do something I need (irrelevant, but it's to generate a ctags-compatible tag file for an in-house DSL). Anyway- I'm opening and reading the file in the context of a with statement, and I'm curious, how do people tend to handle failures in that process? My solution is with open(filename, 'rt') as f: content = f.read() matches = re.findall(REGEX, content) if len(matches) > 0: # do more stuff... pass I put the match check outside of the with statement because I like having the file closed and done with. However, if content never gets built, this will fail. My solution was to initialize content to the empty string just above this bit of code, but the feeling I get is that I'd like the function just to end; an exception gets thrown out of the function or something. In this case, I could put the rest of the function into the with block but that broadens the scope of the open file. I can create content before the with block so that it exists in light of a failure. I'm curious, however, what other solutions do people like to see (assuming the question makes any sense in the first place)? I suppose I'd sorta like something like this: with open(filename, 'rt') as f: content = f.read() else: content = '' matches = re.findall(REGEX, content) I will accept the idea that I just need to deal with it and leave the file open for the rest of the function if that's the general consensus. :)
[ "What I would do is as you said:\ncontent = ''\nwith open(filename, 'rt') as f:\n content = f.read()\n\nmatches = re.findall(REGEX, content)\n\nas the cost for regexing and checking matches would be negligable for an empty string.\nHowever, closing the file immediately isn't that important as long as it is close...
[ 1 ]
[]
[]
[ "python", "with_statement" ]
stackoverflow_0003723212_python_with_statement.txt
Q: Form from Model with File Upload I'm trying to mimic the admin interface for the Photologue app on the front end. To achieve this, I have thus far created a bit of code in the view: def galleryuploader(request): GalleryFormSet = modelformset_factory(GalleryUpload) if request.method == 'POST': formset = GalleryFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() # do something. ... do what? else: formset = GalleryFormSet() return render_to_response("cms_helper/gallery_upload.html", { "formset": formset, }) and a template: <form method="post" action=""> {{ formset }} <input type="submit" /> </form> I'm using django's "form from models" method for generating this front-end form. The problem: when I try to upload a file (because I am uploading photos to a photo gallery), and hit submit, it returns with a form error telling me that a required field was missing (the file). I think I am not checking the request for any files, but even if I were to, I'm not quite sure how to. Here's some documentation about file uploads, but I haven't been able to decipher it yet. If you have any suggestions about how to make this upload form work, I'd be veryyy happy to hear them. Thanks in advance! A: Add the enctype="multipart/form-data" attribute to your form tag. Also you'll need to actually do something with the uploaded files. Here's the example from the django docs: from django.http import HttpResponseRedirect from django.shortcuts import render_to_response # Imaginary function to handle an uploaded file. from somewhere import handle_uploaded_file def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): # you'll need to loop through the uploaded files here. handle_uploaded_file(request.FILES['file']) return HttpResponseRedirect('/success/url/') else: form = UploadFileForm() return render_to_response('upload.html', {'form': form}) def handle_uploaded_file(f): destination = open('some/file/name.txt', 'wb+') for chunk in f.chunks(): destination.write(chunk) destination.close() (See the comment about halfway through)
Form from Model with File Upload
I'm trying to mimic the admin interface for the Photologue app on the front end. To achieve this, I have thus far created a bit of code in the view: def galleryuploader(request): GalleryFormSet = modelformset_factory(GalleryUpload) if request.method == 'POST': formset = GalleryFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() # do something. ... do what? else: formset = GalleryFormSet() return render_to_response("cms_helper/gallery_upload.html", { "formset": formset, }) and a template: <form method="post" action=""> {{ formset }} <input type="submit" /> </form> I'm using django's "form from models" method for generating this front-end form. The problem: when I try to upload a file (because I am uploading photos to a photo gallery), and hit submit, it returns with a form error telling me that a required field was missing (the file). I think I am not checking the request for any files, but even if I were to, I'm not quite sure how to. Here's some documentation about file uploads, but I haven't been able to decipher it yet. If you have any suggestions about how to make this upload form work, I'd be veryyy happy to hear them. Thanks in advance!
[ "Add the enctype=\"multipart/form-data\" attribute to your form tag. Also you'll need to actually do something with the uploaded files. Here's the example from the django docs:\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response\n\n# Imaginary function to handle an uploa...
[ 3 ]
[]
[]
[ "django", "django_forms", "forms", "python", "webforms" ]
stackoverflow_0003723293_django_django_forms_forms_python_webforms.txt
Q: Executing py2exe fails with can't open file 'setup.py' I'm using py2exe and I get the following errors in command prompt. C:\Users\Me>C:\Python26\My_scripts\python.exe setup.py py2exe C:\Python26\My_scripts\python.exe: can't open file 'setup.py': [Errno 2] No such file or directory What am I doing wrong? A: Since your comment confirmed what I expected, I'll follow up with an answer post. You invoked python from the directory you were in when you called the executable. In this case, according to your prompt, you invoked it from C:\Users\Me. Therefore, python is trying to find setup.py under this directory (which doesn't exist). You can either: 1) Change directories to the location of the setup.py file, then invoke python. The full path to the python executable will be necessary if it's not in your PATH or if it's in a different directory, otherwise it is not: C:\Users\Me> cd C:\Python26\My_Scripts C:\Python26\My_Scripts> C:\Python26\My_Scripts\python.exe setup.py py2exe 2) Point python to the absolute path of setup.py: C:\Users\Me> C:\Python26\My_Scripts\python.exe "C:\Python26\My_Scripts\setup.py" py2exe A: You have no file called setup.py in the C:\Users\Me directory. Various possible mistakes you could be making, of which the two likeliest ones: the file might be in the directory in question but with a wrong name (say settup.py, oops, two Ts where one was needed) -- then, rename the file! the file might be in another directory -- then, cd to that directory and try again! Of course, both errors might be happening at the same time (in which case you need to fix both). If you think you made neither mistake show us a dir *.py (from the Me) directory...
Executing py2exe fails with can't open file 'setup.py'
I'm using py2exe and I get the following errors in command prompt. C:\Users\Me>C:\Python26\My_scripts\python.exe setup.py py2exe C:\Python26\My_scripts\python.exe: can't open file 'setup.py': [Errno 2] No such file or directory What am I doing wrong?
[ "Since your comment confirmed what I expected, I'll follow up with an answer post.\nYou invoked python from the directory you were in when you called the executable. In this case, according to your prompt, you invoked it from C:\\Users\\Me. Therefore, python is trying to find setup.py under this directory (which do...
[ 3, 1 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0003723026_py2exe_python.txt
Q: list(y) behavior is "wrong" on first call I have an iterator with a __len__ method defined. Questions: If you call list(y) and y has a __len__ method defined, then __len__ is called.    1) Why? In my output, you will see that the len(list(y)) is 0 on the first try. If you look at the list output, you will see that on the first call, I receive an empty list, and on the second call I receive the "correct" list.    2) Why is it returning a list of length zero at all?    3) Why does the list length correct itself on all subsequent calls? Also notice that calling "enumerate" is not the issue. Class C does the same thing but using a while loop and calls to next(). Code: showcalls = False class A(object): _length = None def __iter__(self): if showcalls: print "iter" self.i = 0 return self def next(self): if showcalls: print "next" i = self.i + 1 self.i = i if i > 2: raise StopIteration else: return i class B(A): def __len__(self): if showcalls: print "len" if self._length is None: for i,x in enumerate(self): pass self._length = i return i else: return self._length class C(A): def __len__(self): if showcalls: print "len" if self._length is None: i = 0 while True: try: self.next() except StopIteration: self._length = i return i else: i += 1 else: return self._length if __name__ == '__main__': a = A() print len(list(a)), len(list(a)), len(list(a)) print b = B() print len(list(b)), len(list(b)), len(list(b)) print c = C() print len(list(c)), len(list(c)), len(list(c)) Output: 2 2 2 0 2 2 0 2 2 A: If you call list(y) and y has a len method defined, then len is called. why? Because it's faster to build the resulting list with the final length, if known from the start, than to begin with an empty list and append one item at a time. And __len__ is, and must be, 100% guaranteed to be reliable. IOW, do not implement special methods like __len__ if and when you can't return a reliable value. As for the second question, your implementations of __len__ are broken because they consume the iterator (and don't return it to its pristine state) -- so they leave no items for following .next calls, so the list constructor gets a StopIteration and decides that your __len__ was just flaky (it's unfortunately flakier than poor list can guess...!-).
list(y) behavior is "wrong" on first call
I have an iterator with a __len__ method defined. Questions: If you call list(y) and y has a __len__ method defined, then __len__ is called.    1) Why? In my output, you will see that the len(list(y)) is 0 on the first try. If you look at the list output, you will see that on the first call, I receive an empty list, and on the second call I receive the "correct" list.    2) Why is it returning a list of length zero at all?    3) Why does the list length correct itself on all subsequent calls? Also notice that calling "enumerate" is not the issue. Class C does the same thing but using a while loop and calls to next(). Code: showcalls = False class A(object): _length = None def __iter__(self): if showcalls: print "iter" self.i = 0 return self def next(self): if showcalls: print "next" i = self.i + 1 self.i = i if i > 2: raise StopIteration else: return i class B(A): def __len__(self): if showcalls: print "len" if self._length is None: for i,x in enumerate(self): pass self._length = i return i else: return self._length class C(A): def __len__(self): if showcalls: print "len" if self._length is None: i = 0 while True: try: self.next() except StopIteration: self._length = i return i else: i += 1 else: return self._length if __name__ == '__main__': a = A() print len(list(a)), len(list(a)), len(list(a)) print b = B() print len(list(b)), len(list(b)), len(list(b)) print c = C() print len(list(c)), len(list(c)), len(list(c)) Output: 2 2 2 0 2 2 0 2 2
[ "\nIf you call list(y) and y has a\n len method defined, then len is called. why?\n\nBecause it's faster to build the resulting list with the final length, if known from the start, than to begin with an empty list and append one item at a time. And __len__ is, and must be, 100% guaranteed to be reliable.\nIOW, d...
[ 6 ]
[]
[]
[ "iterator", "list", "python" ]
stackoverflow_0003723337_iterator_list_python.txt
Q: why i can't get the data form Model.all() using google app engine this is my code in main.py class marker_data(db.Model): geo_pt = db.GeoPtProperty() class HomePage(BaseRequestHandler): def get(self): a=marker_data() a.geo_pt=db.GeoPt(-34.397, 150.644) a.put() datas=marker_data.all() self.render_template('3.1.html',{'datas':datas}) and in the html is : {% for i in datas %} console.log(i) {% endfor %} but the error is: i is not defined so what can i do ? thanks A: The 'i' is interpreted by the templating engine on the server side, so you need: {% for i in datas %} console.log({{ i }}); {% endfor %} A: In addition to the syntax error sje397 mentioned, the .all() method returns a Query object and I think you'll need to call .fetch(n) or .get() on that to retrieve the actual marker_data objects. datas=marker_data.all().fetch(100)
why i can't get the data form Model.all() using google app engine
this is my code in main.py class marker_data(db.Model): geo_pt = db.GeoPtProperty() class HomePage(BaseRequestHandler): def get(self): a=marker_data() a.geo_pt=db.GeoPt(-34.397, 150.644) a.put() datas=marker_data.all() self.render_template('3.1.html',{'datas':datas}) and in the html is : {% for i in datas %} console.log(i) {% endfor %} but the error is: i is not defined so what can i do ? thanks
[ "The 'i' is interpreted by the templating engine on the server side, so you need:\n{% for i in datas %}\n console.log({{ i }});\n{% endfor %}\n\n", "In addition to the syntax error sje397 mentioned, the .all() method returns a Query object and I think you'll need to call .fetch(n) or .get() on that to retrieve...
[ 4, 0 ]
[]
[]
[ "google_app_engine", "javascript", "python" ]
stackoverflow_0003723521_google_app_engine_javascript_python.txt
Q: C data structures Is there a C data structure equatable to the following python structure? data = {'X': 1, 'Y': 2} Basically I want a structure where I can give it an pre-defined string and have it come out with an integer. A: The data-structure you are looking for is called a "hash table" (or "hash map"). You can find the source code for one here. A hash table is a mutable mapping of an integer (usually derived from a string) to another value, just like the dict from Python, which your sample code instantiates. It's called a "hash table" because it performs a hash function on the string to return an integer result, and then directly uses that integer to point to the address of your desired data. This system makes it extremely extremely quick to access and change your information, even if you have tons of it. It also means that the data is unordered because a hash function returns a uniformly random result and puts your data unpredictable all over the map (in a perfect world). A: Also note that if you're doing a quick one-off hash, like a two or three static hash for some lookup: look at gperf, which generates a perfect hash function and generates simple code for that hash. A: The above data structure is a dict type. In C/C++ paralance, a hashmap should be equivalent, Google for hashmap implementation. A: There's nothing built into the language or standard library itself but, depending on your requirements, there are a number of ways to do it. If the data set will remain relatively small, the easiest solution is to probably just have an array of structures along the lines of: typedef struct { char *key; int val; } tElement; then use a sequential search to look them up. Have functions which insert keys, delete keys and look up keys so that, if you need to change it in future, the API itself won't change. Pseudo-code: def init: create g.key[100] as string create g.val[100] as integer set g.size to 0 def add (key,val): if lookup(key) != not_found: return already_exists if g.size == 100: return no_space g.key[g.size] = key g.val[g.size] = val g.size = g.size + 1 return okay def del (key): pos = lookup (key) if pos == not_found: return no_such_key if pos < g.size - 1: g.key[pos] = g.key[g.size-1] g.val[pos] = g.val[g.size-1] g.size = g.size - 1 def find (key): for pos goes from 0 to g.size-1: if g.key[pos] == key: return pos return not_found Insertion means ensuring it doesn't already exist then just tacking an element on to the end (you'll maintain a separate size variable for the structure). Deletion means finding the element then simply overwriting it with the last used element and decrementing the size variable. Now this isn't the most efficient method in the world but you need to keep in mind that it usually only makes a difference as your dataset gets much larger. The difference between a binary tree or hash and a sequential search is irrelevant for, say, 20 entries. I've even used bubble sort for small data sets where a more efficient one wasn't available. That's because it massively quick to code up and the performance is irrelevant. Stepping up from there, you can remove the fixed upper size by using a linked list. The search is still relatively inefficient since you're doing it sequentially but the same caveats apply as for the array solution above. The cost of removing the upper bound is a slight penalty for insertion and deletion. If you want a little more performance and a non-fixed upper limit, you can use a binary tree to store the elements. This gets rid of the sequential search when looking for keys and is suited to somewhat larger data sets. If you don't know how big your data set will be getting, I would consider this the absolute minimum. A hash is probably the next step up from there. This performs a function on the string to get a bucket number (usually treated as an array index of some sort). This is O(1) lookup but the aim is to have a hash function that only allocates one item per bucket, so that no further processing is required to get the value. A degenerate case of "all items in the same bucket" is no different to an array or linked list. For maximum performance, and assuming the keys are fixed and known in advance, you can actually create your own hashing function based on the keys themselves. Knowing the keys up front, you have extra information that allows you to fully optimise a hashing function to generate the actual value so you don't even involve buckets - the value generated by the hashing function can be the desired value itself rather than a bucket to get the value from. I had to put one of these together recently for converting textual months ("January", etc) in to month numbers. You can see the process here. I mention this possibility because of your "pre-defined string" comment. If your keys are limited to "X" and "Y" (as in your example) and you're using a character set with contiguous {W,X,Y} characters (which even covers EBCDIC as well as ASCII though not necessarily every esoteric character set allowed by ISO), the simplest hashing function would be: char *s = "X"; int val = *s - 'W'; Note that this doesn't work well if you feed it bad data. These are ideal for when the data is known to be restricted to certain values. The cost of checking data can often swamp the saving given by a pre-optimised hash function like this. A: C doesn't have any collection classes. C++ has std::map. You might try searching for C implementations of maps, e.g. http://elliottback.com/wp/hashmap-implementation-in-c/ A: A 'trie' or a 'hasmap' should do. The simplest implementation is an array of struct { char *s; int i }; pairs. Check out 'trie' in 'include/nscript.h' and 'src/trie.c' here: http://github.com/nikki93/nscript . Change the 'trie_info' type to 'int'. A: Try a Trie for strings, or a Tree of some sort for integer/pointer types (or anything that can be compared as "less than" or "greater than" another key). Wikipedia has reasonably good articles on both, and they can be implemented in C.
C data structures
Is there a C data structure equatable to the following python structure? data = {'X': 1, 'Y': 2} Basically I want a structure where I can give it an pre-defined string and have it come out with an integer.
[ "The data-structure you are looking for is called a \"hash table\" (or \"hash map\"). You can find the source code for one here.\nA hash table is a mutable mapping of an integer (usually derived from a string) to another value, just like the dict from Python, which your sample code instantiates.\nIt's called a \"ha...
[ 7, 3, 2, 2, 1, 1, 1 ]
[]
[]
[ "c", "data_structures", "dictionary", "hashtable", "python" ]
stackoverflow_0003723314_c_data_structures_dictionary_hashtable_python.txt
Q: Upload files without FieldStorage How could i upload a file to a server without using FieldStorage in python? A: Here is a toy program snippet that should help get you started. Try reading RFC 1867 as well for more guidance. #!/usr/bin/python import os import sys buf = sys.stdin.read(512) print "Content-type: text/html\n\n"; print '<html>' print ''' <form method="post" action="" enctype="multipart/form-data"> <input type="file" name="f"> <input type="submit"> </form> ''' print buf print '</html>' You can use os.environ.items() to get a list of environment variables, notably CONTENT_LENGTH and CONTENT_TYPE (specifically the boundary key/pair) so you know where the demarcation points are for the uploaded content.
Upload files without FieldStorage
How could i upload a file to a server without using FieldStorage in python?
[ "Here is a toy program snippet that should help get you started. Try reading RFC 1867 as well for more guidance.\n\n#!/usr/bin/python\n\nimport os\nimport sys\n\nbuf = sys.stdin.read(512)\n\nprint \"Content-type: text/html\\n\\n\";\nprint '<html>'\nprint '''\n<form method=\"post\" action=\"\" enctype=\"multipart/fo...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0003671981_python_python_3.x.txt
Q: python: timing of __new__ in metaclass The following code doesn't compile; it says NameError: name 'fields' is not defined in the last line. Is it because __new__ isn't called until after the fields assignment is reached? What should I do? class Meta(type): def __new__(mcs, name, bases, attr): attr['fields'] = {} return type.__new__(mcs, name, bases, attr) class A(metaclass = Meta): def __init__(self, name): pass class B(A): fields['key'] = 'value' EDIT: I found that it's not a problem with timing; it's a problem with name hiding. Works fine if I write A.fields instead. I'd like to know why I can't use fields or super().fields. A: The fields['key'] = 'value' runs before the metaclass machinery kicks in. class foo(object): var1 = 'bar' def foobar(self): pass when python hits the class statement, it enters a new local namespace. it evaluates the var1 = 'bar' statement. this is equivalent to locals()['var1'] = 'bar' it then evaluates the def foobar statement. this is equivalent to locals()['var'] = the result of compiling the function It then passes locals(), along with the classname, the inherited classes and the metaclass to the metaclasses __new__ method. In the example case, the metaclass is simply type. It then exits the new local namespace and sticks the class object returned from __new__ in the outer namespace with the name foo. Your code works when you use A.fields because the class A has already been created and the above process has hence been executed with your Meta installing fields in A. You can't use super().fields because the classname B is not defined to pass to super at the time that super would run. that is that you would need it to be super(B).fields but B is defined after class creation. Update Here's some code that will do what you want based on your reply to my comment on the question. def MakeFields(**fields): return fields class Meta(type): def __new__(mcs, name, bases, attr): for base in bases: if hasattr(base, 'fields'): inherited = getattr(base, 'fields') try: attr['fields'].update(inherited) except KeyError: attr['fields'] = inherited except ValueError: pass return type.__new__(mcs, name, bases, attr) class A(metaclass=Meta): fields = MakeFields(id='int',name='varchar') class B(A): fields = MakeFields(count='int') class C(B): pass class Test(object): fields = "asd" class D(C, Test): pass print C.fields print D.fields
python: timing of __new__ in metaclass
The following code doesn't compile; it says NameError: name 'fields' is not defined in the last line. Is it because __new__ isn't called until after the fields assignment is reached? What should I do? class Meta(type): def __new__(mcs, name, bases, attr): attr['fields'] = {} return type.__new__(mcs, name, bases, attr) class A(metaclass = Meta): def __init__(self, name): pass class B(A): fields['key'] = 'value' EDIT: I found that it's not a problem with timing; it's a problem with name hiding. Works fine if I write A.fields instead. I'd like to know why I can't use fields or super().fields.
[ "The fields['key'] = 'value' runs before the metaclass machinery kicks in.\nclass foo(object):\n var1 = 'bar'\n\n def foobar(self):\n pass\n\nwhen python hits the class statement, it enters a new local namespace.\n\nit evaluates the var1 = 'bar' statement. this is equivalent to locals()['var1'] = 'bar'...
[ 4 ]
[]
[]
[ "metaclass", "namespaces", "python" ]
stackoverflow_0003723979_metaclass_namespaces_python.txt
Q: Storing and retrieving a list of Tuples using ConfigParser I would like store some configuration data in a config file. Here's a sample section: [URLs] Google, www.google.com Hotmail, www.hotmail.com Yahoo, www.yahoo.com Is it possible to read this into a list of tuples using the ConfigParser module? If not, what do I use? A: Can you change the separator from comma (,) to a semicolon (:) or use the equals (=) sign? In that case ConfigParser will automatically do it for you. For e.g. I parsed your sample data after changing the comma to equals: # urls.cfg [URLs] Google=www.google.com Hotmail=www.hotmail.com Yahoo=www.yahoo.com # Scriptlet import ConfigParser filepath = '/home/me/urls.cfg' config = ConfigParser.ConfigParser() config.read(filepath) print config.items('URLs') # Returns a list of tuples. # [('hotmail', 'www.hotmail.com'), ('google', 'www.google.com'), ('yahoo', 'www.yahoo.com')] A: import ConfigParser config = ConfigParser.ConfigParser() config.add_section('URLs') config.set('URLs', 'Google', 'www.google.com') config.set('URLs', 'Yahoo', 'www.yahoo.com') with open('example.cfg', 'wb') as configfile: config.write(configfile) config.read('example.cfg') config.items('URLs') # [('google', 'www.google.com'), ('yahoo', 'www.yahoo.com')] The documentation mentions: The ConfigParser module has been renamed to configparser in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.
Storing and retrieving a list of Tuples using ConfigParser
I would like store some configuration data in a config file. Here's a sample section: [URLs] Google, www.google.com Hotmail, www.hotmail.com Yahoo, www.yahoo.com Is it possible to read this into a list of tuples using the ConfigParser module? If not, what do I use?
[ "Can you change the separator from comma (,) to a semicolon (:) or use the equals (=) sign? In that case ConfigParser will automatically do it for you. \nFor e.g. I parsed your sample data after changing the comma to equals:\n# urls.cfg\n[URLs]\nGoogle=www.google.com\nHotmail=www.hotmail.com\nYahoo=www.yahoo.com\n\...
[ 11, 3 ]
[]
[]
[ "configparser", "python" ]
stackoverflow_0003724107_configparser_python.txt
Q: Python subprocess how to determine if child process hangs? How do I know is there my child process got hang while operating? A: Well, how do you tell the difference between a stuck process and a process that takes longer than usual to complete? The short answer is: No, you can't detect if your child process is stuck. I would say that to be able to detect this you need some kind of continuous communication with the process (e.g. look at log files, IPC or similar). Based on this communication you might be able to tell when and if a process is stuck. A: I guess, you are asking, how do you find if the child process is hung while operating. You can't tell easily. A process could be doing a long running operation. The context is important to understand when a process is hung. If you are expecting a process to respond to a user input and is not responsive for a long period then we consider it hung. Process is running probably waiting for some thing that will never happen. "Hung Process" is humanly way of saying that a program has reached a dead end and will be no more useful. You could have a program calculating prime numbers one after another and can run for eons and can not be called a hung process.
Python subprocess how to determine if child process hangs?
How do I know is there my child process got hang while operating?
[ "Well, how do you tell the difference between a stuck process and a process that takes longer than usual to complete? The short answer is: No, you can't detect if your child process is stuck.\nI would say that to be able to detect this you need some kind of continuous communication with the process (e.g. look at lo...
[ 2, 1 ]
[]
[]
[ "parent_child", "process", "python", "subprocess" ]
stackoverflow_0003724238_parent_child_process_python_subprocess.txt
Q: Django model form with selected rows I have a django model roughly as shown below: class Event(db.Model): creator = db.ReferenceProperty(User, required= True) title = db.TextProperty(required = True) description = db.TextProperty(required = True) class Ticket(db.Model): user = db.ReferenceProperty(User, required = True) event = db.ReferenceProperty(Event, required = True) total_seats = db.IntegerProperty(required = True,default=0) available_seats = db.IntegerProperty(required = True,default=0) Now I want to create a form from this model which should contain the events which are own by the logged in users only. Currently it shows a drop down with all the events in it. Is it possible with django forms? I am working on google app engine. Please suggest. A: This is how I'd go about it if this were a pure Django application (rather than app engine). You may perhaps find it useful. The key is to override the __init__() method of your ModelForm class to supply the currently logged in user instance. # forms.py class TicketForm(forms.ModelForm): def __init__(self, current_user, *args, **kwargs): super(TicketForm, self).__init__(*args, **kwargs) self.fields['event'].queryset = Event.objects.filter(creator = current_user) You can then supply the user instance while creating an instance of the form. ticket_form = TicketForm(request.user)
Django model form with selected rows
I have a django model roughly as shown below: class Event(db.Model): creator = db.ReferenceProperty(User, required= True) title = db.TextProperty(required = True) description = db.TextProperty(required = True) class Ticket(db.Model): user = db.ReferenceProperty(User, required = True) event = db.ReferenceProperty(Event, required = True) total_seats = db.IntegerProperty(required = True,default=0) available_seats = db.IntegerProperty(required = True,default=0) Now I want to create a form from this model which should contain the events which are own by the logged in users only. Currently it shows a drop down with all the events in it. Is it possible with django forms? I am working on google app engine. Please suggest.
[ "This is how I'd go about it if this were a pure Django application (rather than app engine). You may perhaps find it useful.\nThe key is to override the __init__() method of your ModelForm class to supply the currently logged in user instance.\n# forms.py\nclass TicketForm(forms.ModelForm):\n def __init__(self,...
[ 1 ]
[]
[]
[ "django_forms", "google_app_engine", "python" ]
stackoverflow_0003724488_django_forms_google_app_engine_python.txt
Q: Efficient way to store dictionary (hash) in file with python? I'm implementing a Unix userland tool that needs to store a hash on the disk. The hash will be read every run of the program, pretty frequently. The hash needs to store "name:path" values only. I looked at the bsddb standard library module for python, but I can see it will be deprecated in Python 3. I also saw the pickle standard library module. I'm not a python guy, so what is the efficient way for hash serialization and frequent open/read/close operations? A: I would start with the shelve module and see if that isn't too slow. It does exactly what you want. import shelve d = shelve.open('filename') d['name'] = 'path' d.close() or to read from it d = shelve.open('filename') d = hash['name'] It's essentially a wrapper around pickle that provides a dictionary abstraction. A: I'd use pickle and see if it's fast enough for your needs. A: I would suggest you use pickle / shelve for serialization of data. http://www.saltycrane.com/blog/2008/01/saving-python-dict-to-file-using-pickle/ http://docs.python.org/library/shelve.html
Efficient way to store dictionary (hash) in file with python?
I'm implementing a Unix userland tool that needs to store a hash on the disk. The hash will be read every run of the program, pretty frequently. The hash needs to store "name:path" values only. I looked at the bsddb standard library module for python, but I can see it will be deprecated in Python 3. I also saw the pickle standard library module. I'm not a python guy, so what is the efficient way for hash serialization and frequent open/read/close operations?
[ "I would start with the shelve module and see if that isn't too slow. It does exactly what you want.\nimport shelve\n\nd = shelve.open('filename')\n\nd['name'] = 'path'\n\nd.close()\n\nor to read from it\nd = shelve.open('filename')\n\nd = hash['name']\n\nIt's essentially a wrapper around pickle that provides a dic...
[ 5, 0, 0 ]
[]
[]
[ "dictionary", "file", "python", "serialization" ]
stackoverflow_0003724540_dictionary_file_python_serialization.txt
Q: Cross platform solution for getting current login name in Python I'm looking for a cross platform solution for getting current login/username in Python. I was surprised that os.getlogin() is only supported under Unix and even there is not necessarily returning what you would expect. A: getpass.getuser() is your friend. A: Here is what I use: import os username = getattr(os, "getlogin", None) if not username: for var in ['USER', 'USERNAME','LOGNAME']: if var in os.environ: username = os.environ[var] print("username: %s" % (username))
Cross platform solution for getting current login name in Python
I'm looking for a cross platform solution for getting current login/username in Python. I was surprised that os.getlogin() is only supported under Unix and even there is not necessarily returning what you would expect.
[ "getpass.getuser() is your friend.\n", "Here is what I use:\nimport os\nusername = getattr(os, \"getlogin\", None)\nif not username:\n for var in ['USER', 'USERNAME','LOGNAME']:\n if var in os.environ:\n username = os.environ[var]\nprint(\"username: %s\" % (username))\n\n" ]
[ 11, 1 ]
[]
[]
[ "authentication", "python" ]
stackoverflow_0003724634_authentication_python.txt
Q: Python ssl problem with multiprocessing I want to send data from a client to the server in a TLS TCP socket from multiple client subprocesses so I share the same ssl socket with all subprocesses. Communication works with one subprocess, but if I use more than one subprocesses, the TLS server crashes with an ssl.SSLError (SSL3_GET_RECORD:decryption failed or bad record mac). More specific: It does not depend which process first calls the SSLSocket.write() method, but this process is the only one from this time on which can call it. If another process calls write(), the server will result in the exception described above. I used this basic code: tlsserver.py import socket, ssl def deal_with_client(connstream): data = connstream.read() while data: print data data = connstream.read() connstream.close() bindsocket = socket.socket() bindsocket.bind(('127.0.0.1', 9998)) bindsocket.listen(5) while True: newsocket, fromaddr = bindsocket.accept() connstream = ssl.wrap_socket(newsocket, server_side=True, certfile="srv.crt", keyfile="srv.key", ssl_version=ssl.PROTOCOL_TLSv1) deal_with_client(connstream) tlsclient.py import socket, ssl import multiprocessing class SubProc: def __init__(self, sock): self.sock = sock def do(self): self.sock.write("Test") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssl_sock = ssl.wrap_socket(s) ssl_sock.connect(('127.0.0.1', 9998)) print "Connected to", repr(ssl_sock.getpeername()) for x in (1,2): subproc = SubProc(ssl_sock) proc = multiprocessing.Process(target=subproc.do) And this is the backtrace: Traceback (most recent call last): File "tlsserver.py", line 21, in <module> deal_with_client(connstream) File "tlsserver.py", line 7, in deal_with_client data = connstream.read() File "/usr/lib64/python2.6/ssl.py", line 136, in read return self._sslobj.read(len) ssl.SSLError: [Errno 1] _ssl.c:1325: error:1408F119:SSL routines:SSL3_GET_RECORD:decryption failed or bad record mac A: The problem is that you're re-using the same connection for both processes. The way SSL encrypts data makes this fail -- the two processes would have to communicate with each other about the state of the shared SSL connection. Even if you do make it work, or if you didn't use SSL, the data would arrive at the server all jumbled up; you would have no real way of distinguishing which bytes came from which process. What you need to do is give each process its own SSL connection, by making the connection in subproc.do. Alternatively, don't have the subprocesses communicate with the server at all, but rather communicate with the main process, and have the main process relay it over the SSL connection.
Python ssl problem with multiprocessing
I want to send data from a client to the server in a TLS TCP socket from multiple client subprocesses so I share the same ssl socket with all subprocesses. Communication works with one subprocess, but if I use more than one subprocesses, the TLS server crashes with an ssl.SSLError (SSL3_GET_RECORD:decryption failed or bad record mac). More specific: It does not depend which process first calls the SSLSocket.write() method, but this process is the only one from this time on which can call it. If another process calls write(), the server will result in the exception described above. I used this basic code: tlsserver.py import socket, ssl def deal_with_client(connstream): data = connstream.read() while data: print data data = connstream.read() connstream.close() bindsocket = socket.socket() bindsocket.bind(('127.0.0.1', 9998)) bindsocket.listen(5) while True: newsocket, fromaddr = bindsocket.accept() connstream = ssl.wrap_socket(newsocket, server_side=True, certfile="srv.crt", keyfile="srv.key", ssl_version=ssl.PROTOCOL_TLSv1) deal_with_client(connstream) tlsclient.py import socket, ssl import multiprocessing class SubProc: def __init__(self, sock): self.sock = sock def do(self): self.sock.write("Test") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssl_sock = ssl.wrap_socket(s) ssl_sock.connect(('127.0.0.1', 9998)) print "Connected to", repr(ssl_sock.getpeername()) for x in (1,2): subproc = SubProc(ssl_sock) proc = multiprocessing.Process(target=subproc.do) And this is the backtrace: Traceback (most recent call last): File "tlsserver.py", line 21, in <module> deal_with_client(connstream) File "tlsserver.py", line 7, in deal_with_client data = connstream.read() File "/usr/lib64/python2.6/ssl.py", line 136, in read return self._sslobj.read(len) ssl.SSLError: [Errno 1] _ssl.c:1325: error:1408F119:SSL routines:SSL3_GET_RECORD:decryption failed or bad record mac
[ "The problem is that you're re-using the same connection for both processes. The way SSL encrypts data makes this fail -- the two processes would have to communicate with each other about the state of the shared SSL connection. Even if you do make it work, or if you didn't use SSL, the data would arrive at the serv...
[ 35 ]
[]
[]
[ "multiprocessing", "python", "ssl" ]
stackoverflow_0003724900_multiprocessing_python_ssl.txt
Q: Why aren't persistent connections supported by URLLib2? After scanning the urllib2 source, it seems that connections are automatically closed even if you do specify keep-alive. Why is this? As it is now I just use httplib for my persistent connections... but wonder why this is disabled (or maybe just ambiguous) in urllib2. A: It's a well-known limit of urllib2 (and urllib as well). IMHO the best attempt so far to fix it and make it right is Garry Bodsworth's coda_network for Python 2.6 or 2.7 -- replacement, patched versions of urllib2 (and some other modules) to support keep-alive (and a bunch of other smaller but quite welcome fixes). A: You might also check out httplib2, which supports persistent connections. Not quite the same as urllib2 (in the sense that it only does http and not "any kind of url"), but easier than httplib (and imho also easier than urllib2 if you really want to do http).
Why aren't persistent connections supported by URLLib2?
After scanning the urllib2 source, it seems that connections are automatically closed even if you do specify keep-alive. Why is this? As it is now I just use httplib for my persistent connections... but wonder why this is disabled (or maybe just ambiguous) in urllib2.
[ "It's a well-known limit of urllib2 (and urllib as well). IMHO the best attempt so far to fix it and make it right is Garry Bodsworth's coda_network for Python 2.6 or 2.7 -- replacement, patched versions of urllib2 (and some other modules) to support keep-alive (and a bunch of other smaller but quite welcome fixes...
[ 7, 3 ]
[]
[]
[ "keep_alive", "python", "urllib2" ]
stackoverflow_0003722577_keep_alive_python_urllib2.txt
Q: Python ctypes, C++ object destruction Consider the following python ctypes - c++ binding: // C++ class A { public: void someFunc(); }; A* A_new() { return new A(); } void A_someFunc(A* obj) { obj->someFunc(); } void A_destruct(A* obj) { delete obj; } # python from ctypes import cdll libA = cdll.LoadLibrary(some_path) class A: def __init__(self): self.obj = libA.A_new() def some_func(self): libA.A_someFunc(self.obj) What's the best way to delete the c++ object, when the python object is not needed any more. [edit] I added the delete function that was suggested, however the problem remains by whom and when the function is called. It should be as convenient as possible. A: You could implement the __del__ method, which calls a destructor function you would have to define: C++ class A { public: void someFunc(); }; A* A_new() { return new A(); } void delete_A(A* obj) { delete obj; } void A_someFunc(A* obj) { obj->someFunc(); } Python from ctypes import cdll libA = cdll.LoadLibrary(some_path) class A: def __init__(self): fun = libA.A_new fun.argtypes = [] fun.restype = ctypes.c_void_p self.obj = fun() def __del__(self): fun = libA.delete_A fun.argtypes = [ctypes.c_void_p] fun.restype = None fun(self.obj) def some_func(self): fun = libA.A_someFunc fun.argtypes = [ctypes.c_void_p] fun.restype = None fun(self.obj) Also note that you left out the self parameter on the __init__ method. Futhermore, you have to specify the return type/argument type explicitly, because ctypes defaults to 32 bit integers, while a pointer is likely 64 bits on modern systems. Some think __del__ is evil. As an alternative, you can use with syntax: class A: def __init__(self): fun = libA.A_new fun.argtypes = [] fun.restype = ctypes.c_void_p self.obj = fun() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): fun = libA.delete_A fun.argtypes = [ctypes.c_void_p] fun.restype = None fun(self.obj) def some_func(self): fun = libA.A_someFunc fun.argtypes = [ctypes.c_void_p] fun.restype = None fun(self.obj) with A() as a: # Do some work a.some_func() A: In general, dlls should provide a method for cleaning up object that they created. That way, memory allocation is encapsulated within the dll. This means, your dll should probably expose a method like void A_delete(A*). A: Export a function from the DLL the frees the object. You have to do this in order to ensure that the same memory management mechanism is used to free the object that was in charge when the object was allocated.
Python ctypes, C++ object destruction
Consider the following python ctypes - c++ binding: // C++ class A { public: void someFunc(); }; A* A_new() { return new A(); } void A_someFunc(A* obj) { obj->someFunc(); } void A_destruct(A* obj) { delete obj; } # python from ctypes import cdll libA = cdll.LoadLibrary(some_path) class A: def __init__(self): self.obj = libA.A_new() def some_func(self): libA.A_someFunc(self.obj) What's the best way to delete the c++ object, when the python object is not needed any more. [edit] I added the delete function that was suggested, however the problem remains by whom and when the function is called. It should be as convenient as possible.
[ "You could implement the __del__ method, which calls a destructor function you would have to define:\nC++\nclass A\n{\npublic:\n void someFunc();\n};\n\nA* A_new() { return new A(); }\nvoid delete_A(A* obj) { delete obj; }\nvoid A_someFunc(A* obj) { obj->someFunc(); }\n\nPython\nfrom ctypes import cdll\n\nlibA =...
[ 10, 2, 2 ]
[]
[]
[ "c++", "ctypes", "python" ]
stackoverflow_0003724987_c++_ctypes_python.txt
Q: Python package/module lazily loading submodules Interesting usecase today: I need to migrate a module in our codebase following code changes. The old mynamespace.Document will disappear and I want to ensure smooth migration by replacing this package by a code object that will dynamically import the correct path and migrate the corresponding objects. In short: # instanciate a dynamic package, but do not load # statically submodules mynamespace.Document = SomeObject() assert 'submodule' not in mynamespace.Document.__dict__ # and later on, when importing it, the submodule # is built if not already available in __dict__ from namespace.Document.submodule import klass c = klass() A few things to note: I am not talking only of migrating code. A simple huge sed would in a sense be enough to change the code in order to migrate some imports, and I would not need a dynamic module. I am talking of objects. A website, holding some live/stored objects will need migration. Those objects will be loaded assuming that mynamespace.Document.submodule.klass exists, and that's the reason for the dynamic module. I need to provide the site with something to load. We cannot, or do not want to change the way objects are unpickled/loaded. For simplicity, let's just say that we want to make sure that the idiom from mynamespace.Document.submodule import klass has to work. I cannot use instead from mynamespace import Document as container; klass = getattr(getattr(container, 'submodule'), 'klass') What I tried: import sys from types import ModuleType class VerboseModule(ModuleType): def __init__(self, name, doc=None): super(VerboseModule, self).__init__(name, doc) sys.modules[name] = self def __repr__(self): return "<%s %s>" % (self.__class__.__name__, self.__name__) def __getattribute__(self, name): if name not in ('__name__', '__repr__', '__class__'): print "fetching attribute %s for %s" % (name, self) return super(VerboseModule, self).__getattribute__(name) class DynamicModule(VerboseModule): """ This module generates a dummy class when asked for a component """ def __getattr__(self, name): class Dummy(object): pass Dummy.__name__ = name Dummy.__module__ = self setattr(self, name, Dummy) return Dummy class DynamicPackage(VerboseModule): """ This package should generate dummy modules """ def __getattr__(self, name): mod = DynamicModule("%s.%s" % (self.__name__, name)) setattr(self, name, mod) return mod DynamicModule("foobar") # (the import prints:) # fetching attribute __path__ for <DynamicModule foobar> # fetching attribute DynamicModuleWorks for <DynamicModule foobar> # fetching attribute DynamicModuleWorks for <DynamicModule foobar> from foobar import DynamicModuleWorks print DynamicModuleWorks DynamicPackage('document') # fetching attribute __path__ for <DynamicPackage document> from document.submodule import ButDynamicPackageDoesNotWork # Traceback (most recent call last): # File "dynamicmodule.py", line 40, in <module> # from document.submodule import ButDynamicPackageDoesNotWork #ImportError: No module named submodule As you can see the Dynamic Package does not work. I do not understand what is happening because document is not even asked for a ButDynamicPackageDoesNotWork attribute. Can anyone clarify what is happening; and if/how I can fix this? A: The problem is that python will bypass the entry in for document in sys.modules and load the file for submodule directly. Of course this doesn't exist. demonstration: >>> import multiprocessing >>> multiprocessing.heap = None >>> import multiprocessing.heap >>> multiprocessing.heap <module 'multiprocessing.heap' from '/usr/lib/python2.6/multiprocessing/heap.pyc'> We would expect that heap is still None because python can just pull it out of sys.modules but That doesn't happen. The dotted notation essentially maps directly to {something on python path}/document/submodule.py and an attempt is made to load that directly. Update The trick is to override pythons importing system. The following code requires your DynamicModule class. import sys class DynamicImporter(object): """this class works as both a finder and a loader.""" def __init__(self, lazy_packages): self.packages = lazy_packages def load_module(self, fullname): """this makes the class a loader. It is given name of a module and expected to return the module object""" print "loading {0}".format(fullname) components = fullname.split('.') components = ['.'.join(components[:i+1]) for i in range(len(components))] for component in components: if component not in sys.modules: DynamicModule(component) print "{0} created".format(component) return sys.modules[fullname] def find_module(self, fullname, path=None): """This makes the class a finder. It is given the name of a module as well as the package that contains it (if applicable). It is expected to return a loader for that module if it knows of one or None in which case other methods will be tried""" if fullname.split('.')[0] in self.packages: print "found {0}".format(fullname) return self else: return None # This is a list of finder objects which is empty by defaule # It is tried before anything else when a request to import a module is encountered. sys.meta_path=[DynamicImporter('foo')] from foo.bar import ThisShouldWork
Python package/module lazily loading submodules
Interesting usecase today: I need to migrate a module in our codebase following code changes. The old mynamespace.Document will disappear and I want to ensure smooth migration by replacing this package by a code object that will dynamically import the correct path and migrate the corresponding objects. In short: # instanciate a dynamic package, but do not load # statically submodules mynamespace.Document = SomeObject() assert 'submodule' not in mynamespace.Document.__dict__ # and later on, when importing it, the submodule # is built if not already available in __dict__ from namespace.Document.submodule import klass c = klass() A few things to note: I am not talking only of migrating code. A simple huge sed would in a sense be enough to change the code in order to migrate some imports, and I would not need a dynamic module. I am talking of objects. A website, holding some live/stored objects will need migration. Those objects will be loaded assuming that mynamespace.Document.submodule.klass exists, and that's the reason for the dynamic module. I need to provide the site with something to load. We cannot, or do not want to change the way objects are unpickled/loaded. For simplicity, let's just say that we want to make sure that the idiom from mynamespace.Document.submodule import klass has to work. I cannot use instead from mynamespace import Document as container; klass = getattr(getattr(container, 'submodule'), 'klass') What I tried: import sys from types import ModuleType class VerboseModule(ModuleType): def __init__(self, name, doc=None): super(VerboseModule, self).__init__(name, doc) sys.modules[name] = self def __repr__(self): return "<%s %s>" % (self.__class__.__name__, self.__name__) def __getattribute__(self, name): if name not in ('__name__', '__repr__', '__class__'): print "fetching attribute %s for %s" % (name, self) return super(VerboseModule, self).__getattribute__(name) class DynamicModule(VerboseModule): """ This module generates a dummy class when asked for a component """ def __getattr__(self, name): class Dummy(object): pass Dummy.__name__ = name Dummy.__module__ = self setattr(self, name, Dummy) return Dummy class DynamicPackage(VerboseModule): """ This package should generate dummy modules """ def __getattr__(self, name): mod = DynamicModule("%s.%s" % (self.__name__, name)) setattr(self, name, mod) return mod DynamicModule("foobar") # (the import prints:) # fetching attribute __path__ for <DynamicModule foobar> # fetching attribute DynamicModuleWorks for <DynamicModule foobar> # fetching attribute DynamicModuleWorks for <DynamicModule foobar> from foobar import DynamicModuleWorks print DynamicModuleWorks DynamicPackage('document') # fetching attribute __path__ for <DynamicPackage document> from document.submodule import ButDynamicPackageDoesNotWork # Traceback (most recent call last): # File "dynamicmodule.py", line 40, in <module> # from document.submodule import ButDynamicPackageDoesNotWork #ImportError: No module named submodule As you can see the Dynamic Package does not work. I do not understand what is happening because document is not even asked for a ButDynamicPackageDoesNotWork attribute. Can anyone clarify what is happening; and if/how I can fix this?
[ "The problem is that python will bypass the entry in for document in sys.modules and load the file for submodule directly. Of course this doesn't exist.\ndemonstration:\n>>> import multiprocessing\n>>> multiprocessing.heap = None\n>>> import multiprocessing.heap\n>>> multiprocessing.heap\n<module 'multiprocessing.h...
[ 4 ]
[]
[]
[ "dynamic", "import", "python" ]
stackoverflow_0003725262_dynamic_import_python.txt
Q: Python String split with multiple regex Hi I have Python String as shown below: <html><table border = 1><tr><td>JDICOM</td><td>Thu Sep 16 10:13:34 CDT 2010</td></tr></html> From above string I am interested in two words JDICOM Thu Sep 16 10:13:34 CDT 2010 I tried find, findall, split but it did not help because of multiple regex. I am quite new to python. If anyone knows please help. A: Statutory Warning: don't use regular expressions to parse (X)HTML. You are much better off using a parser such as BeautifulSoup. For e.g. >>> from BeautifulSoup import BeautifulSoup >>> html = """<html><table border = 1><tr><td>JDICOM</td><td>Thu Sep 16 10:13:34 CDT 2010</td></tr></html>""" >>> soup = BeautifulSoup(html) >>> for each in soup.findAll(name = 'td'): print each.contents[0] JDICOM Thu Sep 16 10:13:34 CDT 2010 >>> That said, here is a regular expression to do the same thing. Warning: this will stop working if the markup is irregular. >>> import re >>> pattern = re.compile('<td>(.*?)</td>', re.I | re.S) >>> for each in pattern.findall(html): print each JDICOM Thu Sep 16 10:13:34 CDT 2010 >>>
Python String split with multiple regex
Hi I have Python String as shown below: <html><table border = 1><tr><td>JDICOM</td><td>Thu Sep 16 10:13:34 CDT 2010</td></tr></html> From above string I am interested in two words JDICOM Thu Sep 16 10:13:34 CDT 2010 I tried find, findall, split but it did not help because of multiple regex. I am quite new to python. If anyone knows please help.
[ "Statutory Warning: don't use regular expressions to parse (X)HTML. You are much better off using a parser such as BeautifulSoup. \nFor e.g. \n>>> from BeautifulSoup import BeautifulSoup\n>>> html = \"\"\"<html><table border = 1><tr><td>JDICOM</td><td>Thu Sep 16 10:13:34 CDT 2010</td></tr></html>\"\"\"\n>>> soup = ...
[ 4 ]
[]
[]
[ "html", "python", "regex" ]
stackoverflow_0003725677_html_python_regex.txt
Q: SCons configuration file and default values I have a project which I build using SCons (and MinGW/gcc depending on the platform). This project depends on several other libraries (lets call them libfoo and libbar) which can be installed on different places for different users. Currently, my SConstruct file embeds hard-coded path to those libraries (say, something like: C:\libfoo). Now, I'd like to add a configuration option to my SConstruct file so that a user who installed libfoo at another location (say C:\custom_path\libfoo) can do something like: > scons --configure --libfoo-prefix=C:\custom_path\libfoo Or: > scons --configure scons: Reading SConscript files ... scons: done reading SConscript files. ### Environment configuration ### Please enter location of 'libfoo' ("C:\libfoo"): C:\custom_path\libfoo Please enter location of 'libbar' ("C:\libfoo"): C:\custom_path\libbar ### Configuration over ### Once chosen, those configuration options should be written to some file and reread automatically every time scons runs. Does scons provide such a mechanism ? How would I achieve this behavior ? I don't exactly master Python so even obvious (but complete) solutions are welcome. Thanks. A: SCons has a feature called "Variables". You can set it up so that it reads from command line argument variables pretty easily. So in your case you would do something like this from the command line: scons LIBFOO=C:\custom_path\libfoo ... and the variable would be remembered between runs. So next time you just run scons and it uses the previous value of LIBFOO. In code you use it like so: # read variables from the cache, a user's custom.py file or command line # arguments var = Variables(['variables.cache', 'custom.py'], ARGUMENTS) # add a path variable var.AddVariables(PathVariable('LIBFOO', 'where the foo library is installed', r'C:\default\libfoo', PathVariable.PathIsDir)) env = Environment(variables=var) env.Program('test', 'main.c', LIBPATH='$LIBFOO') # save variables to a file var.Save('variables.cache', env) If you really wanted to use "--" style options then you could combine the above with the AddOption function, but it is more complicated. This SO question talks about the issues involved in getting values out of the Variables object without passing them through an Environment.
SCons configuration file and default values
I have a project which I build using SCons (and MinGW/gcc depending on the platform). This project depends on several other libraries (lets call them libfoo and libbar) which can be installed on different places for different users. Currently, my SConstruct file embeds hard-coded path to those libraries (say, something like: C:\libfoo). Now, I'd like to add a configuration option to my SConstruct file so that a user who installed libfoo at another location (say C:\custom_path\libfoo) can do something like: > scons --configure --libfoo-prefix=C:\custom_path\libfoo Or: > scons --configure scons: Reading SConscript files ... scons: done reading SConscript files. ### Environment configuration ### Please enter location of 'libfoo' ("C:\libfoo"): C:\custom_path\libfoo Please enter location of 'libbar' ("C:\libfoo"): C:\custom_path\libbar ### Configuration over ### Once chosen, those configuration options should be written to some file and reread automatically every time scons runs. Does scons provide such a mechanism ? How would I achieve this behavior ? I don't exactly master Python so even obvious (but complete) solutions are welcome. Thanks.
[ "SCons has a feature called \"Variables\". You can set it up so that it reads from command line argument variables pretty easily. So in your case you would do something like this from the command line:\nscons LIBFOO=C:\\custom_path\\libfoo\n\n... and the variable would be remembered between runs. So next time you j...
[ 6 ]
[]
[]
[ "configuration", "python", "scons" ]
stackoverflow_0003725205_configuration_python_scons.txt
Q: regular expression help which includes "." in word separation expr = "name + partner_id.country_id.name + city + ' ' + 123 + '123' + 12*2/58%45" print re.findall('\w+[.]',expr) ['name', 'partner_id', 'country_id', 'name', 'city', '123', '123', '12', '2', '58', '45'] I want to include "." so result should be like ['name', 'partner_id.country_id.name', 'city', '123', '123', '12', '2', '58', '45'] A: Try the regex: [\w.]+ Explanation: [...] is the char class \w is a char of a word, short for [a-zA-Z0-9_] . is generally a meta char to match any char but inside a char class its treated as a literal . + for one or more A: Try this: re.findall('[\w.]+',expr) This finds blocks of characters made of letters, numbers, underscores and dots. Your original regex finds a word followed by a single dot, so I don't see how you got the posted results: http://codepad.org/Khsd6IuW .
regular expression help which includes "." in word separation
expr = "name + partner_id.country_id.name + city + ' ' + 123 + '123' + 12*2/58%45" print re.findall('\w+[.]',expr) ['name', 'partner_id', 'country_id', 'name', 'city', '123', '123', '12', '2', '58', '45'] I want to include "." so result should be like ['name', 'partner_id.country_id.name', 'city', '123', '123', '12', '2', '58', '45']
[ "Try the regex:\n[\\w.]+\n\nExplanation:\n\n[...] is the char class\n\\w is a char of a word, short for\n[a-zA-Z0-9_]\n. is generally a meta char to match\nany char but inside a char class its\ntreated as a literal .\n+ for one or more\n\n", "Try this:\nre.findall('[\\w.]+',expr)\n\nThis finds blocks of character...
[ 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003725782_python_regex.txt
Q: Ruby's tap idiom in Python There is a useful Ruby idiom that uses tap which allows you to create an object, do some operations on it and return it (I use a list here only as an example, my real code is more involved): def foo [].tap do |a| b = 1 + 2 # ... and some more processing, maybe some logging, etc. a << b end end >> foo => [1] With Rails there's a similar method called returning, so you can write: def foo returning([]) do |a| b = 1 + 2 # ... and some more processing, maybe some logging, etc. a << b end end which speaks for itself. No matter how much processing you do on the object, it's still clear that it's the return value of the function. In Python I have to write: def foo(): a = [] b = 1 + 2 # ... and some more processing, maybe some logging, etc. a.append(b) return a and I wonder if there is a way to port this Ruby idiom into Python. My first thought was to use with statement, but return with is not valid syntax. A: Short answer: Ruby encourages method chaining, Python doesn't. I guess the right question is: What is Ruby's tap useful for? Now I don't know a lot about Ruby, but by googling I got the impression that tap is conceptually useful as method chaining. In Ruby, the style: SomeObject.doThis().doThat().andAnotherThing() is quite idiomatic. It underlies the concept of fluent interfaces, for example. Ruby's tap is a special case of this where instead of having SomeObject.doThis() you define doThis on the fly. Why I am explaining all this? Because it tells us why tap doesn't have good support in Python. With due caveats, Python doesn't do call chaining. For example, Python list methods generally return None rather than returning the mutated list. Functions like map and filter are not list methods. On the other hand, many Ruby array methods do return the modified array. Other than certain cases like some ORMs, Python code doesn't use fluent interfaces. In the end it is the difference between idiomatic Ruby and idiomatic Python. If you are going from one language to the other you need to adjust. A: You can implement it in Python as follows: def tap(x, f): f(x) return x Usage: >>> tap([], lambda x: x.append(1)) [1] However it won't be so much use in Python 2.x as it is in Ruby because lambda functions in Python are quite restrictive. For example you can't inline a call to print because it is a keyword, so you can't use it for inline debugging code. You can do this in Python 3.x although it isn't as clean as the Ruby syntax. >>> tap(2, lambda x: print(x)) + 3 2 5 A: If you want this bad enough, you can create a context manager class Tap(object): def __enter__(self, obj): return obj def __exit__(*args): pass which you can use like: def foo(): with Tap([]) as a: a.append(1) return a There's no getting around the return statement and with really doesn't do anything here. But you do have Tap right at the start which clues you into what the function is about I suppose. It is better than using lambdas because you aren't limited to expressions and can have pretty much whatever you want in the with statement. Overall, I would say that if you want tap that bad, then stick with ruby and if you need to program in python, use python to write python and not ruby. When I get around to learning ruby, I intend to write ruby ;) A: I had an idea to achieve this using function decorators, but due to the distinction in python between expressions and statements, this ended up still requiring the return to be at the end. The ruby syntax is rarely used in my experience, and is far less readable than the explicit python approach. If python had implicit returns or a way to wrap multiple statements up into a single expression then this would be doable - but it has neither of those things by design. Here's my - somewhat pointless - decorator approach, for reference: class Tapper(object): def __init__(self, initial): self.initial = initial def __call__(self, func): func(self.initial) return self.initial def tap(initial): return Tapper(initial) if __name__ == "__main__": def tapping_example(): @tap([]) def tapping(t): t.append(1) t.append(2) return tapping print repr(tapping_example())
Ruby's tap idiom in Python
There is a useful Ruby idiom that uses tap which allows you to create an object, do some operations on it and return it (I use a list here only as an example, my real code is more involved): def foo [].tap do |a| b = 1 + 2 # ... and some more processing, maybe some logging, etc. a << b end end >> foo => [1] With Rails there's a similar method called returning, so you can write: def foo returning([]) do |a| b = 1 + 2 # ... and some more processing, maybe some logging, etc. a << b end end which speaks for itself. No matter how much processing you do on the object, it's still clear that it's the return value of the function. In Python I have to write: def foo(): a = [] b = 1 + 2 # ... and some more processing, maybe some logging, etc. a.append(b) return a and I wonder if there is a way to port this Ruby idiom into Python. My first thought was to use with statement, but return with is not valid syntax.
[ "Short answer: Ruby encourages method chaining, Python doesn't.\nI guess the right question is: What is Ruby's tap useful for?\nNow I don't know a lot about Ruby, but by googling I got the impression that tap is conceptually useful as method chaining.\nIn Ruby, the style: SomeObject.doThis().doThat().andAnotherThin...
[ 27, 8, 7, 1 ]
[ "I partly agree with others in that it doesn't make much sense to implement this in Python. However, IMHO, Mark Byers's way is the way, but why lambdas(and all that comes with them)? can't you write a separate function to be called when needed?\nAnother way to do basically the same could be \nmap(afunction(), avari...
[ -1, -1 ]
[ "idioms", "python", "ruby" ]
stackoverflow_0003725214_idioms_python_ruby.txt
Q: How do I use a Django custom template tag in a template? I’ve written a custom template tag: def mytag(para): return something In my template I am getting a value {{value}}. Now I am using {{value|mytag}} to apply the tag to the value, and it is throwing a syntax error. A: Your example looks like a filter. If that's all you want, it's fairly simple. Paul's links to the documentation should provide a fairly clear explanation of how and why to do things. Here's a quick start that should get you up and running though. Create a folder in your app called "templatetags" with an empty __init__.py file Create a file to hold your custom tags, we'll say "tags.py" for now. your tags.py file should look something like this: from django import template register = template.Library() @register.filter def mytag(para): return 'something' then, in your template, you'll first have to load your custom tags, then you can have access to it. {% load tags %} My new value is: {{ value|mytag }} A: To use template tags in Django, you wrap the name of the tag in {% and %}, like this: {% mytag %} If your tag takes a parameter, as yours seems to, you pass the parameter after the name of the tag: {% mytag value %} The syntax you were trying to use — {{ value|mytag }} is for template filters, not tags. Template tags: http://docs.djangoproject.com/en/1.2/topics/templates/#tags http://docs.djangoproject.com/en/1.2/howto/custom-template-tags/#writing-custom-template-tags Template filters: http://docs.djangoproject.com/en/1.2/topics/templates/#filters http://docs.djangoproject.com/en/1.2/howto/custom-template-tags/#writing-custom-template-filters
How do I use a Django custom template tag in a template?
I’ve written a custom template tag: def mytag(para): return something In my template I am getting a value {{value}}. Now I am using {{value|mytag}} to apply the tag to the value, and it is throwing a syntax error.
[ "Your example looks like a filter. If that's all you want, it's fairly simple. Paul's links to the documentation should provide a fairly clear explanation of how and why to do things. Here's a quick start that should get you up and running though.\n\nCreate a folder in your app called \"templatetags\" with an empty...
[ 5, 2 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0003726000_django_django_templates_python.txt
Q: What's the recommended way to return a boolean for a collection being non-empty in python? I came across the question Python: What is the best way to check if a list is empty? on SO. Now if I wanted to return a True (False) depending on whether a collection coll is non-empty (empty) from a function, what's the recommended way of doing this ? return not not coll ? A: You could use return bool(coll)
What's the recommended way to return a boolean for a collection being non-empty in python?
I came across the question Python: What is the best way to check if a list is empty? on SO. Now if I wanted to return a True (False) depending on whether a collection coll is non-empty (empty) from a function, what's the recommended way of doing this ? return not not coll ?
[ "You could use\nreturn bool(coll)\n\n" ]
[ 11 ]
[]
[]
[ "collections", "python" ]
stackoverflow_0003726692_collections_python.txt
Q: Django: What is `sys.path` supposed to be? When developing a Django application, what is sys.path supposed to contain? The directory which contains the project, or the directory of the project, or both? A: sys.path should and will have the directory of the project. Depending on what your setup is, it may also contain the directory which contains the project. However, if the motivation behind this question is to ensure that certain files can be found, then you should note that sys.path is just like a normal list and can be appended to. Therefore, you can add a new location to sys.path like so: sys.path.append('/home/USER/some/directory/') where your files can be found. Hope this helps A: As far as I know, it's just a matter of personal taste. I go with the directory which contains the project, but that's just my preference.
Django: What is `sys.path` supposed to be?
When developing a Django application, what is sys.path supposed to contain? The directory which contains the project, or the directory of the project, or both?
[ "sys.path should and will have the directory of the project. Depending on what your setup is, it may also contain the directory which contains the project. \nHowever, if the motivation behind this question is to ensure that certain files can be found, then you should note that sys.path is just like a normal list an...
[ 3, 0 ]
[]
[]
[ "django", "python", "pythonpath" ]
stackoverflow_0003726705_django_python_pythonpath.txt
Q: Using QWebPage via socks I'm confused a bit on usage of QWebPage via socks using httplib2 (http/socks5/socks4). Is there any issues or workaround on it? A: Problem seem to be solved using QNetworkAccessManager QNetworkAccessManager.proxyAuthenticationRequired(proxy, authenticator) proxy – QNetworkProxy authenticator – QAuthenticator
Using QWebPage via socks
I'm confused a bit on usage of QWebPage via socks using httplib2 (http/socks5/socks4). Is there any issues or workaround on it?
[ "Problem seem to be solved using QNetworkAccessManager \nQNetworkAccessManager.proxyAuthenticationRequired(proxy, authenticator)\n\nproxy – QNetworkProxy\nauthenticator – QAuthenticator\n\n" ]
[ 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0003108941_pyqt4_python.txt
Q: How to call an executable as independent process using python in windows After calling an exe using python script in windows, the exe should run independent of this python script and once it is initiated the control should comeback to python script and executes the further script and control of .py file will die. But on other side before finishing execution, the exe should call this python script. Ideas would be highly appreciated. I have tried following commands: os.system("start test.exe") os.startfile("test.exe") os.spawnlv(os.P_NOWAIT, "test.exe") os.spawnv(os.P_NOWAIT, 'C:\Python31\python.exe', ('python', 'test.py')) os.execvp("python3", ("test.py", )) A: I sounds as if you want the callee to callback the caller (sorry for the alliteration :) Since you are using Python 3.1 maybe the subprocess module will provide the intended behavior. It is not a true callback per se, but the calling program can perform decisions based on the output of the called program (exe in this case.)
How to call an executable as independent process using python in windows
After calling an exe using python script in windows, the exe should run independent of this python script and once it is initiated the control should comeback to python script and executes the further script and control of .py file will die. But on other side before finishing execution, the exe should call this python script. Ideas would be highly appreciated. I have tried following commands: os.system("start test.exe") os.startfile("test.exe") os.spawnlv(os.P_NOWAIT, "test.exe") os.spawnv(os.P_NOWAIT, 'C:\Python31\python.exe', ('python', 'test.py')) os.execvp("python3", ("test.py", ))
[ "I sounds as if you want the callee to callback the caller (sorry for the alliteration :) Since you are using Python 3.1 maybe the subprocess module will provide the intended behavior. It is not a true callback per se, but the calling program can perform decisions based on the output of the called program (exe in t...
[ 1 ]
[]
[]
[ "python", "python_3.x", "windows" ]
stackoverflow_0003725859_python_python_3.x_windows.txt
Q: Getting started with Django-Instant Django I've been trying to get Django running and when going through the intro to projects it seems that I keep having trouble when I get to the 'sync database' section. When using InstantDjango this doesn't seem to be as much of a problem. My question is, can one just do Django development with the InstantDjango program or do you really need to run it the normal way? A: InstantDjango uses sqlite by default. What database did you set your normal django to use? and you did you create that database before you ran the syncdb? InstantDjango uses different packaging for all the django required libraries (portable versions) which might be less stable but they should work for your development needs.
Getting started with Django-Instant Django
I've been trying to get Django running and when going through the intro to projects it seems that I keep having trouble when I get to the 'sync database' section. When using InstantDjango this doesn't seem to be as much of a problem. My question is, can one just do Django development with the InstantDjango program or do you really need to run it the normal way?
[ "InstantDjango uses sqlite by default. What database did you set your normal django to use? and you did you create that database before you ran the syncdb?\nInstantDjango uses different packaging for all the django required libraries (portable versions) which might be less stable but they should work for your devel...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000738433_django_python.txt
Q: Get Active Directory group members using PyWin32 I need to list all Active Directory group's members - can I do this without using LDAP queries with PyWin's win32security, for instance? I can lookup accounts' sids and names using it (LookupAccountSid and LookupAccountName), but how about getting all group members? For now I cannot figure out what functions I should use. I have account SID as an input parameter and its Domain name. Thanks! A: This active directory module wraps an interface around win32com.client. active_directory - a lightweight wrapper around COM support for Microsoft's Active Directory Active Directory is Microsoft's answer to LDAP, the industry-standard directory service holding information about users, computers and other resources in a tree structure, arranged by departments or geographical location, and optimized for searching. There are several ways of attaching to Active Directory. This module uses the Dispatchable LDAP:// objects and wraps them lightly in helpful Python classes which do a bit of the otherwise tedious plumbing. The module is quite naive, and has only really been developed to aid searching, but since you can always access the original COM object, there's nothing to stop you using it for any AD operations.
Get Active Directory group members using PyWin32
I need to list all Active Directory group's members - can I do this without using LDAP queries with PyWin's win32security, for instance? I can lookup accounts' sids and names using it (LookupAccountSid and LookupAccountName), but how about getting all group members? For now I cannot figure out what functions I should use. I have account SID as an input parameter and its Domain name. Thanks!
[ "This active directory module wraps an interface around win32com.client.\n\nactive_directory - a lightweight\n wrapper around COM support for\n Microsoft's Active Directory\nActive Directory is Microsoft's answer\n to LDAP, the industry-standard \n directory service holding information\n about users, computer...
[ 3 ]
[]
[]
[ "python", "pywin32" ]
stackoverflow_0003726811_python_pywin32.txt
Q: Why isn't posting a status update to Facebook working? I had a working Python integration to Facebook, using the Graph API and the https://graph.facebook.com/<<id>>/feed URL, for about a month. And then all of a sudden a few days ago, I started getting this back whenever I tried to post a status update: {"error":{"type":"OAuthException","message":"(#200) The user hasn't authorized the application to perform this action"}} I'm requesting (and getting) the publish_stream permission, and I can do other things like get friends, pages, etc. Any ideas? There's a link here http://forum.developers.facebook.net/viewtopic.php?id=73912 that shows there are others dealing with this. Thanks! A: So I now have my app working again. I ended up using the JavaScript API from Facebook, using that to login the user, set the cookie, and then I use the Python SDK from Facebook to make the actual status update. It works. How this is different from what I was doing (my own Python code for doing the same stuff) is beyond me. The token returned by both the JavaScript and my own Python code are identical. So it works, but I'm not sure how.
Why isn't posting a status update to Facebook working?
I had a working Python integration to Facebook, using the Graph API and the https://graph.facebook.com/<<id>>/feed URL, for about a month. And then all of a sudden a few days ago, I started getting this back whenever I tried to post a status update: {"error":{"type":"OAuthException","message":"(#200) The user hasn't authorized the application to perform this action"}} I'm requesting (and getting) the publish_stream permission, and I can do other things like get friends, pages, etc. Any ideas? There's a link here http://forum.developers.facebook.net/viewtopic.php?id=73912 that shows there are others dealing with this. Thanks!
[ "So I now have my app working again. I ended up using the JavaScript API from Facebook, using that to login the user, set the cookie, and then I use the Python SDK from Facebook to make the actual status update. It works.\nHow this is different from what I was doing (my own Python code for doing the same stuff) i...
[ 0 ]
[]
[]
[ "facebook", "oauth", "python" ]
stackoverflow_0003712207_facebook_oauth_python.txt
Q: specify dtype of each object in a python numpy array This is a similar question using dtypes in a list The following snippet creates a "typical test array", the purpose of this array is to test an assortment of things in my program. Is there a way or is it even possible to change the type of elements in an array? import numpy as np import random from random import uniform, randrange, choice # ... bunch of silly code ... def gen_test_array( ua, low_inc, med_inc, num_of_vectors ): #typical_array = [ zone_id, ua, inc, veh, pop, hh, with_se, is_cbd, re, se=0, oe] typical_array = np.zeros( shape = ( num_of_vectors, 11 ) ) for i in range( 0, num_of_vectors ): typical_array[i] = [i, int( ua ), uniform( low_inc / 2, med_inc * 2 ), uniform( 0, 6 ), randrange( 100, 5000 ), randrange( 100, 500 ), choice( [True, False] ), choice( [True, False] ), randrange( 100, 5000 ), randrange( 100, 5000 ), randrange( 100, 5000 ) ] return typical_array A: The way to do this in numpy is to use a structured array. However, in many cases where you're using heterogeneous data, a simple python list is a much better choice. (Or, though it wasn't widely available when this answer was written, a pandas.DataFrame is absolutely ideal for this scenario.) Regardless, the example you gave above will work perfectly as a "normal" numpy array. You can just make everything a float in the example you gave. (Everything appears to be an int, except for two columns of floats... The bools can easily be represented as ints.) Nonetheless, to illustrate using structured dtypes... import numpy as np ua = 5 # No idea what "ua" is in your code above... low_inc, med_inc = 0.5, 2.0 # Again, no idea what these are... num = 100 num_fields = 11 # Use more descriptive names than "col1"! I'm just generating the names as placeholders dtype = {'names':['col%i'%i for i in range(num_fields)], 'formats':2*[np.int] + 2*[np.float] + 2*[np.int] + 2*[np.bool] + 3*[np.int]} data = np.zeros(num, dtype=dtype) # Being rather verbose... data['col0'] = np.arange(num, dtype=np.int) data['col1'] = int(ua) * np.ones(num) data['col2'] = np.random.uniform(low_inc / 2, med_inc * 2, num) data['col3'] = np.random.uniform(0, 6, num) data['col4'] = np.random.randint(100, 5000, num) data['col5'] = np.random.randint(100, 500, num) data['col6'] = np.random.randint(0, 2, num).astype(np.bool) data['col7'] = np.random.randint(0, 2, num).astype(np.bool) data['col8'] = np.random.randint(100, 5000, num) data['col9'] = np.random.randint(100, 5000, num) data['col10'] = np.random.randint(100, 5000, num) print data Which yields a 100-element array with 11 fields: array([ (0, 5, 2.0886534380436226, 3.0111285613794276, 3476, 117, False, False, 4704, 4372, 4062), (1, 5, 2.0977199579338115, 1.8687472941590277, 4635, 496, True, False, 4079, 4263, 3196), ... ... (98, 5, 1.1682309811443277, 1.4100766819689299, 1213, 135, False, False, 1250, 2534, 1160), (99, 5, 1.746554619056416, 5.210411489007637, 1387, 352, False, False, 3520, 3772, 3249)], dtype=[('col0', '<i8'), ('col1', '<i8'), ('col2', '<f8'), ('col3', '<f8'), ('col4', '<i8'), ('col5', '<i8'), ('col6', '|b1'), ('col7', '|b1'), ('col8', '<i8'), ('col9', '<i8'), ('col10', '<i8')]) A: Quoting the first line of chapter 1 of the NumPy reference: NumPy provides an N-dimensional array type, the ndarray, which describes a collection of “items” of the same type. So every member of the array has to be of the same type. The loss of generality here, as compared to regular Python lists, is the trade-off that allows high speed operations on arrays: loops can run without testing the type of each member.
specify dtype of each object in a python numpy array
This is a similar question using dtypes in a list The following snippet creates a "typical test array", the purpose of this array is to test an assortment of things in my program. Is there a way or is it even possible to change the type of elements in an array? import numpy as np import random from random import uniform, randrange, choice # ... bunch of silly code ... def gen_test_array( ua, low_inc, med_inc, num_of_vectors ): #typical_array = [ zone_id, ua, inc, veh, pop, hh, with_se, is_cbd, re, se=0, oe] typical_array = np.zeros( shape = ( num_of_vectors, 11 ) ) for i in range( 0, num_of_vectors ): typical_array[i] = [i, int( ua ), uniform( low_inc / 2, med_inc * 2 ), uniform( 0, 6 ), randrange( 100, 5000 ), randrange( 100, 500 ), choice( [True, False] ), choice( [True, False] ), randrange( 100, 5000 ), randrange( 100, 5000 ), randrange( 100, 5000 ) ] return typical_array
[ "The way to do this in numpy is to use a structured array.\nHowever, in many cases where you're using heterogeneous data, a simple python list is a much better choice. (Or, though it wasn't widely available when this answer was written, a pandas.DataFrame is absolutely ideal for this scenario.)\nRegardless, the ex...
[ 9, 4 ]
[]
[]
[ "arrays", "numpy", "python", "scipy" ]
stackoverflow_0003727369_arrays_numpy_python_scipy.txt
Q: Sorting while preserving order in python What is the best way to sort a list of floats by their value, whiles still keeping record of the initial order. I.e. sorting a: a=[2.3, 1.23, 3.4, 0.4] returns something like a_sorted = [0.4, 1.23, 2.3, 3.4] a_order = [4, 2, 1, 3] If you catch my drift. A: You could do something like this: >>> sorted(enumerate(a), key=lambda x: x[1]) [(3, 0.4), (1, 1.23), (0, 2.3), (2, 3.4)] If you need to indexing to start with 1 instead of 0, enumerate accepts the second parameter. A: Use enumerate to generate the sequence numbers. Use sorted with a key to sort by the floats Use zip to separate out the order from the values For example: a_order, a_sorted = zip(*sorted(enumerate(a), key=lambda item: item[1])) A: If you have numpy installed: import numpy a=[2.3, 1.23, 3.4, 0.4] a_sorted = numpy.sorted(a) a_order = numpy.argsort(a) A: from itertools import izip a_order, a_sorted = [list(b) for b in izip(*sorted(enumerate(a, 1), key=lambda n: n[1]))]
Sorting while preserving order in python
What is the best way to sort a list of floats by their value, whiles still keeping record of the initial order. I.e. sorting a: a=[2.3, 1.23, 3.4, 0.4] returns something like a_sorted = [0.4, 1.23, 2.3, 3.4] a_order = [4, 2, 1, 3] If you catch my drift.
[ "You could do something like this:\n>>> sorted(enumerate(a), key=lambda x: x[1])\n[(3, 0.4), (1, 1.23), (0, 2.3), (2, 3.4)]\n\nIf you need to indexing to start with 1 instead of 0, enumerate accepts the second parameter.\n", "\nUse enumerate to generate the sequence numbers.\nUse sorted with a key to sort by the ...
[ 17, 5, 3, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0003728017_python_sorting.txt
Q: BeautifulSoup or regex HTML table to data structure? I've got an HTML table that I'm trying to parse the information from. However, some of the tables span multiple rows/columns, so what I would like to do is use something like BeautifulSoup to parse the table into some type of Python structure. I'm thinking of just using a list of lists so I would turn something like <tr> <td>1,1</td> <td>1,2</td> </tr> <tr> <td>2,1</td> <td>2,2</td> </tr> into [['1,1', '1,2'], ['2,1', '2,2']] Which I (think) should be fairly straightforward. However, there are some slight complications because some of the cells span multiple rows/cols. Plus there's a lot of completely unnecessary information: <td ondblclick="DoAdd('/student_center/sc_all_rooms/d05/09/2010/editformnew?display=W&amp;style=L&amp;positioning=A&amp;adddirect=yes&amp;accessid=CreateNewEdit&amp;filterblock=N&amp;popeditform=yes&amp;returncalendar=student_center/sc_all_rooms')" class="listdefaultmonthbg" style="cursor:crosshair;" width="5%" nowrap="1" rowspan="1"> <a class="listdatelink" href="/student_center/sc_all_rooms/d05/09/2010/edit?style=L&amp;display=W&amp;positioning=A&amp;filterblock=N&amp;adddirect=yes&amp;accessid=CreateNewEdit">Sep 5</a> </td> And what the code really looks like is even worse. All I really need out of there is: <td rowspan="1">Sep 5</td> Two rows later, there is a with a rowspan of 17. For multi-row spans I was thinking something like this: <tr> <td rowspan="2">Sep 5</td> <td>Some event</td> </tr> <tr> <td>Some other event</td> </tr> would end out like this: [["Sep 5", "Some event"], [None, "Some other event"]] There are multiple tables on the page, and I can find the one I want already, I'm just not sure how to parse out the information I need. I know I can use BeautfulSoup to "RenderContents", but in some cases there are link tags that I need to get rid of (while keeping the text). I was thinking of a process something like this: Find table Count rows in tables (len(table.findAll('tr'))?) Create list Parse table into list (BeautifulSoup syntax???) ??? Profit! (Well, it's a purely internal program, so not really... ) A: There was a recent discussion on the python group on linkedin about a similar issue, and apparently lxml is the most recommended pythonic parser for html pages. http://www.linkedin.com/groupItem?view=&gid=25827&type=member&item=27735259&qid=d2948a0e-6c0c-4256-851b-5e7007859553&goback=.gmp_25827 A: You'll probably need to identify the table with some attrs, id or name. from BeautifulSoup import BeautifulSoup data = """ <table> <tr> <td>1,1</td> <td>1,2</td> </tr> <tr> <td>2,1</td> <td>2,2</td> </tr> </table> """ soup = BeautifulSoup(data) for t in soup.findAll('table'): for tr in t.findAll('tr'): print [td.contents for td in tr.findAll('td')] Edit: What should do the program if there're multiple links? Ex: <td><a href="#">A</a> B <a href="#">C</a></td>
BeautifulSoup or regex HTML table to data structure?
I've got an HTML table that I'm trying to parse the information from. However, some of the tables span multiple rows/columns, so what I would like to do is use something like BeautifulSoup to parse the table into some type of Python structure. I'm thinking of just using a list of lists so I would turn something like <tr> <td>1,1</td> <td>1,2</td> </tr> <tr> <td>2,1</td> <td>2,2</td> </tr> into [['1,1', '1,2'], ['2,1', '2,2']] Which I (think) should be fairly straightforward. However, there are some slight complications because some of the cells span multiple rows/cols. Plus there's a lot of completely unnecessary information: <td ondblclick="DoAdd('/student_center/sc_all_rooms/d05/09/2010/editformnew?display=W&amp;style=L&amp;positioning=A&amp;adddirect=yes&amp;accessid=CreateNewEdit&amp;filterblock=N&amp;popeditform=yes&amp;returncalendar=student_center/sc_all_rooms')" class="listdefaultmonthbg" style="cursor:crosshair;" width="5%" nowrap="1" rowspan="1"> <a class="listdatelink" href="/student_center/sc_all_rooms/d05/09/2010/edit?style=L&amp;display=W&amp;positioning=A&amp;filterblock=N&amp;adddirect=yes&amp;accessid=CreateNewEdit">Sep 5</a> </td> And what the code really looks like is even worse. All I really need out of there is: <td rowspan="1">Sep 5</td> Two rows later, there is a with a rowspan of 17. For multi-row spans I was thinking something like this: <tr> <td rowspan="2">Sep 5</td> <td>Some event</td> </tr> <tr> <td>Some other event</td> </tr> would end out like this: [["Sep 5", "Some event"], [None, "Some other event"]] There are multiple tables on the page, and I can find the one I want already, I'm just not sure how to parse out the information I need. I know I can use BeautfulSoup to "RenderContents", but in some cases there are link tags that I need to get rid of (while keeping the text). I was thinking of a process something like this: Find table Count rows in tables (len(table.findAll('tr'))?) Create list Parse table into list (BeautifulSoup syntax???) ??? Profit! (Well, it's a purely internal program, so not really... )
[ "There was a recent discussion on the python group on linkedin about a similar issue, and apparently lxml is the most recommended pythonic parser for html pages.\nhttp://www.linkedin.com/groupItem?view=&gid=25827&type=member&item=27735259&qid=d2948a0e-6c0c-4256-851b-5e7007859553&goback=.gmp_25827\n", "You'll prob...
[ 2, 0 ]
[]
[]
[ "beautifulsoup", "python", "regex" ]
stackoverflow_0003727661_beautifulsoup_python_regex.txt
Q: python: multiple inheritance and __add__() in base class I've got a base class where I want to handle __add__() and want to support when __add__ing two subclass instances - that is have the methods of both subclasses in the resulting instance. import copy class Base(dict): def __init__(self, **data): self.update(data) def __add__(self, other): result = copy.deepcopy(self) result.update(other) # how do I now join the methods? return result class A(Base): def a(self): print "test a" class B(Base): def b(self): print "test b" if __name__ == '__main__': a = A(a=1, b=2) b = B(c=1) c = a + b c.b() # should work c.a() # should work Edit: To be more specific: I've got a class Hosts that holds a dict(host01=.., host02=..) (hence the subclassing of dict) - this offers some base methods such as run_ssh_commmand_on_all_hosts() Now I've got a subclass HostsLoadbalancer that holds some special methods such as drain(), and I've got a class HostsNagios that holds some nagios-specific methods. What I'm doing then, is something like: nagios_hosts = nagios.gethosts() lb_hosts = loadbalancer.gethosts() hosts = nagios_hosts + lb_hosts hosts.run_ssh_command_on_all_hosts('uname') hosts.drain() # method of HostsLoadbalancer - drains just the loadbalancer-hosts hosts.acknoledge_downtime() # method of NagiosHosts - does this just for the nagios hosts, is overlapping What is the best solution for this problem? I think I can somehow "copy all methods" - like this: for x in dir(other): setattr(self, x, getattr(other, x)) Am I on the right track? Or should I use Abstract Base Classes? A: In general this is a bad idea. You're trying to inject methods into a type. That being said, you can certainly do this in python, but you'll have to realize that you want to create a new type each time you do this. Here's an example: import copy class Base(dict): global_class_cache = {} def __init__(self, **data): self.local_data = data def __add__(self, other): new_instance = self._new_type((type(self), type(other)))() new_instance.update(copy.deepcopy(self).__dict__) new_instance.update(copy.deepcopy(other).__dict__) return new_instance def _new_type(self, parents): parents = tuple(parents) if parents not in Base.global_class_cache: name = '_'.join(cls.__name__ for cls in parents) Base.global_class_cache[parents] = type(name, parents, {}) return Base.global_class_cache[parents] class A(Base): def a(self): print "test a" class B(Base): def b(self): print "test b" if __name__ == '__main__': a = A(a=1, b=2) b = B(c=1) c = a + b c.b() # should work c.a() # should work print c.__class__.__name__ UPDATE I've updated the example to remove manually moving the methods -- we're using mixins here. A: It is difficult to answer your question without more information. If Base is supposed to be a common interface to all classes, then you could use simple inheritance to implement the common behavior while preserving the methods of the subclasses. For instance, imagine that you need a Base class where all the objects have a say_hola() method, but subclasses can have arbitrary additional methods in addition to say_hola(): class Base(object): def say_hola(self): print "hola" class C1(Base): def add(self, a, b): return a+b class C2(Base): def say_bonjour(self): return 'bon jour' This way all instances of C1 and C2 have say_hola() in addition to their specific methods. A more general pattern is to create a Mixin. From Wikipedia: In object-oriented programming languages, a mixin is a class that provides a certain functionality to be inherited by a subclass, while not meant for instantiation (the generation of objects of that class). Inheriting from a mixin is not a form of specialization but is rather a means of collecting functionality. A class may inherit most or all of its functionality from one or more mixins through multiple inheritance.
python: multiple inheritance and __add__() in base class
I've got a base class where I want to handle __add__() and want to support when __add__ing two subclass instances - that is have the methods of both subclasses in the resulting instance. import copy class Base(dict): def __init__(self, **data): self.update(data) def __add__(self, other): result = copy.deepcopy(self) result.update(other) # how do I now join the methods? return result class A(Base): def a(self): print "test a" class B(Base): def b(self): print "test b" if __name__ == '__main__': a = A(a=1, b=2) b = B(c=1) c = a + b c.b() # should work c.a() # should work Edit: To be more specific: I've got a class Hosts that holds a dict(host01=.., host02=..) (hence the subclassing of dict) - this offers some base methods such as run_ssh_commmand_on_all_hosts() Now I've got a subclass HostsLoadbalancer that holds some special methods such as drain(), and I've got a class HostsNagios that holds some nagios-specific methods. What I'm doing then, is something like: nagios_hosts = nagios.gethosts() lb_hosts = loadbalancer.gethosts() hosts = nagios_hosts + lb_hosts hosts.run_ssh_command_on_all_hosts('uname') hosts.drain() # method of HostsLoadbalancer - drains just the loadbalancer-hosts hosts.acknoledge_downtime() # method of NagiosHosts - does this just for the nagios hosts, is overlapping What is the best solution for this problem? I think I can somehow "copy all methods" - like this: for x in dir(other): setattr(self, x, getattr(other, x)) Am I on the right track? Or should I use Abstract Base Classes?
[ "In general this is a bad idea. You're trying to inject methods into a type. That being said, you can certainly do this in python, but you'll have to realize that you want to create a new type each time you do this. Here's an example:\nimport copy\n\nclass Base(dict):\n global_class_cache = {}\n\n def __init_...
[ 1, 0 ]
[]
[]
[ "multiple_inheritance", "python" ]
stackoverflow_0003728166_multiple_inheritance_python.txt