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: Issues when writing a medium/large system There is some hype with languages like Python (that I like very much) and Ruby but I was writing a medium-size system in Python and feel the lack of some tools that I would have if I was using Java: Eclipse features, JUnit integration and some language-features like catching some errors in compile time. Some people says that Java is dead as a language. But large important software are written in Java: Hadoop, Lucene and many others. Is Java a better language than Python or Ruby for medium/large infrastructure software like these? A: You make a valid point in saying that Java is more suited to enterprise software. That's really where Java shines: it works very well for enterprise programming. However, your gripes about the tools in Python and Ruby are unfounded. PyDev for Eclipse takes full advantage of the same features that you would enjoy if you were developing in Java. Ruby has a similar plugin for Eclipse. Unit testing frameworks like pyunit, nose, and others exist for both languages (and I believe PyDev has support for unit tests). Also, just like a Java compiler would catch an error at compile time, a Python script will give syntax errors before you run it, along with an (IMO) much more understandable error system than a Java compiler. Since Python and Ruby are scripting languages, their area of expertise lies more in small tasks, rapid development, and using frameworks like Django or Rails. So yes, more heavy-duty languages like Java are great for enterprise, but there's something to be said for the elegance and ease of use of Python and Ruby. A: This kind of question can get very argumentative... For enterprise software most of time the key factor is political, not technical. If you own the business, stick with the technology that best fits your vision. If not, use Java - it is politically safer. On the technical field, it is almost a tie. A: All much of a muchness really. There are features in Python/Ruby that your aware of that make them a more appealing offering than say Java. Static typing can be your best friend most of the time, and a pain for the other. Lack of tooling is related to adoption. Java/c# has a larger adoption. Corporates/Enterprises and medium to large organizations, like to procure solutions with contracts as opposed to technical merits. From experience Python does have some speed issues, I can't comment on Ruby, but I imagine that if your applications require dedicated speed I would not use python. Also threading and multi-core processing is not as good as it could be in python, although 2.7 seems to improve a lot of the old problems, I think the GIL problem still remains for threading. My only comment on Java is that it now has Oracle behind it, and depending where your sitting and how you like Oracle, might change your attitude to Java. especially if your designing for Open Source solutions.
Issues when writing a medium/large system
There is some hype with languages like Python (that I like very much) and Ruby but I was writing a medium-size system in Python and feel the lack of some tools that I would have if I was using Java: Eclipse features, JUnit integration and some language-features like catching some errors in compile time. Some people says that Java is dead as a language. But large important software are written in Java: Hadoop, Lucene and many others. Is Java a better language than Python or Ruby for medium/large infrastructure software like these?
[ "You make a valid point in saying that Java is more suited to enterprise software. That's really where Java shines: it works very well for enterprise programming.\nHowever, your gripes about the tools in Python and Ruby are unfounded. PyDev for Eclipse takes full advantage of the same features that you would enjoy ...
[ 1, 1, 0 ]
[]
[]
[ "enterprise", "java", "python", "ruby", "system" ]
stackoverflow_0004083554_enterprise_java_python_ruby_system.txt
Q: Removing Spaces from Strings in Python 3.x I need to transform the string: "There are 6 spaces in this string." to: "Thereare6spacesinthisstring." A: You can use replace string = "There are 6 spaces in this string" string = string.replace(' ', '') A: new = "There are 6 spaces in this old_string.".replace(' ', '') If you want to strip all whitespace, including tabs: new = ''.join( old_string.split() ) A: You can use replace() : print(string.replace(" ", "")) You can also delete white characters at the end / beginning (or both!) with rstrip, lstrip or strip.
Removing Spaces from Strings in Python 3.x
I need to transform the string: "There are 6 spaces in this string." to: "Thereare6spacesinthisstring."
[ "You can use replace\nstring = \"There are 6 spaces in this string\"\nstring = string.replace(' ', '')\n\n", "new = \"There are 6 spaces in this old_string.\".replace(' ', '')\n\nIf you want to strip all whitespace, including tabs:\nnew = ''.join( old_string.split() )\n\n", "You can use replace() :\nprint(strin...
[ 15, 4, 2 ]
[]
[]
[ "python", "python_3.x", "string" ]
stackoverflow_0004083772_python_python_3.x_string.txt
Q: Is it possible to use matplotlib and pylab to create filled line graph? I was wondering if it is possible to create a filled line graph, like below, using matplotlib? I have matplotlib 0.91.2 and pylab installed. http://test1.xsports.co.nz/media/Forecast.png A: This example in the matplotlib gallery looks like it will do what you want - you just have to fill between the graph and the x-axis. Alternatively, you could use a bar graph with many single pixel bars (or whatever resolution you wanted). HTH
Is it possible to use matplotlib and pylab to create filled line graph?
I was wondering if it is possible to create a filled line graph, like below, using matplotlib? I have matplotlib 0.91.2 and pylab installed. http://test1.xsports.co.nz/media/Forecast.png
[ "This example in the matplotlib gallery looks like it will do what you want - you just have to fill between the graph and the x-axis.\nAlternatively, you could use a bar graph with many single pixel bars (or whatever resolution you wanted).\nHTH\n" ]
[ 2 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0004083776_matplotlib_python.txt
Q: feature mobile phone tracking application I would like to build a mobile phone tracking application for feature phones which have minimum of gprs connectivity. I would like a user to log in to the application and be able to see the location of their phone through google maps. Any resources or information will be highly appreciated. I would preferably use python. A: As far as I know, there is no way to get Python code running on that kind of mobile platform. Try looking up JavaME and/or Brew. Further, you will need the carrier and device maker to allow your app the get access to the phone's GPS information. This is not a given on the low-end devices. As a first step, most carriers have a free developer relation program. Sign up there and you will have access to many forums with experts in the field. Good luck. :)
feature mobile phone tracking application
I would like to build a mobile phone tracking application for feature phones which have minimum of gprs connectivity. I would like a user to log in to the application and be able to see the location of their phone through google maps. Any resources or information will be highly appreciated. I would preferably use python.
[ "As far as I know, there is no way to get Python code running on that kind of mobile platform.\nTry looking up JavaME and/or Brew. Further, you will need the carrier and device maker to allow your app the get access to the phone's GPS information. This is not a given on the low-end devices.\nAs a first step, most...
[ 1 ]
[]
[]
[ "mobile", "python", "security" ]
stackoverflow_0004081333_mobile_python_security.txt
Q: clarification on comparing objects of different types The following sentences are a cause of confusion for me(from Guido's Tutorial on python.org): "Note that comparing objects of different types is legal. The outcome is deterministic but arbitrary: the types are ordered by their name. Thus, a list is always smaller than a string, a string is always smaller than a tuple, etc."than a tuple, etc." That means that for : a=[90] b=(1) a<b the result should be True. But it is not so! Can you help me out here?than a tuple, etc." Also, what is meant by "The outcome is deterministic but arbitrary"? A: (1) is an int. You probably meant (1,), which is a tuple. A: Please note that you should not rely upon this behavior anymore. Some built-in types cannot be compared with other built-ins, and new data model provides a way to overload comparator functionality. >>> set([1]) > [1] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only compare to a set Moreover, it was removed in py3k altogether: >>> [1,2] > (3,4) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: list() > tuple() >>> [1,2] > "1,2" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: list() > str()
clarification on comparing objects of different types
The following sentences are a cause of confusion for me(from Guido's Tutorial on python.org): "Note that comparing objects of different types is legal. The outcome is deterministic but arbitrary: the types are ordered by their name. Thus, a list is always smaller than a string, a string is always smaller than a tuple, etc."than a tuple, etc." That means that for : a=[90] b=(1) a<b the result should be True. But it is not so! Can you help me out here?than a tuple, etc." Also, what is meant by "The outcome is deterministic but arbitrary"?
[ "(1) is an int. You probably meant (1,), which is a tuple.\n", "Please note that you should not rely upon this behavior anymore. Some built-in types cannot be compared with other built-ins, and new data model provides a way to overload comparator functionality.\n>>> set([1]) > [1]\nTraceback (most recent call las...
[ 6, 3 ]
[]
[]
[ "python" ]
stackoverflow_0004084243_python.txt
Q: querying relation does not give back related object in sqlalchemy I have a very simple table(mapped as AuthToken class), consisting of a string ('token'), and a userid (foreign key to another table), with 'user' as relation ( = class User) session.query(AuthToken.user).one() gives back the token, and the userid (as a tuple), but not the user object. Does anybody know why? thanks! A: You should query mapped classes, not their attributes, if you want to receive objects. token = Session.query(AuthToken).options(eagerload('user')).filter(...).one() user = token.user
querying relation does not give back related object in sqlalchemy
I have a very simple table(mapped as AuthToken class), consisting of a string ('token'), and a userid (foreign key to another table), with 'user' as relation ( = class User) session.query(AuthToken.user).one() gives back the token, and the userid (as a tuple), but not the user object. Does anybody know why? thanks!
[ "You should query mapped classes, not their attributes, if you want to receive objects.\ntoken = Session.query(AuthToken).options(eagerload('user')).filter(...).one()\nuser = token.user\n\n" ]
[ 0 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0004028625_orm_python_sqlalchemy.txt
Q: How can I aggregate dictionaries over class hierarchy (Python) Let's say I have the following class hierarchy: class A(object): _d = {} class B(A): _d = {'b': 1} class C(A): _d = {'b': 2, 'c': 3} class D(B): _d = {'d': 4} Is there a way to write an @property method d on A which will return the aggregated dictionary over all superclasses of an object? For example, B().d would return {'b': 1}, C().d would return {'b': 2, 'c': 3}, and D().d would return {'b': 1, 'd': 4}. A: Use inspect.getmro to skip any concerns with multiple inheritance and avoid the necessity of a recursive call to get all the subclasses. import inspect @property d(self): res = {} subclasses = inspect.getmro(type(self)) for cls in reversed(subclasses): res.update(gettattr(cls, 'd', {})) return res A: Well, straightforward solution is to use __bases__ attribute of the class to traverse inheritance chain. However there are some multiple inheritance issues which may or may not to be a concern for you. def d(self): res = {} def traverse(cls): if hasattr(cls, '_d'): for k,v in cls._d.iteritems(): res[k]=v for basecls in cls.__bases__: traverse(basecls) for k,v in self._d.iteritems(): res[k]=v traverse(self.__class__) return res >>> D().d() {'a': 1, 'c': 4, 'b': 2} A: @property def d(self): res = dict(self._d) for c in self.__class__.__bases__: res.update(getattr(c(),'d',{})) return res
How can I aggregate dictionaries over class hierarchy (Python)
Let's say I have the following class hierarchy: class A(object): _d = {} class B(A): _d = {'b': 1} class C(A): _d = {'b': 2, 'c': 3} class D(B): _d = {'d': 4} Is there a way to write an @property method d on A which will return the aggregated dictionary over all superclasses of an object? For example, B().d would return {'b': 1}, C().d would return {'b': 2, 'c': 3}, and D().d would return {'b': 1, 'd': 4}.
[ "Use inspect.getmro to skip any concerns with multiple inheritance and avoid the necessity of a recursive call to get all the subclasses.\nimport inspect\n\n@property\nd(self):\n res = {}\n subclasses = inspect.getmro(type(self))\n for cls in reversed(subclasses):\n res.update(gettattr(cls, 'd', {})...
[ 4, 2, 2 ]
[]
[]
[ "dictionary", "inheritance", "python" ]
stackoverflow_0004084385_dictionary_inheritance_python.txt
Q: A more pythonic way to write this expression? I'm supposed to take a list of words and sort it, except I need to group all Strings that begin with 'x' first. Here's what I got: list_1 = [] list_2 = [] for word in words: list_1.append(word) if word[0] == 'x' else list_2.append(word) return sorted(list_1) + sorted(list_2) But I have a feeling there is a much more elegant way to do this... EDIT Example: ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']. A: >>> words = ['xoo', 'dsd', 'xdd'] >>> sorted(words, key=lambda x: (x[0] != 'x', x)) ['xdd', 'xoo', 'dsd'] Explanation: the key function returns a pair (tuple). The first element is False or True, depending on whether the first char in the string is 'x'. False sorts before True, so strings starting with 'x' will be first in the sorted output. The second element in the tuple will be used to compare two elements that are the same in the first element, so all the strings starting with 'x' will be sorted amongst themselves, and all the strings not starting with 'x' will be sorted amongst themselves. A: First: stop saying "pythonic" when you mean "clean". It's just a cheesy buzzword. Don't use terniary expressions like that; it's meant to be used as part of an expression, not as flow control. This is cleaner: for word in words: if word[0] == 'x': list_1.append(word) else: list_2.append(word) You can improve it a bit more--using terniary expressions like this is fine: for word in words: target = list_1 if word[0] == 'x' else list_2 target.append(word) If words is a container and not an iterator, you could use: list_1 = [word for word in words if word[0] == 'x'] list_2 = [word for word in words if word[0] != 'x'] Finally, we can scrap the whole thing, and instead use two sorts: result = sorted(words) result = sorted(result, key=lambda word: word[0] != 'x') which first sorts normally, then uses the stable property of Python sorts to move words beginning with "x" to the front without otherwise changing the ordering. A: words = ['xoo', 'dsd', 'xdd'] list1 = [word for word in words if word[0] == 'x'] list2 = [word for word in words if word[0] != 'x'] A: It should be noted that sorted was added in Python 2.4 . If you would like a shorter version which is a bit cleaner and somewhat more backwards compatible you can alternatively use the .sort() functionality directly off of list. It should also be noted that empty strings will throw an exception when using x[0] style array indexing syntax in this case (as many examples have). .startswith() should be used instead, as is properly used in Tony Veijalainen's answer. >>> words = ['mix', 'xyz', '', 'apple', 'xanadu', 'aardvark'] >>> words.sort(key=lambda x: (not x.startswith('x'), x)) >>> words ['xanadu', 'xyz', '', 'aardvark', 'apple', 'mix'] The only disadvantage is that you're mutating the given object. This may be remedied by slicing the list beforehand. >>> words = ['mix', 'xyz', '', 'apple', 'xanadu', 'aardvark'] >>> new_words = words[:] >>> new_words.sort(key=lambda x: (not x.startswith('x'), x)) >>> new_words ['xanadu', 'xyz', '', 'aardvark', 'apple', 'mix'] >>> words ['mix', 'xyz', '', 'apple', 'xanadu', 'aardvark'] A: words = ['xoo', 'dsd', 'xdd'] list1=filter(lambda word:word[0]=='x',words) list2=filter(lambda word:word[0]!='x',words) A: To resend variation SilenGhosts code (feel free to copy, SilentGhost) as code not command prompt log notinorder = ['mix', 'xyz', '', 'apple', 'xanadu', 'aardvark'] print sorted(notinorder, key = lambda x: (not x.startswith('x'), x)) A: >>> x = ['abc', 'xyz', 'bcd', 'xabc'] >>> y = [ele for ele in x if ele.startswith('x')] >>> y ['xyz', 'xabc'] >>> z = [ele for ele in x if not ele.startswith('x')] >>> z ['abc', 'bcd'] A: More along the lines of your original solution: l1=[] l2=[] for w in sorted(words): (l1 if w[0] == 'x' else l2).append(w) l1.extend(l2) return l1
A more pythonic way to write this expression?
I'm supposed to take a list of words and sort it, except I need to group all Strings that begin with 'x' first. Here's what I got: list_1 = [] list_2 = [] for word in words: list_1.append(word) if word[0] == 'x' else list_2.append(word) return sorted(list_1) + sorted(list_2) But I have a feeling there is a much more elegant way to do this... EDIT Example: ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'].
[ ">>> words = ['xoo', 'dsd', 'xdd']\n>>> sorted(words, key=lambda x: (x[0] != 'x', x))\n['xdd', 'xoo', 'dsd']\n\nExplanation: the key function returns a pair (tuple). The first element is False or True, depending on whether the first char in the string is 'x'. False sorts before True, so strings starting with 'x' wi...
[ 40, 9, 6, 5, 2, 2, 1, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0004077249_python_sorting.txt
Q: Using Cython to expose functionality to another application I have this C++ code that shows how to extend a software by compiling it to a DLL and putting it in the application folder: #include <windows.h> #include <DemoPlugin.h> /** A helper function to convert a char array into a LPBYTE array. */ LPBYTE message(const char* message, long* pLen) { size_t length = strlen(message); LPBYTE mem = (LPBYTE) GlobalAlloc(GPTR, length + 1); for (unsigned int i = 0; i < length; i++) { mem[i] = message[i]; } *pLen = length + 1; return mem; } long __stdcall Execute(char* pMethodName, char* pParams, char** ppBuffer, long* pBuffSize, long* pBuffType) { *pBuffType = 1; if (strcmp(pMethodName, "") == 0) { *ppBuffer = (char*) message("Hello, World!", pBuffSize); } else if (strcmp(pMethodName, "Count") == 0) { char buffer[1024]; int length = strlen(pParams); *ppBuffer = (char*) message(itoa(length, buffer, 10), pBuffSize); } else { *ppBuffer = (char*) message("Incorrect usage.", pBuffSize); } return 0; } Is is possible to make a plugin this way using Cython? Or even py2exe? The DLL just has to have an entry point, right? Or should I just compile it natively and embed Python using elmer? A: I think the solution is to use both. Let me explain. Cython makes it convenient to make a fast plugin using python but inconvenient (if at all possible) to make the right "kind" of DLL. You would probably have to use the standalone mode so that the necessary python runtime is included and then mess with the generated c code so an appropriate DLL gets compiled. Conversely, elmer makes it convenient to make the DLL but runs "pure" python code which might not be fast enough. I assume speed is an issue because you are considering cython as opposed to simple embedding. My suggestion is this: the pure python code that elmer executes should import a standard cython python extension and execute code from it. This way you don't have to hack anything ugly and you have the best of both worlds. One more solution to consider is using shedskin, because that way you can get c++ code from your python code that is independent from the python runtime.
Using Cython to expose functionality to another application
I have this C++ code that shows how to extend a software by compiling it to a DLL and putting it in the application folder: #include <windows.h> #include <DemoPlugin.h> /** A helper function to convert a char array into a LPBYTE array. */ LPBYTE message(const char* message, long* pLen) { size_t length = strlen(message); LPBYTE mem = (LPBYTE) GlobalAlloc(GPTR, length + 1); for (unsigned int i = 0; i < length; i++) { mem[i] = message[i]; } *pLen = length + 1; return mem; } long __stdcall Execute(char* pMethodName, char* pParams, char** ppBuffer, long* pBuffSize, long* pBuffType) { *pBuffType = 1; if (strcmp(pMethodName, "") == 0) { *ppBuffer = (char*) message("Hello, World!", pBuffSize); } else if (strcmp(pMethodName, "Count") == 0) { char buffer[1024]; int length = strlen(pParams); *ppBuffer = (char*) message(itoa(length, buffer, 10), pBuffSize); } else { *ppBuffer = (char*) message("Incorrect usage.", pBuffSize); } return 0; } Is is possible to make a plugin this way using Cython? Or even py2exe? The DLL just has to have an entry point, right? Or should I just compile it natively and embed Python using elmer?
[ "I think the solution is to use both. Let me explain.\nCython makes it convenient to make a fast plugin using python but inconvenient (if at all possible) to make the right \"kind\" of DLL. You would probably have to use the standalone mode so that the necessary python runtime is included and then mess with the gen...
[ 3 ]
[]
[]
[ "c", "c++", "cython", "python" ]
stackoverflow_0004083150_c_c++_cython_python.txt
Q: get some substring from readline() in python with regular expression I use tcpdump to sniff my network packet and I want to get some info out of the stored file. My file have 2 separated lines but they repeated many times. 23:30:43.170344 IP (tos 0x0, ttl 64, id 55731, offset 0, flags [DF], proto TCP (6), length 443) 192.168.98.138.49341 > 201.20.49.239.80: Flags [P.], seq 562034569:562034972, ack 364925832, win 5840, length 403 I want to get timestamp(23:30:43.170344) and id(id 55731) and offset(23:30:43.170344) from first line(all line like this on my file). and store in a different list. And get 2 separated ip (192.168.98.138.49341 and 201.20.49.239.80) and seq (seq 562034569:562034972) and ack(ack 364925832) from the second (all line like this on my file) line and store in a different list. If I can do this with a regular expression it would be best. A: For the first portion, to get timestamp, id and offset. I am sure this is a crude regex. >>> import re >>> l = '23:30:43.170344 IP (tos 0x0, ttl 64, id 55731, offset 0, flags [DF], proto TCP (6), length 443)' >>> k = re.compile(r'^([0-9:]+\.[0-9]+) IP \(.* id ([0-9]+), offset ([0-9]+).*\)') >>> x = k.match(l) >>> x.groups() ('23:30:43.170344', '55731', '0') >>> x.groups()[0] '23:30:43.170344' >>> x.groups()[1] '55731' >>> x.groups()[2] '0' >>> For the second part: >>> l = '192.168.98.138.49341 > 201.20.49.239.80: Flags [P.], seq 562034569:562034972, ack 364925832, win 5840, length 403' >>> k = re.compile(r'^([0-9.]+) > ([0-9.]+): .* seq ([0-9:]+), ack ([0-9]+).*') >>> x = k.match(l) >>> for y in x.groups(): print y ... 192.168.98.138.49341 201.20.49.239.80 562034569:562034972 364925832 For a read up on re module: http://www.doughellmann.com/PyMOTW/re/
get some substring from readline() in python with regular expression
I use tcpdump to sniff my network packet and I want to get some info out of the stored file. My file have 2 separated lines but they repeated many times. 23:30:43.170344 IP (tos 0x0, ttl 64, id 55731, offset 0, flags [DF], proto TCP (6), length 443) 192.168.98.138.49341 > 201.20.49.239.80: Flags [P.], seq 562034569:562034972, ack 364925832, win 5840, length 403 I want to get timestamp(23:30:43.170344) and id(id 55731) and offset(23:30:43.170344) from first line(all line like this on my file). and store in a different list. And get 2 separated ip (192.168.98.138.49341 and 201.20.49.239.80) and seq (seq 562034569:562034972) and ack(ack 364925832) from the second (all line like this on my file) line and store in a different list. If I can do this with a regular expression it would be best.
[ "For the first portion, to get timestamp, id and offset.\nI am sure this is a crude regex. \n>>> import re\n>>> l = '23:30:43.170344 IP (tos 0x0, ttl 64, id 55731, offset 0, flags [DF], proto TCP (6), length 443)'\n>>> k = re.compile(r'^([0-9:]+\\.[0-9]+) IP \\(.* id ([0-9]+), offset ([0-9]+).*\\)')\n>>> x = k.matc...
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004085121_python_regex.txt
Q: Python app engine: how to save a image? This is what I got from flex 4 file reference upload: self.request = Request: POST /UPLOAD Accept: text/* Cache-Control: no-cache Connection: Keep-Alive Content-Length: 51386 Content-Type: multipart/form-data; boundary=----------ei4cH2gL6ae0ei4ae0gL6GI3KM7ei4 Host: localhost:8080 User-Agent: Shockwave Flash ------------ei4cH2gL6ae0ei4ae0gL6GI3KM7ei4 Content-Disposition: form-data; name="Filename" 36823_117825034935819_100001249682611_118718_676534_n.jpg ------------ei4cH2gL6ae0ei4ae0gL6GI3KM7ei4 Content-Disposition: form-data; name="Filedata"; filename="36823_117825034935819_100001249682611_118718_676534_n.jpg" Content-Type: application/octet-stream ���� [AND OTHER STRANGE CHARACTERS] My class: class Upload(webapp.RequestHandler): def post(self): content = self.request.get("Filedata") return "done!" Now what I'm missing in the Upload class in order to save that file to disk? i have in the content var some strange characters (viewing in debug). A: An App Engine application cannot: write to the filesystem. Applications must use the App Engine datastore for storing persistent data. What you need to do is presenting a form with a file upload field to the user. When the form is submitted, the file is uploaded and the Blobstore creates a blob from the file's contents and returns a blob key useful to retrieve and serve the blob later. The maximum object size permitted is 2 gigabytes. Here is a working snippet that you can try as is: #!/usr/bin/env python # import os import urllib from google.appengine.ext import blobstore from google.appengine.ext import webapp from google.appengine.ext.webapp import blobstore_handlers from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app class MainHandler(webapp.RequestHandler): def get(self): upload_url = blobstore.create_upload_url('/upload') self.response.out.write('<html><body>') self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url) self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit" name="submit" value="Submit"> </form></body></html>""") class UploadHandler(blobstore_handlers.BlobstoreUploadHandler): def post(self): upload_files = self.get_uploads('file') blob_info = upload_files[0] self.redirect('/serve/%s' % blob_info.key()) class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler): def get(self, resource): resource = str(urllib.unquote(resource)) blob_info = blobstore.BlobInfo.get(resource) self.send_blob(blob_info) def main(): application = webapp.WSGIApplication( [('/', MainHandler), ('/upload', UploadHandler), ('/serve/([^/]+)?', ServeHandler), ], debug=True) run_wsgi_app(application) if __name__ == '__main__': main() EDIT1: in your specific case you could use a BlobProperty (limited to 1MB) to store your request: class Photo(db.Model): imageblob = db.BlobProperty() then adapt your webapp.RequestHandler to save your request: class Upload(webapp.RequestHandler): def post(self): image = self.request.get("Filedata") photo = Photo() photo.imageblob = db.Blob(image) photo.put() EDIT2: You don't need to change your app.yaml, just add a new handler and map it in your WSGI. To retrieve the stored photo you should add another handler to serve your photos: class DownloadImage(webapp.RequestHandler): def get(self): photo= db.get(self.request.get("photo_id")) if photo: self.response.headers['Content-Type'] = "image/jpeg" self.response.out.write(photo.imageblob) else: self.response.out.write("Image not available") then map your new DownloadImage class: application = webapp.WSGIApplication([ ... ('/i', DownloadImage), ... ], debug=True) You would be able to get images with a url like: yourapp/i?photo_id = photo_key As requested, if for any odd reason you really want to serve your images using this kind of url www.mysite.com/i/photo_key.jpg , you may want to try with this: class Download(webapp.RequestHandler): def get(self, photo_id): photo= db.get(db.Key(photo_id)) if photo: self.response.headers['Content-Type'] = "image/jpeg" self.response.out.write(photo.imageblob) else: self.response.out.write("Image not available") with a slightly different mapping: application = webapp.WSGIApplication([ ... ('/i/(\d+)\.jpg', DownloadImage), ... ], debug=True)
Python app engine: how to save a image?
This is what I got from flex 4 file reference upload: self.request = Request: POST /UPLOAD Accept: text/* Cache-Control: no-cache Connection: Keep-Alive Content-Length: 51386 Content-Type: multipart/form-data; boundary=----------ei4cH2gL6ae0ei4ae0gL6GI3KM7ei4 Host: localhost:8080 User-Agent: Shockwave Flash ------------ei4cH2gL6ae0ei4ae0gL6GI3KM7ei4 Content-Disposition: form-data; name="Filename" 36823_117825034935819_100001249682611_118718_676534_n.jpg ------------ei4cH2gL6ae0ei4ae0gL6GI3KM7ei4 Content-Disposition: form-data; name="Filedata"; filename="36823_117825034935819_100001249682611_118718_676534_n.jpg" Content-Type: application/octet-stream ���� [AND OTHER STRANGE CHARACTERS] My class: class Upload(webapp.RequestHandler): def post(self): content = self.request.get("Filedata") return "done!" Now what I'm missing in the Upload class in order to save that file to disk? i have in the content var some strange characters (viewing in debug).
[ "\nAn App Engine application cannot:\n\nwrite to the filesystem. Applications must use the App Engine\n datastore for storing persistent data.\n\n\nWhat you need to do is presenting a form with a file upload field to the user.\nWhen the form is submitted, the file is uploaded and the Blobstore creates a blob from ...
[ 6 ]
[]
[]
[ "google_app_engine", "python", "upload" ]
stackoverflow_0004054471_google_app_engine_python_upload.txt
Q: How to get the return value (like Ajax) using task queue on Google App Engine I can use a task queue to change the database value, but how can I get the return value like Ajax using task queue? This is my code: from google.appengine.api.labs import taskqueue from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app import os class Counter(db.Model): count = db.IntegerProperty(indexed=False) class BaseRequestHandler(webapp.RequestHandler): def render_template(self, filename, template_values={}): values={ } template_values.update(values) path = os.path.join(os.path.dirname(__file__), 'templates', filename) self.response.out.write(template.render(path, template_values)) class CounterHandler(BaseRequestHandler): def get(self): self.render_template('counters.html',{'counters': Counter.all()}) def post(self): key = self.request.get('key') # Add the task to the default queue. for loop in range(0,1): a=taskqueue.add(url='/worker', params={'key': key}) #self.redirect('/') self.response.out.write(a) class CounterWorker(webapp.RequestHandler): def post(self): # should run at most 1/s key = self.request.get('key') def txn(): counter = Counter.get_by_key_name(key) if counter is None: counter = Counter(key_name=key, count=1) else: counter.count += 1 counter.put() db.run_in_transaction(txn) self.response.out.write('sss')#used for get by task queue def main(): run_wsgi_app(webapp.WSGIApplication([ ('/', CounterHandler), ('/worker', CounterWorker), ])) if __name__ == '__main__': main() How can I show the 'sss'? A: The current Task Queue API doesn't support processing return values or sending them back to the point of origin. Your appengine process isn't long-lived enough for that programming paradigm to work. In your example, it looks like what you want is something like this: Create task Return AJAX code that will poll a task-status handler Task processes, updates datastore with a return value Task-status url returns updated value Alternatively, if you don't want to return the 'sss' to the client but instead need it for further processing, you'll need to split your method into multiple parts. The first part creates the task and then exits. At the end of the task's process, it adds a new task itself to call back into the second part with the return value.
How to get the return value (like Ajax) using task queue on Google App Engine
I can use a task queue to change the database value, but how can I get the return value like Ajax using task queue? This is my code: from google.appengine.api.labs import taskqueue from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app import os class Counter(db.Model): count = db.IntegerProperty(indexed=False) class BaseRequestHandler(webapp.RequestHandler): def render_template(self, filename, template_values={}): values={ } template_values.update(values) path = os.path.join(os.path.dirname(__file__), 'templates', filename) self.response.out.write(template.render(path, template_values)) class CounterHandler(BaseRequestHandler): def get(self): self.render_template('counters.html',{'counters': Counter.all()}) def post(self): key = self.request.get('key') # Add the task to the default queue. for loop in range(0,1): a=taskqueue.add(url='/worker', params={'key': key}) #self.redirect('/') self.response.out.write(a) class CounterWorker(webapp.RequestHandler): def post(self): # should run at most 1/s key = self.request.get('key') def txn(): counter = Counter.get_by_key_name(key) if counter is None: counter = Counter(key_name=key, count=1) else: counter.count += 1 counter.put() db.run_in_transaction(txn) self.response.out.write('sss')#used for get by task queue def main(): run_wsgi_app(webapp.WSGIApplication([ ('/', CounterHandler), ('/worker', CounterWorker), ])) if __name__ == '__main__': main() How can I show the 'sss'?
[ "The current Task Queue API doesn't support processing return values or sending them back to the point of origin. Your appengine process isn't long-lived enough for that programming paradigm to work.\nIn your example, it looks like what you want is something like this:\n\nCreate task\nReturn AJAX code that will po...
[ 2 ]
[]
[]
[ "ajax", "google_app_engine", "python", "task_queue" ]
stackoverflow_0004085075_ajax_google_app_engine_python_task_queue.txt
Q: How do I serialize this into JSON? { "_id" : ObjectId("4ccb42cb8aad692e01000004"), "loc" : { "lat" : 37.799506, "long" : -122.459445 }, "test_set" : 1, "title" : "Melissa Mills Housewife 01 SIGNED", "num_comments" : 58, "down_votes" : 66, "up_votes" : 79, "image_url" : "http://farm2.static.flickr.com/1374/5126544615_79170591e5_m.jpg", "image_url_thumb" : "http://farm2.static.flickr.com/1374/5126544615_79170591e5_t.jpg", "date" : "Fri Oct 29 2010 21:55:23 GMT+0000 (UTC)", "flickr_id" : "5126544615" } One of the elements in thelist is above. thejson = simplejson.dumps({"results":thelist}) However, I can't serialize this because of the date field. It can't serialize datetime. A: I doubt that the problem has to do anything with datetime: in your dictionary, there is no datetime object at all, but the "date" key has a regular string value. More likely, the problem is that it can't serialize the ObjectId class. To overcome this limitation, create a new class inheriting from JSONEncoder, and overriding the default method. A: Unless i'm missing something - its the ObjectId that is causing the error (works for me here without it). You might want to consider munging or removing that field if not needed. The date parses fine. A: This works for me. I have removed ObjectId as I do not have the class with me. result = { "loc" : { "lat" : 37.799506, "long" : -122.459445 }, "test_set" : 1, "title" : "Melissa Mills Housewife 01 SIGNED", "num_comments" : 58, "down_votes" : 66, "up_votes" : 79, "image_url" : "http://farm2.static.flickr.com/1374/5126544615_79170591e5_m.jpg", "image_url_thumb" : "http://farm2.static.flickr.com/1374/5126544615_79170591e5_t.jpg", "date" : "Fri Oct 29 2010 21:55:23 GMT+0000 (UTC)", "flickr_id" : "5126544615" } import simplejson thejson = simplejson.dumps(result) print thejson Output: {"down_votes": 66, "loc": {"lat": 37.799506000000001, "long": -122.459445}, "image_url": "http://farm2.static.flickr.com/1374/5126544615_79170591e5_m.jpg", "test_set": 1, "title": "Melissa Mills Housewife 01 SIGNED", "up_votes": 79, "num_comments": 58, "image_url_thumb": "http://farm2.static.flickr.com/1374/5126544615_79170591e5_t.jpg", "date": "Fri Oct 29 2010 21:55:23 GMT+0000 (UTC)", "flickr_id": "5126544615"} And if you are getting the following error, then you need to have class ObjectId : "_id" : ObjectId("4ccb42cb8aad692e01000004"), NameError: name 'ObjectId' is not defined
How do I serialize this into JSON?
{ "_id" : ObjectId("4ccb42cb8aad692e01000004"), "loc" : { "lat" : 37.799506, "long" : -122.459445 }, "test_set" : 1, "title" : "Melissa Mills Housewife 01 SIGNED", "num_comments" : 58, "down_votes" : 66, "up_votes" : 79, "image_url" : "http://farm2.static.flickr.com/1374/5126544615_79170591e5_m.jpg", "image_url_thumb" : "http://farm2.static.flickr.com/1374/5126544615_79170591e5_t.jpg", "date" : "Fri Oct 29 2010 21:55:23 GMT+0000 (UTC)", "flickr_id" : "5126544615" } One of the elements in thelist is above. thejson = simplejson.dumps({"results":thelist}) However, I can't serialize this because of the date field. It can't serialize datetime.
[ "I doubt that the problem has to do anything with datetime: in your dictionary, there is no datetime object at all, but the \"date\" key has a regular string value.\nMore likely, the problem is that it can't serialize the ObjectId class. To overcome this limitation, create a new class inheriting from JSONEncoder, a...
[ 6, 1, 1 ]
[]
[]
[ "datetime", "javascript", "json", "python", "serialization" ]
stackoverflow_0004085276_datetime_javascript_json_python_serialization.txt
Q: Echo Program Help I need some guidance on how best to run this program. Im trying to come up with a python program that accepts input from the user and prints them out until the word quit is inputted in which the program quits but not before printing the inputs twice.. For example 2.0' 6.0 3.5 quit 2.0 6.0 3.5 2.0 6.0 3.5 Thanks so much for helping =) inputs = [] inp = raw_input(" Enter number or quit: ") while inp!="quit": inp = float(inp) inputs.append(inp) inp = raw_input("Enter number or quit': ") if inp == "quit": print inputs, "quit", inputs * 2 now how do i get them on seperate lines? A: [Edited answer] You are converting raw_input to float and then trying to compare with a string. Shouldn't you compare first and then print. Apart from this mistake you are doing fine! A: Edited to improve visual clarity: 1 #!/usr/bin/env python 2 3 if __name__ == "__main__": 4 inputs = [] 5 while True: 6 inp = raw_input("Enter number|`quit': ") 7 if inp.lower() == "quit": 8 break 9 try: inp = float(inp) 10 except: 11 print "Not a number, ignored" 12 continue 13 print inp 14 inputs.append(inp) 15 for i in inputs: print i
Echo Program Help
I need some guidance on how best to run this program. Im trying to come up with a python program that accepts input from the user and prints them out until the word quit is inputted in which the program quits but not before printing the inputs twice.. For example 2.0' 6.0 3.5 quit 2.0 6.0 3.5 2.0 6.0 3.5 Thanks so much for helping =) inputs = [] inp = raw_input(" Enter number or quit: ") while inp!="quit": inp = float(inp) inputs.append(inp) inp = raw_input("Enter number or quit': ") if inp == "quit": print inputs, "quit", inputs * 2 now how do i get them on seperate lines?
[ "[Edited answer]\nYou are converting raw_input to float and then trying to compare with a string. Shouldn't you compare first and then print. \nApart from this mistake you are doing fine!\n", "Edited to improve visual clarity:\n1 #!/usr/bin/env python\n2 \n3 if __name__ == \"__main__\":\n4 inputs = []\n5 whil...
[ 0, -1 ]
[]
[]
[ "python", "user_input" ]
stackoverflow_0004084442_python_user_input.txt
Q: what is a request object in python socketserver api In python socketserver api, as well as xmlrpcserver, there are mentioned many times the request object,for example: SimpleXMLRPCServer.process_request(self, request, client_address): But I cannot find any description to this request object. What is it ? where in the python doc can I find the the expaination(it's attribute,method,etc) of the request object? A: You can use the source (of SocketServer.py in this case) to answer such questions. process_request is called in _handle_request_noblock, which gets the request from get_request. What that does depends on the SocketServer subclass. For a TCPServer, you'll find that it is the result of the socket accept() call.
what is a request object in python socketserver api
In python socketserver api, as well as xmlrpcserver, there are mentioned many times the request object,for example: SimpleXMLRPCServer.process_request(self, request, client_address): But I cannot find any description to this request object. What is it ? where in the python doc can I find the the expaination(it's attribute,method,etc) of the request object?
[ "You can use the source (of SocketServer.py in this case) to answer such questions. process_request is called in _handle_request_noblock, which gets the request from get_request. What that does depends on the SocketServer subclass. For a TCPServer, you'll find that it is the result of the socket accept() call.\n" ]
[ 1 ]
[]
[]
[ "python", "request", "sockets", "xml_rpc" ]
stackoverflow_0004085364_python_request_sockets_xml_rpc.txt
Q: How to check the last element of a python list? In python I need a stack, and I'm using a list for it. In the documenation it says that you can use append() and pop() for stack operations but what about accessing the top of the stack without removing it? How to do that in the most readable way? Because all I came up with is stack[-1:][0] which looks a bit ugly for me, there must be a better way. A: No need to slice. stack[-1] A: stack[-1] ist the last element EDIT renamed the previously list called variable (Thanks, Tim McNamara).
How to check the last element of a python list?
In python I need a stack, and I'm using a list for it. In the documenation it says that you can use append() and pop() for stack operations but what about accessing the top of the stack without removing it? How to do that in the most readable way? Because all I came up with is stack[-1:][0] which looks a bit ugly for me, there must be a better way.
[ "No need to slice.\nstack[-1]\n\n", "stack[-1] ist the last element\nEDIT renamed the previously list called variable (Thanks, Tim McNamara). \n" ]
[ 21, 2 ]
[]
[]
[ "list", "python", "stack" ]
stackoverflow_0004085417_list_python_stack.txt
Q: Problems Connecting to Minimized Signal Problem: I have a gtk.Dialog. Whenever the 'minimize' button on the dialog is clicked, the window is destroyed. Question: How can I connect to the minimize button of a gtk.Dialog so that I can iconify the window? A: Are you sure it's the minimize button? Because GTK doesn't deal with (or even know about the existence of) minimize buttons at all, they are part of the window manager.
Problems Connecting to Minimized Signal
Problem: I have a gtk.Dialog. Whenever the 'minimize' button on the dialog is clicked, the window is destroyed. Question: How can I connect to the minimize button of a gtk.Dialog so that I can iconify the window?
[ "Are you sure it's the minimize button? Because GTK doesn't deal with (or even know about the existence of) minimize buttons at all, they are part of the window manager.\n" ]
[ 0 ]
[]
[]
[ "gtk", "pygtk", "python", "user_interface" ]
stackoverflow_0004081020_gtk_pygtk_python_user_interface.txt
Q: Is Django 1.2.3 competable with Python 2.6.5 Just curious to know, Test module won't work properly with django 1.2.3 when update from django 1.1.1 (now on python 2.6.5) A: Yes. You're having other problems.
Is Django 1.2.3 competable with Python 2.6.5
Just curious to know, Test module won't work properly with django 1.2.3 when update from django 1.1.1 (now on python 2.6.5)
[ "Yes. You're having other problems.\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004085826_django_python.txt
Q: Can any one suggest a good networking project in python I want to do a networking project using python. Can any one suggest a useful project in networking? I am aiming to complete it within next 5 months or so. A: Without a doubt, if you want to have a good understanding with implementation, Twisted is the way to go. Just by going through the documentation, you will get lots of ideas for a project. And also, these Twisted tutorials (introduction) are the best (based on a question I asked earlier on SO) A: Take a simple socket or UDP based protocol and write a form of proxy using a subclass of SimpleHTTPServer, which manages sessions, talks to a server and allows web browsers to access the service over HTTP, thereby bringing old technologies to the world of HTML5. I'll elaborate: [Web browser with JavaScript*] | | (talks over HTTP) V [SimpleHTTPServer in Python*] | | (Has a pool of) | +--------- [TCP or UDP client 1*] +--------- [TCP or UDP client n*] | | (Which all talk to) V [Some other servers] * You write this part The end result being that your web browser can do things that it was never supposed to do. The simplest example could be something which manages telnet sessions, allowing a JavaScript client to play nethack over telnet. Other ideas along the same vein, Windows file sharing, monitoring performance counters, remote desktop / VNC and so on.
Can any one suggest a good networking project in python
I want to do a networking project using python. Can any one suggest a useful project in networking? I am aiming to complete it within next 5 months or so.
[ "Without a doubt, if you want to have a good understanding with implementation, Twisted is the way to go. Just by going through the documentation, you will get lots of ideas for a project.\nAnd also, these Twisted tutorials (introduction) are the best (based on a question I asked earlier on SO)\n", "Take a simple...
[ 6, 4 ]
[]
[]
[ "python" ]
stackoverflow_0004084776_python.txt
Q: Multiple reactors (main loops) in one application through threading (or alternative means) I've got an idea for an app I'd like to work on to learn a bit more about Twisted and WebSockets. I was thinking of integrating a previously written IRC Bot into a web application. As far as I can see it, I would need three reactors to make it work: Primary Reactor: Web Server (HTTP). This would be your average twisted.web application. When you access it, you can POST an IRC server/channel to connection. The web server would then talk to a different reactor in a different thread, which is... Secondary Reactor: IRC Bot. This would be an IRC bot running via the Twisted IRC client protocol. It would join a channel, and whenever something was said, it would take that data and push it to yet another reactor, on yet another thread, which is... Tertiary Reactor: WebSocket Server (WS): Since WebSockets don't use the regular HTTP Protocol, they need their own server (or so it seems, looking at examples such as this. When the IRC bot receives a message, it tells the WebSocket Server to push that message to connected clients. In my mind, this makes sense. It seems like it would be possible. Does anyone have any examples of multiple reactors running in separate threads, or is this something I've imagined that can't be done in the current incarnation of Twisted. Are there any architecture changes that can (or should) be made to minimize the reactor count, etc? Thanks for any help. A: Lucky for you, it is easy to reduce the number of reactors, specifically, to 1: You can only ever have a single reactor, in a single thread, in any given Twisted process. If you try to have more, nothing will work. The whole point of a reactor, actually, is to facilitate having multiple sources of events combined into a single thread. If you want to listen on 3 different ports with 3 different protocols, your application might look like this: from twisted.internet import reactor reactor.listenTCP(4321, FirstProtocolFactory()) reactor.listenTCP(5432, SecondProtocolFactory()) reactor.listenTCP(6543, ThirdProtocolFactory()) reactor.run() Of course, you may not actually be calling listenTCP directly yourself, as you probably want to use Service objects from twisted.application.internet if you are using twistd, either via a .tac file or a twistd plugin. And you won't need to call reactor.run() yourself, if twistd is doing it for you. My point here is that, via whatever means, you load up the reactor with all the events you expect it to react to - listening servers, client connections, timed events - and it will react to each one as it occurs. (Hence, "reactor".) For the specific values of what FirstProtocolFactory, SecondProtocolFactory, and ThirdProtocolFactory should be, see the links in pyfunc's answer. A: No, I don't think you need multiple reactors. What you need, is a multi-service multi-protocol application. This is where Twisted really shines. So your application should start a web service, IRC Bot service and WebSocket server. Use twisted application service framework, specially starting a multi service http://twistedmatrix.com/documents/10.1.0/core/howto/application.html http://twistedmatrix.com/documents/10.1.0/api/twisted.application.service.MultiService.html Check out the IRC bot implementation and twisted IRC protocol support: http://twistedmatrix.com/documents/10.1.0/api/twisted.words.protocols.irc.IRC.html http://twistedmatrix.com/documents/current/words/ http://code.google.com/p/pyfibot/ and for websocket and twisted http://twistedmatrix.com/trac/export/29073/branches/websocket-4173-2/doc/web/howto/websocket.xhtml
Multiple reactors (main loops) in one application through threading (or alternative means)
I've got an idea for an app I'd like to work on to learn a bit more about Twisted and WebSockets. I was thinking of integrating a previously written IRC Bot into a web application. As far as I can see it, I would need three reactors to make it work: Primary Reactor: Web Server (HTTP). This would be your average twisted.web application. When you access it, you can POST an IRC server/channel to connection. The web server would then talk to a different reactor in a different thread, which is... Secondary Reactor: IRC Bot. This would be an IRC bot running via the Twisted IRC client protocol. It would join a channel, and whenever something was said, it would take that data and push it to yet another reactor, on yet another thread, which is... Tertiary Reactor: WebSocket Server (WS): Since WebSockets don't use the regular HTTP Protocol, they need their own server (or so it seems, looking at examples such as this. When the IRC bot receives a message, it tells the WebSocket Server to push that message to connected clients. In my mind, this makes sense. It seems like it would be possible. Does anyone have any examples of multiple reactors running in separate threads, or is this something I've imagined that can't be done in the current incarnation of Twisted. Are there any architecture changes that can (or should) be made to minimize the reactor count, etc? Thanks for any help.
[ "Lucky for you, it is easy to reduce the number of reactors, specifically, to 1:\nYou can only ever have a single reactor, in a single thread, in any given Twisted process. If you try to have more, nothing will work.\nThe whole point of a reactor, actually, is to facilitate having multiple sources of events combin...
[ 20, 5 ]
[]
[]
[ "events", "multithreading", "python", "reactor", "twisted" ]
stackoverflow_0004084090_events_multithreading_python_reactor_twisted.txt
Q: Creating a dictionary from an iterable What is the easiest way to create a dictionary from an iterable and assigning it some default value? I tried: >>> x = dict(zip(range(0, 10), range(0))) But that doesn't work since range(0) is not an iterable as I thought it would not be (but I tried anyways!) So how do I go about it? If I do: >>> x = dict(zip(range(0, 10), 0)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: zip argument #2 must support iteration This doesn't work either. Any suggestions? A: In python 3, You can use a dict comprehension. >>> {i:0 for i in range(0,10)} {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0} Fortunately, this has been backported in python 2.7 so that's also available there. A: You need the dict.fromkeys method, which does exactly what you want. From the docs: fromkeys(...) dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. v defaults to None. So what you need is: >>> x = dict.fromkeys(range(0, 10), 0) >>> x {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0} A: PulpFiction gives the practical way to do it. But just for interest, you can make your solution work by using itertools.repeat for a repeating 0. x = dict(zip(range(0, 10), itertools.repeat(0))) A: You may want to consider using the defaultdict subclass from the standard library's collections module. By using it you may not even need to iterate though the iterable since keys associated with the specified default value will be created whenever you first access them. In the sample code below I've inserted a gratuitous for loop to force a number of them to be created so the following print statement will have something to display. from collections import defaultdict dflt_dict = defaultdict(lambda:42) # depending on what you're doing this might not be necessary... for k in xrange(0,10): dflt_dict[k] # accessing any key adds it with the specified default value print dflt_dict.items() # [(0, 42), (1, 42), (2, 42), (3, 42), ... (6, 42), (7, 42), (8, 42), (9, 42)]
Creating a dictionary from an iterable
What is the easiest way to create a dictionary from an iterable and assigning it some default value? I tried: >>> x = dict(zip(range(0, 10), range(0))) But that doesn't work since range(0) is not an iterable as I thought it would not be (but I tried anyways!) So how do I go about it? If I do: >>> x = dict(zip(range(0, 10), 0)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: zip argument #2 must support iteration This doesn't work either. Any suggestions?
[ "In python 3, You can use a dict comprehension.\n>>> {i:0 for i in range(0,10)}\n{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}\n\nFortunately, this has been backported in python 2.7 so that's also available there.\n", "You need the dict.fromkeys method, which does exactly what you want.\nFrom the d...
[ 32, 23, 2, 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0004084749_dictionary_python.txt
Q: With the GAE Bulk Uploader script, how do I deal with empty values in the CSV? I've set up my app.yaml and data_uploader files as suggested in this document. My CSV file has some null values (the spreadsheet that I exported had some empty cells). When I run the script, I get this error in the log file: [ERROR ] Error in WorkerThread-0: Value should not be empty; received []. My guess is that it is because some values are empty in the csv file, How can I make sure that the empty values are either imported as '' into the datastore, or not imported at all (the model properties are all optional). Thanks, David. A: You probably should customize your bulkloader.yaml giving the right directive in the property map section. Check if the import_transform element on your model kind property that gives problem is set, and try to use the none_if_empty directive . - property: fooproperty external_name: fooproperty import_transform: transform.none_if_empty(foopropertytype) This is what none_if_empty does: def none_if_empty(fn): """A wrapper for a value to return None if it's empty. Useful on import. Can be used in config files (e.g. "transform.none_if_empty(int)" or as a decorator. Args: fn: Single argument transform function. Returns: Wrapped function. """ def wrapper(value): if value == '' or value is None: return None return fn(value) return wrapper Afaik, bulkloader generates the bulkloader.yaml file inferring the proper configuration using the production datastore stats; just check if the assumptions made are correct.
With the GAE Bulk Uploader script, how do I deal with empty values in the CSV?
I've set up my app.yaml and data_uploader files as suggested in this document. My CSV file has some null values (the spreadsheet that I exported had some empty cells). When I run the script, I get this error in the log file: [ERROR ] Error in WorkerThread-0: Value should not be empty; received []. My guess is that it is because some values are empty in the csv file, How can I make sure that the empty values are either imported as '' into the datastore, or not imported at all (the model properties are all optional). Thanks, David.
[ "You probably should customize your bulkloader.yaml giving the right directive in the property map section. \nCheck if the import_transform element on your model kind property that gives problem is set, and try to use the none_if_empty directive .\n- property: fooproperty\n external_name: fooproperty\n import_tra...
[ 1 ]
[]
[]
[ "csv", "google_app_engine", "python" ]
stackoverflow_0003908524_csv_google_app_engine_python.txt
Q: How to MySQL to store multi-params for HTTP POST? HTTP Post may have multiple params such as: http://example.com/controller/ (while params=({'country':'US'},{'city':'NYC'}) I am developing a web spider with Python, I face a problem how to track difference with same url with different params. Now I can load the content, but I have no idea how to store the post params in a field of SQLite3 table. It is easy to store the params in database like MySQL for system developer, but since the params of different sites are various. I prefer to store the post params in single field, rather than one-on-one relationship mapping in a table. HTTP GET >>> import urllib >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params) >>> print f.read() HTTP POST >>> import urllib >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params) >>> print f.read() My project configuration: Python + SQLite3 Store http url and post params and tracking the changes. The post params contains multiple key-value pairs The stored params should be decoded back to params. The encode issues should be covered. I saw multiple solutions like JSON, XML and YAML. I guess this format actually stored as string (CHAR) type in SQLite, in UTF-8. But I have no idea if there is any handy way to convert them back to Python tuple type? Or, can I encode the post params into get params with + and & symbal, and decode it back to post params? Sorry, I am just a newbie for Python. A: You can convert to and from json easily like this: >>> import json >>> json.dumps({'spam': 1, 'eggs': 2, 'bacon': 0}) '{"eggs": 2, "bacon": 0, "spam": 1}' >>> json.loads('{"eggs": 2, "bacon": 0, "spam": 1}') {u'eggs': 2, u'bacon': 0, u'spam': 1} >>> json.dumps((1,2,3,4)) '[1, 2, 3, 4]' >>> json.loads('[1, 2, 3, 4]') [1, 2, 3, 4] >>> Better use it because it is more versatile than home made & separated encoding, it supports any nesting complexity. A: I would probably go with Frost's suggestion - JSON encoding is far more robust. However, there have been situations in the past where I've been forced to go a simpler route: >>> d = {'spam': 1, 'eggs': 2, 'bacon': 0} >>> l = [(a +":"+str(b)) for a,b in d.items()] >>> ','.join(l) 'eggs:2,bacon:0,spam:1' Obviously your delimiters (, and : in this case) need to be carefully chosen, but this works in a pinch.
How to MySQL to store multi-params for HTTP POST?
HTTP Post may have multiple params such as: http://example.com/controller/ (while params=({'country':'US'},{'city':'NYC'}) I am developing a web spider with Python, I face a problem how to track difference with same url with different params. Now I can load the content, but I have no idea how to store the post params in a field of SQLite3 table. It is easy to store the params in database like MySQL for system developer, but since the params of different sites are various. I prefer to store the post params in single field, rather than one-on-one relationship mapping in a table. HTTP GET >>> import urllib >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params) >>> print f.read() HTTP POST >>> import urllib >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params) >>> print f.read() My project configuration: Python + SQLite3 Store http url and post params and tracking the changes. The post params contains multiple key-value pairs The stored params should be decoded back to params. The encode issues should be covered. I saw multiple solutions like JSON, XML and YAML. I guess this format actually stored as string (CHAR) type in SQLite, in UTF-8. But I have no idea if there is any handy way to convert them back to Python tuple type? Or, can I encode the post params into get params with + and & symbal, and decode it back to post params? Sorry, I am just a newbie for Python.
[ "You can convert to and from json easily like this:\n>>> import json\n>>> json.dumps({'spam': 1, 'eggs': 2, 'bacon': 0})\n'{\"eggs\": 2, \"bacon\": 0, \"spam\": 1}'\n>>> json.loads('{\"eggs\": 2, \"bacon\": 0, \"spam\": 1}')\n{u'eggs': 2, u'bacon': 0, u'spam': 1}\n\n>>> json.dumps((1,2,3,4))\n'[1, 2, 3, 4]'\n>>> js...
[ 3, 0 ]
[]
[]
[ "post", "python", "sqlite" ]
stackoverflow_0004085925_post_python_sqlite.txt
Q: Python/Tkinter: Stretch an image horizontally? Is it possible to stretch an image horizontally? Use case: I have a one pixel wide (60 pixel tall) image that I would like to stretch horizontally to fill its parent container. The purpose of stretching this image is to give the container in question the appearance of a gradient background. Here's what I tried without success (the gradient image shows up, but just centers itself vs. stretching): import Tkinter as tkinter root = tkinter.Tk() image = tkinter.PhotoImage( file='gradient1.gif' ) imgBackground = tkinter.Label( image=image ) imgBackground.pack( side='top', fill='x', expand=True ) root.mainloop() A: No, there is no way to stretch an image to fill the container. However, you can detect when a widget changes size and you can "repaint" the gradient. Use a canvas, and create a binding to <Configure> that draws the gradient. It sounds slow but it's plenty fast enough assuming you don't have hundreds of these.
Python/Tkinter: Stretch an image horizontally?
Is it possible to stretch an image horizontally? Use case: I have a one pixel wide (60 pixel tall) image that I would like to stretch horizontally to fill its parent container. The purpose of stretching this image is to give the container in question the appearance of a gradient background. Here's what I tried without success (the gradient image shows up, but just centers itself vs. stretching): import Tkinter as tkinter root = tkinter.Tk() image = tkinter.PhotoImage( file='gradient1.gif' ) imgBackground = tkinter.Label( image=image ) imgBackground.pack( side='top', fill='x', expand=True ) root.mainloop()
[ "No, there is no way to stretch an image to fill the container. However, you can detect when a widget changes size and you can \"repaint\" the gradient. Use a canvas, and create a binding to <Configure> that draws the gradient. It sounds slow but it's plenty fast enough assuming you don't have hundreds of these.\n"...
[ 1 ]
[]
[]
[ "image", "python", "tkinter", "user_interface" ]
stackoverflow_0004084383_image_python_tkinter_user_interface.txt
Q: Open a new window in Vim-embedded python script I've just started wrapping my head around vim+python scripts (having no experience with native vim scripts). How can I open a new window to contain the stdout from a background process? Currently, after reading some :help python, the only option I see is something like: cmd = ":bel new" vim.command(cmd) A: Since vim.command can execute most (if not all?) ex commands, you can simply call :new +read!ls from within it. :new splits the current window and puts a new (empty, no name) buffer into the upper window. It takes an argument +[cmd] which we use to execute read!cmd which reads the stdout of cmd after the bang into the buffer. Be aware that you need to escape spaces in your command with \ All in all you get vim.command("new +read!cmd") :python vim.command("new +read!ls") to read in the contents of the current directory into a new buffer in a n cichew, horizontally split window. If you want to handle escaping of special characters, consider using python's re.escape(): :py import re;vim.command("new +read!"+re.escape("ls Dire*")) which should be sufficient for most cases. If in doubt, check its documentation and compare it to that of your shell.
Open a new window in Vim-embedded python script
I've just started wrapping my head around vim+python scripts (having no experience with native vim scripts). How can I open a new window to contain the stdout from a background process? Currently, after reading some :help python, the only option I see is something like: cmd = ":bel new" vim.command(cmd)
[ "Since vim.command can execute most (if not all?) ex commands, you can simply call :new +read!ls from within it.\n:new splits the current window and puts a new (empty, no name) buffer into the upper window. It takes an argument +[cmd] which we use to execute read!cmd which reads the stdout of cmd after the bang int...
[ 3 ]
[]
[]
[ "python", "scripting", "vim" ]
stackoverflow_0003546952_python_scripting_vim.txt
Q: python queue concurrency process management The use case is as follows : I have a script that runs a series of non-python executables to reduce (pulsar) data. I right now use subprocess.Popen(..., shell=True) and then the communicate function of subprocess to capture the standard out and standard error from the non-python executables and the captured output I log using the python logging module. The problem is: just one core of the possible 8 get used now most of the time. I want to spawn out multiple processes each doing a part of the data set in parallel and I want to keep track of progres. It is a script / program to analyze data from a low frequencey radio telescope (LOFAR). The easier to install / manage and test the better. I was about to build code to manage all this but im sure it must already exist in some easy library form. A: Maybe Celery will serve your needs. A: The subprocess module can start multiple processes for you just fine, and keep track of them. The problem, though, is reading the output from each process without blocking any other processes. Depending on the platform there's several ways of doing this: using the select module to see which process has data to be read, setting the output pipes non-blocking using the fnctl module, using threads to read each process's data (which subprocess.Popen.communicate itself uses on Windows, because it doesn't have the other two options.) In each case the devil is in the details, though. Something that handles all this for you is Twisted, which can spawn as many processes as you want, and can call your callbacks with the data they produce (as well as other situations.) A: If I understand correctly what you are doing, I might suggest a slightly different approach. Try establishing a single unit of work as a function and then layer on the parallel processing after that. For example: Wrap the current functionality (calling subprocess and capturing output) into a single function. Have the function create a result object that can be returned; alternatively, the function could write out to files as you see fit. Create an iterable (list, etc.) that contains an input for each chunk of data for step 1. Create a multiprocessing Pool and then capitalize on its map() functionality to execute your function from step 1 for each of the items in step 2. See the python multiprocessing docs for details. You could also use a worker/Queue model. The key, I think, is to encapsulate the current subprocess/output capture stuff into a function that does the work for a single chunk of data (whatever that is). Layering on the parallel processing piece is then quite straightforward using any of several techniques, only a couple of which were described here.
python queue concurrency process management
The use case is as follows : I have a script that runs a series of non-python executables to reduce (pulsar) data. I right now use subprocess.Popen(..., shell=True) and then the communicate function of subprocess to capture the standard out and standard error from the non-python executables and the captured output I log using the python logging module. The problem is: just one core of the possible 8 get used now most of the time. I want to spawn out multiple processes each doing a part of the data set in parallel and I want to keep track of progres. It is a script / program to analyze data from a low frequencey radio telescope (LOFAR). The easier to install / manage and test the better. I was about to build code to manage all this but im sure it must already exist in some easy library form.
[ "Maybe Celery will serve your needs.\n", "The subprocess module can start multiple processes for you just fine, and keep track of them. The problem, though, is reading the output from each process without blocking any other processes. Depending on the platform there's several ways of doing this: using the select ...
[ 2, 2, 0 ]
[]
[]
[ "concurrency", "process", "python", "queue" ]
stackoverflow_0004086311_concurrency_process_python_queue.txt
Q: Should I be using SQLObject, SQLAlchemy, or SQLAlchemy + Elixir? I've been using SQLObject for a long while, but noticed that SQLAlchemy has become a lot more popular in the last couple years: http://www.google.com/trends?q=sqlobject,+sqlalchemy Are there compelling reasons to switch to SQLAlchemy? How is its performance relative to SQLObject? Its usability? And what is the added performance overhead for using Elixir? My needs are basic, simple CRUD. Nothing exotic. I've seen this related question, but it was asked 1+ year ago and didn't have much response. A: I used SqlObject extensively as part of TurboGears 0.9, but switched to SqlAlchemy + elixir as a drop in replacement for SqlObject even before TurboGears did. Note that even without elixir, SqlAlchemy has it's own declarative style class definitions: http://docs.sqlalchemy.org/en/rel_1_0/orm/extensions/declarative/index.html If you are unsure about performance, it shouldn't be too much work to drop in elixir as a replacement in your app and do some quick profiling. I'd guess that the performance differences between SqlObject/SQL/SQLA+elixir pale in comparison to the time spent writing and reading data to/from the database. Note that SqlAlchemy affords much greater control over eager/lazy loading of relationships and columns, which helps the memory footprint & performance of your app in lots of cases. Probably the most compelling reason to switch is that SqlAlchemy is that it is being actively developed (although I don't know too much about dev status of SqlObject any more). As a secondary reason, you can be assured that if your needs get more complex, it's quite likely that there is someone else that has already attempted to bang the square peg of Python objects into the round hole of SQL successfully with SqlAlchemy.
Should I be using SQLObject, SQLAlchemy, or SQLAlchemy + Elixir?
I've been using SQLObject for a long while, but noticed that SQLAlchemy has become a lot more popular in the last couple years: http://www.google.com/trends?q=sqlobject,+sqlalchemy Are there compelling reasons to switch to SQLAlchemy? How is its performance relative to SQLObject? Its usability? And what is the added performance overhead for using Elixir? My needs are basic, simple CRUD. Nothing exotic. I've seen this related question, but it was asked 1+ year ago and didn't have much response.
[ "I used SqlObject extensively as part of TurboGears 0.9, but switched to SqlAlchemy + elixir as a drop in replacement for SqlObject even before TurboGears did.\nNote that even without elixir, SqlAlchemy has it's own declarative style class definitions:\nhttp://docs.sqlalchemy.org/en/rel_1_0/orm/extensions/declarati...
[ 11 ]
[]
[]
[ "python", "python_elixir", "sqlalchemy", "sqlobject" ]
stackoverflow_0004066803_python_python_elixir_sqlalchemy_sqlobject.txt
Q: How to output in the log window in perforce client p4v using custom tools We're developing perforce custom tools in python and we're outputting messages during the script execution. It shows up in p4win but we're mainly using p4v and the output doesn't show up in the log window. Is there a way to output there or in any other pane without resorting to run the tool in a terminal window? A: When Python is directing its output to a pipe rather than straight to a terminal, it buffers its output by default. I think you can work around this by either passing the "-u" parameter when invoking Python (e.g., python -u myscript.py arg1 arg2) to tell it not to buffer, or by calling sys.stdout.flush() throughout your script any time you want it to make sure that the output has made it to P4V. See also: http://kb.perforce.com/article/914/sending-script-output-to-p4vs-custom-tool-terminal (It looks like that question was asked and answered after you asked here on Stack Overflow. Sorry if you're already well aware of it.)
How to output in the log window in perforce client p4v using custom tools
We're developing perforce custom tools in python and we're outputting messages during the script execution. It shows up in p4win but we're mainly using p4v and the output doesn't show up in the log window. Is there a way to output there or in any other pane without resorting to run the tool in a terminal window?
[ "When Python is directing its output to a pipe rather than straight to a terminal, it buffers its output by default. I think you can work around this by either passing the \"-u\" parameter when invoking Python (e.g., python -u myscript.py arg1 arg2) to tell it not to buffer, or by calling sys.stdout.flush() through...
[ 1 ]
[]
[]
[ "customtool", "logging", "perforce", "python" ]
stackoverflow_0002608361_customtool_logging_perforce_python.txt
Q: Integrate Python's Django into a C++ application I would like to integrate Python, and specifically Django, to a C++ application. This is for many reasons which include, but not limited to: Ease of data handling and feature development in python Django's amazing ORM Django's instant admin interface etc... My specific application is a real-time event intensive application. The Python\Django aspects should mainly come in the initial data loading part, batch data dumps and semi-real time web access for tracking and configuration. How would you go about integrating these very different programing languages and design concepts? A: I would strongly recommend considering to integrate the other way around: your C++ application into Python. A good article on the tradeoffs of extending vs. embedding. Also, re the Django/web server part, it's not always recommended to have a monolithic application that's too large. Consider breaking the web-serving part into a separate application, purely Django on Python, that will communicate with your main application via either OS files or sockets, or some other IPC. You're still welcome to add Python to your main application (by extending or embedding) for the other needs.
Integrate Python's Django into a C++ application
I would like to integrate Python, and specifically Django, to a C++ application. This is for many reasons which include, but not limited to: Ease of data handling and feature development in python Django's amazing ORM Django's instant admin interface etc... My specific application is a real-time event intensive application. The Python\Django aspects should mainly come in the initial data loading part, batch data dumps and semi-real time web access for tracking and configuration. How would you go about integrating these very different programing languages and design concepts?
[ "I would strongly recommend considering to integrate the other way around: your C++ application into Python. A good article on the tradeoffs of extending vs. embedding.\nAlso, re the Django/web server part, it's not always recommended to have a monolithic application that's too large. Consider breaking the web-serv...
[ 4 ]
[]
[]
[ "c++", "django", "integration", "python" ]
stackoverflow_0004086888_c++_django_integration_python.txt
Q: how to develop a python wrapper for a C code? Well given a C code , is there a way that i can use other languages like python to execute the C code . What i am trying to say is , there are soo many modules which are built using a language , but also offer access via different languages , is there any way to do that ? A: Of course, it's called "extending" in the Python world. The official documentation is here. A short excerpt: This document describes how to write modules in C or C++ to extend the Python interpreter with new modules. Those modules can define new functions but also new object types and their methods. The document also describes how to embed the Python interpreter in another application, for use as an extension language. Finally, it shows how to compile and link extension modules so that they can be loaded dynamically (at run time) into the interpreter, if the underlying operating system supports this feature. An even easier way for Python would be using the ctypes standard package to run code in DLLs. A: Many ways. Generically, this is often called a Foreign Function Interface. That Wikipedia page says the following about Python: * The major dynamic languages, such as Python, Perl, Tcl, and Ruby, all provide easy access to native code written in C/C++ (or any other language obeying C/C++ calling conventions). o Python additionally provides the Ctypes module 2, which can load C functions from shared libraries/DLLs on-the-fly and translate simple data types automatically between Python and C semantics. For example: import ctypes libc = ctypes.CDLL('/lib/libc.so.6' ) # under Linux/Unix t = libc.time(None) # equivalent C code: t = time(NULL) print t A popular choice that supports many languages is SWIG
how to develop a python wrapper for a C code?
Well given a C code , is there a way that i can use other languages like python to execute the C code . What i am trying to say is , there are soo many modules which are built using a language , but also offer access via different languages , is there any way to do that ?
[ "Of course, it's called \"extending\" in the Python world. The official documentation is here. A short excerpt:\n\nThis document describes how to write\n modules in C or C++ to extend the\n Python interpreter with new modules.\n Those modules can define new functions\n but also new object types and their\n met...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004087240_python.txt
Q: (python) meaning of st_mode Can anyone tell me what is the meaning of the number from the ST_MODE function? Example: >>>import os >>>stat = os.stat('/home') >>>print stat.st_mode 16877 it prints 16877. What is that for? A: It's the permission bits of the file. >>> oct(16877) '040755' See the various stat.S_* attributes for more info. A: The standard stat module can help you interpret these values from os.stat: The stat module defines constants and functions for interpreting the results of os.stat(), os.fstat() and os.lstat() (if they exist). For complete details about the stat(), fstat() and lstat() calls, consult the documentation for your system.
(python) meaning of st_mode
Can anyone tell me what is the meaning of the number from the ST_MODE function? Example: >>>import os >>>stat = os.stat('/home') >>>print stat.st_mode 16877 it prints 16877. What is that for?
[ "It's the permission bits of the file.\n>>> oct(16877)\n'040755'\n\nSee the various stat.S_* attributes for more info.\n", "The standard stat module can help you interpret these values from os.stat:\n\nThe stat module defines constants and\n functions for interpreting the results\n of os.stat(), os.fstat() and\...
[ 29, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004087427_python.txt
Q: Logging worker processes with Parallel Python I've inherited the maintenance of some scientific computing using Parallel Python on a cluster. With Parallel Python, jobs are submitted to a ppserver, which (in this case) talks to already-running ppserver processes on other computers, dishing tasks out to ppworkers processes. I'd like to use the standard library logging module to log errors and debugging information from the functions that get submitted to a ppserver. Since these ppworkers run as separate processes (on separate computers) I'm not sure how to properly structure the logging. Must I log to a separate file for each process? Maybe there's a log handler that would make it all better? Also, I want reports on what process on what computer has hit an error, but the code I'm writing the logging in probably isn't aware of these things; maybe that should be happening at the ppserver level? (Version of the question cross-posted on Parallel Python Forums, I'll post an answer here if I get something there about this from a non SO user) A: One way to solve your problem is to do the following: In each worker process, use a logging.handlers.SocketHandler to send events from the worker to a dedicated logger process. Create a dedicated logger process which listens for logging events on a socket, based on the working example given in the docs at https://docs.python.org/3/howto/logging-cookbook.html#sending-and-receiving-logging-events-across-a-network Profit ;-) If you catch exceptions in your worker functions and log them, then you should be able to get visibility of errors across all workers in one place. A: I'd use Python's logging and socket APIs. Just follow the example here. Simply start a ppworker dedicated to logging somewhere, and create a new logging.Logger in each of the other workers with a logging.SocketHandler specifying the hostname and port of the machine running the logging ppworker. If you have a syslog server running, you can also use Python's syslog module, which is documented here.
Logging worker processes with Parallel Python
I've inherited the maintenance of some scientific computing using Parallel Python on a cluster. With Parallel Python, jobs are submitted to a ppserver, which (in this case) talks to already-running ppserver processes on other computers, dishing tasks out to ppworkers processes. I'd like to use the standard library logging module to log errors and debugging information from the functions that get submitted to a ppserver. Since these ppworkers run as separate processes (on separate computers) I'm not sure how to properly structure the logging. Must I log to a separate file for each process? Maybe there's a log handler that would make it all better? Also, I want reports on what process on what computer has hit an error, but the code I'm writing the logging in probably isn't aware of these things; maybe that should be happening at the ppserver level? (Version of the question cross-posted on Parallel Python Forums, I'll post an answer here if I get something there about this from a non SO user)
[ "One way to solve your problem is to do the following:\n\nIn each worker process, use a logging.handlers.SocketHandler to send events from the worker to a dedicated logger process.\nCreate a dedicated logger process which listens for logging events on a socket, based on the working example given in the docs at http...
[ 6, 2 ]
[]
[]
[ "logging", "parallel_python", "python" ]
stackoverflow_0004005180_logging_parallel_python_python.txt
Q: Django: Import CSV file and handle clash of unique values correctly I want to write a Python script to import the contents of CSV file into a Django app's database. So for each CSV record, I create an instance of my model, set the appropriate values from the parsed CSV line and call save on the model instance. For example, see below: for row in dataReader: person=Person() person.name=row[0] person.age=row[1] person.save() Now, lets say that the name Field is marked as unique in the Model. What's the best way to handle the situation where the record being imported has the same Name value as one already in the database? Should I check for this before calling save? How? Should I catch an exception? What would the code look like? EDIT: If a record already exists in the db with the same name field, I would still like to update the other fields. For example, if I was importing Fred,43 and there was already a record Fred,42 in the db it should update the db to Fred,43. EDIT: Thanks for all the answers. This approach, pointed to by chefsmart, is the one I think I will go with: try: obj = Person.objects.get(name=name) except Person.DoesNotExist: obj = Person() obj.name = name obj.age = age obj.save() A: One of the Django orm function that i love so much is get_or_create() so i will suggest you do like this: for row in dataReader: person_record, created = person.get_or_create(name=row[0], age=row[1]) you can check after if you want to change the old record in person_record or check if the record was created if created: and do what ever you want with it .. hope this will help A: See this http://blog.roseman.org.uk/2010/03/9/easy-create-or-update/ I guess it can be adapted to your case. A: Something like that: for row in dataReader: try: Person.objects.get(name=row[0]) #write some errlog here possibly or update the model except Person.DoesNotExist: Person.object.create(name=row[0],age=row[1]) It will possibly be better to know you stumbled into duplicate or not. Also you don't depend on whether the model was written correctly or database supports unique keys etc. A: Catch the django.db.IntegrityError, I reckon
Django: Import CSV file and handle clash of unique values correctly
I want to write a Python script to import the contents of CSV file into a Django app's database. So for each CSV record, I create an instance of my model, set the appropriate values from the parsed CSV line and call save on the model instance. For example, see below: for row in dataReader: person=Person() person.name=row[0] person.age=row[1] person.save() Now, lets say that the name Field is marked as unique in the Model. What's the best way to handle the situation where the record being imported has the same Name value as one already in the database? Should I check for this before calling save? How? Should I catch an exception? What would the code look like? EDIT: If a record already exists in the db with the same name field, I would still like to update the other fields. For example, if I was importing Fred,43 and there was already a record Fred,42 in the db it should update the db to Fred,43. EDIT: Thanks for all the answers. This approach, pointed to by chefsmart, is the one I think I will go with: try: obj = Person.objects.get(name=name) except Person.DoesNotExist: obj = Person() obj.name = name obj.age = age obj.save()
[ "One of the Django orm function that i love so much is get_or_create()\nso i will suggest you do like this:\nfor row in dataReader:\n person_record, created = person.get_or_create(name=row[0], age=row[1])\n\nyou can check after if you want to change the old record in person_record or check if the record was crea...
[ 5, 2, 1, 0 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0004086630_database_django_python.txt
Q: Why does Parallel Python work the way it does? In Parallel Python, why is it necessary to wrap any modules the function passed will need along with variables and namespaces in that job submission call - how necessary is it to preserve module level "global" variables? (if that's all that's going on) submit function: submit(self, func, args=(), depfuncs=(), modules=(), callback=None, callbackargs=(),group='default', globals=None) Submits function to the execution queue func - function to be executed args - tuple with arguments of the 'func' depfuncs - tuple with functions which might be called from 'func' modules - tuple with module names to import callback - callback function which will be called with argument list equal to callbackargs+(result,) as soon as calculation is done callbackargs - additional arguments for callback function group - job group, is used when wait(group) is called to wait for jobs in a given group to finish globals - dictionary from which all modules, functions and classes will be imported, for instance: globals=globals() A: The reason that pp works the way it does, is that it makes a fresh instance of the Python interpreter for every worker, which is completely independent from anything that has run before or since. This ensures that there are no unintended side-effects, such as __future__ imports being active in the worker process. The problem with this is that it makes things way more complicated to get right, and in my experience with pp, not particularly robust. pp does try to make things a bit easier for the user, but seems to introduce more problems than it solves in its efforts to do that. If I were to write code that was designed for use on a cluster from the start, I would probably end up using pp, but I've found that adapting existing code to work with pp is a nightmare.
Why does Parallel Python work the way it does?
In Parallel Python, why is it necessary to wrap any modules the function passed will need along with variables and namespaces in that job submission call - how necessary is it to preserve module level "global" variables? (if that's all that's going on) submit function: submit(self, func, args=(), depfuncs=(), modules=(), callback=None, callbackargs=(),group='default', globals=None) Submits function to the execution queue func - function to be executed args - tuple with arguments of the 'func' depfuncs - tuple with functions which might be called from 'func' modules - tuple with module names to import callback - callback function which will be called with argument list equal to callbackargs+(result,) as soon as calculation is done callbackargs - additional arguments for callback function group - job group, is used when wait(group) is called to wait for jobs in a given group to finish globals - dictionary from which all modules, functions and classes will be imported, for instance: globals=globals()
[ "The reason that pp works the way it does, is that it makes a fresh instance of the Python interpreter for every worker, which is completely independent from anything that has run before or since. This ensures that there are no unintended side-effects, such as __future__ imports being active in the worker process. ...
[ 3 ]
[]
[]
[ "parallel_processing", "parallel_python", "python" ]
stackoverflow_0004074297_parallel_processing_parallel_python_python.txt
Q: django template date filter format string question I have a datetime value that is available in a django template. I am trying to format the date as "d-mmm" so for example dates are formated as: 5-Mar 10-Mar 4-Apr etc. I have tried different combinations - NOTHING works so far?. I hope I dont have to write a custom filter just to format a date ? [Edit] I tried the 'obvious' format string like: 'j-M', 'j-N', (even 'j-mmm' and 'd-mmm') A: Have you tried {{ some_date|date:"j-M" }}? http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
django template date filter format string question
I have a datetime value that is available in a django template. I am trying to format the date as "d-mmm" so for example dates are formated as: 5-Mar 10-Mar 4-Apr etc. I have tried different combinations - NOTHING works so far?. I hope I dont have to write a custom filter just to format a date ? [Edit] I tried the 'obvious' format string like: 'j-M', 'j-N', (even 'j-mmm' and 'd-mmm')
[ "Have you tried {{ some_date|date:\"j-M\" }}?\nhttp://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\n" ]
[ 14 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004087717_django_python.txt
Q: Email notification on file change in particular directory with Python I would like to script a function wich is looking in a particular directory for files, if there are new files, it should send out an notification email. I already prepared a script which is looking for new files in a directory, it write the notification about a new file into the console. But now I would like to notified via email, as soon as there has a new file arrived. Could someone help? import os, time def run(): path_to_watch = "//D$:/testfolder/" print "watching: " + path_to_watch before = dict ([(f, None) for f in os.listdir (path_to_watch)]) while 1: after = dict ([(f, None) for f in os.listdir (path_to_watch)]) added = [f for f in after if not f in before] removed = [f for f in before if not f in after] if added: print "Added: ", ", ".join (added) if removed: print "Removed: ", ", ".join (removed) before = after time.sleep (10) if __name__ == "__main__": print run() A: It's very simple if you have an SMTP mail server set up (i'm assuming you have a mail system!). Will take you about 10 lines of code in total. Here is a python example. If you have any problems, we will need more information to help further. For example, what mail system you are using e.t.c. A: OKI, in this case I have worked out my own solution. Probably it can help somebody with a similar task to resolve. import os, time, smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText path_to_watch = "//networkpath/test/filetest" print "watching: " + path_to_watch before = dict ([(f, None) for f in os.listdir (path_to_watch)]) while 1: after = dict ([(f, None) for f in os.listdir (path_to_watch)]) added = [f for f in after if not f in before] removed = [f for f in before if not f in after] if removed: print "Removed: ", ", ".join (removed) if added: print "Added: ", ", ".join (added) me = "me@test.de" you = "you@test.de" msg = MIMEMultipart('alternative') msg['Subject'] = "New file has approached." msg['From'] = me msg['To'] = you text = "New file has approached in:\n\\\networkpath\test\filetest" part1 = MIMEText(text, 'plain') msg.attach(part1) s = smtplib.SMTP('smtp.test.com') s.sendmail(me, you, msg.as_string()) s.quit() time.sleep (10) before = after Have fun!
Email notification on file change in particular directory with Python
I would like to script a function wich is looking in a particular directory for files, if there are new files, it should send out an notification email. I already prepared a script which is looking for new files in a directory, it write the notification about a new file into the console. But now I would like to notified via email, as soon as there has a new file arrived. Could someone help? import os, time def run(): path_to_watch = "//D$:/testfolder/" print "watching: " + path_to_watch before = dict ([(f, None) for f in os.listdir (path_to_watch)]) while 1: after = dict ([(f, None) for f in os.listdir (path_to_watch)]) added = [f for f in after if not f in before] removed = [f for f in before if not f in after] if added: print "Added: ", ", ".join (added) if removed: print "Removed: ", ", ".join (removed) before = after time.sleep (10) if __name__ == "__main__": print run()
[ "It's very simple if you have an SMTP mail server set up (i'm assuming you have a mail system!). Will take you about 10 lines of code in total. Here is a\npython example.\nIf you have any problems, we will need more information to help further. For example, what mail system you are using e.t.c.\n", "OKI, in this...
[ 1, 0 ]
[]
[]
[ "email", "file", "notifications", "python" ]
stackoverflow_0003987134_email_file_notifications_python.txt
Q: What's the best solution for OpenID with Django? Please note: this is an ancient question with ancient answers. Most of the linked apps are now unmaintained. These days, most people seem to use django-allauth or python-social-auth. I'll leave the original question intact below for posterity's sake. There are at least half a dozen Django apps that provide OpenID authentication for Django: django-openid django-openid-auth another django-openid-auth, which seems to be dead django-authopenid django-socialauth (which also provides authentication with Twitter and Facebook accounts) django-socialregistration (has Facebook and Twitter authentication, too) django-openid-consumer, a fork of Simon Willison's original django-openid. Seems more suited for simple blog comments than a full fledged registration workflow django-social-auth I played around with a couple of them. Simon Willison's django-openid made a good impression, but as he is at the forefront of trendsetting in Djangoland, I sometimes have difficulties wrapping my head around his trends (e.g. the whole dynamic urlpatterns system in django-openid). What's more, I couldn't get login to work with Google. django-authopenid made a good impression, and it seems to have good integration with django-registration. django-socialauth and django-socialregistration have support for Twitter and Facebook, which is definitely a plus. Who knows if and when Facebook will start to be an OpenID provider...? socialauth seems to have its share of problems, though. So, what is the best OpenID app out there? Please share any positive (and negative) experience. Thanks! A: The one that has proven to work best for me, and which seems most up-to-date is the one over at launchpad. It integrated seamlessly with my application that already utilizes the django.auth module. https://launchpad.net/django-openid-auth To get a copy run: bzr branch lp:django-openid-auth Or install it via PyPI pip install django-openid-auth A: The last post for this thread is in February. It's been almost 8 months and I'm pretty sure a lot of things have been changed. I am very interested in Django-Socialauth since it supports gmail, yahoo, facebook, twitter, and OpenID. I found two forks that seem up-to-date: https://github.com/uswaretech/Django-Socialauth https://github.com/agiliq/Django-Socialauth The second fork has been recently updated at this moment. I was wondering if anyone has recently used any of these forks? I am looking for the most reliable one for my website. Thanks Update: The most up-to-date fork appears to be omab/django-social-auth, which is also what the pypi package points at. A: I prefer django-authopenid, but I think most of the mature solutions are pretty equal at this point. Still, it is what I see used the most. I've made a handful of customizations to how we use it without having to actually fork it, and that's a huge plus in my book. In other words, its fairly hookable. A: Don't forget Elf Sternberg's fork of django-socialauth - he's working to clean up what he sees as a lot of bad implementation decisions in the original socialauth app. Looks clean so far but it's unclear whether his project will have momentum. A: django-socialauth is good for me A: You could try pinax
What's the best solution for OpenID with Django?
Please note: this is an ancient question with ancient answers. Most of the linked apps are now unmaintained. These days, most people seem to use django-allauth or python-social-auth. I'll leave the original question intact below for posterity's sake. There are at least half a dozen Django apps that provide OpenID authentication for Django: django-openid django-openid-auth another django-openid-auth, which seems to be dead django-authopenid django-socialauth (which also provides authentication with Twitter and Facebook accounts) django-socialregistration (has Facebook and Twitter authentication, too) django-openid-consumer, a fork of Simon Willison's original django-openid. Seems more suited for simple blog comments than a full fledged registration workflow django-social-auth I played around with a couple of them. Simon Willison's django-openid made a good impression, but as he is at the forefront of trendsetting in Djangoland, I sometimes have difficulties wrapping my head around his trends (e.g. the whole dynamic urlpatterns system in django-openid). What's more, I couldn't get login to work with Google. django-authopenid made a good impression, and it seems to have good integration with django-registration. django-socialauth and django-socialregistration have support for Twitter and Facebook, which is definitely a plus. Who knows if and when Facebook will start to be an OpenID provider...? socialauth seems to have its share of problems, though. So, what is the best OpenID app out there? Please share any positive (and negative) experience. Thanks!
[ "The one that has proven to work best for me, and which seems most up-to-date is the one over at launchpad.\nIt integrated seamlessly with my application that already utilizes the django.auth module.\nhttps://launchpad.net/django-openid-auth\nTo get a copy run:\nbzr branch lp:django-openid-auth\n\nOr install it via...
[ 87, 32, 12, 8, 5, 1 ]
[]
[]
[ "django", "openid", "python" ]
stackoverflow_0002123369_django_openid_python.txt
Q: Read XML file just like python's lxml with C#? <Connections> <Connection ID = "1" Source="1:0" Sink="4:0"/> <Connection ID = "2" Source="2:0" Sink="4:1"/> <Connection ID = "3" Source="2:0" Sink="5:0"/> <Connection ID = "4" Source="3:0" Sink="5:1"/> <Connection ID = "5" Source="4:0" Sink="6:0"/> <Connection ID = "6" Source="5:0" Sink="7:0"/> </Connections> When I need to get info from the previous XML code, Python's lxml can be used as follows. def getNodeList(self): connection = self.doc.find('Connections') cons = connection.find('Connection') for con in cons.iter(): con.get("ID") # get attribute ... What C# libraries/function can I use for getting the info like python's lxml? I mean, can I use find()/iter() or similar with C#? What C# libraries are similar to python's lxml? ADDED Based on dtb's answer, I could get what I needed. using System; using System.Xml; using System.Xml.Linq; namespace HIR { class Dummy { static void Main(String[] argv) { XDocument doc = XDocument.Load("test2.xml"); var connection = doc.Descendants("Connections"); // .First(); var cons = connection.Elements("Connection"); foreach (var con in cons) { var id = (string)con.Attribute("ID"); Console.WriteLine(id); } } } } I had to remove the 'First()' to avoid compiler error. With mono I could run the following to get the binary. dmcs /r:System.Xml.Linq main.cs A: You want to use LINQ-to-XML: void GetNodeList() { var connection = this.doc.Descendants("Connections").First(); var cons = connection.Elements("Connection"); foreach (var con in cons) { var id = (string)con.Attribute("ID"); } } A: I would use XElement: var xml = XElement.Parse(xmlString); foreach (var connection in xml.Elements("Connection")) { Console.WriteLine(connection.Attribute("ID").Value); }
Read XML file just like python's lxml with C#?
<Connections> <Connection ID = "1" Source="1:0" Sink="4:0"/> <Connection ID = "2" Source="2:0" Sink="4:1"/> <Connection ID = "3" Source="2:0" Sink="5:0"/> <Connection ID = "4" Source="3:0" Sink="5:1"/> <Connection ID = "5" Source="4:0" Sink="6:0"/> <Connection ID = "6" Source="5:0" Sink="7:0"/> </Connections> When I need to get info from the previous XML code, Python's lxml can be used as follows. def getNodeList(self): connection = self.doc.find('Connections') cons = connection.find('Connection') for con in cons.iter(): con.get("ID") # get attribute ... What C# libraries/function can I use for getting the info like python's lxml? I mean, can I use find()/iter() or similar with C#? What C# libraries are similar to python's lxml? ADDED Based on dtb's answer, I could get what I needed. using System; using System.Xml; using System.Xml.Linq; namespace HIR { class Dummy { static void Main(String[] argv) { XDocument doc = XDocument.Load("test2.xml"); var connection = doc.Descendants("Connections"); // .First(); var cons = connection.Elements("Connection"); foreach (var con in cons) { var id = (string)con.Attribute("ID"); Console.WriteLine(id); } } } } I had to remove the 'First()' to avoid compiler error. With mono I could run the following to get the binary. dmcs /r:System.Xml.Linq main.cs
[ "You want to use LINQ-to-XML:\nvoid GetNodeList()\n{\n var connection = this.doc.Descendants(\"Connections\").First();\n var cons = connection.Elements(\"Connection\");\n\n foreach (var con in cons)\n {\n var id = (string)con.Attribute(\"ID\");\n }\n}\n\n", "I would use XElement:\nvar xml = ...
[ 4, 0 ]
[]
[]
[ "c#", "lxml", "python", "xml" ]
stackoverflow_0004087847_c#_lxml_python_xml.txt
Q: Efficient way of Element lookup in a Python List? I have a list of files in a directory. I have to process only certain files from that directory. filelist is my desired file-list. How do I go about achieving this? Not interested in a bash solution since I have to do it all in this one Python script. Thanks much! for record in result: filelist.append(record[0]) print filelist for file in os.listdir(sys.argv[1].strip() + "/"): for file in filelist: #This doesn't work, how else do I do this? If file equals to my desired file-list, then do something. print file Sorry guys, not sure how I missed this! Early morning coding I guess!! Mods, please close it unless someone wants to chip in with an efficient way of doing it. for file in os.listdir(sys.argv[1].strip() + "/"): if file in filelist: print file A: Sounds like you want to do a test: for file in os.listdir(sys.argv[1].strip() + "/"): if file in filelist: # Found a file in the wanted-list. print file A: If order and uniqueness don't matter, you can use a set intersection, which will be much more efficient. import set os_list = os.listdir(sys.argv[1].strip() + "/") for file in set(os_list) & set(filelist): #... Example of improvement: import random import timeit l = [random.randint(1,10000) for i in range(1000)] l2 = [random.randint(1,10000) for i in range(1000)] def f1(): l3 = [] for i in l: if i in l2: l3.append(i) return l3 def f2(): l3 = [] for i in set(l) & set(l2): l3.append(i) return l3 t1 = timeit.Timer('f1()', 'from __main__ import f1') print t1.timeit(100) #2.0850549985 t2 = timeit.Timer('f2()', 'from __main__ import f2') print t2.timeit(100) #0.0162533142857 A: It looks like you just want to do something like this: for file in os.listdir(sys.argv[1].strip() + "/"): if file in filelist: print file Note that I just changed the second for to an if. However, since you were asking about efficiency, you probably want to change filelist from being a list to being a set or a dict to make the in operator more efficient. A: Something like this: print [x for x in os.listdir(sys.argv[1].strip() + "/") if x in filelist]
Efficient way of Element lookup in a Python List?
I have a list of files in a directory. I have to process only certain files from that directory. filelist is my desired file-list. How do I go about achieving this? Not interested in a bash solution since I have to do it all in this one Python script. Thanks much! for record in result: filelist.append(record[0]) print filelist for file in os.listdir(sys.argv[1].strip() + "/"): for file in filelist: #This doesn't work, how else do I do this? If file equals to my desired file-list, then do something. print file Sorry guys, not sure how I missed this! Early morning coding I guess!! Mods, please close it unless someone wants to chip in with an efficient way of doing it. for file in os.listdir(sys.argv[1].strip() + "/"): if file in filelist: print file
[ "Sounds like you want to do a test:\nfor file in os.listdir(sys.argv[1].strip() + \"/\"):\n if file in filelist:\n # Found a file in the wanted-list.\n print file\n\n", "If order and uniqueness don't matter, you can use a set intersection, which will be much more efficient.\nimport set\nos_list =...
[ 3, 3, 1, 1 ]
[]
[]
[ "arrays", "list", "lookup", "python", "traversal" ]
stackoverflow_0004088092_arrays_list_lookup_python_traversal.txt
Q: WIth django, can you do something similiar to user = User.new(params[:user]) during a form post? in ruby/ror you can do this: user = User.new(params[:user]) which populates a new object with the values from a posted form. Can something similar be done using django/python? A: Look at the model form documentation. Basically, the code would look like: f = UserForm(request.POST or None) user = f.save() A: If you are talking about Django's built-in auth app, then keep in mind that there are a few considerations when creating users, such as passwords, unique usernames, etc
WIth django, can you do something similiar to user = User.new(params[:user]) during a form post?
in ruby/ror you can do this: user = User.new(params[:user]) which populates a new object with the values from a posted form. Can something similar be done using django/python?
[ "Look at the model form documentation. Basically, the code would look like:\nf = UserForm(request.POST or None)\nuser = f.save()\n\n", "If you are talking about Django's built-in auth app, then keep in mind that there are a few considerations when creating users, such as passwords, unique usernames, etc\n" ]
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004087609_django_python.txt
Q: re-combining a list/dictionary in python following on from this question i have the following lists in python which i want to recombine into a dictionary/list: from fromfruits = { "names" : ['banana','grapefruit','apple'] , "colors" : ['yellow','pink','green'], ... } to tofruits = [ {'name':'banana','color':'yellow',...}, {'name':'grapefruit','color':'pink',...}, {'name':'apple','color':'green',...} ] what's the best way to do it so that i can have n properties listed in fromfruits? please help! :) A: Since the request is now to be more general: >>> from itertools import izip >>> ff = {'colors': ['yellow', 'pink', 'green'], 'names': ['banana', 'grapefruit', 'apple'], 'blah': ['a','b','c']} >>> [dict(izip(ff.iterkeys(), v)) for v in izip(*ff.itervalues())] [{'blah': 'a', 'colors': 'yellow', 'names': 'banana'}, {'blah': 'b', 'colors': 'pink', 'names': 'grapefruit'}, {'blah': 'c', 'colors': 'green', 'names': 'apple'}] since the order of keys and values are the same (assuming no intervening modifications to the dictionary). A: It'd be pretty hard to go from keys like 'names' to 'name', teaching the program how to do proper english singlularization ... so i renamed the keys in the input: ff = dict(name=['banana','grapefruit','apple'], color=['yellow','pink','green'], yummy=[True,False,True]) You can solve this problem with zip again: # make fruits [('yellow', True, 'banana'), ('pink', False, 'grapefruit'), ... ] fruits = zip(*ff.itervalues()) # then add the names to each fruit tofruits = [dict(zip(ff.iterkeys(),fruit)) for fruit in fruits] # gives: [{'color': 'yellow', 'yummy': True, 'name': 'banana'}, ... ] A: [dict((x, fromfruits[x][n]) for x in fromfruits.keys()) for n in range(len(next(fromfruits.itervalues())))] Optimize as desired. A: >>> fromfruits {'colors': ['yellow', 'pink', 'green'], 'names': ['banana', 'grapefruit', 'apple']} >>> [{'name': name, 'color': color} for name in fromfruits['names'] for color in fromfruits['colors']] [{'color': 'yellow', 'name': 'banana'}, {'color': 'pink', 'name': 'banana'}, {'color': 'green', 'name': 'banana'}, {'color': 'yellow', 'name': 'grapefruit'}, {'color': 'pink', 'name': 'grapefruit'}, {'color': 'green', 'name': 'grapefruit'}, {'color': 'yellow', 'name': 'apple'}, {'color': 'pink', 'name': 'apple'}, {'color': 'green', 'name': 'apple'}] And now in some more detail (re-formatted for clarity): >>>[{'name': name, 'color': color} for name in fromfruits['names'] for color in fromfruits['colors']] This is a "list comprehension" with a double for which goes over all combinations of names and colors. You can add a third loop if you want to mix in other attributes, like "shape" or whatever. A: not very pythonic, but ... keys = fromfruits.keys() nvals = len(fromfruits[keys[0]]) tofruits = [ ] for i in range(nvals): tofruits.append ({ }) for k in keys: tofruits[-1][k] = fromfruits[k][i] A: This problem is a bit more convoluted than the average list comprehension because of the nested dictionaries. However if you can create the right iterable then a list comprehension is the way to go. Try: tofruits = [ {'name':n, 'color':c} for n,c in zip(fromfruits['names'], fromfruits['colors']) ] Here the zip function is used to produce tuples which match the correct name and color. This is a good way to go here because both are stored in basic lists within the fromfruits dict. These tuples (from zip) are then unpacked into n and c, which are then used as in a typical list comprehension.
re-combining a list/dictionary in python
following on from this question i have the following lists in python which i want to recombine into a dictionary/list: from fromfruits = { "names" : ['banana','grapefruit','apple'] , "colors" : ['yellow','pink','green'], ... } to tofruits = [ {'name':'banana','color':'yellow',...}, {'name':'grapefruit','color':'pink',...}, {'name':'apple','color':'green',...} ] what's the best way to do it so that i can have n properties listed in fromfruits? please help! :)
[ "Since the request is now to be more general:\n>>> from itertools import izip\n>>> ff = {'colors': ['yellow', 'pink', 'green'], 'names': ['banana', 'grapefruit', 'apple'], 'blah': ['a','b','c']}\n\n>>> [dict(izip(ff.iterkeys(), v)) for v in izip(*ff.itervalues())]\n[{'blah': 'a', 'colors': 'yellow', 'names': 'banan...
[ 4, 3, 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "list", "loops", "python" ]
stackoverflow_0004087622_dictionary_list_loops_python.txt
Q: Converting an unknown timestamp to a datetime in Python I'm getting a timestamp back from the WordPress API, but the usual method of converting from timestamp to datetime is failing me. I run this: print pages[1]['dateCreated'] print datetime.fromtimestamp(pages[1]['dateCreated']) And get this: 20100228T09:25:07 Traceback (most recent call last): File "C:\Python26\Lib\SITE-P~1\PYTHON~1\pywin\framework\scriptutils.py", line 325, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\mmorisy\Desktop\My Dropbox\python\betterblogmaster3.py", line 28, in <module> print datetime.fromtimestamp(pages[1]['dateCreated']) AttributeError: DateTime instance has no attribute '__float__' Any suggestions? A: Assume you've from datetime import datetime: print datetime.strptime(pages[1]['dateCreated'],'%Y%m%dT%H:%M:%S')
Converting an unknown timestamp to a datetime in Python
I'm getting a timestamp back from the WordPress API, but the usual method of converting from timestamp to datetime is failing me. I run this: print pages[1]['dateCreated'] print datetime.fromtimestamp(pages[1]['dateCreated']) And get this: 20100228T09:25:07 Traceback (most recent call last): File "C:\Python26\Lib\SITE-P~1\PYTHON~1\pywin\framework\scriptutils.py", line 325, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\mmorisy\Desktop\My Dropbox\python\betterblogmaster3.py", line 28, in <module> print datetime.fromtimestamp(pages[1]['dateCreated']) AttributeError: DateTime instance has no attribute '__float__' Any suggestions?
[ "Assume you've from datetime import datetime:\nprint datetime.strptime(pages[1]['dateCreated'],'%Y%m%dT%H:%M:%S')\n\n" ]
[ 3 ]
[]
[]
[ "datetime", "python", "timestamp" ]
stackoverflow_0004088506_datetime_python_timestamp.txt
Q: Assigning dates to samples in matplotlib Given some arbitrary numpy array of data, how can I plot it to make dates appear on the x axis? In this case, sample 0 will be some time, say 7:00, and every sample afterwards will be spaced one minute apart, so that for 60 samples, the time displayed should be 7:00, 7:01, ..., 7:59. I looked at some of the other questions on here but they all required actually setting a date and some other stuff that felt very over the top compared to what I'd like to do. Thanks! Christoph A: If you use an array of datetime objects for your x-axis, the plot() function will behave like you want (assuming that you don't want all 60 labels from 7:00 to 7:59 to be displayed). Here is a sample code: import random from pylab import * from datetime import * N = 60 t0 = datetime.combine(date.today(), time(7,0,0)) delta_t = timedelta(minutes=1) x_axis = t0 + arange(N)*delta_t plot(x_axis, random(N)) show() Concerning the use of the combine() function, see question python time + timedelta equivalent
Assigning dates to samples in matplotlib
Given some arbitrary numpy array of data, how can I plot it to make dates appear on the x axis? In this case, sample 0 will be some time, say 7:00, and every sample afterwards will be spaced one minute apart, so that for 60 samples, the time displayed should be 7:00, 7:01, ..., 7:59. I looked at some of the other questions on here but they all required actually setting a date and some other stuff that felt very over the top compared to what I'd like to do. Thanks! Christoph
[ "If you use an array of datetime objects for your x-axis, the plot() function will behave like you want (assuming that you don't want all 60 labels from 7:00 to 7:59 to be displayed). Here is a sample code:\nimport random\nfrom pylab import *\nfrom datetime import *\nN = 60\nt0 = datetime.combine(date.today(), time...
[ 1 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0004088005_matplotlib_numpy_python.txt
Q: raw_input() is deprecated in python 3.1? Possible Duplicate: Easy: How to use Raw_input in 3.1 in old style i can entering data with this function A: raw_input is now input per http://docs.python.org/dev/py3k/whatsnew/3.0.html A: raw_input has been renamed to input. The 2.x input, which eval'd the input, was removed. A: You should use input() instead, which uses the behavior of raw_input() from 2.x. A: in Python 3 you use input function
raw_input() is deprecated in python 3.1?
Possible Duplicate: Easy: How to use Raw_input in 3.1 in old style i can entering data with this function
[ "raw_input is now input per http://docs.python.org/dev/py3k/whatsnew/3.0.html\n", "raw_input has been renamed to input. The 2.x input, which eval'd the input, was removed.\n", "You should use input() instead, which uses the behavior of raw_input() from 2.x.\n", "in Python 3 you use input function\n" ]
[ 3, 3, 0, 0 ]
[]
[]
[ "python", "raw_input" ]
stackoverflow_0004088692_python_raw_input.txt
Q: Pythonistas, how do I move data from top to bottom to left to right in MySQL (think multiple values for each ID)? Task at hand is to move data as shown in table 1 to that of table 2. Table (1) ID Val -- --- 1 a 1 b 1 c 2 k 3 l 3 m 3 n Val columns depend on the number of unique values for each ID. in this case it is 3 but it can be 20 in real world! Table (2) ID Val1 Val2 Val3 -- -- -- -- 1 a b c 2 k 3 l m n How am I tackling it for smaller values of Val columns (3 in this case) : I create a temp table. create table test(ID int not null, b int auto_increment not null,primary key(ID,b), Val varchar(255)); I then insert data in to test. I get the following (I have to create the Val columns manually): ID Val b -- --- -- 1 a 1 1 b 2 1 c 3 2 k 1 3 l 1 3 m 2 3 n 3 I know that this is a tedious process with lot of manual work. This was before I fell in love with Python! An efficient solution in Python for this problem is really appreciated! This is what I have so far import MySQLdb import itertools import dbstring cursor = db.cursor() cursor.execute("select ID, val from mytable") mydata = cursor.fetchall() IDlist = [] vallist = [] finallist = [] for record in mydata: IDlist.append(record[1]) vallist.append(record[2]) zipped = zip(IDlist,vallist) zipped.sort(key=lambda x:x[0]) for i, j in itertools.groupby(zipped, key=lambda x:x[0]): finallist = [k[1] for k in j] finallist.insert(0, i) finallist += [None] * (4 - len(finallist)) ### Making it a uniform size list myvalues.append(finallist) cursor.executemany("INSERT INTO temptable VALUES (%s, %s, %s, %s)", myvalues) db.close() A: the pytonic way to do this is to use itertools.groupby import itertools a = [(1, 'a'), (1, 'b'), (2, 'c')] # groupby need sorted value so sorted in case a.sort(key=lambda x:x[0]) for i, j in itertools.groupby(a, key=lambda x:x[0]): print i, [k[1] for k in j] return 1 ['a', 'b'] 2 ['c']
Pythonistas, how do I move data from top to bottom to left to right in MySQL (think multiple values for each ID)?
Task at hand is to move data as shown in table 1 to that of table 2. Table (1) ID Val -- --- 1 a 1 b 1 c 2 k 3 l 3 m 3 n Val columns depend on the number of unique values for each ID. in this case it is 3 but it can be 20 in real world! Table (2) ID Val1 Val2 Val3 -- -- -- -- 1 a b c 2 k 3 l m n How am I tackling it for smaller values of Val columns (3 in this case) : I create a temp table. create table test(ID int not null, b int auto_increment not null,primary key(ID,b), Val varchar(255)); I then insert data in to test. I get the following (I have to create the Val columns manually): ID Val b -- --- -- 1 a 1 1 b 2 1 c 3 2 k 1 3 l 1 3 m 2 3 n 3 I know that this is a tedious process with lot of manual work. This was before I fell in love with Python! An efficient solution in Python for this problem is really appreciated! This is what I have so far import MySQLdb import itertools import dbstring cursor = db.cursor() cursor.execute("select ID, val from mytable") mydata = cursor.fetchall() IDlist = [] vallist = [] finallist = [] for record in mydata: IDlist.append(record[1]) vallist.append(record[2]) zipped = zip(IDlist,vallist) zipped.sort(key=lambda x:x[0]) for i, j in itertools.groupby(zipped, key=lambda x:x[0]): finallist = [k[1] for k in j] finallist.insert(0, i) finallist += [None] * (4 - len(finallist)) ### Making it a uniform size list myvalues.append(finallist) cursor.executemany("INSERT INTO temptable VALUES (%s, %s, %s, %s)", myvalues) db.close()
[ "the pytonic way to do this is to use itertools.groupby\nimport itertools\n\na = [(1, 'a'), (1, 'b'), (2, 'c')]\n\n# groupby need sorted value so sorted in case\na.sort(key=lambda x:x[0])\n\nfor i, j in itertools.groupby(a, key=lambda x:x[0]):\n print i, [k[1] for k in j]\n\nreturn\n1 ['a', 'b']\n2 ['c']\n\n" ]
[ 2 ]
[]
[]
[ "data_manipulation", "mysql", "python" ]
stackoverflow_0004088639_data_manipulation_mysql_python.txt
Q: Formatting large integers in Python I am dealing with large integral numbers in my script and I want to format the numbers into strings using the 'K', 'M' and 'B' postfix chars to denote scale of thousands, millions or billionsб respectively. Rather than rolling my own function, I wonder if there is an built-in function that either does this "out of the box", or at least would be useful when writing my own function to do this type of formatting? A: There's no built-in way to do this in the Python standard library, but there's a nice example of what you want to achieve here.
Formatting large integers in Python
I am dealing with large integral numbers in my script and I want to format the numbers into strings using the 'K', 'M' and 'B' postfix chars to denote scale of thousands, millions or billionsб respectively. Rather than rolling my own function, I wonder if there is an built-in function that either does this "out of the box", or at least would be useful when writing my own function to do this type of formatting?
[ "There's no built-in way to do this in the Python standard library, but there's a nice example of what you want to achieve here.\n" ]
[ 3 ]
[]
[]
[ "largenumber", "python", "string_formatting" ]
stackoverflow_0004088700_largenumber_python_string_formatting.txt
Q: python int doesn't have __iadd__() method? I know this is bad practice: >>> a = 5 >>> a.__radd__(5) 10 >>> a 5 >>> a.__iadd__(5) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'int' object has no attribute '__iadd__' Out of curiosity, if an int object doesn't have __iadd__, then how does += work? A: Out of curiosity, if an int object doesn't have __iadd__, then how does += work? a += 5 Becomes a = a + 5 Because there's no __iadd__ for immutable objects. This is (in effect) a = a.__add__( 5 ) And works nicely. A new int object is created by __add__. Some of the rules are here http://docs.python.org/reference/datamodel.html#coercion-rules. A: If an object does not have __iadd__, __add__ will be used. Method __iadd__ is suposed to be an optimized inplace __add__ case, it is not mandatory.
python int doesn't have __iadd__() method?
I know this is bad practice: >>> a = 5 >>> a.__radd__(5) 10 >>> a 5 >>> a.__iadd__(5) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'int' object has no attribute '__iadd__' Out of curiosity, if an int object doesn't have __iadd__, then how does += work?
[ "\nOut of curiosity, if an int object doesn't have __iadd__, then how does += work?\n\na += 5\n\nBecomes\na = a + 5\n\nBecause there's no __iadd__ for immutable objects.\nThis is (in effect)\na = a.__add__( 5 )\n\nAnd works nicely. A new int object is created by __add__.\nSome of the rules are here http://docs.pyt...
[ 6, 3 ]
[]
[]
[ "immutability", "integer", "python" ]
stackoverflow_0004088731_immutability_integer_python.txt
Q: Can python mechanize handle HTTP auth? Mechanize (Python) is failing with 401 for me to open http digest URLs. I googled and tried debugging but no success. My code looks like this. import mechanize project = "test" baseurl = "http://trac.somewhere.net" loginurl = "%s/%s/login" % (baseurl, project) b = mechanize.Browser() b.add_password(baseurl, "user", "secret", "some Realm") b.open(loginurl) A: Mechanize claims that the parameters should be uri, username and password as parameters, but you have four parameters. Four parameters are correct for urllib2.add_password, but then the first parameter should be the realm, not the uri. http://wwwsearch.sourceforge.net/mechanize/ I'd try to change that first. Does trac require digest? if not a next step could be to try using basic auth, as a test to see if that works, since you can add that with just addHeader: import base64 from mechanize import Browser browser = Browser() browser.addheaders.append(('Authorization', 'Basic %s' % base64.encodestring('%s:%s' % (user, pwd)))) A: For http authentication with mechanize you need to provide the complete url to the add_password method and not just the host base address. import mechanize project = "test" baseurl = "http://trac.somewhere.net" loginurl = "%s/%s/login" % (baseurl, project) b = mechanize.Browser() b.add_password(loginurl, "user", "secret", "some Realm") b.open(loginurl) A: #!/usr/bin/env python # -*- coding: utf-8 -*- import mechanize a=mechanize.Browser() a.open("http://www.facebook.com/login.php") a.select_form(nr=0) #form number. a["email"]="mailaddress" a["pass"]="password" a.submit() print a
Can python mechanize handle HTTP auth?
Mechanize (Python) is failing with 401 for me to open http digest URLs. I googled and tried debugging but no success. My code looks like this. import mechanize project = "test" baseurl = "http://trac.somewhere.net" loginurl = "%s/%s/login" % (baseurl, project) b = mechanize.Browser() b.add_password(baseurl, "user", "secret", "some Realm") b.open(loginurl)
[ "Mechanize claims that the parameters should be uri, username and password as parameters, but you have four parameters. Four parameters are correct for urllib2.add_password, but then the first parameter should be the realm, not the uri.\nhttp://wwwsearch.sourceforge.net/mechanize/\nI'd try to change that first.\nDo...
[ 6, 4, 0 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0001097380_mechanize_python.txt
Q: comparing two dictionary lists in python I have two dictionaries {key1:[list_of_objects ], {key2:[list_of_objects ]} e.g dict1 = {key1:['a', 'b', 'c', 'd' ], key2: ['f', 'g', 'h' ] } dict2 = {key1:['a', 'b', 'c', 'd'], key2: ['f', 'g', 'h', 'i' ] } For eack key in both dict1 and dict2, i want to compare the items in the lists. i.e compare each value in dict1[key1] with the correcponding value in dict2[key1] and so on. The items in the lists are objects, so will runing something like if dict1[key1][0].some_function() = = dict2[key1][0].some_function() then condition what is the fastest way to run this comparision? A: for key in dict1.keys(): for a,b in zip(dict1[key],dict2[key]): if a.some_function() == b.some_function(): #do something If your lists are very long you could swap zip for izip from collections. A: sets make it easy: for key in dict1.keys(): diff = set(dict1[key]).symmetric_difference(dict2[key]) if diff: print "%s: %s" % (key, diff) # or do whatever
comparing two dictionary lists in python
I have two dictionaries {key1:[list_of_objects ], {key2:[list_of_objects ]} e.g dict1 = {key1:['a', 'b', 'c', 'd' ], key2: ['f', 'g', 'h' ] } dict2 = {key1:['a', 'b', 'c', 'd'], key2: ['f', 'g', 'h', 'i' ] } For eack key in both dict1 and dict2, i want to compare the items in the lists. i.e compare each value in dict1[key1] with the correcponding value in dict2[key1] and so on. The items in the lists are objects, so will runing something like if dict1[key1][0].some_function() = = dict2[key1][0].some_function() then condition what is the fastest way to run this comparision?
[ "for key in dict1.keys():\n for a,b in zip(dict1[key],dict2[key]):\n if a.some_function() == b.some_function():\n #do something\n\nIf your lists are very long you could swap zip for izip from collections.\n", "sets make it easy:\nfor key in dict1.keys():\n diff = set(dict1[key]).symmetric_d...
[ 0, 0 ]
[]
[]
[ "compare", "dictionary", "python" ]
stackoverflow_0004088398_compare_dictionary_python.txt
Q: Is there a more pythonic way to do this dictionary iteration? I have a dictionary in the view layer, that I am passing to my templates. The dictionary values are (mostly) lists, although a few scalars also reside in the dictionary. The lists if present are initialized to None. The None values are being printed as 'None' in the template, so I wrote this little function to clean out the Nones before passing the dictionary of lists to the template. Since I am new to Python, I am wondering if there could be a more pythonic way of doing this? # Clean the table up and turn Nones into '' for k, v in table.items(): #debug_str = 'key: %s, value: %s' % (k,v) #logging.debug(debug_str) try: for i, val in enumerate(v): if val == None: v[i] = '' except TypeError: continue; A: Have you looked at defaultdict within collections? You'd have a dictionary formed via defaultdict(list) which initializes an empty list when a key is queried and that key does not exist. A: filtered_dict = dict((k, v) for k, v in table.items() if v is not None) or in Python 2.7+, use the dictionary comprehension syntax: filtered_dict = {k: v for k, v in table.items() if v is not None}
Is there a more pythonic way to do this dictionary iteration?
I have a dictionary in the view layer, that I am passing to my templates. The dictionary values are (mostly) lists, although a few scalars also reside in the dictionary. The lists if present are initialized to None. The None values are being printed as 'None' in the template, so I wrote this little function to clean out the Nones before passing the dictionary of lists to the template. Since I am new to Python, I am wondering if there could be a more pythonic way of doing this? # Clean the table up and turn Nones into '' for k, v in table.items(): #debug_str = 'key: %s, value: %s' % (k,v) #logging.debug(debug_str) try: for i, val in enumerate(v): if val == None: v[i] = '' except TypeError: continue;
[ "Have you looked at defaultdict within collections? You'd have a dictionary formed via\ndefaultdict(list)\n\nwhich initializes an empty list when a key is queried and that key does not exist.\n", "filtered_dict = dict((k, v) for k, v in table.items() if v is not None)\n\nor in Python 2.7+, use the dictionary com...
[ 3, 0 ]
[]
[]
[ "django_templates", "django_views", "python" ]
stackoverflow_0004088471_django_templates_django_views_python.txt
Q: How to export python functions and reuse them in another app I was wondering if there is any way to export python functions to dll. There is py2exe and I can successfully create exe file. My program should be used by another program written in delphi (there is possibility of importing dll's in delphi). So I was wondering what would be the best way to connect those 2 applications. Now I can only create exe, execute process in delphi and communicate in some way. But I don't think that's nice way. Maybe somebody have any experience in this subject? A: There are some pretty big challenges to making languages work well together. As a simple alternative to trying to hook python code directly into delphi, you could consider using something like an xmlrpc server to provide python functionality remotely. http://docs.python.org/library/xmlrpclib.html Of course, any protocol could be used; xmlrpc just has some useful server utilities in python and presumably has a client library in delphi. A: You can re-use python functions via modules. Integrating with other language is a different task all together. py2exe packs all dependent modules and additional dlls required by an application so that it can be easily distributed without creating any installation dependencies for the user. Cross - language integration requires some work. To integrate with "C", there are various ways like cython etc. If there is similar facility available with delphi, you might be able to use it. Check out some of these references, it will make it more clear to you on what direction to take. http://wiki.python.org/moin/IntegratingPythonWithOtherLanguages http://www.atug.com/andypatterns/pythonDelphiTalk.htm http://www.google.com/search?aq=f&sourceid=chrome&ie=UTF-8&q=python+delphi (Google search)
How to export python functions and reuse them in another app
I was wondering if there is any way to export python functions to dll. There is py2exe and I can successfully create exe file. My program should be used by another program written in delphi (there is possibility of importing dll's in delphi). So I was wondering what would be the best way to connect those 2 applications. Now I can only create exe, execute process in delphi and communicate in some way. But I don't think that's nice way. Maybe somebody have any experience in this subject?
[ "There are some pretty big challenges to making languages work well together. As a simple alternative to trying to hook python code directly into delphi, you could consider using something like an xmlrpc server to provide python functionality remotely. \nhttp://docs.python.org/library/xmlrpclib.html\nOf course, a...
[ 1, 0 ]
[]
[]
[ "dll", "export", "python" ]
stackoverflow_0004089569_dll_export_python.txt
Q: tkinter: grid method strange behavior I want this code to do this: Create 4 frames with this layout (dashes mean the frame spans that column): -X- XXX Within each of these frames (X's) there should be two rows like this: cowN,1 cowN,2 It seems like the grid() method is global ONLY and is never specific to a single frame... #!/usr/apps/Python/bin/python from Tkinter import * master = Tk() frame1 = Frame(master).grid(row=0,columnspan=3) frame2 = Frame(master).grid(row=1,column=0) frame3 = Frame(master).grid(row=1,column=1) frame4 = Frame(master).grid(row=1,column=2) #->Frame1 contents Label(frame1, text='cow1,1').grid(row=0) Label(frame1, text='cow1,2').grid(row=1) #->Frame2 contents Label(frame2, text='cow2,1').grid(row=0) Label(frame2, text='cow2,2').grid(row=1) #->Frame3 contents Label(frame3, text='cow3,1').grid(row=0) Label(frame3, text='cow3,2').grid(row=1) #->Frame4 contents Label(frame4, text='cow4,1').grid(row=0) Label(frame4, text='cow4,2').grid(row=1) master.mainloop() A: The problem with your code is that your are not keeping a reference to the Frame objects on your frameN variables: you create the objects, and call their grid method: you store the return of the grid method on the variables, which is None. So, your labels are being created with None as their master. Just change your lines to read: frame1 = Frame(master); frame1.grid(row=0, columnspan=3)
tkinter: grid method strange behavior
I want this code to do this: Create 4 frames with this layout (dashes mean the frame spans that column): -X- XXX Within each of these frames (X's) there should be two rows like this: cowN,1 cowN,2 It seems like the grid() method is global ONLY and is never specific to a single frame... #!/usr/apps/Python/bin/python from Tkinter import * master = Tk() frame1 = Frame(master).grid(row=0,columnspan=3) frame2 = Frame(master).grid(row=1,column=0) frame3 = Frame(master).grid(row=1,column=1) frame4 = Frame(master).grid(row=1,column=2) #->Frame1 contents Label(frame1, text='cow1,1').grid(row=0) Label(frame1, text='cow1,2').grid(row=1) #->Frame2 contents Label(frame2, text='cow2,1').grid(row=0) Label(frame2, text='cow2,2').grid(row=1) #->Frame3 contents Label(frame3, text='cow3,1').grid(row=0) Label(frame3, text='cow3,2').grid(row=1) #->Frame4 contents Label(frame4, text='cow4,1').grid(row=0) Label(frame4, text='cow4,2').grid(row=1) master.mainloop()
[ "The problem with your code is that your are not keeping a reference to the Frame objects on your frameN variables: you create the objects, and call their grid method: you store the return of the grid method on the variables, which is None.\nSo, your labels are being created with None as their master. \nJust chang...
[ 2 ]
[]
[]
[ "frames", "grid", "python", "tkinter" ]
stackoverflow_0004088390_frames_grid_python_tkinter.txt
Q: TinyMce File browser for pylons? Do you now some AJAX based filebrowser to TinyMCE which can I use in my pylons app? A: It seems like the closest thing to what you want is TinyMCE Image Manager, which claims to have file management capabilities. However, it's not very clear what you're asking, so you may want to clarify your question.
TinyMce File browser for pylons?
Do you now some AJAX based filebrowser to TinyMCE which can I use in my pylons app?
[ "It seems like the closest thing to what you want is TinyMCE Image Manager, which claims to have file management capabilities. However, it's not very clear what you're asking, so you may want to clarify your question. \n" ]
[ 0 ]
[]
[]
[ "pylons", "python", "tinymce" ]
stackoverflow_0002838227_pylons_python_tinymce.txt
Q: What is the way data is stored in *.npy? I'm saving NumPy arrays using numpy.save function. I want other developers to have capability to read data from those file using C language. So I need to know,how numpy organizes binary data in file.OK, it's obvious when I'm saving array of 'i4' but what about array of arrays that contains some structures?Can't find any info in documentation UPD : lets say tha data is something like : dt = np.dtype([('outer','(3,)<i4'),('outer2',[('inner','(10,)<i4'),('inner2','f8')])]) UPD2 : What about saving "dynamic" data (dtype - object) import numpy as np a = [0,0,0] b = [0,0] c = [a,b] dtype = np.dtype([('Name', '|S2'), ('objValue', object)]) data = np.zeros(3, dtype) data[0]['objValue'] = a data[1]['objValue'] = b data[2]['objValue'] = c data[0]['Name'] = 'a' data[1]['Name'] = 'b' data[2]['Name'] = 'c' np.save(r'D:\in.npy', data) Is it real to read that thing from C? A: The npy file format is documented in numpy's NEP 1 — A Simple File Format for NumPy Arrays. For instance, the code >>> dt=numpy.dtype([('outer','(3,)<i4'), ... ('outer2',[('inner','(10,)<i4'),('inner2','f8')])]) >>> a=numpy.array([((1,2,3),((10,11,12,13,14,15,16,17,18,19),3.14)), ... ((4,5,6),((-1,-2,-3,-4,-5,-6,-7,-8,-9,-20),6.28))],dt) >>> numpy.save('1.npy', a) results in the file: 93 4E 55 4D 50 59 magic ("\x93NUMPY") 01 major version (1) 00 minor version (0) 96 00 HEADER_LEN (0x0096 = 150) 7B 27 64 65 73 63 72 27 3A 20 5B 28 27 6F 75 74 65 72 27 2C 20 27 3C 69 34 27 2C 20 28 33 2C 29 29 2C 20 28 27 6F 75 74 65 72 32 27 2C 20 5B 28 27 69 6E 6E 65 72 27 2C 20 27 3C 69 34 27 2C 20 28 31 30 2C 29 29 2C 20 28 27 69 6E 6E 65 72 32 Header, describing the data structure 27 2C 20 27 3C 66 38 27 "{'descr': [('outer', '<i4', (3,)), 29 5D 29 5D 2C 20 27 66 ('outer2', [ 6F 72 74 72 61 6E 5F 6F ('inner', '<i4', (10,)), 72 64 65 72 27 3A 20 46 ('inner2', '<f8')] 61 6C 73 65 2C 20 27 73 )], 68 61 70 65 27 3A 20 28 'fortran_order': False, 32 2C 29 2C 20 7D 20 20 'shape': (2,), }" 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 01 00 00 00 02 00 00 00 03 00 00 00 (1,2,3) 0A 00 00 00 0B 00 00 00 0C 00 00 00 0D 00 00 00 0E 00 00 00 0F 00 00 00 10 00 00 00 11 00 00 00 12 00 00 00 13 00 00 00 (10,11,12,13,14,15,16,17,18,19) 1F 85 EB 51 B8 1E 09 40 3.14 04 00 00 00 05 00 00 00 06 00 00 00 (4,5,6) FF FF FF FF FE FF FF FF FD FF FF FF FC FF FF FF FB FF FF FF FA FF FF FF F9 FF FF FF F8 FF FF FF F7 FF FF FF EC FF FF FF (-1,-2,-3,-4,-5,-6,-7,-8,-9,-20) 1F 85 EB 51 B8 1E 19 40 6.28 A: The format is described in numpy/lib/format.py, where you can also see the Python source code used to load npy files. np.load is defined here.
What is the way data is stored in *.npy?
I'm saving NumPy arrays using numpy.save function. I want other developers to have capability to read data from those file using C language. So I need to know,how numpy organizes binary data in file.OK, it's obvious when I'm saving array of 'i4' but what about array of arrays that contains some structures?Can't find any info in documentation UPD : lets say tha data is something like : dt = np.dtype([('outer','(3,)<i4'),('outer2',[('inner','(10,)<i4'),('inner2','f8')])]) UPD2 : What about saving "dynamic" data (dtype - object) import numpy as np a = [0,0,0] b = [0,0] c = [a,b] dtype = np.dtype([('Name', '|S2'), ('objValue', object)]) data = np.zeros(3, dtype) data[0]['objValue'] = a data[1]['objValue'] = b data[2]['objValue'] = c data[0]['Name'] = 'a' data[1]['Name'] = 'b' data[2]['Name'] = 'c' np.save(r'D:\in.npy', data) Is it real to read that thing from C?
[ "The npy file format is documented in numpy's NEP 1 — A Simple File Format for NumPy Arrays.\nFor instance, the code \n>>> dt=numpy.dtype([('outer','(3,)<i4'),\n... ('outer2',[('inner','(10,)<i4'),('inner2','f8')])])\n>>> a=numpy.array([((1,2,3),((10,11,12,13,14,15,16,17,18,19),3.14)),\n... ...
[ 48, 6 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0004090080_numpy_python.txt
Q: Infrastructure for a "news-feed" I'd like to offer a news-feed like feature for users of our website. When the user logs in, he is shown a list of the latest updates across various areas of the site. I'm afraid that this is going to be difficult to scale. What are some networking / database topologies that can support a scalable infrastructure without having lots of copies of the same data? (I'd like to make it so if a piece of data is updated, each user's feed is also updated live). Thanks for the assistance and advice. A: Don't prematurely optimize. This might be more of a question for the Server Fault crowd. Performance at scale often requires having lots of copies of the same data - you tagged the question "facebook," and that's part of how Facebook does it. Twitter, too. You are asking for a system that's fast ("updated live"), cheap ("without having lots of copies of the same data") and good (does the previous two correctly). Pick two.
Infrastructure for a "news-feed"
I'd like to offer a news-feed like feature for users of our website. When the user logs in, he is shown a list of the latest updates across various areas of the site. I'm afraid that this is going to be difficult to scale. What are some networking / database topologies that can support a scalable infrastructure without having lots of copies of the same data? (I'd like to make it so if a piece of data is updated, each user's feed is also updated live). Thanks for the assistance and advice.
[ "\nDon't prematurely optimize. \nThis might be more of a question for the Server Fault crowd. \nPerformance at scale often requires having lots of copies of the same data - you tagged the question \"facebook,\" and that's part of how Facebook does it. Twitter, too. You are asking for a system that's fast (\"upd...
[ 0 ]
[]
[]
[ "facebook", "feed", "infrastructure", "pylons", "python" ]
stackoverflow_0002703549_facebook_feed_infrastructure_pylons_python.txt
Q: execute sqlserver store procedure using python I have this code from win32com.client import Dispatch connection_string = "Provider=SQLNCLI;server=%s;initial catalog=%s;user id=%s;password=%s"%(server,db_name,user,pwd) dbConn = Dispatch("ADODB.Connection") dbConn.Open( connection_string ) ( rs, result ) = s.dbConn.Execute( query_string ) while not rs.EOF: for field in rs.Fields : dic[str( field.name )] = str( field.value ) print dic rs.MoveNext() it works fine on 'select' , 'insert' and 'update' operations. the code execute the store procedures but it close the record set before the while statment. here is the error: ... pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'ADODB.Recordset', u'Operation is not allowed when the object is closed.' ... A: Not sure if this will help, but here's how to do it with pyODBC: cn = pyodbc.connect("DSN=myDBName") cn.autocommit = True cr = cn.cursor() cr.execute("set nocount on") cr.execute("exec myStoredProc") ... cr.close() cn.close()
execute sqlserver store procedure using python
I have this code from win32com.client import Dispatch connection_string = "Provider=SQLNCLI;server=%s;initial catalog=%s;user id=%s;password=%s"%(server,db_name,user,pwd) dbConn = Dispatch("ADODB.Connection") dbConn.Open( connection_string ) ( rs, result ) = s.dbConn.Execute( query_string ) while not rs.EOF: for field in rs.Fields : dic[str( field.name )] = str( field.value ) print dic rs.MoveNext() it works fine on 'select' , 'insert' and 'update' operations. the code execute the store procedures but it close the record set before the while statment. here is the error: ... pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'ADODB.Recordset', u'Operation is not allowed when the object is closed.' ...
[ "Not sure if this will help, but here's how to do it with pyODBC:\n cn = pyodbc.connect(\"DSN=myDBName\")\n cn.autocommit = True\n cr = cn.cursor()\n cr.execute(\"set nocount on\")\n cr.execute(\"exec myStoredProc\")\n ...\n cr.close()\n cn.close()\n\n" ]
[ 0 ]
[]
[]
[ "python", "sql_server_2005" ]
stackoverflow_0004090165_python_sql_server_2005.txt
Q: Integrating SQLAlchemy's ORM with existing classes in pylons I have a class in my existing python project, User, that I would like to map to tables. But I'm not sure what the best way to do this is? Does this mean I can remove: class User: pass from my model/__ init __.py? Or should I leave that in there, and have something like: from project.model.user import User class User: pass In essence, having (2) different classes with the same name? Thanks. A: You should not define a class that maps onto a table in the model's __init__.py file, nor should you have two different clases with the same name. Classes that map onto tables belong in your project's model directory, grouped into modules. Then import the classes in __init__.py to make them available.
Integrating SQLAlchemy's ORM with existing classes in pylons
I have a class in my existing python project, User, that I would like to map to tables. But I'm not sure what the best way to do this is? Does this mean I can remove: class User: pass from my model/__ init __.py? Or should I leave that in there, and have something like: from project.model.user import User class User: pass In essence, having (2) different classes with the same name? Thanks.
[ "You should not define a class that maps onto a table in the model's __init__.py file, nor should you have two different clases with the same name. \nClasses that map onto tables belong in your project's model directory, grouped into modules. Then import the classes in __init__.py to make them available. \n" ]
[ 0 ]
[]
[]
[ "orm", "pylons", "python", "sqlalchemy" ]
stackoverflow_0002365459_orm_pylons_python_sqlalchemy.txt
Q: How to catch FTP errors? e.g., socket.error: [Errno 10060] I'm using the ftplib module to upload files: files = [ a.txt , b.txt , c.txt ] s = ftplib.FTP(ftp_server , ftp_user , ftp_pw) # Connect to FTP for i in range(len(files)): f = open(files[i], 'rb') stor = 'stor ' + files[i] s.storbinary(stor, f) f.close() # close file s.quit() # close ftp How do I catch the following error? socket.error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond And what other errors are common when using the FTP module that I should also catch? Thanks for any help or pointers. A: import socket try: s = ftplib.FTP(ftp_server , ftp_user , ftp_pw) # Connect to FTP except socket.error, e: print "do something with %s" % e this will catch all socket errors (whatever their "errno" -- ones 10000 and up are quite Windows specific, they're very different on Unix). See the docs for other exceptions that may be raised; they're all in the tuple ftplib.all_errors (as is socket.error and the last biggie, IOError) so you can handily catch them all with except ftplib.all_errors, e:. A: I had a similar error. What I had to do instead is catch the socket.error at the line s.storbinary(stor, f) as well as the initial connection.
How to catch FTP errors? e.g., socket.error: [Errno 10060]
I'm using the ftplib module to upload files: files = [ a.txt , b.txt , c.txt ] s = ftplib.FTP(ftp_server , ftp_user , ftp_pw) # Connect to FTP for i in range(len(files)): f = open(files[i], 'rb') stor = 'stor ' + files[i] s.storbinary(stor, f) f.close() # close file s.quit() # close ftp How do I catch the following error? socket.error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond And what other errors are common when using the FTP module that I should also catch? Thanks for any help or pointers.
[ "import socket\n\ntry:\n s = ftplib.FTP(ftp_server , ftp_user , ftp_pw) # Connect to FTP\nexcept socket.error, e:\n print \"do something with %s\" % e\n\nthis will catch all socket errors (whatever their \"errno\" -- ones 10000 and up are quite Windows specific, they're very different on Unix).\nSee the docs ...
[ 3, 2 ]
[]
[]
[ "ftp", "ftplib", "python" ]
stackoverflow_0002823937_ftp_ftplib_python.txt
Q: Why can I not import this class? I have three classes having to import each others methods. The statements would be as follows in the corresponding files with classes: File A with class a from B import b File B with class b from C import c File C with class c from A import a Why does this not work in python? I rather get the error message: ImportError: cannot import name a A: What you have is a classic circular import problem in Python. Have you taken a look at previous questions on SO, like this one? A: Python can't find it. Is it in the proper directory, does it actually exist?
Why can I not import this class?
I have three classes having to import each others methods. The statements would be as follows in the corresponding files with classes: File A with class a from B import b File B with class b from C import c File C with class c from A import a Why does this not work in python? I rather get the error message: ImportError: cannot import name a
[ "What you have is a classic circular import problem in Python. Have you taken a look at previous questions on SO, like this one?\n", "Python can't find it. Is it in the proper directory, does it actually exist?\n" ]
[ 2, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0004090588_class_python.txt
Q: Overriding default tab behaviour in Python Tkinter I am writing an application in Python using Tkinter to manage my GUI. There is a text entry box on which I am trying to implement an autocompletion function which will bind to the Tab key. I have bound the tab key to my entry box, but when I press tab, the program attempts to cycle between GUI elements. How do I override this default behavior so that the GUI will only carry out my specified command on the key press? A: Return 'break' at the end of your event handler. It interrupts event propagation. def my_tab_handler(event): ... # handle tab event return 'break' # interrupts event propagation to default handlers
Overriding default tab behaviour in Python Tkinter
I am writing an application in Python using Tkinter to manage my GUI. There is a text entry box on which I am trying to implement an autocompletion function which will bind to the Tab key. I have bound the tab key to my entry box, but when I press tab, the program attempts to cycle between GUI elements. How do I override this default behavior so that the GUI will only carry out my specified command on the key press?
[ "Return 'break' at the end of your event handler. It interrupts event propagation.\ndef my_tab_handler(event):\n ... # handle tab event\n return 'break' # interrupts event propagation to default handlers\n\n" ]
[ 11 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0004090683_python_tkinter_user_interface.txt
Q: Weird PyPI authentication behavior I'm trying to upload my package to PyPI. It asks me to identify, I do, it gives an OK response (which doesn't happen unless the identification is right), but then it claims I didn't identify! Why? [...] removing 'build\bdist.win32\egg' (and everything under it) running register We need to know who you are, so please choose either: 1. use your existing login, 2. register as a new user, 3. have the server generate a new password for you (and email it to you), or 4. quit Your selection [default 1]: 1 Username: coolRR Password: Server response (200): OK running upload Submitting dist\garlicsim-0.1.zip to http://pypi.python.org/pypi Upload failed (401): You must be identified to edit package information removing 'build' (and everything under it) error: garlicsim-0.1: No such file or directory A: I've never encountered that myself, but some things to check: Make sure you can login to PyPI using your browser with the username and password. Check that ~/.pypirc has the correct contents. If it does not exist, try creating it. Check your setup.cfg file to make sure all the PyPI settings (if any) are correct. Try building your package as separate check before you run the commands to upload/register, then try python setup.py upload. A: You were using an old version of Python (and Distutils as a result). This bug was fixed in r68415 2009-01-09 by Tarek Ziade. Try to upload with any Python 2.x version released afterwards.
Weird PyPI authentication behavior
I'm trying to upload my package to PyPI. It asks me to identify, I do, it gives an OK response (which doesn't happen unless the identification is right), but then it claims I didn't identify! Why? [...] removing 'build\bdist.win32\egg' (and everything under it) running register We need to know who you are, so please choose either: 1. use your existing login, 2. register as a new user, 3. have the server generate a new password for you (and email it to you), or 4. quit Your selection [default 1]: 1 Username: coolRR Password: Server response (200): OK running upload Submitting dist\garlicsim-0.1.zip to http://pypi.python.org/pypi Upload failed (401): You must be identified to edit package information removing 'build' (and everything under it) error: garlicsim-0.1: No such file or directory
[ "I've never encountered that myself, but some things to check:\n\nMake sure you can login to PyPI using your browser with the username and password.\nCheck that ~/.pypirc has the correct contents. If it does not exist, try creating it.\nCheck your setup.cfg file to make sure all the PyPI settings (if any) are corre...
[ 1, 1 ]
[]
[]
[ "distribution", "distutils", "pypi", "python" ]
stackoverflow_0001750186_distribution_distutils_pypi_python.txt
Q: How can you make Pylons email you the full post parameters with an error report? Pylons can email you errors when something goes wrong in production mode, but it truncates the post parameters so it's hard to see what the error is. Is there a way to make it email you the whole thing? A: You can actually make Pylons email you errors in development, testing, and production modes, just so long as you put the correct email information in the .ini file. The facilities for emailing you error messages come from the WebError middleware, particularly the weberror.reporter module. The only truncating that occurs there is in the subject line of the email. It is possible that the error is being truncated before it gets to WebError. You may want to, on a test deployment, tweak the WebError middleware of your Pylons project to double-check what it's accepting in and sending out. Can you give an example of such a truncated error message email? Do you mean that it truncates the HTTP POST data of a request that caused an error?
How can you make Pylons email you the full post parameters with an error report?
Pylons can email you errors when something goes wrong in production mode, but it truncates the post parameters so it's hard to see what the error is. Is there a way to make it email you the whole thing?
[ "You can actually make Pylons email you errors in development, testing, and production modes, just so long as you put the correct email information in the .ini file. \nThe facilities for emailing you error messages come from the WebError middleware, particularly the weberror.reporter module. The only truncating t...
[ 0 ]
[]
[]
[ "post", "pylons", "python" ]
stackoverflow_0003283111_post_pylons_python.txt
Q: where to store a log file name in python? I have a Python program that consists of several modules. The "main" module creates a file variable log_file for logging the output; all the other modules would need to write to that file as well. However, I don't want to import the "main" module into other modules, since it would be a really weird dependency (not to mention it might not even work due to circular dependency). Where, then, should I store the log_file variable? EDIT: Following @pyfunc answer - would this be ok: --- config.py --- # does not mention log_file # unless it's required for syntax reasons; in which case log_file = None # ... --- main.py --- from datetime import datetime import config.py log_filename = str(datetime.now()) + '.txt' config.log_file = open(log_filename, 'w') # ... --- another_module.py --- import config.py # ... config.log_file.write(some_stuff) A: Put the "global" variable in a "settings" module. settings.py log_file = "/path/to/file" main.py import settings import logging logging.basicConfig(filename=settings.log_file,level=logging.DEBUG) logging.debug("This should go to the log file") other_module.py import logging logging.debug("This is a message from another place.") While the logging module may solve your immediate problem and many others, the settings module pattern is useful for a lot of other things besides log file names. It is used by Django to configure just about everything. A: One way is to take all that code into another module so that you could import it in main file and other modules as well. Hope you have checked on : http://docs.python.org/library/logging.html
where to store a log file name in python?
I have a Python program that consists of several modules. The "main" module creates a file variable log_file for logging the output; all the other modules would need to write to that file as well. However, I don't want to import the "main" module into other modules, since it would be a really weird dependency (not to mention it might not even work due to circular dependency). Where, then, should I store the log_file variable? EDIT: Following @pyfunc answer - would this be ok: --- config.py --- # does not mention log_file # unless it's required for syntax reasons; in which case log_file = None # ... --- main.py --- from datetime import datetime import config.py log_filename = str(datetime.now()) + '.txt' config.log_file = open(log_filename, 'w') # ... --- another_module.py --- import config.py # ... config.log_file.write(some_stuff)
[ "Put the \"global\" variable in a \"settings\" module.\nsettings.py\nlog_file = \"/path/to/file\"\n\nmain.py\nimport settings\nimport logging\nlogging.basicConfig(filename=settings.log_file,level=logging.DEBUG)\n\nlogging.debug(\"This should go to the log file\")\n\nother_module.py\nimport logging\nlogging.debug(\"...
[ 2, 1 ]
[]
[]
[ "module", "python", "python_3.x" ]
stackoverflow_0004090652_module_python_python_3.x.txt
Q: Where is the best place to associate a 'form display text' with SQLAlchemy mapped property? In django orm I can use the 'verbose_name' kwarg to set a label that will be displayed in model forms. Now I'm dynamically generating WTForms for each model in a SQLAlchemy mapped backend, but I'm not sure where to associate a display text to use in the auto generated fields for each form. For example, in django I could do this: class User(models.Model): name = CharField(max_length=50, verbose_name='Enter your username') password = CharField(max_length=50, verbose_name='Enter your password') In SQLAlchemy: class User(Base): name = Column(String) password = Column(String) In this simple case, how could I associate the texts 'Enter your username' and 'Enter your password' with the 'name' and 'password' attributes respectively? A: You could duplicate that functionality by using the 'info' keyword argument to Column. That would look like this: Class User(Base): name = Column(String, info={verbose_name: 'Enter your username',}) password = Column(String, info={verbose_name: 'Enter your password',}) Then you could pull info['verbose_name'] out when you dynamically generate a form.
Where is the best place to associate a 'form display text' with SQLAlchemy mapped property?
In django orm I can use the 'verbose_name' kwarg to set a label that will be displayed in model forms. Now I'm dynamically generating WTForms for each model in a SQLAlchemy mapped backend, but I'm not sure where to associate a display text to use in the auto generated fields for each form. For example, in django I could do this: class User(models.Model): name = CharField(max_length=50, verbose_name='Enter your username') password = CharField(max_length=50, verbose_name='Enter your password') In SQLAlchemy: class User(Base): name = Column(String) password = Column(String) In this simple case, how could I associate the texts 'Enter your username' and 'Enter your password' with the 'name' and 'password' attributes respectively?
[ "You could duplicate that functionality by using the 'info' keyword argument to Column. That would look like this:\nClass User(Base):\n name = Column(String, info={verbose_name: 'Enter your username',})\n password = Column(String, info={verbose_name: 'Enter your password',})\n\nThen you could pull info['verb...
[ 3 ]
[]
[]
[ "django", "pylons", "python", "sqlalchemy" ]
stackoverflow_0003949131_django_pylons_python_sqlalchemy.txt
Q: Is there a way to resend UDP packets using Twisted? Problem: Simple UDP proxy - receive UDP packets from multiple sources on port X and forward (resend) them to IP Y on port Z. Description: I am able to create a simple UDP server using twisted, and receive incoming packets easily. However, I cant find a way to resend these packets (their data) further, using Twisted. Is there a specific, kosher and Twisted-like way of doing that in twisted, or should I use simple python sock.sendto way in the method that handles received data in Twisted? A: You do something like this: class MyProtocol(DatagramProtocol): def datagramReceived(self, datagram, addr): # use self.transport.write to send stuff some_where = ('192.168.0.1',5001) self.transport.write( datagram, some_where )
Is there a way to resend UDP packets using Twisted?
Problem: Simple UDP proxy - receive UDP packets from multiple sources on port X and forward (resend) them to IP Y on port Z. Description: I am able to create a simple UDP server using twisted, and receive incoming packets easily. However, I cant find a way to resend these packets (their data) further, using Twisted. Is there a specific, kosher and Twisted-like way of doing that in twisted, or should I use simple python sock.sendto way in the method that handles received data in Twisted?
[ "You do something like this:\nclass MyProtocol(DatagramProtocol):\n def datagramReceived(self, datagram, addr):\n # use self.transport.write to send stuff\n some_where = ('192.168.0.1',5001)\n self.transport.write( datagram, some_where )\n\n" ]
[ 2 ]
[]
[]
[ "forwarding", "proxy", "python", "twisted", "udp" ]
stackoverflow_0004090572_forwarding_proxy_python_twisted_udp.txt
Q: How can I pass variables between two classes/windows in PyGtk? I am starting out with PyGtk and am having trouble understanding the interaction of windows. My very simple question is the following. Suppose I have a class that simply creates a window with a text-entry field. When clicking the "ok" button in that window, I want to pass the text in the entry field to another window, created by another class, with a gtk menu and create a new entry with the content of the text field. How do I implement this? A: Let's call A the Menu, and B the window with the text-entry field. If I understood correctly A calls B and when Ok button is pressed in B, A needs to update its menu. In this scenario you could create a callback function in A, meant to be called when B's ok button is pressed. When you create B you can pass this callback, here's an example: class B(gtk.Window): def __init__(self, callback): gtk.Window.__init__(self) self.callback = callback # Create components: # self.entry, self.ok_button ... self.ok_button.connect("clicked", self.clicked) def clicked(self, button): self.callback(self.entry.get_text()) class A(gtk.Window): def create_popup(self): popup = B(self.popup_callback) popup.show() def popup_callback(self, text): # Update menu with new text # ...
How can I pass variables between two classes/windows in PyGtk?
I am starting out with PyGtk and am having trouble understanding the interaction of windows. My very simple question is the following. Suppose I have a class that simply creates a window with a text-entry field. When clicking the "ok" button in that window, I want to pass the text in the entry field to another window, created by another class, with a gtk menu and create a new entry with the content of the text field. How do I implement this?
[ "Let's call A the Menu, and B the window with the text-entry field.\nIf I understood correctly A calls B and when Ok button is pressed in B, A needs to update its menu.\nIn this scenario you could create a callback function in A, meant to be called when B's ok button is pressed. When you create B you can pass this ...
[ 2 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0004090804_pygtk_python.txt
Q: How can I pass a user input string to a function as arguments in a python script? I want to pass a user input string to a function, using the space separated words as it's arguments. However, what makes this a problem is that I don't know how many arguments the user will give. A: def your_function(*args): # 'args' is now a list that contains all of the arguments ...do stuff... input_args = user_string.split() your_function(*input_args) # Convert a list into the arguments to a function http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists Granted, if you're the one designing the function, you could just design it to accept a list as a single argument, instead of requiring separate arguments. A: The easy way, using str.split and argument unpacking: f(*the_input.split(' ')) However, this won't perform any conversions (all arguments will still be strings) and split has a few caveats (e.g. '1,,2'.split(',') == ['1', '', '2']; refer to docs). A: A couple of options. You can make the function take a list of arguments: def fn(arg_list): #process fn(["Here", "are", "some", "args"]) #note that this is being passed as a single list parameter Or you can collect the arguments in an arbitrary argument list: def fn(*arg_tuple): #process fn("Here", "are", "some", "args") #this is being passed as four separate string parameters In both cases, arg_list and arg_tuple will be nearly identical, the only difference being that one is a list and the other a tuple: ["Here, "are", "some", "args"] or ("Here", "are", "some", "args").
How can I pass a user input string to a function as arguments in a python script?
I want to pass a user input string to a function, using the space separated words as it's arguments. However, what makes this a problem is that I don't know how many arguments the user will give.
[ "def your_function(*args):\n # 'args' is now a list that contains all of the arguments\n ...do stuff...\n\ninput_args = user_string.split()\nyour_function(*input_args) # Convert a list into the arguments to a function\n\nhttp://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists\nGranted, if yo...
[ 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004091054_python.txt
Q: Python/Tkinter: Turn on/off screen updates like wxPython Freeze/Thaw? Does Tkinter provide a way to temporarily turn off screen updates (when performing a large amount of screen activity) and then turn on screen updates when the UI updates are complete? Many GUI frameworks have this feature. wxPython provides Freeze and Thaw methods for this functionality. The Windows Win32api supports this as well via LockWindowUpdate( hWnd | 0 ). Googling on "tkinter freeze thaw" and "tkinter lockwindowupdate" came up emtpy. A: No, Tkinter has no such thing. However, the screen is only updated via the event loop, so if all of your "large amount of screen activity" is happening in a single method, none of the activity will show up until your method finishes and the event loop is re-entered (or you explicitly call .update_idletasks())
Python/Tkinter: Turn on/off screen updates like wxPython Freeze/Thaw?
Does Tkinter provide a way to temporarily turn off screen updates (when performing a large amount of screen activity) and then turn on screen updates when the UI updates are complete? Many GUI frameworks have this feature. wxPython provides Freeze and Thaw methods for this functionality. The Windows Win32api supports this as well via LockWindowUpdate( hWnd | 0 ). Googling on "tkinter freeze thaw" and "tkinter lockwindowupdate" came up emtpy.
[ "No, Tkinter has no such thing. However, the screen is only updated via the event loop, so if all of your \"large amount of screen activity\" is happening in a single method, none of the activity will show up until your method finishes and the event loop is re-entered (or you explicitly call .update_idletasks())\n"...
[ 1 ]
[]
[]
[ "python", "pywin32", "tkinter", "user_interface", "win32ole" ]
stackoverflow_0004088996_python_pywin32_tkinter_user_interface_win32ole.txt
Q: How to change the app name in OSX menubar in a pure-Python application bundle? I am trying to create a pure-Python application bundle for a wxPython app. I created the .app directory with the files described in Apple docs, with an Info.plist file etc. The only difference between a "normal" app and this bundle is that the entry point (CFBundleExecutable) is a script which starts with the following line: #!/usr/bin/env python2.5 Everything works fine except that the application name in the OSX menubar is still "Python" although I have set the CFBundleName in Info.plist (I copied the result of py2app, actually). The full Info.plist can be viewed here. How can I change this? I have read everywhere that the menubar name is only determined by CFBundleName. How is it possible that the Python interpreter can change this in runtime? Note: I was using py2app before, but the result was too large (>50 MB instead of the current 100KB) and it was not even portable between Leopard and Snow Leopard... so it seems to be much easier to create a pure-Python app bundle "by hand" than transforming the output of py2app. A: Change a key called LSHasLocalizedDisplayName in Info.plist to true, as in: <key>LSHasLocalizedDisplayName</key> <true/> and then create a file in the executable bundle foo.app/Contents/Resources/English.lproj/InfoPlist.strings which has lines CFBundleName="name in the menu bar"; CFBundleDisplayName="name in the Finder"; A: The "Build Applet.app" that comes with the Python developer tools is actually a pure-Python app bundle. It does the following: a Python interpreter is placed (or linked) into the MacOS/ directory the executable script (Foo.app/Contents/MacOS/Foo) sets up some environment variables and calls os.execve() to this interpreter. The executable script looks like this (it is assumed that the entry point of the program is in Resources/main.py): #!/System/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python import sys, os execdir = os.path.dirname(sys.argv[0]) executable = os.path.join(execdir, "Python") resdir = os.path.join(os.path.dirname(execdir), "Resources") libdir = os.path.join(os.path.dirname(execdir), "Frameworks") mainprogram = os.path.join(resdir, "main.py") sys.argv.insert(1, mainprogram) pypath = os.getenv("PYTHONPATH", "") if pypath: pypath = ":" + pypath os.environ["PYTHONPATH"] = resdir + pypath os.environ["PYTHONEXECUTABLE"] = executable os.environ["DYLD_LIBRARY_PATH"] = libdir os.environ["DYLD_FRAMEWORK_PATH"] = libdir os.execve(executable, sys.argv, os.environ) A: Actually, if you create a soft link to the python executable and use that rather than the executable itself (inside your MyApp.app/Contents/MacOs/-script-), everything seems to work properly. I personally use a "#! /bin/sh" script instead and just use the "exec" command. (I you may still have to use wx.App.SetAppName(MyAppName).) For example: #! /bin/sh export PYTHONPATH=/Applications/MyApp.app/Contents/Resources/[myPythonCode] export DYLD_LIBRARY_PATH=/Library/Frameworks/Python.framework/Versions/2.6/lib exec "/Applications/MyApp.app/Contents/MacOS/[SoftLinkToPythonExe]" "/Applications/MyApp.app/Contents/Resources/myAppMain.py"
How to change the app name in OSX menubar in a pure-Python application bundle?
I am trying to create a pure-Python application bundle for a wxPython app. I created the .app directory with the files described in Apple docs, with an Info.plist file etc. The only difference between a "normal" app and this bundle is that the entry point (CFBundleExecutable) is a script which starts with the following line: #!/usr/bin/env python2.5 Everything works fine except that the application name in the OSX menubar is still "Python" although I have set the CFBundleName in Info.plist (I copied the result of py2app, actually). The full Info.plist can be viewed here. How can I change this? I have read everywhere that the menubar name is only determined by CFBundleName. How is it possible that the Python interpreter can change this in runtime? Note: I was using py2app before, but the result was too large (>50 MB instead of the current 100KB) and it was not even portable between Leopard and Snow Leopard... so it seems to be much easier to create a pure-Python app bundle "by hand" than transforming the output of py2app.
[ "Change a key called LSHasLocalizedDisplayName in Info.plist to true, as in:\n<key>LSHasLocalizedDisplayName</key>\n<true/>\n\nand then create a file in the executable bundle\nfoo.app/Contents/Resources/English.lproj/InfoPlist.strings\n\nwhich has lines\nCFBundleName=\"name in the menu bar\";\nCFBundleDisplayName=\...
[ 3, 3, 1 ]
[]
[]
[ "bundle", "macos", "py2app", "python", "wxpython" ]
stackoverflow_0002932211_bundle_macos_py2app_python_wxpython.txt
Q: plotting unix timestamps in matplotlib I'd like to make a generic value -vs- time plot with python's matplotlib module. My times are in unix time but I'd like them to show up in a readable format on the plot's x-axis. I have read answers about plotting with datetime objects but this method seems to remove hour/min/sec information and rails timestamps to the full day. Is there a way to generate these plots and show more granular labels? A: It is possible to call plt.plot(dates,values) with dates being a list of datetime.datetime objects. The plot will include xticks in a format like '%Y-%m-%d' and as you zoom in, automatically change to one that shows hours, minutes, seconds. However, it sounds like you desire more control than this. Perhaps it is not showing the hours, minutes, seconds at the scale you wish. In that case, you can set up your own date formatter: ax=plt.gca() xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S') ax.xaxis.set_major_formatter(xfmt) Unfortunately, if you pass datetime.datetime objects to plt.plot, the xticks automatically chosen by matplotlib seems to always have seconds equal to zero. For example, if you run import matplotlib.pyplot as plt import matplotlib.dates as md import numpy as np import datetime as dt import time n=20 duration=1000 now=time.mktime(time.localtime()) timestamps=np.linspace(now,now+duration,n) dates=[dt.datetime.fromtimestamp(ts) for ts in timestamps] values=np.sin((timestamps-now)/duration*2*np.pi) plt.subplots_adjust(bottom=0.2) plt.xticks( rotation=25 ) ax=plt.gca() xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S') ax.xaxis.set_major_formatter(xfmt) plt.plot(dates,values) plt.show() then you get nicely formatted dates, but all the xtick seconds are zero. So what's the solution? If you convert your timestamps --> datetime.datetime objects --> matplotlib datenums yourself, and pass the datenums to plt.plot, then the seconds are preserved. PS. By "matplotlib datenum" I mean the kind of number returned by matplotlib.dates.date2num. import matplotlib.pyplot as plt import matplotlib.dates as md import numpy as np import datetime as dt import time n=20 duration=1000 now=time.mktime(time.localtime()) timestamps=np.linspace(now,now+duration,n) dates=[dt.datetime.fromtimestamp(ts) for ts in timestamps] datenums=md.date2num(dates) values=np.sin((timestamps-now)/duration*2*np.pi) plt.subplots_adjust(bottom=0.2) plt.xticks( rotation=25 ) ax=plt.gca() xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S') ax.xaxis.set_major_formatter(xfmt) plt.plot(datenums,values) plt.show()
plotting unix timestamps in matplotlib
I'd like to make a generic value -vs- time plot with python's matplotlib module. My times are in unix time but I'd like them to show up in a readable format on the plot's x-axis. I have read answers about plotting with datetime objects but this method seems to remove hour/min/sec information and rails timestamps to the full day. Is there a way to generate these plots and show more granular labels?
[ "It is possible to call plt.plot(dates,values) with dates being a list of datetime.datetime objects. The plot will include xticks in a format like '%Y-%m-%d' and as you zoom in, automatically change to one that shows hours, minutes, seconds. \nHowever, it sounds like you desire more control than this. Perhaps it is...
[ 92 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0004090383_matplotlib_python.txt
Q: Backprop implementation issue What I am supposed to do. I have an black and white image (100x100px): I am supposed to train a backpropagation neural network with this image. The inputs are x, y coordinates of the image (from 0 to 99) and output is either 1 (white color) or 0 (black color). Once the network has learned, I would like it to reproduce the image based on its weights and get the closest possible image to the original. Here is my backprop implementation: import os import math import Image import random from random import sample #------------------------------ class definitions class Weight: def __init__(self, fromNeuron, toNeuron): self.value = random.uniform(-0.5, 0.5) self.fromNeuron = fromNeuron self.toNeuron = toNeuron fromNeuron.outputWeights.append(self) toNeuron.inputWeights.append(self) self.delta = 0.0 # delta value, this will accumulate and after each training cycle used to adjust the weight value def calculateDelta(self, network): self.delta += self.fromNeuron.value * self.toNeuron.error class Neuron: def __init__(self): self.value = 0.0 # the output self.idealValue = 0.0 # the ideal output self.error = 0.0 # error between output and ideal output self.inputWeights = [] self.outputWeights = [] def activate(self, network): x = 0.0; for weight in self.inputWeights: x += weight.value * weight.fromNeuron.value # sigmoid function if x < -320: self.value = 0 elif x > 320: self.value = 1 else: self.value = 1 / (1 + math.exp(-x)) class Layer: def __init__(self, neurons): self.neurons = neurons def activate(self, network): for neuron in self.neurons: neuron.activate(network) class Network: def __init__(self, layers, learningRate): self.layers = layers self.learningRate = learningRate # the rate at which the network learns self.weights = [] for hiddenNeuron in self.layers[1].neurons: for inputNeuron in self.layers[0].neurons: self.weights.append(Weight(inputNeuron, hiddenNeuron)) for outputNeuron in self.layers[2].neurons: self.weights.append(Weight(hiddenNeuron, outputNeuron)) def setInputs(self, inputs): self.layers[0].neurons[0].value = float(inputs[0]) self.layers[0].neurons[1].value = float(inputs[1]) def setExpectedOutputs(self, expectedOutputs): self.layers[2].neurons[0].idealValue = expectedOutputs[0] def calculateOutputs(self, expectedOutputs): self.setExpectedOutputs(expectedOutputs) self.layers[1].activate(self) # activation function for hidden layer self.layers[2].activate(self) # activation function for output layer def calculateOutputErrors(self): for neuron in self.layers[2].neurons: neuron.error = (neuron.idealValue - neuron.value) * neuron.value * (1 - neuron.value) def calculateHiddenErrors(self): for neuron in self.layers[1].neurons: error = 0.0 for weight in neuron.outputWeights: error += weight.toNeuron.error * weight.value neuron.error = error * neuron.value * (1 - neuron.value) def calculateDeltas(self): for weight in self.weights: weight.calculateDelta(self) def train(self, inputs, expectedOutputs): self.setInputs(inputs) self.calculateOutputs(expectedOutputs) self.calculateOutputErrors() self.calculateHiddenErrors() self.calculateDeltas() def learn(self): for weight in self.weights: weight.value += self.learningRate * weight.delta def calculateSingleOutput(self, inputs): self.setInputs(inputs) self.layers[1].activate(self) self.layers[2].activate(self) #return round(self.layers[2].neurons[0].value, 0) return self.layers[2].neurons[0].value #------------------------------ initialize objects etc inputLayer = Layer([Neuron() for n in range(2)]) hiddenLayer = Layer([Neuron() for n in range(10)]) outputLayer = Layer([Neuron() for n in range(1)]) learningRate = 0.4 network = Network([inputLayer, hiddenLayer, outputLayer], learningRate) # let's get the training set os.chdir("D:/stuff") image = Image.open("backprop-input.gif") pixels = image.load() bbox = image.getbbox() width = 5#bbox[2] # image width height = 5#bbox[3] # image height trainingInputs = [] trainingOutputs = [] b = w = 0 for x in range(0, width): for y in range(0, height): if (0, 0, 0, 255) == pixels[x, y]: color = 0 b += 1 elif (255, 255, 255, 255) == pixels[x, y]: color = 1 w += 1 trainingInputs.append([float(x), float(y)]) trainingOutputs.append([float(color)]) print "\nOriginal image ... Black:"+str(b)+" White:"+str(w)+"\n" #------------------------------ let's train for i in range(500): for j in range(len(trainingOutputs)): network.train(trainingInputs[j], trainingOutputs[j]) network.learn() for w in network.weights: w.delta = 0.0 #------------------------------ let's check b = w = 0 for x in range(0, width): for y in range(0, height): out = network.calculateSingleOutput([float(x), float(y)]) if 0.0 == round(out): color = (0, 0, 0, 255) b += 1 elif 1.0 == round(out): color = (255, 255, 255, 255) w += 1 pixels[x, y] = color #print out print "\nAfter learning the network thinks ... Black:"+str(b)+" White:"+str(w)+"\n" Obviously, there is some issue with my implementation. The above code returns: Original image ... Black:21 White:4 After learning the network thinks ... Black:25 White:0 It does the same thing if I try to use larger training set (I'm testing just 25 pixels from the image above for testing purposes). It returns that all pixels should be black after learning. Now, if I use a manual training set like this instead: trainingInputs = [ [0.0,0.0], [1.0,0.0], [2.0,0.0], [0.0,1.0], [1.0,1.0], [2.0,1.0], [0.0,2.0], [1.0,2.0], [2.0,2.0] ] trainingOutputs = [ [0.0], [1.0], [1.0], [0.0], [1.0], [0.0], [0.0], [0.0], [1.0] ] #------------------------------ let's train for i in range(500): for j in range(len(trainingOutputs)): network.train(trainingInputs[j], trainingOutputs[j]) network.learn() for w in network.weights: w.delta = 0.0 #------------------------------ let's check for inputs in trainingInputs: print network.calculateSingleOutput(inputs) The output is for example: 0.0330125791296 # this should be 0, OK 0.953539182136 # this should be 1, OK 0.971854575477 # this should be 1, OK 0.00046146137467 # this should be 0, OK 0.896699762781 # this should be 1, OK 0.112909223162 # this should be 0, OK 0.00034058462280 # this should be 0, OK 0.0929886299643 # this should be 0, OK 0.940489647869 # this should be 1, OK In other words the network guessed all pixels right (both black and white). Why does it say all pixels should be black if I use actual pixels from the image instead of hard coded training set like the above? I tried changing the amount of neurons in the hidden layers (up to 100 neurons) with no success. This is a homework. This is also a continuation of my previous question about backprop. A: It's been a while, but I did get my degree in this stuff, so I think hopefully some of it has stuck. From what I can tell, you're too deeply overloading your middle layer neurons with the input set. That is, your input set consists of 10,000 discrete input values (100 pix x 100 pix); you're attempting to encode those 10,000 values into 10 neurons. This level of encoding is hard (I suspect it's possible, but certainly hard); at the least, you'd need a LOT of training (more than 500 runs) to get it to reproduce reasonably. Even with 100 neurons for the middle layer, you're looking at a relatively dense compression level going on (100 pixels to 1 neuron). As to what to do about these problems; well, that's tricky. You can increase your number of middle neurons dramatically, and you'll get a reasonable effect, but of course it'll take a long time to train. However, I think there might be a different solution; if possible, you might consider using polar coordinates instead of cartesian coordinates for the input; quick eyeballing of the input pattern indicates a high level of symmetry, and effectively you'd be looking at a linear pattern with a repeated predictable deformation along the angular coordinate, which it seems would encode nicely in a small number of middle layer neurons. This stuff is tricky; going for a general solution for pattern encoding (as your original solution does) is very complex, and can usually (even with large numbers of middle layer neurons) require a lot of training passes; on the other hand, some advance heuristic task breakdown and a little bit of problem redefinition (i.e. advance converting from cartesian to polar coordinates) can give good solutions for well defined problem sets. Therein, of course, is the perpetual rub; general solutions are hard to come by, but slightly more specified solutions can be quite nice indeed. Interesting stuff, in any event!
Backprop implementation issue
What I am supposed to do. I have an black and white image (100x100px): I am supposed to train a backpropagation neural network with this image. The inputs are x, y coordinates of the image (from 0 to 99) and output is either 1 (white color) or 0 (black color). Once the network has learned, I would like it to reproduce the image based on its weights and get the closest possible image to the original. Here is my backprop implementation: import os import math import Image import random from random import sample #------------------------------ class definitions class Weight: def __init__(self, fromNeuron, toNeuron): self.value = random.uniform(-0.5, 0.5) self.fromNeuron = fromNeuron self.toNeuron = toNeuron fromNeuron.outputWeights.append(self) toNeuron.inputWeights.append(self) self.delta = 0.0 # delta value, this will accumulate and after each training cycle used to adjust the weight value def calculateDelta(self, network): self.delta += self.fromNeuron.value * self.toNeuron.error class Neuron: def __init__(self): self.value = 0.0 # the output self.idealValue = 0.0 # the ideal output self.error = 0.0 # error between output and ideal output self.inputWeights = [] self.outputWeights = [] def activate(self, network): x = 0.0; for weight in self.inputWeights: x += weight.value * weight.fromNeuron.value # sigmoid function if x < -320: self.value = 0 elif x > 320: self.value = 1 else: self.value = 1 / (1 + math.exp(-x)) class Layer: def __init__(self, neurons): self.neurons = neurons def activate(self, network): for neuron in self.neurons: neuron.activate(network) class Network: def __init__(self, layers, learningRate): self.layers = layers self.learningRate = learningRate # the rate at which the network learns self.weights = [] for hiddenNeuron in self.layers[1].neurons: for inputNeuron in self.layers[0].neurons: self.weights.append(Weight(inputNeuron, hiddenNeuron)) for outputNeuron in self.layers[2].neurons: self.weights.append(Weight(hiddenNeuron, outputNeuron)) def setInputs(self, inputs): self.layers[0].neurons[0].value = float(inputs[0]) self.layers[0].neurons[1].value = float(inputs[1]) def setExpectedOutputs(self, expectedOutputs): self.layers[2].neurons[0].idealValue = expectedOutputs[0] def calculateOutputs(self, expectedOutputs): self.setExpectedOutputs(expectedOutputs) self.layers[1].activate(self) # activation function for hidden layer self.layers[2].activate(self) # activation function for output layer def calculateOutputErrors(self): for neuron in self.layers[2].neurons: neuron.error = (neuron.idealValue - neuron.value) * neuron.value * (1 - neuron.value) def calculateHiddenErrors(self): for neuron in self.layers[1].neurons: error = 0.0 for weight in neuron.outputWeights: error += weight.toNeuron.error * weight.value neuron.error = error * neuron.value * (1 - neuron.value) def calculateDeltas(self): for weight in self.weights: weight.calculateDelta(self) def train(self, inputs, expectedOutputs): self.setInputs(inputs) self.calculateOutputs(expectedOutputs) self.calculateOutputErrors() self.calculateHiddenErrors() self.calculateDeltas() def learn(self): for weight in self.weights: weight.value += self.learningRate * weight.delta def calculateSingleOutput(self, inputs): self.setInputs(inputs) self.layers[1].activate(self) self.layers[2].activate(self) #return round(self.layers[2].neurons[0].value, 0) return self.layers[2].neurons[0].value #------------------------------ initialize objects etc inputLayer = Layer([Neuron() for n in range(2)]) hiddenLayer = Layer([Neuron() for n in range(10)]) outputLayer = Layer([Neuron() for n in range(1)]) learningRate = 0.4 network = Network([inputLayer, hiddenLayer, outputLayer], learningRate) # let's get the training set os.chdir("D:/stuff") image = Image.open("backprop-input.gif") pixels = image.load() bbox = image.getbbox() width = 5#bbox[2] # image width height = 5#bbox[3] # image height trainingInputs = [] trainingOutputs = [] b = w = 0 for x in range(0, width): for y in range(0, height): if (0, 0, 0, 255) == pixels[x, y]: color = 0 b += 1 elif (255, 255, 255, 255) == pixels[x, y]: color = 1 w += 1 trainingInputs.append([float(x), float(y)]) trainingOutputs.append([float(color)]) print "\nOriginal image ... Black:"+str(b)+" White:"+str(w)+"\n" #------------------------------ let's train for i in range(500): for j in range(len(trainingOutputs)): network.train(trainingInputs[j], trainingOutputs[j]) network.learn() for w in network.weights: w.delta = 0.0 #------------------------------ let's check b = w = 0 for x in range(0, width): for y in range(0, height): out = network.calculateSingleOutput([float(x), float(y)]) if 0.0 == round(out): color = (0, 0, 0, 255) b += 1 elif 1.0 == round(out): color = (255, 255, 255, 255) w += 1 pixels[x, y] = color #print out print "\nAfter learning the network thinks ... Black:"+str(b)+" White:"+str(w)+"\n" Obviously, there is some issue with my implementation. The above code returns: Original image ... Black:21 White:4 After learning the network thinks ... Black:25 White:0 It does the same thing if I try to use larger training set (I'm testing just 25 pixels from the image above for testing purposes). It returns that all pixels should be black after learning. Now, if I use a manual training set like this instead: trainingInputs = [ [0.0,0.0], [1.0,0.0], [2.0,0.0], [0.0,1.0], [1.0,1.0], [2.0,1.0], [0.0,2.0], [1.0,2.0], [2.0,2.0] ] trainingOutputs = [ [0.0], [1.0], [1.0], [0.0], [1.0], [0.0], [0.0], [0.0], [1.0] ] #------------------------------ let's train for i in range(500): for j in range(len(trainingOutputs)): network.train(trainingInputs[j], trainingOutputs[j]) network.learn() for w in network.weights: w.delta = 0.0 #------------------------------ let's check for inputs in trainingInputs: print network.calculateSingleOutput(inputs) The output is for example: 0.0330125791296 # this should be 0, OK 0.953539182136 # this should be 1, OK 0.971854575477 # this should be 1, OK 0.00046146137467 # this should be 0, OK 0.896699762781 # this should be 1, OK 0.112909223162 # this should be 0, OK 0.00034058462280 # this should be 0, OK 0.0929886299643 # this should be 0, OK 0.940489647869 # this should be 1, OK In other words the network guessed all pixels right (both black and white). Why does it say all pixels should be black if I use actual pixels from the image instead of hard coded training set like the above? I tried changing the amount of neurons in the hidden layers (up to 100 neurons) with no success. This is a homework. This is also a continuation of my previous question about backprop.
[ "It's been a while, but I did get my degree in this stuff, so I think hopefully some of it has stuck.\nFrom what I can tell, you're too deeply overloading your middle layer neurons with the input set. That is, your input set consists of 10,000 discrete input values (100 pix x 100 pix); you're attempting to encode ...
[ 5 ]
[]
[]
[ "artificial_intelligence", "machine_learning", "matlab", "neural_network", "python" ]
stackoverflow_0004091172_artificial_intelligence_machine_learning_matlab_neural_network_python.txt
Q: String error in my python api wrapper class I'm writing an API wrapper to a couple of different web services. I have a method that has an article url, and I want to extract text from it using alchemyapi. def extractText(self): #All Extract Text Methods ---------------------------------------------------------// #Extract page text from a web URL (ignoring navigation links, ads, etc.). if self.alchemyapi == True: self.full_text = self.alchemyObj.URLGetText(self.article_link) which goes to the following code in the python wrapper def URLGetText(self, url, textParams=None): self.CheckURL(url) if textParams == None: textParams = AlchemyAPI_TextParams() textParams.setUrl(url) return self.GetRequest("URLGetText", "url", textParams) def GetRequest(self, apiCall, apiPrefix, paramObject): endpoint = 'http://' + self._hostPrefix + '.alchemyapi.com/calls/' + apiPrefix + '/' + apiCall endpoint += '?apikey=' + self._apiKey + paramObject.getParameterString() handle = urllib.urlopen(endpoint) result = handle.read() handle.close() xpathQuery = '/results/status' nodes = etree.fromstring(result).xpath(xpathQuery) if nodes[0].text != "OK": raise 'Error making API call.' return result However I get this error --- Traceback (most recent call last): File "<stdin>", line 1, in <module> File "text_proc.py", line 97, in __init__ self.alchemyObj.loadAPIKey("api_key.txt"); File "text_proc.py", line 115, in extractText if self.alchemyapi == True: File "/Users/Diesel/Desktop/AlchemyAPI.py", line 502, in URLGetText return self.GetRequest("URLGetText", "url", textParams) File "/Users/Diesel/Desktop/AlchemyAPI.py", line 618, in GetRequest raise 'Error making API call.' I know I'm somehow passing the url string to the api wrapper in a faulty format, but I can't figure out how to fix it. A: You should raise Exception or a subclass thereof, instead of a string. A: The information provided is not actually very helpful to diagnose or solve the problem. Have you considered taking a look at the response from the server? You might inspect a complete traffic log using Fiddler. Additionally, the SDK provided by Alchemy doesn't seem to be of - cough, cough - the greatest quality. Since it really consists only of around 600 lines of source code, I'd consider writing a shorter, more robust / pythonic / whatever SDK. I might also add that right now, even the on-site demo at the Alchemy web site is failing, so maybe your problem is related to that. I really suggest taking a look at the traffic. A: You're getting the error because your function GetRequest() raising a string as an exception: if nodes[0].text != "OK": raise 'Error making API call.' If that's not what you want, you have two options: You can have the function return the string or None, or You can pass the error message to a real subclass of Exception (as suggested by knutin) In either case, if you are assigning that return value to a variable, you can handle it accordingly. Here is an example: Option 1 Let's assume you decide to have GetRequest() return None: def URLGetText(self, url, textParams=None): self.CheckURL(url) if textParams == None: textParams = AlchemyAPI_TextParams() textParams.setUrl(url) # Capture the value of GetRequest() before returning it retval = self.GetRequest("URLGetText", "url", textParams) if retval is None: print 'Error making API call.' # print the error but still return return retval def GetRequest(self, apiCall, apiPrefix, paramObject): # ... if nodes[0].text != "OK": return None return result This option is a little ambiguous. How do you know that it was really an error, or the return value truly was None? Option 2 This is probably the better way to do it: First create an subclass of Exception: class GetRequestError(Exception): """Error returned from GetRequest()""" pass Then raise it in GetRequest()`: def URLGetText(self, url, textParams=None): self.CheckURL(url) if textParams == None: textParams = AlchemyAPI_TextParams() textParams.setUrl(url) # Attempt to get a legit return value & handle errors try: retval = self.GetRequest(apiCall, apiPrefix, paramObject) except GetRequestError as err: print err # prints 'Error making API call.' # handle the error here retval = None return retval def GetRequest(self, apiCall, apiPrefix, paramObject): # ... if nodes[0].text != "OK": raise GetRequestError('Error making API call.') return result This way you're raising a legitimate error when GetRequest() doesn't return the desired result, and then you can handle the error using a try..except block and optionally print the error, stop the program there, or keep going (which is what I think you want to do based on your question). A: This is Shaun from AlchemyAPI. We just posted a new version of the python SDK that raises exceptions properly. You can get it here http://www.alchemyapi.com/tools/. If you have any other feedback about the SDK, please message me. Thanks for using our NLP service.
String error in my python api wrapper class
I'm writing an API wrapper to a couple of different web services. I have a method that has an article url, and I want to extract text from it using alchemyapi. def extractText(self): #All Extract Text Methods ---------------------------------------------------------// #Extract page text from a web URL (ignoring navigation links, ads, etc.). if self.alchemyapi == True: self.full_text = self.alchemyObj.URLGetText(self.article_link) which goes to the following code in the python wrapper def URLGetText(self, url, textParams=None): self.CheckURL(url) if textParams == None: textParams = AlchemyAPI_TextParams() textParams.setUrl(url) return self.GetRequest("URLGetText", "url", textParams) def GetRequest(self, apiCall, apiPrefix, paramObject): endpoint = 'http://' + self._hostPrefix + '.alchemyapi.com/calls/' + apiPrefix + '/' + apiCall endpoint += '?apikey=' + self._apiKey + paramObject.getParameterString() handle = urllib.urlopen(endpoint) result = handle.read() handle.close() xpathQuery = '/results/status' nodes = etree.fromstring(result).xpath(xpathQuery) if nodes[0].text != "OK": raise 'Error making API call.' return result However I get this error --- Traceback (most recent call last): File "<stdin>", line 1, in <module> File "text_proc.py", line 97, in __init__ self.alchemyObj.loadAPIKey("api_key.txt"); File "text_proc.py", line 115, in extractText if self.alchemyapi == True: File "/Users/Diesel/Desktop/AlchemyAPI.py", line 502, in URLGetText return self.GetRequest("URLGetText", "url", textParams) File "/Users/Diesel/Desktop/AlchemyAPI.py", line 618, in GetRequest raise 'Error making API call.' I know I'm somehow passing the url string to the api wrapper in a faulty format, but I can't figure out how to fix it.
[ "You should raise Exception or a subclass thereof, instead of a string.\n", "The information provided is not actually very helpful to diagnose or solve the problem. Have you considered taking a look at the response from the server? You might inspect a complete traffic log using Fiddler. \nAdditionally, the SDK pr...
[ 2, 2, 0, 0 ]
[]
[]
[ "api", "python", "wrapper" ]
stackoverflow_0004056073_api_python_wrapper.txt
Q: Trying to find a pure python scrollbar, slider or guage widget to control the x axis of a graph (wxPython) Does anyone know of an example / tutorial of one? I want to control the x-min and x-max values of an xy plot (for mpl) using mouse clicks / drag & drop in wxPython- Thx in advance. --DM A: This should be pretty easy to do. Have you looked at the docs and this example? So when the slider changes, you can easily set the values you desire. Also, there is a SetMin and SetMax method for what you want. A: The RulerCtrl widget by Andrea Gavana can probably do what you want. It's "pure Python" as much as any Python GUI can be in the sense that it's built from wxPython primitives. Below is a screenshot from the wxPython demo. You can click on the arrows and drag them along the ruler.
Trying to find a pure python scrollbar, slider or guage widget to control the x axis of a graph (wxPython)
Does anyone know of an example / tutorial of one? I want to control the x-min and x-max values of an xy plot (for mpl) using mouse clicks / drag & drop in wxPython- Thx in advance. --DM
[ "This should be pretty easy to do. Have you looked at the docs and this example?\nSo when the slider changes, you can easily set the values you desire. Also, there is a SetMin and SetMax method for what you want.\n", "The RulerCtrl widget by Andrea Gavana can probably do what you want. \nIt's \"pure Python\" as ...
[ 1, 0 ]
[]
[]
[ "matplotlib", "python", "wxpython" ]
stackoverflow_0004081133_matplotlib_python_wxpython.txt
Q: CTRL-C behaves differently in Python I've recently started learning Python (long time Java programmer here) and currently in the process of writing some simple server programs. The problem is, for a seemingly similar piece of code, the Java counterpart properly responds to the SIGINT signal (Ctrl+C) whereas the Python one doesn't. This is seen when a separate thread is used to spawn the server. Code is as follows: // Java code package pkg; import java.io.*; import java.net.*; public class ServerTest { public static void main(final String[] args) throws Exception { final Thread t = new Server(); t.start(); } } class Server extends Thread { @Override public void run() { try { final ServerSocket sock = new ServerSocket(12345); while(true) { final Socket clientSock = sock.accept(); clientSock.close(); } } catch(Exception e) { e.printStackTrace(); } } } and Python code: # Python code import threading, sys, socket, signal def startserver(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 12345)) s.listen(1) while True: csock, caddr = s.accept() csock.sendall('Get off my lawn kids...\n') csock.close() if __name__ == '__main__': try: t = threading.Thread(target=startserver) t.start() except: sys.exit(1) In both the above code snippets, I create a simple server which listens to TCP requests on the given port. When Ctrl+C is pressed in case of the Java code, the JVM exits whereas in the case of the Python code, all I get is a ^C at the shell. The only way I can stop the server is press Ctrl+Z and then manually kill the process. So I come up with a plan; why not have a sighandler which listens for Ctrl+Z and quits the application? Cool, so I come up with: import threading, sys, socket, signal def startserver(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 12345)) s.listen(1) while True: csock, caddr = s.accept() csock.sendall('Get off my lawn kids...\n') csock.close() def ctrlz_handler(*args, **kwargs): sys.exit(1) if __name__ == '__main__': try: signal.signal(signal.SIGTSTP, ctrlz_handler) t = threading.Thread(target=startserver) t.start() except: sys.exit(1) But now, it seems as I've made the situation even worse! Now pressing Ctrl+C at the shell emits '^C' and pressing Ctrl+Z at the shell emits '^Z'. So my question is, why this weird behaviour? I'd probably have multiple server processes running as separate threads in the same process so any clean way of killing the server when the process receives SIGINT? BTW using Python 2.6.4 on Ubuntu. TIA, sasuke A: Several issues: Don't catch all exceptions and silently exit. That's the worst possible thing you can do. Unless you really know what you're doing, never catch SIGTSTP. It's not a signal meant for applications to intercept, and if you're catching it, chances are you're doing something wrong. KeyboardInterrupt is only sent to the initial thread of the program, and never to other threads. This is done for a couple reasons. Generally, you want to deal with ^C in a single place, and not in a random, arbitrary thread that happens to receive the exception. Also, it helps guarantee that, in normal operation, most threads never receive asynchronous exceptions; this is useful since (in all languages, including Java) they're very hard to deal with reliably. You're never going to see the KeyboardInterrupt here, because your main thread exits immediately after starting the secondary thread. There's no main thread to receive the exception, and it's simply discarded. The fix is two-fold: keep the main thread around, so the KeyboardInterrupt has somewhere to go, and only catch KeyboardInterrupt, not all exceptions. import threading, sys, socket, signal, time def startserver(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 12345)) s.listen(1) while True: csock, caddr = s.accept() csock.sendall('Get off my lawn kids...\n') csock.close() if __name__ == '__main__': try: t = threading.Thread(target=startserver) t.start() # Wait forever, so we can receive KeyboardInterrupt. while True: time.sleep(1) except KeyboardInterrupt: print "^C received" sys.exit(1) # We never get here. raise RuntimeError, "not reached" A: the thread your create is not daemonic, so it doesn't exit when the parent thread exits; the main exits right after it starts the child thread, python process waits for the child thread to be terminated; offtop: do not forget to close the sockets; you should implement some stop mechanism for the child thread. A simple workround: check some stopped flag in the while loop that accepts client connections (use a module-level, or extend the threading.Thread class to encapsulate it), set that flag to True and kick the server socket (by connecting) on Ctrl+C and/or Ctrl+Z or without them; wait in the main block for while t.isAlive(): time.sleep(1). Here is a sample code: import threading, sys, socket, signal, time class Server(threading.Thread): def init(self): threading.Thread.init(self) self._stop = False self._port =12345 def stop(self): self.__stop = True self.kick() def kick(self): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('', self.__port)) s.close() except IOError, e: print "Failed to kick the server:", e def run(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', self._port)) s.listen(1) try: while True: csock, caddr = s.accept() if self._stop: print "Stopped, breaking" break print "client connected from", caddr try: csock.sendall('Get off my lawn kids...\n') finally: csock.close() finally: s.close() if name == 'main': t = Server() # if it is failed to stop the thread properly, it will exit t.setDaemon(True) t.start() try: while t.isAlive(): time.sleep(1) except: # Ctrl+C brings us here print "Maybe, you have interrupted this thing?" t.stop() # t.join() may be called here, or another synchronization should appear to # make sure the server stopped correctly I don't know why it show stop,kick,run methods as module-level and puts more than one newlines, sorry
CTRL-C behaves differently in Python
I've recently started learning Python (long time Java programmer here) and currently in the process of writing some simple server programs. The problem is, for a seemingly similar piece of code, the Java counterpart properly responds to the SIGINT signal (Ctrl+C) whereas the Python one doesn't. This is seen when a separate thread is used to spawn the server. Code is as follows: // Java code package pkg; import java.io.*; import java.net.*; public class ServerTest { public static void main(final String[] args) throws Exception { final Thread t = new Server(); t.start(); } } class Server extends Thread { @Override public void run() { try { final ServerSocket sock = new ServerSocket(12345); while(true) { final Socket clientSock = sock.accept(); clientSock.close(); } } catch(Exception e) { e.printStackTrace(); } } } and Python code: # Python code import threading, sys, socket, signal def startserver(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 12345)) s.listen(1) while True: csock, caddr = s.accept() csock.sendall('Get off my lawn kids...\n') csock.close() if __name__ == '__main__': try: t = threading.Thread(target=startserver) t.start() except: sys.exit(1) In both the above code snippets, I create a simple server which listens to TCP requests on the given port. When Ctrl+C is pressed in case of the Java code, the JVM exits whereas in the case of the Python code, all I get is a ^C at the shell. The only way I can stop the server is press Ctrl+Z and then manually kill the process. So I come up with a plan; why not have a sighandler which listens for Ctrl+Z and quits the application? Cool, so I come up with: import threading, sys, socket, signal def startserver(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 12345)) s.listen(1) while True: csock, caddr = s.accept() csock.sendall('Get off my lawn kids...\n') csock.close() def ctrlz_handler(*args, **kwargs): sys.exit(1) if __name__ == '__main__': try: signal.signal(signal.SIGTSTP, ctrlz_handler) t = threading.Thread(target=startserver) t.start() except: sys.exit(1) But now, it seems as I've made the situation even worse! Now pressing Ctrl+C at the shell emits '^C' and pressing Ctrl+Z at the shell emits '^Z'. So my question is, why this weird behaviour? I'd probably have multiple server processes running as separate threads in the same process so any clean way of killing the server when the process receives SIGINT? BTW using Python 2.6.4 on Ubuntu. TIA, sasuke
[ "Several issues:\n\nDon't catch all exceptions and silently exit. That's the worst possible thing you can do.\nUnless you really know what you're doing, never catch SIGTSTP. It's not a signal meant for applications to intercept, and if you're catching it, chances are you're doing something wrong.\nKeyboardInterru...
[ 5, 1 ]
[]
[]
[ "java", "python", "sockets" ]
stackoverflow_0004090891_java_python_sockets.txt
Q: Trying to produce monospaced output in pyqt browser I have modified a short piece of pyqt code to produce real-time rendering of a user's expression. I have used sympy's pretty-printing function for this, however the output does not appear correctly as the QTextBrowser uses a proportional rather than a monospaced font. As a beginner I would also welcome any other thoughts you had on the code. Many thanks and best wishes, Geddes from __future__ import division import sys import sympy from PyQt4.QtCore import * from PyQt4.QtGui import * class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) self.browser = QTextBrowser() self.lineedit = QLineEdit("please type an expression") self.lineedit.selectAll() layout = QVBoxLayout() layout.addWidget(self.browser) layout.addWidget(self.lineedit) self.setLayout(layout) self.lineedit.setFocus() self.connect(self.lineedit, SIGNAL("textChanged (const QString&)"),self.updateUi) def updateUi(self): text = unicode(self.lineedit.text()) for z in range(0,9): text = text.replace('x'+str(z),'x^'+str(z)) text = text.replace(')'+str(z),')^'+str(z)) text = text.replace(str(z)+'x',str(z)+'*x') text = text.replace(str(z)+'(',str(z)+'*(') try: self.browser.append(sympy.printing.pretty(sympy.sympify(text))) self.browser.clear() self.browser.append(sympy.printing.pretty(sympy.sympify(text))) except: if text=='': self.browser.clear() app = QApplication(sys.argv) form = Form() form.show() app.exec_() A: You should be able to change the font with setFontFamily. Concerning your code: I haven't really worked with PyQt yet (only some hacks like the font family in qbzr...), so I can't tell you if everything is okay. But the following is not a good idea: except: if text=='': self.browser.clear() Never catch all exceptions with except:. This will also catch BaseExceptions like SystemExit, which shouldn't be caught unless you have a reason to do so. Always catch specific exceptions, or if you're at the highest level (before the unhandled exception handler is executed) and want to log errors, rather use except Exception: which will only handle exceptions based on Exception. if text=='' - I think if not text is more "pythonic". A: QTextBrowser inherits QTextEdit, so you can use the setCurrentFont(QFont) method to set a monospace font. self.browser = QTextBrowser() self.browser.setCurrentFont(QFont("Courier New")) #Or whatever monospace font family you want... As for general comments on style, there's probably a way do change your text replacement stuff in updateUi() to regex, but I can't be sure without seeing sample data to figure out what you're trying to do. Also, you should probably refactor try: self.browser.append(sympy.printing.pretty(sympy.sympify(text))) self.browser.clear() self.browser.append(sympy.printing.pretty(sympy.sympify(text))) except: if text=='': self.browser.clear() Into something more like: self.browser.clear() try: self.browser.append(sympy.printing.pretty(sympy.sympify(text))) except: if text=='': self.browser.clear() Except probably catching the actual Exception you're expecting. EDIT Here's something for the equation normalizing it looks like you're trying to do, it works with lowercase a-z and real numbers: def updateUi(self): text = unicode(self.lineedit.text()) text = re.sub(r'(\d+)([\(]|[a-z])',r'\1*\2',text) #for multiplication text = re.sub(r'([a-z]|[\)])(\d+)',r'\1^\2',text) #for exponentiation The first pattern looks for 1 or more digits \d+ followed by an open parenthesis, or a single letter a-z [\(]|[a-z]. It uses parentheses to capture the digit part of the pattern and the variable part of the pattern, and inserts a * between them. \1*\2. The second pattern looks for a variable a-z or a close parenthesis [a-z]|[\)], followed by one or more digits \d+. It uses the grouping parentheses to capture the digit and the variable again, and inserts a ^ between them \1^\2. It's not quite perfect (doesn't handle xy --> x*y) but its closer. If you want to make a full computer algebra system you'll probably need to build a dedicated parser :)
Trying to produce monospaced output in pyqt browser
I have modified a short piece of pyqt code to produce real-time rendering of a user's expression. I have used sympy's pretty-printing function for this, however the output does not appear correctly as the QTextBrowser uses a proportional rather than a monospaced font. As a beginner I would also welcome any other thoughts you had on the code. Many thanks and best wishes, Geddes from __future__ import division import sys import sympy from PyQt4.QtCore import * from PyQt4.QtGui import * class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) self.browser = QTextBrowser() self.lineedit = QLineEdit("please type an expression") self.lineedit.selectAll() layout = QVBoxLayout() layout.addWidget(self.browser) layout.addWidget(self.lineedit) self.setLayout(layout) self.lineedit.setFocus() self.connect(self.lineedit, SIGNAL("textChanged (const QString&)"),self.updateUi) def updateUi(self): text = unicode(self.lineedit.text()) for z in range(0,9): text = text.replace('x'+str(z),'x^'+str(z)) text = text.replace(')'+str(z),')^'+str(z)) text = text.replace(str(z)+'x',str(z)+'*x') text = text.replace(str(z)+'(',str(z)+'*(') try: self.browser.append(sympy.printing.pretty(sympy.sympify(text))) self.browser.clear() self.browser.append(sympy.printing.pretty(sympy.sympify(text))) except: if text=='': self.browser.clear() app = QApplication(sys.argv) form = Form() form.show() app.exec_()
[ "You should be able to change the font with setFontFamily.\nConcerning your code: I haven't really worked with PyQt yet (only some hacks like the font family in qbzr...), so I can't tell you if everything is okay. But the following is not a good idea:\n except:\n if text=='': self.browser.clear()\n\n\nNev...
[ 4, 1 ]
[]
[]
[ "pyqt", "python", "sympy" ]
stackoverflow_0004091276_pyqt_python_sympy.txt
Q: How do I create a numpy array from string? I have a file reader that reads n bytes from a file and returns a string of chars representing that (binary) data. I want to read up n bytes into a numpy array of numbers and run a FFT on it, but I'm having trouble creating an array from a string. A couple lines of example would be awesome. Edit: I'm reading raw binary data, and so the string I get looks like '\x01\x05\x03\xff'.... I want this to become [1, 5, 3, 255]. A: In Python 2, you can do this directly with numpy.fromstring: import numpy as np s = '\x01\x05\x03\xff' a = np.fromstring(s, dtype='uint8') Once completing this, a is array([ 1, 5, 3, 255]) and you can use the regular scipy/numpy FFT routines. In Python 3, the switch to default Unicode strings means that you would read in the data as a bytestring and use the frombuffer command instead: import numpy as np s = b'\x01\x05\x03\xff' a = np.frombuffer(s, dtype='uint8') to get the same results. A: >>> '\x01\x05\x03\xff' '\x01\x05\x03\xff' >>> map(ord, '\x01\x05\x03\xff') [1, 5, 3, 255] >>> numpy.array(map(ord, '\x01\x05\x03\xff')) array([ 1, 5, 3, 255]) A: Without knowing what you've got coming in it's tough, but if it were comma delimited integers you could do something like this: myInts = map(int, myString.split(','))
How do I create a numpy array from string?
I have a file reader that reads n bytes from a file and returns a string of chars representing that (binary) data. I want to read up n bytes into a numpy array of numbers and run a FFT on it, but I'm having trouble creating an array from a string. A couple lines of example would be awesome. Edit: I'm reading raw binary data, and so the string I get looks like '\x01\x05\x03\xff'.... I want this to become [1, 5, 3, 255].
[ "In Python 2, you can do this directly with numpy.fromstring:\nimport numpy as np\ns = '\\x01\\x05\\x03\\xff'\na = np.fromstring(s, dtype='uint8')\n\nOnce completing this, a is array([ 1, 5, 3, 255]) and you can use the regular scipy/numpy FFT routines.\nIn Python 3, the switch to default Unicode strings means that...
[ 21, 5, 1 ]
[]
[]
[ "arrays", "fft", "numpy", "python" ]
stackoverflow_0004090981_arrays_fft_numpy_python.txt
Q: subprocess.call requiring all parameters to be separated by commas I used to be able to do a subprocess.call(["command","-option value -option value"]) and it would work there was a change to the command to work properly with things in quotes, but now I have to change my subprocess call command to look like this: subprocess.call(["command","-option","value","-option","value"]) is there something I can do to get it to work the other way again in python? the os.system("command -option value -option value") works the same as it did before. A: Avoid shell=True if you can -- it's a security risk. For this purpose, shlex.split suffices: import subprocess import shlex subprocess.call(shlex.split("command -option value -option value")) A: You'll need to specify shell=True to get subprocess.call to interpret the string. See the note in the subprocess.Popen constructor documentation (the subprocess.call method takes the same arguments as the subprocess.Popen constructor).
subprocess.call requiring all parameters to be separated by commas
I used to be able to do a subprocess.call(["command","-option value -option value"]) and it would work there was a change to the command to work properly with things in quotes, but now I have to change my subprocess call command to look like this: subprocess.call(["command","-option","value","-option","value"]) is there something I can do to get it to work the other way again in python? the os.system("command -option value -option value") works the same as it did before.
[ "Avoid shell=True if you can -- it's a security risk. For this purpose, shlex.split suffices:\nimport subprocess\nimport shlex\nsubprocess.call(shlex.split(\"command -option value -option value\"))\n\n", "You'll need to specify shell=True to get subprocess.call to interpret the string.\nSee the note in the subpr...
[ 44, 3 ]
[]
[]
[ "python" ]
stackoverflow_0004091242_python.txt
Q: Nice way (for CPU) to wait for a free lock in Python I have a generic class called "lockingValue" that may be referenced by several threads. This is to prevent a race condition. class lockingValue(object): def __init__(self,value=None): self._locked=False self._value=value def _lock(self): while self._locked: pass self._locked = True def _unlock(self): self._locked = False def update(self,val): self._lock() self._value=val def value(self): return copy.copy(self._value) What I'm looking for specifically is a nicer way to wait for the lock to become free. The following is liable to peg the CPU and I would like to avoid it. def _lock(self): while self._locked: pass self._locked = True Update: I am interested in suggestions and examples of a better & safer design to do this sort of inner-process communication & tracking (tabulating progress across many threads for example). A: Check out threading.Lock(). import threading class lockingValue(object): def __init__(self,value=None): self._lock = threading.Lock() self._value = value def _lock(self): self._lock.acquire() def _unlock(self): self._lock.release() def update(self, val): self._lock() self._value = val self._unlock() def value(self): return copy.copy(self._value) As your code stands right now, in your _lock method, several threads could be waiting in the while loop, and multiple of them could make it out of the loop simultaneously if the OS thread scheduling conspired against you. Edit Updated update to unlock when finished based on khachik's comment. A: Why not wrap your class around Python's own Lock object? Then you don't have to worry about how it's implemented. It even acts as a context manager, so you can use cute syntax like this: with myLock: doSomething()
Nice way (for CPU) to wait for a free lock in Python
I have a generic class called "lockingValue" that may be referenced by several threads. This is to prevent a race condition. class lockingValue(object): def __init__(self,value=None): self._locked=False self._value=value def _lock(self): while self._locked: pass self._locked = True def _unlock(self): self._locked = False def update(self,val): self._lock() self._value=val def value(self): return copy.copy(self._value) What I'm looking for specifically is a nicer way to wait for the lock to become free. The following is liable to peg the CPU and I would like to avoid it. def _lock(self): while self._locked: pass self._locked = True Update: I am interested in suggestions and examples of a better & safer design to do this sort of inner-process communication & tracking (tabulating progress across many threads for example).
[ "Check out threading.Lock().\nimport threading\n\nclass lockingValue(object):\n def __init__(self,value=None):\n self._lock = threading.Lock()\n self._value = value\n\n def _lock(self):\n self._lock.acquire()\n\n def _unlock(self):\n self._lock.release()\n\n def update(self, ...
[ 3, 3 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0004091565_multithreading_python.txt
Q: Incrementing previous entry by 1 I'm trying to set up a project listing where when I set up a project it has a project number (example 10-1000). I want to be able to add a new project and have it append 1 to the project number, (example, next project # will be 10-1001). I am having a bit of trouble figuring out the first step. here is my models.py class Project(models.Model): client = models.ForeignKey(Clients, related_name='projects') created_by = models.ForeignKey(User, related_name='created_by') #general information proj_name = models.CharField(max_length=255, verbose_name='Project Name') quote = models.CharField(max_length=10, verbose_name='Quote #', unique=True) desc = models.TextField(verbose_name='Description') starts_on = models.DateField(verbose_name='Start Date') completed_on = models.DateField(verbose_name='Finished On') def __unicode__(self): return u'%s' % (self.proj_name) #get the current status of the projectget_value_display def current_status(self): try: return self.status.all().order_by('-id')[:1][0] except: return None My views.py showing the add @login_required def addProject(request): if request.method == 'POST': form = AddSingleProjectForm(request.POST) if form.is_valid(): project = form.save(commit=False) project.created_by = request.user today = datetime.date.today() project.quote = "%s-%s" % (str(today.year)[2:4], project.quote) project.save() project.status.create( value = form.cleaned_data.get('status', None) ) return HttpResponseRedirect('/project/') else: form = AddSingleProjectForm() return render_to_response('project/addProject.html', { 'form': form, 'user':request.user}, context_instance=RequestContext(request)) and my forms.py class AddSingleProjectForm(ModelForm): status = forms.ChoiceField(choices=STATUS_CHOICES) def __init__(self, *args, **kwargs): super(AddSingleProjectForm, self).__init__(*args, **kwargs) self.fields['status'].initial = self.instance.current_status() class Meta: model = Project exclude = ('pre_quote', 'created_by') def save(self, force_insert=False, force_update=False, commit=True): f = super(AddSingleProjectForm, self).save(commit=False) if commit: f.save() print "form save method was called with commit TRUE" return f Any suggestions would be greatly appreciated. Thanks everyone! A: It looks to me that your "quote" is two things: a monotonically incrementing "project number", and a year. Since that's what they are, they have a regular structure. Exclude them from your form and view entirely, and create two new fields: "quote_year" and "quote_id." Your save would then look something like this: def save(self, *args, **kwargs): if not self.quote_year and not self.quote_id: self.quote_year = datetime.date.today().year % 100 quote_ids = self.objects.filter(quote_year = self.quote_year).order_by('-quote_id') self.quote_id = 1 if quote_ids.exists(): self.quote_id = quote_ids[0].quote_id + 1 super(Project, self).save(*args, **kwargs) This basically tests to see if there are any quote_ids for the current year and, if not, initialize to 1, otherwise initialize to the highest quote_id plus 1. In order to save yourself grief rendering the quote ID again and again, add this to your model as well: @property def quote(self): return '%02d-%05d' % (self.quote_year, self.quote_id) My code assumes that you want the project part of the number to reset to zero for the first project of each year.
Incrementing previous entry by 1
I'm trying to set up a project listing where when I set up a project it has a project number (example 10-1000). I want to be able to add a new project and have it append 1 to the project number, (example, next project # will be 10-1001). I am having a bit of trouble figuring out the first step. here is my models.py class Project(models.Model): client = models.ForeignKey(Clients, related_name='projects') created_by = models.ForeignKey(User, related_name='created_by') #general information proj_name = models.CharField(max_length=255, verbose_name='Project Name') quote = models.CharField(max_length=10, verbose_name='Quote #', unique=True) desc = models.TextField(verbose_name='Description') starts_on = models.DateField(verbose_name='Start Date') completed_on = models.DateField(verbose_name='Finished On') def __unicode__(self): return u'%s' % (self.proj_name) #get the current status of the projectget_value_display def current_status(self): try: return self.status.all().order_by('-id')[:1][0] except: return None My views.py showing the add @login_required def addProject(request): if request.method == 'POST': form = AddSingleProjectForm(request.POST) if form.is_valid(): project = form.save(commit=False) project.created_by = request.user today = datetime.date.today() project.quote = "%s-%s" % (str(today.year)[2:4], project.quote) project.save() project.status.create( value = form.cleaned_data.get('status', None) ) return HttpResponseRedirect('/project/') else: form = AddSingleProjectForm() return render_to_response('project/addProject.html', { 'form': form, 'user':request.user}, context_instance=RequestContext(request)) and my forms.py class AddSingleProjectForm(ModelForm): status = forms.ChoiceField(choices=STATUS_CHOICES) def __init__(self, *args, **kwargs): super(AddSingleProjectForm, self).__init__(*args, **kwargs) self.fields['status'].initial = self.instance.current_status() class Meta: model = Project exclude = ('pre_quote', 'created_by') def save(self, force_insert=False, force_update=False, commit=True): f = super(AddSingleProjectForm, self).save(commit=False) if commit: f.save() print "form save method was called with commit TRUE" return f Any suggestions would be greatly appreciated. Thanks everyone!
[ "It looks to me that your \"quote\" is two things: a monotonically incrementing \"project number\", and a year. Since that's what they are, they have a regular structure. Exclude them from your form and view entirely, and create two new fields: \"quote_year\" and \"quote_id.\"\nYour save would then look something...
[ 0 ]
[]
[]
[ "django", "django_forms", "django_models", "django_views", "python" ]
stackoverflow_0004090019_django_django_forms_django_models_django_views_python.txt
Q: printing to a file in Python: redirect vs print's file argument vs write I have a bunch of print calls that I need to write to a file instead of stdout. (I don't need stdout at all.) I am considering three approaches. Are there any advantages (including performance) to any one of them? Full redirect, which I saw here: import sys saveout = sys.stdout fsock = open('out.log', 'w') sys.stdout = fsock print(x) # and many more print calls # later if I ever need it: # sys.stdout = saveout # fsock.close() Redirect in each print statement: fsock = open('out.log', 'w') print(x, file = fsock) # and many more print calls Write function: fsock = open('out.log', 'w') fsock.write(str(x)) # and many more write calls A: I would not expect any durable performance differences among these approaches. The advantage of the first approach is that any reasonably well-behaved code which you rely upon (modules you import) will automatically pick up your desired redirection. The second approach has no advantage. It's only suitable for debugging or throwaway code ... and not even a good idea for that. You want your output decisions to be consolidated in a few well-defined places, not scattered across your code in every call to print(). In Python3 print() is a function rather than a statement. This allows you to re-define it, if you like. So you can def print(*args) if you want. You can also call __builtins__.print() if you need access to it, within the definition of your own custom print(), for example. The third approach ... and by extension the principle that all of your output should be generated in specific functions and class methods that you define for that purpose ... is probably best. You should keep your output and formatting separated from your core functionality as much as possible. By keeping them separate you allow your core to be re-used. (For example you might start with something that's intended to run from a text/shell console, and later need to provide a Web UI, a full-screen (curses) front end or a GUI for it. You may also build entirely different functionality around it ... in situations where the resulting data needs to be returned in its native form (as objects) rather than pulled in as text (output) and re-parsed into new objects. For example I've had more than one occasional where something I wrote to perform some complex queries and data gathering from various sources and print a report ... say of the discrepancies ... later need to be adapted into a form which could spit out the data in some form (such as YAML/JSON) that could be fed into some other system (say, for reconciling one data source against another. If, from the outset, you keep the main operations separate from the output and formatting then this sort of adaptation is relatively easy. Otherwise it entails quite a bit of refactoring (sometimes tantamount to a complete re-write). A: From the filenames you're using in your question, it sounds like you're wanting to create a log file. Have you consider the Python logging module instead? A: I think that semantics is imporant: I would suggest first approach for situation when you printing the same stuff you would print to console. Semantics will be the same. For more complex situation I would use standard logging module. The second and third approach are a bit different in case you are printing text lines. Second approach - print adds the newline and write does not. I would use the third approach in writing mainly binary or non-textual format and I would use redirect in print statement in the most other cases.
printing to a file in Python: redirect vs print's file argument vs write
I have a bunch of print calls that I need to write to a file instead of stdout. (I don't need stdout at all.) I am considering three approaches. Are there any advantages (including performance) to any one of them? Full redirect, which I saw here: import sys saveout = sys.stdout fsock = open('out.log', 'w') sys.stdout = fsock print(x) # and many more print calls # later if I ever need it: # sys.stdout = saveout # fsock.close() Redirect in each print statement: fsock = open('out.log', 'w') print(x, file = fsock) # and many more print calls Write function: fsock = open('out.log', 'w') fsock.write(str(x)) # and many more write calls
[ "I would not expect any durable performance differences among these approaches.\nThe advantage of the first approach is that any reasonably well-behaved code which you rely upon (modules you import) will automatically pick up your desired redirection.\nThe second approach has no advantage. It's only suitable for d...
[ 6, 4, 4 ]
[]
[]
[ "file", "python", "python_3.x", "redirect", "stdout" ]
stackoverflow_0004090997_file_python_python_3.x_redirect_stdout.txt
Q: server-side scripting for web pages with Python: nothing happens I'm trying to learn to use Python to create dynamic web content. Problem I'm having right out the door, though, is that when I try to do a mySQL query, absolutely nothing happens. There's no error message... it looks like the script simply stops running when I import the module that enables connection to the database. This does do exactly what I'd expect when I try to run it from the command line. #!/usr/bin/python print "Content-Type: text/xml" print #if I type, for example, print "<b>test</b>" here, it appears in the browser window #msql contains the credentials for connecting to database #it is NOT in public_html import msql #no print instructions after this point are followed connex=msql.msqlConn() db=msql.MySQLdb cursor=connex.cursor(db.cursors.DictCursor) cursor.execute("SELECT * FROM userActions") #run the query xmlOutput="" rows=cursor.fetchall() #output the results for row in rows: xmlOutput+="<action>" xmlOutput+="<actionId>"+str(row["actionId"])+"</actionId>" xmlOutput+="<userId>"+str(row["userId"])+"</userId>" xmlOutput+="<actText>"+str(row["action"])+"</actText>" xmlOutput+="<date>"+str(row["dateStamp"])+"</date>" xmlOutput+="</action>" xmlOutput="<list>"+xmlOutput+"</list>" print xmlOutput This would be my first stab at this, so it merely stands to reason that this should work. I've found nothing online that would suggest otherwise, though. A: Please, take 24h to learn something like Django. Django has an ORM and a XML serializer that will make your life easier ensuring proper (and legal) xml, it really pays up. A: You can enable cgi traceback to see what happens: import cgitb cgitb.enable() (I don't think it causes your problem, and clients understand \n as well but it is better to use sys.write("...\r\n") instead of print to print HTTP headers) Edited: try to add Content-length: XXXX\r\n to the header.
server-side scripting for web pages with Python: nothing happens
I'm trying to learn to use Python to create dynamic web content. Problem I'm having right out the door, though, is that when I try to do a mySQL query, absolutely nothing happens. There's no error message... it looks like the script simply stops running when I import the module that enables connection to the database. This does do exactly what I'd expect when I try to run it from the command line. #!/usr/bin/python print "Content-Type: text/xml" print #if I type, for example, print "<b>test</b>" here, it appears in the browser window #msql contains the credentials for connecting to database #it is NOT in public_html import msql #no print instructions after this point are followed connex=msql.msqlConn() db=msql.MySQLdb cursor=connex.cursor(db.cursors.DictCursor) cursor.execute("SELECT * FROM userActions") #run the query xmlOutput="" rows=cursor.fetchall() #output the results for row in rows: xmlOutput+="<action>" xmlOutput+="<actionId>"+str(row["actionId"])+"</actionId>" xmlOutput+="<userId>"+str(row["userId"])+"</userId>" xmlOutput+="<actText>"+str(row["action"])+"</actText>" xmlOutput+="<date>"+str(row["dateStamp"])+"</date>" xmlOutput+="</action>" xmlOutput="<list>"+xmlOutput+"</list>" print xmlOutput This would be my first stab at this, so it merely stands to reason that this should work. I've found nothing online that would suggest otherwise, though.
[ "Please, take 24h to learn something like Django. Django has an ORM and a XML serializer that will make your life easier ensuring proper (and legal) xml, it really pays up.\n", "You can enable cgi traceback to see what happens:\nimport cgitb\ncgitb.enable()\n\n(I don't think it causes your problem, and clients un...
[ 1, 0 ]
[]
[]
[ "mysql", "python", "xml" ]
stackoverflow_0004091167_mysql_python_xml.txt
Q: a little bit of python help i need a little help here, since i am new to python, i am trying to do a nice app that can tell me if my website is down or not, then send it to twitter. class Tweet(webapp.RequestHandler): def get(self): import oauth client = oauth.TwitterClient(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, None ) webstatus = {"status": "this is where the site status need's to be", "lat": 44.42765100, "long":26.103172 } client.make_request('http://twitter.com/statuses/update.json', token=TWITTER_ACCESS_TOKEN, secret=TWITTER_ACCESS_TOKEN_SECRET, additional_params=webstatus, protected=True, method='POST' ) self.response.out.write(webstatus) def main(): application = webapp.WSGIApplication([('/', Tweet)]) util.run_wsgi_app(application) if __name__ == '__main__': main() now the check website part is missing, so i am extremely new to python and i need a little bit of help any idea of a function/class that can check a specific url and the answer/error code can be send to twitter using the upper script and i need a little bit of help at implementing url check in the script above, this is my first time interacting with python. if you are wondering, upper class uses https://github.com/mikeknapp/AppEngine-OAuth-Library lib cheers PS: the url check functionality need's to be based on urlfetch class, more safe for google appengine A: You could use Google App Engine URL Fetch API. The fetch() function returns a Response object containing the HTTP status_code. Just fetch the url and check the status with something like this: from google.appengine.api import urlfetch def is_down(url): result = urlfetch.fetch(url, method = urlfetch.HEAD) return result.status_code != 200 A: Checking if a website exists: import httplib from httplib import HTTP from urlparse import urlparse def checkUrl(url): p = urlparse(url) h = HTTP(p[1]) h.putrequest('HEAD', p[2]) h.endheaders() return h.getreply()[0] == httplib.OK We only get the header of a given URL and check the response code of the web server. Update: The last line is modified according to the remark of Daenyth.
a little bit of python help
i need a little help here, since i am new to python, i am trying to do a nice app that can tell me if my website is down or not, then send it to twitter. class Tweet(webapp.RequestHandler): def get(self): import oauth client = oauth.TwitterClient(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, None ) webstatus = {"status": "this is where the site status need's to be", "lat": 44.42765100, "long":26.103172 } client.make_request('http://twitter.com/statuses/update.json', token=TWITTER_ACCESS_TOKEN, secret=TWITTER_ACCESS_TOKEN_SECRET, additional_params=webstatus, protected=True, method='POST' ) self.response.out.write(webstatus) def main(): application = webapp.WSGIApplication([('/', Tweet)]) util.run_wsgi_app(application) if __name__ == '__main__': main() now the check website part is missing, so i am extremely new to python and i need a little bit of help any idea of a function/class that can check a specific url and the answer/error code can be send to twitter using the upper script and i need a little bit of help at implementing url check in the script above, this is my first time interacting with python. if you are wondering, upper class uses https://github.com/mikeknapp/AppEngine-OAuth-Library lib cheers PS: the url check functionality need's to be based on urlfetch class, more safe for google appengine
[ "You could use Google App Engine URL Fetch API.\nThe fetch() function returns a Response object containing the HTTP status_code.\nJust fetch the url and check the status with something like this:\nfrom google.appengine.api import urlfetch\ndef is_down(url):\n result = urlfetch.fetch(url, method = urlfetch.HEAD)\...
[ 3, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004090116_google_app_engine_python.txt
Q: Python Timers not working I have the following code: def countdown(): def countdown1(): print 'countdown1' def countdown2(): def countdown3(): takePic() self.pic.set_markup("<span size='54000'>1</span>"); print 1 t3 = Timer(1.0, countdown3) t3.start() self.pic.set_markup("<span size='54000'>2</span>"); print 2 t2 = Timer(1.0, countdown2) t2.start() self.pic.set_markup("<span size='54000'>3</span>"); print 3 t1 = Timer(1.0, countdown1) t1.start() countdown() It should show a countdown from 3. The number 3 appears, but afterwards nothing happens. help? A: Your main thread is probably exiting before any timers fire. The simplest and crudest way to fix this is to get the main thread to sleep for as long as necessary. A saner option is to signal something like a semaphore at the end of countdown3 and wait on it in the main thread. A more elegant solution, which can be integrated with a broader scheduling and asynchrony framework, is to invert the flow of control using generators: def countdown(): self.pic.set_markup("<span size='54000'>3</span>"); print 3 yield 1.0 print 'countdown1' self.pic.set_markup("<span size='54000'>2</span>"); print 2 yield 1.0 self.pic.set_markup("<span size='54000'>1</span>"); print 1 yield 1.0 takePic() for t in countdown(): time.sleep(t) A: Why not just .join() your timer threads after you .start() them, so that the rest of your code waits until the timers are done to continue? A: Are you sure some other command isn't blocking? Like set_markup? A simplified example works for me: >>> from threading import Timer >>> def lvl1(): def lvl2(): print "evaling lvl2" def lvl3(): print "evaling lvl3" print "TakePic()" print 1 t3 = Timer(1.0, lvl3) t3.start() print 2 t2 = Timer(2.0, lvl2) t2.start() >>> lvl1() 2 >>> evaling lvl2 1 evaling lvl3 TakePic()
Python Timers not working
I have the following code: def countdown(): def countdown1(): print 'countdown1' def countdown2(): def countdown3(): takePic() self.pic.set_markup("<span size='54000'>1</span>"); print 1 t3 = Timer(1.0, countdown3) t3.start() self.pic.set_markup("<span size='54000'>2</span>"); print 2 t2 = Timer(1.0, countdown2) t2.start() self.pic.set_markup("<span size='54000'>3</span>"); print 3 t1 = Timer(1.0, countdown1) t1.start() countdown() It should show a countdown from 3. The number 3 appears, but afterwards nothing happens. help?
[ "Your main thread is probably exiting before any timers fire. The simplest and crudest way to fix this is to get the main thread to sleep for as long as necessary. A saner option is to signal something like a semaphore at the end of countdown3 and wait on it in the main thread.\nA more elegant solution, which can b...
[ 2, 1, 0 ]
[]
[]
[ "multithreading", "python", "timer" ]
stackoverflow_0004092053_multithreading_python_timer.txt
Q: How can I improve my paw detection? After my previous question on finding toes within each paw, I started loading up other measurements to see how it would hold up. Unfortunately, I quickly ran into a problem with one of the preceding steps: recognizing the paws. You see, my proof of concept basically took the maximal pressure of each sensor over time and would start looking for the sum of each row, until it finds on that != 0.0. Then it does the same for the columns and as soon as it finds more than 2 rows with that are zero again. It stores the minimal and maximal row and column values to some index. As you can see in the figure, this works quite well in most cases. However, there are a lot of downsides to this approach (other than being very primitive): Humans can have 'hollow feet' which means there are several empty rows within the footprint itself. Since I feared this could happen with (large) dogs too, I waited for at least 2 or 3 empty rows before cutting off the paw. This creates a problem if another contact made in a different column before it reaches several empty rows, thus expanding the area. I figure I could compare the columns and see if they exceed a certain value, they must be separate paws. The problem gets worse when the dog is very small or walks at a higher pace. What happens is that the front paw's toes are still making contact, while the hind paw's toes just start to make contact within the same area as the front paw! With my simple script, it won't be able to split these two, because it would have to determine which frames of that area belong to which paw, while currently I would only have to look at the maximal values over all frames. Examples of where it starts going wrong: So now I'm looking for a better way of recognizing and separating the paws (after which I'll get to the problem of deciding which paw it is!). Update: I've been tinkering to get Joe's (awesome!) answer implemented, but I'm having difficulties extracting the actual paw data from my files. The coded_paws shows me all the different paws, when applied to the maximal pressure image (see above). However, the solution goes over each frame (to separate overlapping paws) and sets the four Rectangle attributes, such as coordinates or height/width. I can't figure out how to take these attributes and store them in some variable that I can apply to the measurement data. Since I need to know for each paw, what its location is during which frames and couple this to which paw it is (front/hind, left/right). So how can I use the Rectangles attributes to extract these values for each paw? I have the measurements I used in the question setup in my public Dropbox folder (example 1, example 2, example 3). For anyone interested I also set up a blog to keep you up to date :-) A: If you're just wanting (semi) contiguous regions, there's already an easy implementation in Python: SciPy's ndimage.morphology module. This is a fairly common image morphology operation. Basically, you have 5 steps: def find_paws(data, smooth_radius=5, threshold=0.0001): data = sp.ndimage.uniform_filter(data, smooth_radius) thresh = data > threshold filled = sp.ndimage.morphology.binary_fill_holes(thresh) coded_paws, num_paws = sp.ndimage.label(filled) data_slices = sp.ndimage.find_objects(coded_paws) return object_slices Blur the input data a bit to make sure the paws have a continuous footprint. (It would be more efficient to just use a larger kernel (the structure kwarg to the various scipy.ndimage.morphology functions) but this isn't quite working properly for some reason...) Threshold the array so that you have a boolean array of places where the pressure is over some threshold value (i.e. thresh = data > value) Fill any internal holes, so that you have cleaner regions (filled = sp.ndimage.morphology.binary_fill_holes(thresh)) Find the separate contiguous regions (coded_paws, num_paws = sp.ndimage.label(filled)). This returns an array with the regions coded by number (each region is a contiguous area of a unique integer (1 up to the number of paws) with zeros everywhere else)). Isolate the contiguous regions using data_slices = sp.ndimage.find_objects(coded_paws). This returns a list of tuples of slice objects, so you could get the region of the data for each paw with [data[x] for x in data_slices]. Instead, we'll draw a rectangle based on these slices, which takes slightly more work. The two animations below show your "Overlapping Paws" and "Grouped Paws" example data. This method seems to be working perfectly. (And for whatever it's worth, this runs much more smoothly than the GIF images below on my machine, so the paw detection algorithm is fairly fast...) Here's a full example (now with much more detailed explanations). The vast majority of this is reading the input and making an animation. The actual paw detection is only 5 lines of code. import numpy as np import scipy as sp import scipy.ndimage import matplotlib.pyplot as plt from matplotlib.patches import Rectangle def animate(input_filename): """Detects paws and animates the position and raw data of each frame in the input file""" # With matplotlib, it's much, much faster to just update the properties # of a display object than it is to create a new one, so we'll just update # the data and position of the same objects throughout this animation... infile = paw_file(input_filename) # Since we're making an animation with matplotlib, we need # ion() instead of show()... plt.ion() fig = plt.figure() ax = fig.add_subplot(111) fig.suptitle(input_filename) # Make an image based on the first frame that we'll update later # (The first frame is never actually displayed) im = ax.imshow(infile.next()[1]) # Make 4 rectangles that we can later move to the position of each paw rects = [Rectangle((0,0), 1,1, fc='none', ec='red') for i in range(4)] [ax.add_patch(rect) for rect in rects] title = ax.set_title('Time 0.0 ms') # Process and display each frame for time, frame in infile: paw_slices = find_paws(frame) # Hide any rectangles that might be visible [rect.set_visible(False) for rect in rects] # Set the position and size of a rectangle for each paw and display it for slice, rect in zip(paw_slices, rects): dy, dx = slice rect.set_xy((dx.start, dy.start)) rect.set_width(dx.stop - dx.start + 1) rect.set_height(dy.stop - dy.start + 1) rect.set_visible(True) # Update the image data and title of the plot title.set_text('Time %0.2f ms' % time) im.set_data(frame) im.set_clim([frame.min(), frame.max()]) fig.canvas.draw() def find_paws(data, smooth_radius=5, threshold=0.0001): """Detects and isolates contiguous regions in the input array""" # Blur the input data a bit so the paws have a continous footprint data = sp.ndimage.uniform_filter(data, smooth_radius) # Threshold the blurred data (this needs to be a bit > 0 due to the blur) thresh = data > threshold # Fill any interior holes in the paws to get cleaner regions... filled = sp.ndimage.morphology.binary_fill_holes(thresh) # Label each contiguous paw coded_paws, num_paws = sp.ndimage.label(filled) # Isolate the extent of each paw data_slices = sp.ndimage.find_objects(coded_paws) return data_slices def paw_file(filename): """Returns a iterator that yields the time and data in each frame The infile is an ascii file of timesteps formatted similar to this: Frame 0 (0.00 ms) 0.0 0.0 0.0 0.0 0.0 0.0 Frame 1 (0.53 ms) 0.0 0.0 0.0 0.0 0.0 0.0 ... """ with open(filename) as infile: while True: try: time, data = read_frame(infile) yield time, data except StopIteration: break def read_frame(infile): """Reads a frame from the infile.""" frame_header = infile.next().strip().split() time = float(frame_header[-2][1:]) data = [] while True: line = infile.next().strip().split() if line == []: break data.append(line) return time, np.array(data, dtype=np.float) if __name__ == '__main__': animate('Overlapping paws.bin') animate('Grouped up paws.bin') animate('Normal measurement.bin') Update: As far as identifying which paw is in contact with the sensor at what times, the simplest solution is to just do the same analysis, but use all of the data at once. (i.e. stack the input into a 3D array, and work with it, instead of the individual time frames.) Because SciPy's ndimage functions are meant to work with n-dimensional arrays, we don't have to modify the original paw-finding function at all. # This uses functions (and imports) in the previous code example!! def paw_regions(infile): # Read in and stack all data together into a 3D array data, time = [], [] for t, frame in paw_file(infile): time.append(t) data.append(frame) data = np.dstack(data) time = np.asarray(time) # Find and label the paw impacts data_slices, coded_paws = find_paws(data, smooth_radius=4) # Sort by time of initial paw impact... This way we can determine which # paws are which relative to the first paw with a simple modulo 4. # (Assuming a 4-legged dog, where all 4 paws contacted the sensor) data_slices.sort(key=lambda dat_slice: dat_slice[2].start) # Plot up a simple analysis fig = plt.figure() ax1 = fig.add_subplot(2,1,1) annotate_paw_prints(time, data, data_slices, ax=ax1) ax2 = fig.add_subplot(2,1,2) plot_paw_impacts(time, data_slices, ax=ax2) fig.suptitle(infile) def plot_paw_impacts(time, data_slices, ax=None): if ax is None: ax = plt.gca() # Group impacts by paw... for i, dat_slice in enumerate(data_slices): dx, dy, dt = dat_slice paw = i%4 + 1 # Draw a bar over the time interval where each paw is in contact ax.barh(bottom=paw, width=time[dt].ptp(), height=0.2, left=time[dt].min(), align='center', color='red') ax.set_yticks(range(1, 5)) ax.set_yticklabels(['Paw 1', 'Paw 2', 'Paw 3', 'Paw 4']) ax.set_xlabel('Time (ms) Since Beginning of Experiment') ax.yaxis.grid(True) ax.set_title('Periods of Paw Contact') def annotate_paw_prints(time, data, data_slices, ax=None): if ax is None: ax = plt.gca() # Display all paw impacts (sum over time) ax.imshow(data.sum(axis=2).T) # Annotate each impact with which paw it is # (Relative to the first paw to hit the sensor) x, y = [], [] for i, region in enumerate(data_slices): dx, dy, dz = region # Get x,y center of slice... x0 = 0.5 * (dx.start + dx.stop) y0 = 0.5 * (dy.start + dy.stop) x.append(x0); y.append(y0) # Annotate the paw impacts ax.annotate('Paw %i' % (i%4 +1), (x0, y0), color='red', ha='center', va='bottom') # Plot line connecting paw impacts ax.plot(x,y, '-wo') ax.axis('image') ax.set_title('Order of Steps') A: I'm no expert in image detection, and I don't know Python, but I'll give it a whack... To detect individual paws, you should first only select everything with a pressure greater than some small threshold, very close to no pressure at all. Every pixel/point that is above this should be "marked." Then, every pixel adjacent to all "marked" pixels becomes marked, and this process is repeated a few times. Masses that are totally connected would be formed, so you have distinct objects. Then, each "object" has a minimum and maximum x and y value, so bounding boxes can be packed neatly around them. Pseudocode: (MARK) ALL PIXELS ABOVE (0.5) (MARK) ALL PIXELS (ADJACENT) TO (MARK) PIXELS REPEAT (STEP 2) (5) TIMES SEPARATE EACH TOTALLY CONNECTED MASS INTO A SINGLE OBJECT MARK THE EDGES OF EACH OBJECT, AND CUT APART TO FORM SLICES. That should about do it. A: Note: I say pixel, but this could be regions using an average of the pixels. Optimization is another issue... Sounds like you need to analyze a function (pressure over time) for each pixel and determine where the function turns (when it changes > X in the other direction it is considered a turn to counter errors). If you know at what frames it turns, you will know the frame where the pressure was the most hard and you will know where it was the least hard between the two paws. In theory, you then would know the two frames where the paws pressed the most hard and can calculate an average of those intervals. after which I'll get to the problem of deciding which paw it is! This is the same tour as before, knowing when each paw applies the most pressure helps you decide.
How can I improve my paw detection?
After my previous question on finding toes within each paw, I started loading up other measurements to see how it would hold up. Unfortunately, I quickly ran into a problem with one of the preceding steps: recognizing the paws. You see, my proof of concept basically took the maximal pressure of each sensor over time and would start looking for the sum of each row, until it finds on that != 0.0. Then it does the same for the columns and as soon as it finds more than 2 rows with that are zero again. It stores the minimal and maximal row and column values to some index. As you can see in the figure, this works quite well in most cases. However, there are a lot of downsides to this approach (other than being very primitive): Humans can have 'hollow feet' which means there are several empty rows within the footprint itself. Since I feared this could happen with (large) dogs too, I waited for at least 2 or 3 empty rows before cutting off the paw. This creates a problem if another contact made in a different column before it reaches several empty rows, thus expanding the area. I figure I could compare the columns and see if they exceed a certain value, they must be separate paws. The problem gets worse when the dog is very small or walks at a higher pace. What happens is that the front paw's toes are still making contact, while the hind paw's toes just start to make contact within the same area as the front paw! With my simple script, it won't be able to split these two, because it would have to determine which frames of that area belong to which paw, while currently I would only have to look at the maximal values over all frames. Examples of where it starts going wrong: So now I'm looking for a better way of recognizing and separating the paws (after which I'll get to the problem of deciding which paw it is!). Update: I've been tinkering to get Joe's (awesome!) answer implemented, but I'm having difficulties extracting the actual paw data from my files. The coded_paws shows me all the different paws, when applied to the maximal pressure image (see above). However, the solution goes over each frame (to separate overlapping paws) and sets the four Rectangle attributes, such as coordinates or height/width. I can't figure out how to take these attributes and store them in some variable that I can apply to the measurement data. Since I need to know for each paw, what its location is during which frames and couple this to which paw it is (front/hind, left/right). So how can I use the Rectangles attributes to extract these values for each paw? I have the measurements I used in the question setup in my public Dropbox folder (example 1, example 2, example 3). For anyone interested I also set up a blog to keep you up to date :-)
[ "If you're just wanting (semi) contiguous regions, there's already an easy implementation in Python: SciPy's ndimage.morphology module. This is a fairly common image morphology operation. \n\nBasically, you have 5 steps:\ndef find_paws(data, smooth_radius=5, threshold=0.0001):\n data = sp.ndimage.uniform_filter...
[ 363, 5, 1 ]
[]
[]
[ "image_processing", "python" ]
stackoverflow_0004087919_image_processing_python.txt
Q: py2exe error when compiling i was made some python script and i want to make this script to exe file. but when compiling this script to exe, some error encounter i was try to resolve this problem but no luck. following is script source if anyone can help me really much appreciate! # -*- coding: utf-8 -*- import lxml,cookielib,urllib,configobj,sys,getopt,string,mechanize,time,os from lxml import etree from lxml.html import parse, fromstring import sys, getopt, string import lxml.html br = mechanize.Browser() cj = cookielib.LWPCookieJar() br.set_cookiejar(cj) br.set_handle_equiv(True) br.set_handle_gzip(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) # Follows refresh 0 but not hangs on refresh > 0 br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) # Want debugging messages? br.set_debug_http(False) br.set_debug_redirects(False) br.set_debug_responses(False) # User-Agent (this is cheating, ok?) br.addheaders = [('User-agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)')] SAVEFILE= 'betextract.txt' post_count = 0 mac = '' def getMacAddress(): if sys.platform == 'win32': for line in os.popen("ipconfig /all"): if line.lstrip().startswith('Physical Address'): mac = line.split(':')[1].strip().replace('-',':') break else: for line in os.popen("/sbin/ifconfig"): if line.find('Ether') > -1: mac = line.split()[4] break return mac print mac getMacAddress() print mac def safeunicode(s): s = str(s).decode('utf-8') try: return s.encode('euc-kr').decode('cp949') except UnicodeDecodeError: return s #check_demo() #from configobj import ConfigObj Template 화일 불러오기 ini config = configobj.ConfigObj('config.ini') section1 = config['NAVERPASS'] section2 = config['NAVERID'] section3 = config['Nblogkeyword'] section4 = config['end_line'] section5 = config['Content'] section6 = config['HongboSubject'] section7 = config['HongboBody'] NAVERPASS = section1['NAVERPASS'] NAVERID = section2['NAVERID'] Nblogkeyword = section3['Nblogkeyword'] end_line = section4['end_line'] Content = section5['Content'] HongboSubject = section6['HongboSubject'] HongboBody = section7['HongboBody'] enkw = str(Nblogkeyword).decode('cp949') #아래부분에서 빼기를 위한 int로 변환 end_line = int(section4['end_line']) start_line = 0 while end_line: #end_line = end_line - 9 form = { 'where': 'post', 'sm' : 'ab_pge', 'query' : enkw, 'st' : 'sim', 'date_option' : '-1', 'date_from' : '', 'date_to' : '', 'dup_remove' : '1', 'post_blogid' : '', 'post_blogurl' : '', 'post_blogurl_without' : '', 'detail_and_query' : '', 'detail_not_query' : '', 'detail_or_query' : '' , 'detail_udp_query' : '', 'srchby' : 'all', 'nso' : 'so%3Ar%2Ca%3Aall%2Cp%3A', 'ie' : 'utf8', 'start' : start_line } qstring = urllib.urlencode(form) f = urllib.urlopen('http://cafeblog.search.naver.com/search.naver?%s' %qstring) html = f.read() f.close() start_line += 10 end_line = end_line - 10 s= [] html = lxml.html.fromstring(html) save = open(SAVEFILE, 'w+') for content in html.cssselect('li.sh_blog_top'): try: subject = content.cssselect('dl dt a.sh_blog_title b')[0].text_content() body = content.cssselect('dl dd.sh_blog_passage')[0].text_content() print u'[+추출중+] %s | %s ' %(subject , body) chen = '%s|%s' %(subject, body) #중요 이런식으로 처리를 해야함 꼭 인코딩! title2 = chen.encode('cp949') save.write(title2 + '\n') except Exception, err: sys.stderr.write(u'에러발생 => 에러 자동처리중... %s\n' % str(err)) content = '' break save.close() #print subject , body #s.append(subject) #s.append(body) #print '|'.join(s) ## Show the response headers #print br.info() ## or ##print br.response().info() #for link in br.links(): #print link br.open('http://nid.naver.com/nidlogin.login') #for f in br.forms(): #print f br.select_form(nr=0) br.form['id']=NAVERID br.form['pw']=NAVERPASS #br.click(type="submit", nr=0) #print br.forms() #br.submit(name="URL", nr=0) #html = br.response().read() #print html br.form.action='https://nid.naver.com/nidlogin.login' #javascript source analysis!! have to find inside javascript source br.submit() html = br.response().read() #decoded = br.response().read().decode('utf-8') #print html br.open('http://m.blog.naver.com/') save = open(SAVEFILE) for line in save: sub = line.split('|')[0] con = line.split('|')[1].replace('\n', '') #print sub, con br.open('http://m.blog.naver.com/PostWriteForm.nhn?blogId=ylgwn&categoryNo=') #print br.response().read() #for f in br.forms(): #print f br.select_form(nr=0) entest = "%s" %(sub) br.form['post.title']= sub.decode('cp949') + HongboSubject.decode('cp949') br.form['post.contents.contentsValue']= con.decode('cp949') + HongboBody.decode('cp949') #req = br.click_link(text=u'확인') #br.open(req) #br.form.click(kind="clickable") #for link in br.links(): #print link #br.follow_link(nr=1 #br.follow_link(text=u"확인") #req = br.click(type="submit") #br.open(req) br.form.action='http://m.blog.naver.com/PostWrite.nhn' br.submit() post_count += 1 print str(post_count ) +u'개 글올리기 성공!!' save.close() print u'블로그 글올리기 완료!' A: Looks to me like you're printing gzipped data to the command line. Possibly because the data returned by the server is not being decompressed by urllib when it is compiled to an exe. Try manually removing the Accept-Encoding header, this would prevent the server from returning compressed data and prevent your script from failing. You might also want to try urllib2 or another solution to download the data from the web.
py2exe error when compiling
i was made some python script and i want to make this script to exe file. but when compiling this script to exe, some error encounter i was try to resolve this problem but no luck. following is script source if anyone can help me really much appreciate! # -*- coding: utf-8 -*- import lxml,cookielib,urllib,configobj,sys,getopt,string,mechanize,time,os from lxml import etree from lxml.html import parse, fromstring import sys, getopt, string import lxml.html br = mechanize.Browser() cj = cookielib.LWPCookieJar() br.set_cookiejar(cj) br.set_handle_equiv(True) br.set_handle_gzip(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) # Follows refresh 0 but not hangs on refresh > 0 br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) # Want debugging messages? br.set_debug_http(False) br.set_debug_redirects(False) br.set_debug_responses(False) # User-Agent (this is cheating, ok?) br.addheaders = [('User-agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)')] SAVEFILE= 'betextract.txt' post_count = 0 mac = '' def getMacAddress(): if sys.platform == 'win32': for line in os.popen("ipconfig /all"): if line.lstrip().startswith('Physical Address'): mac = line.split(':')[1].strip().replace('-',':') break else: for line in os.popen("/sbin/ifconfig"): if line.find('Ether') > -1: mac = line.split()[4] break return mac print mac getMacAddress() print mac def safeunicode(s): s = str(s).decode('utf-8') try: return s.encode('euc-kr').decode('cp949') except UnicodeDecodeError: return s #check_demo() #from configobj import ConfigObj Template 화일 불러오기 ini config = configobj.ConfigObj('config.ini') section1 = config['NAVERPASS'] section2 = config['NAVERID'] section3 = config['Nblogkeyword'] section4 = config['end_line'] section5 = config['Content'] section6 = config['HongboSubject'] section7 = config['HongboBody'] NAVERPASS = section1['NAVERPASS'] NAVERID = section2['NAVERID'] Nblogkeyword = section3['Nblogkeyword'] end_line = section4['end_line'] Content = section5['Content'] HongboSubject = section6['HongboSubject'] HongboBody = section7['HongboBody'] enkw = str(Nblogkeyword).decode('cp949') #아래부분에서 빼기를 위한 int로 변환 end_line = int(section4['end_line']) start_line = 0 while end_line: #end_line = end_line - 9 form = { 'where': 'post', 'sm' : 'ab_pge', 'query' : enkw, 'st' : 'sim', 'date_option' : '-1', 'date_from' : '', 'date_to' : '', 'dup_remove' : '1', 'post_blogid' : '', 'post_blogurl' : '', 'post_blogurl_without' : '', 'detail_and_query' : '', 'detail_not_query' : '', 'detail_or_query' : '' , 'detail_udp_query' : '', 'srchby' : 'all', 'nso' : 'so%3Ar%2Ca%3Aall%2Cp%3A', 'ie' : 'utf8', 'start' : start_line } qstring = urllib.urlencode(form) f = urllib.urlopen('http://cafeblog.search.naver.com/search.naver?%s' %qstring) html = f.read() f.close() start_line += 10 end_line = end_line - 10 s= [] html = lxml.html.fromstring(html) save = open(SAVEFILE, 'w+') for content in html.cssselect('li.sh_blog_top'): try: subject = content.cssselect('dl dt a.sh_blog_title b')[0].text_content() body = content.cssselect('dl dd.sh_blog_passage')[0].text_content() print u'[+추출중+] %s | %s ' %(subject , body) chen = '%s|%s' %(subject, body) #중요 이런식으로 처리를 해야함 꼭 인코딩! title2 = chen.encode('cp949') save.write(title2 + '\n') except Exception, err: sys.stderr.write(u'에러발생 => 에러 자동처리중... %s\n' % str(err)) content = '' break save.close() #print subject , body #s.append(subject) #s.append(body) #print '|'.join(s) ## Show the response headers #print br.info() ## or ##print br.response().info() #for link in br.links(): #print link br.open('http://nid.naver.com/nidlogin.login') #for f in br.forms(): #print f br.select_form(nr=0) br.form['id']=NAVERID br.form['pw']=NAVERPASS #br.click(type="submit", nr=0) #print br.forms() #br.submit(name="URL", nr=0) #html = br.response().read() #print html br.form.action='https://nid.naver.com/nidlogin.login' #javascript source analysis!! have to find inside javascript source br.submit() html = br.response().read() #decoded = br.response().read().decode('utf-8') #print html br.open('http://m.blog.naver.com/') save = open(SAVEFILE) for line in save: sub = line.split('|')[0] con = line.split('|')[1].replace('\n', '') #print sub, con br.open('http://m.blog.naver.com/PostWriteForm.nhn?blogId=ylgwn&categoryNo=') #print br.response().read() #for f in br.forms(): #print f br.select_form(nr=0) entest = "%s" %(sub) br.form['post.title']= sub.decode('cp949') + HongboSubject.decode('cp949') br.form['post.contents.contentsValue']= con.decode('cp949') + HongboBody.decode('cp949') #req = br.click_link(text=u'확인') #br.open(req) #br.form.click(kind="clickable") #for link in br.links(): #print link #br.follow_link(nr=1 #br.follow_link(text=u"확인") #req = br.click(type="submit") #br.open(req) br.form.action='http://m.blog.naver.com/PostWrite.nhn' br.submit() post_count += 1 print str(post_count ) +u'개 글올리기 성공!!' save.close() print u'블로그 글올리기 완료!'
[ "Looks to me like you're printing gzipped data to the command line. Possibly because the data returned by the server is not being decompressed by urllib when it is compiled to an exe.\nTry manually removing the Accept-Encoding header, this would prevent the server from returning compressed data and prevent your scr...
[ 1 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0004052385_py2exe_python.txt
Q: Creating aliases for Python packages? I have a directory, let's call it Storage full of packages with unwieldy names like mypackage-xxyyzzww, and of course Storage is on my PYTHONPATH. Since packages have long unmemorable names, all of the packages are symlinked to friendlier names, such as mypackage. Now, I don't want to rely on file system symbolic links to do this, instead I tried mucking around with sys.path and sys.modules. Currently I'm doing something like this: import imp imp.load_package('mypackage', 'Storage/mypackage-xxyyzzww') How bad is it to do things this way, and is there a chance this will break in the future? One funny thing is that there's even no mention of imp.load_package function in the docs. EDIT: besides not relying on symbolic links, I can't use PYTHONPATH variable anymore. A: Instead of using imp, you can assign different names to imported modules. import mypackage_xxyyzzww as mypackage If you then create a __init__.py file inside of Storage, you can add several of the above lines to make importing easier. Storage/__init__.py: import mypackage_xxyyzzww as mypackage import otherpackage_xxyyzzww as otherpackage Interpreter: >>> from Storage import mypackage, otherpackage A: importlib may be more appropriate, as it uses/implements the PEP302 mechanism. Follow the DictImporter example, but override find_module to find the real filename and store it in the dict, then override load_module to get the code from the found file. You shouldn't need to use sys.path once you've created your Storage module #from importlib import abc import imp import os import sys import logging logging.basicConfig(level=logging.DEBUG) dprint = logging.debug class MyImporter(object): def __init__(self,path): self.path=path self.names = {} def find_module(self,fullname,path=None): dprint("find_module({fullname},{path})".format(**locals())) ml = imp.find_module(fullname,path) dprint(repr(ml)) raise ImportError def load_module(self,fullname): dprint("load_module({fullname})".format(**locals())) return imp.load_module(fullname) raise ImportError def load_storage( path, modname=None ): if modname is None: modname = os.path.basename(path) mod = imp.new_module(modname) sys.modules[modname] = mod assert mod.__name__== modname mod.__path__=[path] #sys.meta_path.append(MyImporter(path)) mod.__loader__= MyImporter(path) return mod if __name__=="__main__": load_storage("arbitrary-path-to-code/Storage") from Storage import plain from Storage import mypkg Then when you import Storage.mypackage, python will immediately use your importer without bothering to look on sys.path That doesn't work. The code above does work to import ordinary modules under Storage without requiring Storage to be on sys.path, but both 3.1 and 2.6 seem to ignore the loader attribute mentioned in PEP302. If I uncomment the sys.meta_path line, 3.1 dies with StackOverflow, and 2.6 dies with ImportError. hmmm... I'm out of time now, but may look at it later. A: Packages are just entries in the namespace. You should not name your path components with anything that is not a legal python variable name.
Creating aliases for Python packages?
I have a directory, let's call it Storage full of packages with unwieldy names like mypackage-xxyyzzww, and of course Storage is on my PYTHONPATH. Since packages have long unmemorable names, all of the packages are symlinked to friendlier names, such as mypackage. Now, I don't want to rely on file system symbolic links to do this, instead I tried mucking around with sys.path and sys.modules. Currently I'm doing something like this: import imp imp.load_package('mypackage', 'Storage/mypackage-xxyyzzww') How bad is it to do things this way, and is there a chance this will break in the future? One funny thing is that there's even no mention of imp.load_package function in the docs. EDIT: besides not relying on symbolic links, I can't use PYTHONPATH variable anymore.
[ "Instead of using imp, you can assign different names to imported modules.\nimport mypackage_xxyyzzww as mypackage\n\nIf you then create a __init__.py file inside of Storage, you can add several of the above lines to make importing easier.\nStorage/__init__.py:\nimport mypackage_xxyyzzww as mypackage\nimport otherp...
[ 10, 4, 0 ]
[]
[]
[ "package", "python" ]
stackoverflow_0004090945_package_python.txt
Q: Why does setting a default parameter value make this function a closure? I'm writing an application where Tags are linkable and there's a need to retrieve the entire chain of linked Tags. Self-reference is not allowed. Running the following code ends up with some very strange results: class Tag(object): def __init__(self, name): self.name = name self.links = [] def __repr__(self): return "<Tag {0}>".format(self.name) def link(self, tag): self.links.append(tag) def tag_chain(tag, known=[]): chain = [] if tag not in known: known.append(tag) print "Known: {0}".format(known) for link in tag.links: if link in known: continue else: known.append(link) chain.append(link) chain.extend(tag_chain(link, known)) return chain a = Tag("a") b = Tag("b") c = Tag("c") a.link(b) b.link(c) c.link(a) o = tag_chain(a) print "Result:", o print "------------------" o = tag_chain(a) print "Result:", o Results: Known: [<Tag a>] Known: [<Tag a>, <Tag b>] Known: [<Tag a>, <Tag b>, <Tag c>] Result: [<Tag b>, <Tag c>] ------------------ Known: [<Tag a>, <Tag b>, <Tag c>] Result: [] So, somehow, I've accidentally created a closure. As far as I can see, known should have gone out of scope and died off once the function call completed. If I change the definition of chain_tags() to not set a default value, the problem goes away: ... def tag_chain(tag, known): ... o = tag_chain(a, []) print "Result:", o print "------------------" o = tag_chain(a, []) print "Result:", o Why is this? A: This is a common mistake in Python: def tag_chain(tag, known=[]): # ... known=[] doesn't mean that if known is unsupplied, make it an empty list; in fact, it binds known to an "anonymous" list. Each time that known defaults to that list, it is the same list. The typical pattern to do what you intended here, is: def tag_chain(tag, known=None): if known is None: known = [] # ... which correctly initializes known to an empty list if it is not provided. A: Maybe as an extra eplanation what happens: Default parameters are simply stored on the function object itself (ie tag_chain.func_defaults in Py2 ) and used to extend the argument when needed: >>> def x(a=['here']): ... a.append(a[-1]*2) ... >>> x <function x at 0x0053DB70> >>> x.func_defaults (['here'],) In this example you can watch the default list grow there: >>> x() >>> x.func_defaults (['here', 'herehere'],) >>> x() >>> x.func_defaults (['here', 'herehere', 'herehereherehere'],) Modifying default arguments is somewhat like changing class variables.
Why does setting a default parameter value make this function a closure?
I'm writing an application where Tags are linkable and there's a need to retrieve the entire chain of linked Tags. Self-reference is not allowed. Running the following code ends up with some very strange results: class Tag(object): def __init__(self, name): self.name = name self.links = [] def __repr__(self): return "<Tag {0}>".format(self.name) def link(self, tag): self.links.append(tag) def tag_chain(tag, known=[]): chain = [] if tag not in known: known.append(tag) print "Known: {0}".format(known) for link in tag.links: if link in known: continue else: known.append(link) chain.append(link) chain.extend(tag_chain(link, known)) return chain a = Tag("a") b = Tag("b") c = Tag("c") a.link(b) b.link(c) c.link(a) o = tag_chain(a) print "Result:", o print "------------------" o = tag_chain(a) print "Result:", o Results: Known: [<Tag a>] Known: [<Tag a>, <Tag b>] Known: [<Tag a>, <Tag b>, <Tag c>] Result: [<Tag b>, <Tag c>] ------------------ Known: [<Tag a>, <Tag b>, <Tag c>] Result: [] So, somehow, I've accidentally created a closure. As far as I can see, known should have gone out of scope and died off once the function call completed. If I change the definition of chain_tags() to not set a default value, the problem goes away: ... def tag_chain(tag, known): ... o = tag_chain(a, []) print "Result:", o print "------------------" o = tag_chain(a, []) print "Result:", o Why is this?
[ "This is a common mistake in Python:\ndef tag_chain(tag, known=[]):\n # ...\n\nknown=[] doesn't mean that if known is unsupplied, make it an empty list; in fact, it binds known to an \"anonymous\" list. Each time that known defaults to that list, it is the same list.\nThe typical pattern to do what you intended h...
[ 9, 3 ]
[]
[]
[ "closures", "python", "recursion" ]
stackoverflow_0004092233_closures_python_recursion.txt
Q: Running python 64 with shebang (#!) on Mac I use python 64bit as follows. alias python64='arch -x86_64 /usr/bin/python2.6' How can I run python 64bit mode with shebang(#!)? ??? #!/usr/bin/python2.6 ??? A: #!/path/to/arch -x86_64 /usr/bin/python2.6 I dont have a mac to test right now, but usually in *nix you can find the path to an executable using: which arch A: In OS X 10.6 arch is /usr/bin/arch, so your line is #!/usr/bin/arch -x86_64 /usr/bin/python2.6 In general, if you don't know the path you can always use the env command in the shebang as shown here, which is guaranteed to be in /usr/bin. So, #!/usr/bin/env arch -x86_64 /usr/bin/python2.6 will also work.
Running python 64 with shebang (#!) on Mac
I use python 64bit as follows. alias python64='arch -x86_64 /usr/bin/python2.6' How can I run python 64bit mode with shebang(#!)? ??? #!/usr/bin/python2.6 ???
[ "#!/path/to/arch -x86_64 /usr/bin/python2.6\n\nI dont have a mac to test right now, but usually in *nix you can find the path to an executable using:\nwhich arch\n\n", "In OS X 10.6 arch is /usr/bin/arch, so your line is\n#!/usr/bin/arch -x86_64 /usr/bin/python2.6\n\nIn general, if you don't know the path you can...
[ 1, 1 ]
[]
[]
[ "64_bit", "python", "shebang" ]
stackoverflow_0004092497_64_bit_python_shebang.txt
Q: Reportlab PDF version generation problems I am using reportlab PDF package with platypus to generate some PDF files. On linux server and on windows box I have the same python application, same version of reportlab package (although slightly different python version - 2.6.5 vs 2.6.6). I am using my own fonts, I do not depend on system fonts. Lately, I have noticed that PDF generated on these two platforms are a bit different - some paragraphs are a few points vertically up in one version compared to the other version. I was trying to found what is the difference between these plaforms, but I have failed to find difference. Finally, when I compare PDF files, one file is PDF 1.3 and second is PDF 1.4 version so I think that problem must be this. I am not aware of any option how to set PDF version in reportlab, please can anyone point me out how to set proper version of generated PDF file, or maybe to set some additional properties of reportlab output? UPDATE: using reportlab version 2.4: reportlab.__version__: $Id: __init__.py 3649 2010-01-20 14:45:53Z damian $ A: Are you attempting to generate them with the exact code on each system? I did a quick search in the reportlab source code and found some comments stating that if you utilize the setFillAlpha or setStrokeAlpha methods then it will cause a PDF 1.4 to be generated instead of 1.3. Edit: Looking further, I'm fairly certain that these methods are the only reason reportlab would ever generate a PDF 1.4 file. It seems to always default to 1.3 otherwise. As far as I can see there is no interface which would allow you to switch versions. However, you could modify the source pretty easily to do so. Just search for pdfdoc.py and change this line (It is around line 85 in reportlab 2.5) from PDF_VERSION_DEFAULT = (1, 3) to PDF_VERSION_DEFAULT = (1, 4) This will force it to always generate PDF 1.4 documents. Hope this helps.
Reportlab PDF version generation problems
I am using reportlab PDF package with platypus to generate some PDF files. On linux server and on windows box I have the same python application, same version of reportlab package (although slightly different python version - 2.6.5 vs 2.6.6). I am using my own fonts, I do not depend on system fonts. Lately, I have noticed that PDF generated on these two platforms are a bit different - some paragraphs are a few points vertically up in one version compared to the other version. I was trying to found what is the difference between these plaforms, but I have failed to find difference. Finally, when I compare PDF files, one file is PDF 1.3 and second is PDF 1.4 version so I think that problem must be this. I am not aware of any option how to set PDF version in reportlab, please can anyone point me out how to set proper version of generated PDF file, or maybe to set some additional properties of reportlab output? UPDATE: using reportlab version 2.4: reportlab.__version__: $Id: __init__.py 3649 2010-01-20 14:45:53Z damian $
[ "Are you attempting to generate them with the exact code on each system? I did a quick search in the reportlab source code and found some comments stating that if you utilize the setFillAlpha or setStrokeAlpha methods then it will cause a PDF 1.4 to be generated instead of 1.3.\nEdit:\nLooking further, I'm fairly c...
[ 1 ]
[]
[]
[ "pdf_generation", "python", "reportlab" ]
stackoverflow_0004091043_pdf_generation_python_reportlab.txt
Q: Passing strings[]'s as byte[] I'm working on a network in which my python script will communicate with my java application. The python script is passing a DataPacket (just a packet that holds some strings and a little other data) to the java server for processing. I know how to pack the information into a byte array, but how do I unpack it to be used as strings? What I've got so far is I have to parse the arrays of data in the packet and send it in bits and pieces. Is this the only way to do this? Can I use ByteInputStream and if so how? thanks ~Aedon A: I'm not sure that what you're doing is quite right, in that you're fragmenting your strings into separate packets. This could cause problems with multibyte strings. However, you may wish to check out ByteArrayOutputStream. You can write into this, then convert to a String using toString(enc), where enc is the encoding you've used in your Python to convert your strings into bytes in the first place. Looking at your comment below, it appears you need some means to serialise in Python and deserialise in Java. Leaving aside solutions like XML serialisation, have you looked at possible solutions like Google Protocol Buffers ?
Passing strings[]'s as byte[]
I'm working on a network in which my python script will communicate with my java application. The python script is passing a DataPacket (just a packet that holds some strings and a little other data) to the java server for processing. I know how to pack the information into a byte array, but how do I unpack it to be used as strings? What I've got so far is I have to parse the arrays of data in the packet and send it in bits and pieces. Is this the only way to do this? Can I use ByteInputStream and if so how? thanks ~Aedon
[ "I'm not sure that what you're doing is quite right, in that you're fragmenting your strings into separate packets. This could cause problems with multibyte strings.\nHowever, you may wish to check out ByteArrayOutputStream. You can write into this, then convert to a String using toString(enc), where enc is the enc...
[ 1 ]
[]
[]
[ "byte", "inputstream", "java", "networking", "python" ]
stackoverflow_0004092604_byte_inputstream_java_networking_python.txt
Q: Python - BeautifulSoup html parsing handle gbk encoding poorly - Chinese webscraping problem I have been tinkering with the following script: # -*- coding: utf8 -*- import codecs from BeautifulSoup import BeautifulSoup, NavigableString, UnicodeDammit import urllib2,sys import time try: import timeoutsocket # http://www.timo-tasi.org/python/timeoutsocket.py timeoutsocket.setDefaultSocketTimeout(10) except ImportError: pass h=u'\u3000\u3000\u4fe1\u606f\u901a\u4fe1\u6280\u672f' address=urllib2.urlopen('http://stock.eastmoney.com/news/1408,20101022101395594.html').read() soup=BeautifulSoup(address) p=soup.findAll('p') t=p[2].string[:10] with the following output: print t ¡¡¡¡ÐÅϢͨ print h   信息通 t u'\xa1\xa1\xa1\xa1\xd0\xc5\xcf\xa2\xcd\xa8' h u'\u3000\u3000\u4fe1\u606f\u901a' h.encode('gbk') '\xa1\xa1\xa1\xa1\xd0\xc5\xcf\xa2\xcd\xa8' Simply put: When I pass in this html through BeautifulSoup, it takes the gbk encoded text and thinks that it is unicode, not recognizing that it needs to be decoded first. "h" and "t" should be the same, however, as h is just me taking the text from the html file and converting it manually. how do I solve this problem? best wheaton A: The file's meta tag claims that the character set is GB2312, but the data contains a character from the newer GBK/GB18030 and this is what's tripping BeautifulSoup up: simon@lucifer:~$ python Python 2.7 (r27:82508, Jul 3 2010, 21:12:11) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import urllib2 >>> data = urllib2.urlopen('http://stock.eastmoney.com/news/1408,20101022101395594.html').read() >>> data.decode("gb2312") Traceback (most recent call last): File "", line 1, in UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 20148-20149: illegal multibyte sequence At this point, UnicodeDammit bails out, tries chardet, UTF-8 and finally Windows-1252, which always succeeds - this is what you got, by the looks of it. If we tell the decoder to replace unrecognised characters with a '?', we can see the character that's missing in GB2312: >>> print data[20140:20160].decode("gb2312", "replace") 毒尾气二�英的排放难 Using the correct encoding: >>> print data[20140:20160].decode("gb18030", "replace") 毒尾气二噁英的排放难 >>> from BeautifulSoup import BeautifulSoup >>> s = BeautifulSoup(data, fromEncoding="gb18030") >>> print s.findAll("p")[2].string[:10]   信息通信技术是& Also: >>> print s.findAll("p")[2].string   信息通信技术是&ldquo;十二五&rdquo;规划重点发展方向,行业具有很强的内在增长潜 力,增速远高于GDP。软件外包、服务外包、管理软件、车载导航、网上购物、网络游戏、 移动办公、移动网络游戏、网络视频等均存在很强的潜在需求,使信息技术行业继续保持较 高增长。
Python - BeautifulSoup html parsing handle gbk encoding poorly - Chinese webscraping problem
I have been tinkering with the following script: # -*- coding: utf8 -*- import codecs from BeautifulSoup import BeautifulSoup, NavigableString, UnicodeDammit import urllib2,sys import time try: import timeoutsocket # http://www.timo-tasi.org/python/timeoutsocket.py timeoutsocket.setDefaultSocketTimeout(10) except ImportError: pass h=u'\u3000\u3000\u4fe1\u606f\u901a\u4fe1\u6280\u672f' address=urllib2.urlopen('http://stock.eastmoney.com/news/1408,20101022101395594.html').read() soup=BeautifulSoup(address) p=soup.findAll('p') t=p[2].string[:10] with the following output: print t ¡¡¡¡ÐÅϢͨ print h   信息通 t u'\xa1\xa1\xa1\xa1\xd0\xc5\xcf\xa2\xcd\xa8' h u'\u3000\u3000\u4fe1\u606f\u901a' h.encode('gbk') '\xa1\xa1\xa1\xa1\xd0\xc5\xcf\xa2\xcd\xa8' Simply put: When I pass in this html through BeautifulSoup, it takes the gbk encoded text and thinks that it is unicode, not recognizing that it needs to be decoded first. "h" and "t" should be the same, however, as h is just me taking the text from the html file and converting it manually. how do I solve this problem? best wheaton
[ "The file's meta tag claims that the character set is GB2312, but the data contains a character from the newer GBK/GB18030 and this is what's tripping BeautifulSoup up:\n\nsimon@lucifer:~$ python\nPython 2.7 (r27:82508, Jul 3 2010, 21:12:11) \n[GCC 4.0.1 (Apple Inc. build 5493)] on darwin\nType \"help\", \"copyrig...
[ 5 ]
[]
[]
[ "beautifulsoup", "python", "unicode", "unicode_string", "web_scraping" ]
stackoverflow_0004092606_beautifulsoup_python_unicode_unicode_string_web_scraping.txt
Q: subclassing float to force fixed point printing precision in python [Python 3.1] I'm following up on this answer: class prettyfloat(float): def __repr__(self): return "%0.2f" % self I know I need to keep track of my float literals (i.e., replace 3.0 with prettyfloat(3.0), etc.), and that's fine. But whenever I do any calculations, prettyfloat objects get converted into float. What's the easiest way to fix it? EDIT: I need exactly two decimal digits; and I need it across the whole code, including where I print a dictionary with float values inside. That makes any formatting functions hard to use. I can't use Decimal global setting, since I want computations to be at full precision (just printing at 2 decimal points). @Glenn Maynard: I agree I shouldn't override __repr__; if anything, it would be just __str__. But it's a moot point because of the following point. @Glenn Maynard and @singularity: I won't subclass float, since I agree it will look very ugly in the end. I will stop trying to be clever, and just call a function everywhere a float is being printed. Though I am really sad that I can't override __str__ in the builtin class float. Thank you! A: I had a look at the answer you followed up on, and I think you're confusing data and its representation. @Robert Rossney suggested to subclass float so you could map() an iterable of standard, non-adulterated floats into prettyfloats for display purposes: # Perform all our computations using standard floats. results = compute_huge_numbers(42) # Switch to prettyfloats for printing. print(map(prettyfloat, results)) In other words, you were not supposed to (and you shouldn't) use prettyfloat as a replacement for float everywhere in your code. Of course, inheriting from float to solve that problem is overkill, since it's a representation problem and not a data problem. A simple function would be enough: def prettyfloat(number): return "%0.2f" % number # Works the same. Now, if it's not about representation after all, and what you actually want to achieve is fixed-point computations limited to two decimal places everywhere in your code, that's another story entirely. A: that because prettyfloat (op) prettyfloat don't return a prettyfloat example: >>> prettyfloat(0.6) 0.60 # type prettyfloat >>> prettyfloat(0.6) + prettyfloat(4.4) 5.0 # type float solution if you don't want to cast every operation result manually to prettyfloat and if you still want to use prettyfloat is to override all operators. example with operator __add__ (which is ugly) class prettyfloat(float): def __repr__(self): return "%0.2f" % self def __add__(self, other): return prettyfloat(float(self) + other) >>> prettyfloat(0.6) + prettyfloat(4.4) 5.00 by doing this i think you will have also to change the name from prettyfloat to uglyfloat :) , Hope this will help A: Use decimal. This is what it's for. >>> import decimal >>> decimal.getcontext().prec = 2 >>> one = decimal.Decimal("1.0") >>> three = decimal.Decimal("3.0") >>> one / three Decimal('0.33') ...unless you actually want to work with full-precision floats everywhere in your code but print them rounded to two decimal places. In that case, you need to rewrite your printing logic.
subclassing float to force fixed point printing precision in python
[Python 3.1] I'm following up on this answer: class prettyfloat(float): def __repr__(self): return "%0.2f" % self I know I need to keep track of my float literals (i.e., replace 3.0 with prettyfloat(3.0), etc.), and that's fine. But whenever I do any calculations, prettyfloat objects get converted into float. What's the easiest way to fix it? EDIT: I need exactly two decimal digits; and I need it across the whole code, including where I print a dictionary with float values inside. That makes any formatting functions hard to use. I can't use Decimal global setting, since I want computations to be at full precision (just printing at 2 decimal points). @Glenn Maynard: I agree I shouldn't override __repr__; if anything, it would be just __str__. But it's a moot point because of the following point. @Glenn Maynard and @singularity: I won't subclass float, since I agree it will look very ugly in the end. I will stop trying to be clever, and just call a function everywhere a float is being printed. Though I am really sad that I can't override __str__ in the builtin class float. Thank you!
[ "I had a look at the answer you followed up on, and I think you're confusing data and its representation.\n@Robert Rossney suggested to subclass float so you could map() an iterable of standard, non-adulterated floats into prettyfloats for display purposes:\n# Perform all our computations using standard floats.\nre...
[ 5, 3, 1 ]
[]
[]
[ "built_in_types", "floating_point", "python", "python_3.x", "subclass" ]
stackoverflow_0004092674_built_in_types_floating_point_python_python_3.x_subclass.txt
Q: Link 2 attributes in a database We are looking for advice to find a solution to this problem : We consider that we have the following database table Article (id, title, content) We store 2 articles on this table article1(1, title1, content1) article2(2, title2, content2) The primary key is the id and we want to know if there is a way to "link" the article2.title with the article1.title. For example, if the articles have the same title, we want to use only one entry so article2.title should be a kind of pointer to article1.title. The system will check the data before storing it in the database and if title2 = title1, a link should be created without inserting the title2. There is a way to do that with Python and any database management system ? It's for a school project, so any help will be really appreciated Thank you in advance :-) A: This is RDBS 101 but I'll answer anyway. Setup some schema like this: article id title_id content title id title Then you can get the articles and titles using an INNER JOIN. SELECT article.id, title.title, article.content FROM article INNER JOIN title ON title.id = article.title_id I'll leave the inserts up to you, but it should be pretty obvious at this point. As for a CMS and database ORM, I'd recommend Flask and SqlAlchemy respectively. However, Flask isn't a CMS, but rather a lightweight web framework that's easy to learn and use.
Link 2 attributes in a database
We are looking for advice to find a solution to this problem : We consider that we have the following database table Article (id, title, content) We store 2 articles on this table article1(1, title1, content1) article2(2, title2, content2) The primary key is the id and we want to know if there is a way to "link" the article2.title with the article1.title. For example, if the articles have the same title, we want to use only one entry so article2.title should be a kind of pointer to article1.title. The system will check the data before storing it in the database and if title2 = title1, a link should be created without inserting the title2. There is a way to do that with Python and any database management system ? It's for a school project, so any help will be really appreciated Thank you in advance :-)
[ "This is RDBS 101 but I'll answer anyway. Setup some schema like this:\narticle\n id\n title_id\n content\n\ntitle\n id\n title\n\nThen you can get the articles and titles using an INNER JOIN.\nSELECT\n article.id,\n title.title,\n article.content\nFROM article \nINNER JOIN title ON\n tit...
[ 1 ]
[]
[]
[ "content_management_system", "database", "python" ]
stackoverflow_0004092827_content_management_system_database_python.txt
Q: how to verify a hash in python? I have a hashtable in python of strings. So, each entry is a string. The strings could possibly start with "/" which implies they are file names. What would be a quick way to take a hashtable like this, and for each string in it that starts with a "/" verify whether the file exists? If the file does not exist, then the A: To find if the string begins with a forward slash: str.startswith('/') or str[0] == '/' To find if a file is valid: import os.path os.path.exists(str) You can loop through your hashtable using a for statement. Putting it all together (assuming the potential paths are the values in the hashtable [called a dict in python]): import os.path for val in table.values(): if val.startswith('/') and not os.path.exists(val): print "BAD FILE!!! ", val
how to verify a hash in python?
I have a hashtable in python of strings. So, each entry is a string. The strings could possibly start with "/" which implies they are file names. What would be a quick way to take a hashtable like this, and for each string in it that starts with a "/" verify whether the file exists? If the file does not exist, then the
[ "To find if the string begins with a forward slash:\nstr.startswith('/')\n\nor\nstr[0] == '/'\n\nTo find if a file is valid:\nimport os.path\nos.path.exists(str)\n\nYou can loop through your hashtable using a for statement. Putting it all together (assuming the potential paths are the values in the hashtable [call...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0004092886_python.txt
Q: Eliminate dups and sum corresponding terms in lists Given these 2 lists L2 = [A,B,C,D,A,B] L3 = [3,2,1,2,2,1] I want to obtain L2_WANTED = [A,B,C,D] L3_WANTED = [5,3,1,2] The lists are always ordered and same size and elements correspond as key value pairs eg A:3, B:2 and so on. The objective is to eliminate the dups in L2 and sum the corresponding terms in L3 to obtain a new list with matching pairs. This is to keep a running list of items as they are added to the lists. I tried to write a function with index but it started to get ugly. I checked itertools but could not find anything that relates; I looked at starmap() but couldn't make it work. Probably this can be done with list comprehension as well. I would appreciate any clues or directions about how to achieve this most simple way. Thank you. EDİT @SimonC: >>> l2_sum = {} >>> for i in range(0, len(L2)): key = L2[i] num = L3[i] l2_sum[key] = l2_sum.get(key, 0) + num >>> l2_sum {'A': 5, 'C': 1, 'B': 3, 'D': 2} >>> How does this eliminate the dupes and add the numbers? Can you give a clue? Thanks. A: I am sure there are more elegant answer there and would come in the replies. But for some simple answers: L2 = ['A','B','C','D','A','B'] L3 = [3,2,1,2,2,1] L4 = zip(L2, L3) L5 = [] L6 = [] def freduce(l): for x, y in l: print x , y if x in L5: k = L5.index(x) L6[k] += y else: L5.append(x) L6.append(y) freduce(L4) print L5 print L6 Output: ['A', 'B', 'C', 'D'] [5, 3, 1, 2] [Edited answer for understanding the second implementation] >>> L3 = [3,2,1,2,2,1] >>> L2 = ['A','B','C','D','A','B'] >>> range(0, len(L2)) [0, 1, 2, 3, 4, 5] >>> Hence in for i in range(0, len(L2)): ... i becomes an index Using this index, you could extract information from L3 and L2 by doing: key = L2[i] num = L3[i] Then you add information to the dict l2_sum[key] = l2_sum.get(key, 0) + num Here l2_sum.get(key, 0) returns 0 if the key is not present otherwise the current value. I hope it is clear enough. A: I think using zip is a nice way to combine the lists. The dict.update portion will do the summing since I fetch the previous value and update it: foo = dict() for x, y in zip(['A', 'B', 'C', 'D', 'A', 'B'], [3, 2, 1, 2, 2, 1]): foo[x] = y + foo.get(x, 0) print foo Outputs: {'A': 5, 'C': 1, 'B': 3, 'D': 2} Edit: While the above is fine, I'd also consider using itertools.izip which allows you to do the zip as you build the dictionary. This way you'll save on memory. All you'd need to do is replace zip with itertools.izip after importing iterools A: This will do it, but as per pyfunc, there are better ways: l2_sum = {} for i in range(0,len(L2)): key = L2[i] num = L3[i] l2_sum[key] = l2_sum.get(key, 0) + num L2_WANTED = sorted(l2_sum.keys()) L3_WANTED = [l2_sum[key] for key in L2_WANTED]
Eliminate dups and sum corresponding terms in lists
Given these 2 lists L2 = [A,B,C,D,A,B] L3 = [3,2,1,2,2,1] I want to obtain L2_WANTED = [A,B,C,D] L3_WANTED = [5,3,1,2] The lists are always ordered and same size and elements correspond as key value pairs eg A:3, B:2 and so on. The objective is to eliminate the dups in L2 and sum the corresponding terms in L3 to obtain a new list with matching pairs. This is to keep a running list of items as they are added to the lists. I tried to write a function with index but it started to get ugly. I checked itertools but could not find anything that relates; I looked at starmap() but couldn't make it work. Probably this can be done with list comprehension as well. I would appreciate any clues or directions about how to achieve this most simple way. Thank you. EDİT @SimonC: >>> l2_sum = {} >>> for i in range(0, len(L2)): key = L2[i] num = L3[i] l2_sum[key] = l2_sum.get(key, 0) + num >>> l2_sum {'A': 5, 'C': 1, 'B': 3, 'D': 2} >>> How does this eliminate the dupes and add the numbers? Can you give a clue? Thanks.
[ "I am sure there are more elegant answer there and would come in the replies.\nBut for some simple answers:\nL2 = ['A','B','C','D','A','B']\nL3 = [3,2,1,2,2,1]\n\nL4 = zip(L2, L3)\n\nL5 = []\nL6 = []\ndef freduce(l):\n for x, y in l:\n print x , y\n if x in L5:\n k = L5.index(x)\n ...
[ 2, 2, 1 ]
[]
[]
[ "list_comprehension", "python", "python_itertools" ]
stackoverflow_0004084369_list_comprehension_python_python_itertools.txt
Q: How would I implement a ranking algorithm in my website to sort database data? I want to implement a ranking system on a website I've been working on and have decided to go with the Hacker News algorithm. My reasoning for choosing this algorithm is simply because it's been described here. I was looking at this Python code (the language I'm using to build my site) and couldn't figure out how I would implement it. def calculate_score(votes, item_hour_age, gravity=1.8): return (votes - 1) / pow((item_hour_age+2), gravity) Given the tables: posts: id | title | time_submitted votes: id | postid | userid | score How would I pull the data from the database? The ideal solution (most efficient) would be to construct a MySQL query to retrieve the top 10 posts ranked using the algorithm. But given that Hacker News has it implemented in Arc, it makes me think they pull out all the posts then run them through the algorithm to rank them. Reddit also comes to mind for this... They use a non-relational database schema so I would assume they, like Hacker News, perform the rankings in their code - not the database. How would you implement this? EDIT: one post can have many votes as I would like to log which user votes on which post. A: You can use the data you need in the ORDER BY clause. SELECT p.id, p.title, p.time_submitted, SUM(v.score) as num_votes FROM posts p, votes v WHERE v.postid = p.id GROUP BY p.id ORDER BY (SUM(v.score) - 1) / POW(TIMESTAMPDIFF(HOUR,p.time_submitted,NOW()) + INTERVAL 2 HOUR, 1.8) DESC LIMIT 100 A: In your case, the number of votes would be returned by: SELECT count(*) FROM votes WHERE postid=<THE POST'S ID>; If you want to consider score, you could include that in the query but the formula you provided is not equipped to handle it. The item hour age is simply the current time subtracted from the time submitted: SELECT HOUR(TIMEDIFF(NOW(), time_submitted)) FROM posts WHERE id=<THE POST'S ID>; This can also be done entirely in SQL: SELECT id FROM posts ORDER BY (((SELECT count(*) FROM votes WHERE postid=posts.id) - 1) / MOD(HOUR(TIMEDIFF(NOW(), time_submitted) + INTERVAL 2 HOURS), <GRAVITY>)) LIMIT 10;
How would I implement a ranking algorithm in my website to sort database data?
I want to implement a ranking system on a website I've been working on and have decided to go with the Hacker News algorithm. My reasoning for choosing this algorithm is simply because it's been described here. I was looking at this Python code (the language I'm using to build my site) and couldn't figure out how I would implement it. def calculate_score(votes, item_hour_age, gravity=1.8): return (votes - 1) / pow((item_hour_age+2), gravity) Given the tables: posts: id | title | time_submitted votes: id | postid | userid | score How would I pull the data from the database? The ideal solution (most efficient) would be to construct a MySQL query to retrieve the top 10 posts ranked using the algorithm. But given that Hacker News has it implemented in Arc, it makes me think they pull out all the posts then run them through the algorithm to rank them. Reddit also comes to mind for this... They use a non-relational database schema so I would assume they, like Hacker News, perform the rankings in their code - not the database. How would you implement this? EDIT: one post can have many votes as I would like to log which user votes on which post.
[ "You can use the data you need in the ORDER BY clause.\nSELECT p.id, p.title, p.time_submitted, SUM(v.score) as num_votes \n FROM posts p, votes v\n WHERE v.postid = p.id\nGROUP BY p.id\nORDER BY \n (SUM(v.score) - 1) / POW(TIMESTAMPDIFF(HOUR,p.time_submitted,NOW()) + INTERVAL 2 HOUR, 1.8) DESC\nLIMIT 100\n\n", ...
[ 4, 0 ]
[]
[]
[ "algorithm", "implementation", "python", "sql" ]
stackoverflow_0004093115_algorithm_implementation_python_sql.txt
Q: Python: Programming 8051 Can I program 8051 using Python? I'm not getting any of the to program 8051 in python environment. If anybody knows, please help me. A: There is Python-on-a-Chip, but note its "disclaimer": "The PyMite VM DOES NOT HAVE: A built-in compiler Any of Python's libraries (no batteries included) A ready-to-go solution for the beginner (you need to know C and how to work with microcontrollers)" Thus, if the questioner's goal for python was to avoid dealing with the strangeness of the 8051, this may not help. In particular, the 8051 is a "Harvard" style architecture, with separate RAM and ROM codespaces, and with very limited internal RAM, and larger external RAM that can be accessed only via loading the special DPTR register and then reading or writing indirectly, plus there's no external RAM stack support, nor intrinsic support for stack-based variables. Thus, most "general purpose" high-level languages need lots of customization and reworking to run on the 8051. A good 8051-specific C-compiler can hide many of these low-level details, but you wind up burning lots of cycles to do things that are single instructions on desktop CPUs and even on most newer embedded controller architectures, and even if you can live with that level of in-efficiency, you still need to sort out the various memory spaces and other specifics. So, getting Python to work on the 8051 is likely to be a challenging project for someone deeply familiar with its quirky architecture. If your goal is to dump a python onto the 8051 to avoid needing to learn these quirks, I'm not sure that is possible. (But, I suppose the C compilers keep getting better and better...) A: Python-on-a-Chip looks about as close as you're going to get. It can run on some things that are just a bit beefier than the 8051.
Python: Programming 8051
Can I program 8051 using Python? I'm not getting any of the to program 8051 in python environment. If anybody knows, please help me.
[ "There is Python-on-a-Chip, but note its \"disclaimer\":\n\n\"The PyMite VM DOES NOT HAVE:\n\nA built-in compiler\nAny of Python's libraries (no batteries included)\nA ready-to-go solution for the beginner (you need to know C and how to work with microcontrollers)\"\n\n\nThus, if the questioner's goal for python wa...
[ 6, 4 ]
[]
[]
[ "8051", "low_level", "microcontroller", "python" ]
stackoverflow_0004059703_8051_low_level_microcontroller_python.txt
Q: How do I monitor a "stuck" Python script? I have a data-intensive Python script that uses HTTP connections to download data. I usually run it overnight. Sometimes the connection will fail, or a website will be unavailable momentarily. I have basic error-handling that catches these exceptions and tries again periodically, exiting gracefully (and logging errors) after 5 minutes of retrying. However, I've noticed that sometimes the job just freezes. No error is thrown, and the job is still running, sometimes hours after the last print message. What is the best way to: monitor a Python script, detect if it is unresponsive after a given interval, exit it if it is unresponsive, and start another one? UPDATE Thank you all for your help. As a few of you have pointed out, the urllib and socket modules don't have timeouts set properly. I am using Python 2.5 with the Freebase and urllib2 modules, and catching and handling MetawebErrors and urllib2.URLErrors. Here is a sample of err output after the last script hung for 12 hours: File "/home/matthew/dev/projects/myapp_module/project/app/myapp/contrib/freebase/api/session.py", line 369, in _httpreq_json resp, body = self._httpreq(*args, **kws) File "/home/matthew/dev/projects/myapp_module/project/app/myapp/contrib/freebase/api/session.py", line 355, in _httpreq return self._http_request(url, method, body, headers) File "/home/matthew/dev/projects/myapp_module/project/app/myapp/contrib/freebase/api/httpclients.py", line 33, in __call__ resp = self.opener.open(req) File "/usr/lib/python2.5/urllib2.py", line 381, in open response = self._open(req, data) File "/usr/lib/python2.5/urllib2.py", line 399, in _open '_open', req) File "/usr/lib/python2.5/urllib2.py", line 360, in _call_chain result = func(*args) File "/usr/lib/python2.5/urllib2.py", line 1107, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/lib/python2.5/urllib2.py", line 1080, in do_open r = h.getresponse() File "/usr/lib/python2.5/httplib.py", line 928, in getresponse response.begin() File "/usr/lib/python2.5/httplib.py", line 385, in begin version, status, reason = self._read_status() File "/usr/lib/python2.5/httplib.py", line 343, in _read_status line = self.fp.readline() File "/usr/lib/python2.5/socket.py", line 372, in readline data = recv(1) KeyboardInterrupt You'll notice the socket error at the bottom. Since I'm using Python 2.5 and don't have access to the third urllib2.urlopen option, is there another way to watch for and catch this error? For example, I'm catching URLErrrors - is there another type of error in urllib2 or socket that I can catch which will help me? A: It sounds like there is a bug in your script. The answer is not to monitor the bug, but to hunt down the bug and fix it. We can't help you find the bug without seeing some code. But as a general idea, you might want to use logging to pinpoint where the problem is occurring, and write unit tests to help you build confidence about which parts of your code do not have the bug. Another idea is to break your "stuck" program with Ctrl-C and to study the traceback message. It will show you what line your program was last executing. That may give you a clue where the script is going wrong. A: Since the program is doing web communication, I'd fire up a debugging proxy like Charles http://www.charlesproxy.com/ and see if there's anything kooky happening in the back-and-forth between your script and the server. Also consider that the socket module has no timeout set by default and therefore can hang. As of python 2.6, however, you can pass a third argument to urllib2.urlopen (if you are using urllib2, that is), specifying a request timeout period in seconds. That way the script will error out rather than go catatonic waiting from a response from a perhaps uncooperative server. If you haven't already, I'd check these things out before trying anything more elaborate. Update for python 2.5: To do this in python < 2.6, you would have to set the timeout value directly in the socket module, which urllib2 uses. I haven't tried this, but it presumably works. Found this info at http://www.voidspace.org.uk/python/articles/urllib2.shtml: import socket import urllib2 # timeout in seconds timeout = 10 socket.setdefaulttimeout(timeout) # this call to urllib2.urlopen now uses the default timeout # we have set in the socket module req = urllib2.Request('http://www.voidspace.org.uk') response = urllib2.urlopen(req) A: a simple way to do what you ask is to make use of UDP packets sent by your current program to another harvesting program that monitors the output. If it doesn't receive a packet in a certain amount of time, it kills the other python process then restarts another one A: You could run your script in pdb and break in when you suspect it's frozen. It won't work on its own, but might help you figure out why it's freezing.
How do I monitor a "stuck" Python script?
I have a data-intensive Python script that uses HTTP connections to download data. I usually run it overnight. Sometimes the connection will fail, or a website will be unavailable momentarily. I have basic error-handling that catches these exceptions and tries again periodically, exiting gracefully (and logging errors) after 5 minutes of retrying. However, I've noticed that sometimes the job just freezes. No error is thrown, and the job is still running, sometimes hours after the last print message. What is the best way to: monitor a Python script, detect if it is unresponsive after a given interval, exit it if it is unresponsive, and start another one? UPDATE Thank you all for your help. As a few of you have pointed out, the urllib and socket modules don't have timeouts set properly. I am using Python 2.5 with the Freebase and urllib2 modules, and catching and handling MetawebErrors and urllib2.URLErrors. Here is a sample of err output after the last script hung for 12 hours: File "/home/matthew/dev/projects/myapp_module/project/app/myapp/contrib/freebase/api/session.py", line 369, in _httpreq_json resp, body = self._httpreq(*args, **kws) File "/home/matthew/dev/projects/myapp_module/project/app/myapp/contrib/freebase/api/session.py", line 355, in _httpreq return self._http_request(url, method, body, headers) File "/home/matthew/dev/projects/myapp_module/project/app/myapp/contrib/freebase/api/httpclients.py", line 33, in __call__ resp = self.opener.open(req) File "/usr/lib/python2.5/urllib2.py", line 381, in open response = self._open(req, data) File "/usr/lib/python2.5/urllib2.py", line 399, in _open '_open', req) File "/usr/lib/python2.5/urllib2.py", line 360, in _call_chain result = func(*args) File "/usr/lib/python2.5/urllib2.py", line 1107, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/lib/python2.5/urllib2.py", line 1080, in do_open r = h.getresponse() File "/usr/lib/python2.5/httplib.py", line 928, in getresponse response.begin() File "/usr/lib/python2.5/httplib.py", line 385, in begin version, status, reason = self._read_status() File "/usr/lib/python2.5/httplib.py", line 343, in _read_status line = self.fp.readline() File "/usr/lib/python2.5/socket.py", line 372, in readline data = recv(1) KeyboardInterrupt You'll notice the socket error at the bottom. Since I'm using Python 2.5 and don't have access to the third urllib2.urlopen option, is there another way to watch for and catch this error? For example, I'm catching URLErrrors - is there another type of error in urllib2 or socket that I can catch which will help me?
[ "It sounds like there is a bug in your script. The answer is not to monitor the bug, but to hunt down the bug and fix it.\nWe can't help you find the bug without seeing some code. But as a general idea, you might want to use logging to pinpoint where the problem is occurring, and write unit tests to help you build ...
[ 7, 4, 1, 1 ]
[]
[]
[ "freebase", "python", "scripting", "sockets", "urllib2" ]
stackoverflow_0004093166_freebase_python_scripting_sockets_urllib2.txt
Q: I use tornado frameworks. I can use dict and list types in tornado templates, but when I use a object in the templates, it render as memory address for detail. I import Solrpy package to use. As for the document on Django project to introduce the pagenator. I pass the pagenator.page (Solrpage) object to tornado template but it doesn't work. I can'd use any method of Solrpage. instead it is rendered as a memory address. below is the way to use the paginator , which is also the way I use from django.core.paginator import Paginator, InvalidPage, EmptyPage def listing(request): contact_list = Contacts.objects.all() paginator = Paginator(contact_list, 25) # Show 25 contacts per page # Make sure page request is an int. If not, deliver first page. try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 # If page request (9999) is out of range, deliver last page of results. try: contacts = paginator.page(page) except (EmptyPage, InvalidPage): contacts = paginator.page(paginator.num_pages) return render_to_response('list.html', {"contacts": contacts}) {% for contact in contacts.object_list %} {# Each "contact" is a Contact model object. #} {{ contact.full_name|upper }} ... {% endfor %} {% if contacts.has_previous %} previous {% endif %} Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}. .... A: Your class definition needs a __str__( self ) method to render as something other than a random address in a template.
I use tornado frameworks. I can use dict and list types in tornado templates, but when I use a object in the templates, it render as memory address
for detail. I import Solrpy package to use. As for the document on Django project to introduce the pagenator. I pass the pagenator.page (Solrpage) object to tornado template but it doesn't work. I can'd use any method of Solrpage. instead it is rendered as a memory address. below is the way to use the paginator , which is also the way I use from django.core.paginator import Paginator, InvalidPage, EmptyPage def listing(request): contact_list = Contacts.objects.all() paginator = Paginator(contact_list, 25) # Show 25 contacts per page # Make sure page request is an int. If not, deliver first page. try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 # If page request (9999) is out of range, deliver last page of results. try: contacts = paginator.page(page) except (EmptyPage, InvalidPage): contacts = paginator.page(paginator.num_pages) return render_to_response('list.html', {"contacts": contacts}) {% for contact in contacts.object_list %} {# Each "contact" is a Contact model object. #} {{ contact.full_name|upper }} ... {% endfor %} {% if contacts.has_previous %} previous {% endif %} Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}. ....
[ "Your class definition needs a __str__( self ) method to render as something other than a random address in a template.\n" ]
[ 2 ]
[]
[]
[ "pagination", "python", "solr", "tornado" ]
stackoverflow_0004093540_pagination_python_solr_tornado.txt
Q: dynamically assigning function to __dir__ of an instance I am trying to dynamically assign a function to __del__ of an instance of a class so that it gets called when using dir() on that object. I need __dir__ to be unique for each instance of the class. As a stripped down example, I have tried: import types class Foo(object): def __init__(self, arg): def __dir__(self): print "in __dir__" return [arg] self.__dir__ = types.MethodType(__dir__, self, self.__class__) foo = Foo('bar') print dir(foo) print print foo.__dir__() This prints: ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] in __dir__ ['bar'] If I instead do this: class Foo(object): def __dir__(self): print "in __dir__" return ['bar'] foo = Foo() print dir(foo) that outputs: in __dir__ ['bar'] as expected, but can not be customized for each instance of the class. Any ideas? A: Ok, based on your comment I worked things a bit. I think this might be closer to the behavior you're looking for. Calling dir with no args gives all the names in the local scope and calling it on __class__ gives all class names. This ignores the defined __dir__ which can be called later on. I'm curious what you're using this for, maybe there is a simpler way to get the intended behavior? class Foo(object): def __init__(self, arg=None): self.arg = arg print dir(self.__class__) + dir() def __dir__(self): return [self.arg()] def dirfoo(): return ["new thing"] foo = Foo(dirfoo) print dir(foo)
dynamically assigning function to __dir__ of an instance
I am trying to dynamically assign a function to __del__ of an instance of a class so that it gets called when using dir() on that object. I need __dir__ to be unique for each instance of the class. As a stripped down example, I have tried: import types class Foo(object): def __init__(self, arg): def __dir__(self): print "in __dir__" return [arg] self.__dir__ = types.MethodType(__dir__, self, self.__class__) foo = Foo('bar') print dir(foo) print print foo.__dir__() This prints: ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] in __dir__ ['bar'] If I instead do this: class Foo(object): def __dir__(self): print "in __dir__" return ['bar'] foo = Foo() print dir(foo) that outputs: in __dir__ ['bar'] as expected, but can not be customized for each instance of the class. Any ideas?
[ "Ok, based on your comment I worked things a bit. I think this might be closer to the behavior you're looking for. Calling dir with no args gives all the names in the local scope and calling it on __class__ gives all class names. This ignores the defined __dir__ which can be called later on. I'm curious what you're...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004093607_python.txt