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: Use python decorators on class methods and subclass methods Goal: Make it possible to decorate class methods. When a class method gets decorated, it gets stored in a dictionary so that other class methods can reference it by a string name. Motivation: I want to implement the equivalent of ASP.Net's WebMethods. I am building this on top of google app engine, but that does not affect the point of difficulty that I am having. How it Would look if it worked: class UsefulClass(WebmethodBaseClass): def someMethod(self, blah): print(blah) @webmethod def webby(self, blah): print(blah) # the implementation of this class could be completely different, it does not matter # the only important thing is having access to the web methods defined in sub classes class WebmethodBaseClass(): def post(self, methodName): webmethods[methodName]("kapow") ... a = UsefulClass() a.post("someMethod") # should error a.post("webby") # prints "kapow" There could be other ways to go about this. I am very open to suggestions A: This is unnecessary. Just use getattr: class WebmethodBaseClass(): def post(self, methodName): getattr(self, methodName)("kapow") The only caveat is that you have to make sure that only methods intended for use as webmethods can be used thus. The simplest solution, IMO, is to adopt the convention that non-webmethods start with an underscore and have the post method refuse to service such names. If you really want to use decorators, try this: def webmethod(f): f.is_webmethod = True return f and get post to check for the existence of the is_webmethod attribute before calling the method. A: This would seem to be the simplest approach to meet your specs as stated: webmethods = {} def webmethod(f): webmethods[f.__name__] = f return f and, in WebmethodBaseClass, def post(self, methodName): webmethods[methodName](self, "kapow") I suspect you want something different (e.g., separate namespaces for different subclasses vs a single global webmethods dictionary...?), but it's hard to guess without more info exactly how your desires differ from your specs -- so maybe you can tell us how this simplistic approach fails to achieve some of your desiderata, so it can be enriched according to what you actually want. A: class UsefulClass(WebmethodBaseClass): def someMethod(self, blah): print(blah) @webmethod def webby(self, blah): print(blah) class WebmethodBaseClass(): def post(self, methodName): method = getattr(self, methodName) if method.webmethod: method("kapow") ... def webmethod(f): f.webmethod = True return f a = UsefulClass() a.post("someMethod") # should error a.post("webby") # prints "kapow"
Use python decorators on class methods and subclass methods
Goal: Make it possible to decorate class methods. When a class method gets decorated, it gets stored in a dictionary so that other class methods can reference it by a string name. Motivation: I want to implement the equivalent of ASP.Net's WebMethods. I am building this on top of google app engine, but that does not affect the point of difficulty that I am having. How it Would look if it worked: class UsefulClass(WebmethodBaseClass): def someMethod(self, blah): print(blah) @webmethod def webby(self, blah): print(blah) # the implementation of this class could be completely different, it does not matter # the only important thing is having access to the web methods defined in sub classes class WebmethodBaseClass(): def post(self, methodName): webmethods[methodName]("kapow") ... a = UsefulClass() a.post("someMethod") # should error a.post("webby") # prints "kapow" There could be other ways to go about this. I am very open to suggestions
[ "This is unnecessary. Just use getattr:\nclass WebmethodBaseClass():\n def post(self, methodName):\n getattr(self, methodName)(\"kapow\")\n\nThe only caveat is that you have to make sure that only methods intended for use as webmethods can be used thus. The simplest solution, IMO, is to adopt the convention that non-webmethods start with an underscore and have the post method refuse to service such names.\nIf you really want to use decorators, try this:\ndef webmethod(f):\n f.is_webmethod = True\n return f\n\nand get post to check for the existence of the is_webmethod attribute before calling the method.\n", "This would seem to be the simplest approach to meet your specs as stated:\nwebmethods = {}\n\ndef webmethod(f):\n webmethods[f.__name__] = f\n return f\n\nand, in WebmethodBaseClass,\ndef post(self, methodName):\n webmethods[methodName](self, \"kapow\")\n\nI suspect you want something different (e.g., separate namespaces for different subclasses vs a single global webmethods dictionary...?), but it's hard to guess without more info exactly how your desires differ from your specs -- so maybe you can tell us how this simplistic approach fails to achieve some of your desiderata, so it can be enriched according to what you actually want.\n", "class UsefulClass(WebmethodBaseClass):\n\n def someMethod(self, blah):\n print(blah)\n\n @webmethod\n def webby(self, blah):\n print(blah)\n\nclass WebmethodBaseClass():\n def post(self, methodName):\n method = getattr(self, methodName)\n if method.webmethod:\n method(\"kapow\")\n\n ...\n\ndef webmethod(f):\n f.webmethod = True\n return f\n\na = UsefulClass()\na.post(\"someMethod\") # should error\na.post(\"webby\") # prints \"kapow\"\n\n" ]
[ 4, 1, 0 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002711101_decorator_python.txt
Q: some register.inclusion_tag error in my code using django my helloworld_tags: from django import template register = template.Library() def show_profile(): return {"eee": '333'} register.inclusion_tag("b.html")(show_profile) my view: def b(request): return render_to_response('b.html') my html: {% load helloworld_tags%} dsad {{ eee }} but only show 'dsad' ,not show 'dsad333' why?? thanks updated but when i set this in c.html: {% load helloworld_tags%} and change the view: def b(request): return render_to_response('c.html') and the b.html is: dsad {{ eee }} it is show nothing now , why ? thanks updated2 it is ok now ,when i add this to c.html: {% load helloworld_tags%} {% show_profile %} A: This can't possibly work. You need one template for the view to render, and another different template for the inclusion template. You can't use the same template for both uses, it simply doesn't make any sense.
some register.inclusion_tag error in my code using django
my helloworld_tags: from django import template register = template.Library() def show_profile(): return {"eee": '333'} register.inclusion_tag("b.html")(show_profile) my view: def b(request): return render_to_response('b.html') my html: {% load helloworld_tags%} dsad {{ eee }} but only show 'dsad' ,not show 'dsad333' why?? thanks updated but when i set this in c.html: {% load helloworld_tags%} and change the view: def b(request): return render_to_response('c.html') and the b.html is: dsad {{ eee }} it is show nothing now , why ? thanks updated2 it is ok now ,when i add this to c.html: {% load helloworld_tags%} {% show_profile %}
[ "This can't possibly work. You need one template for the view to render, and another different template for the inclusion template. You can't use the same template for both uses, it simply doesn't make any sense.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002711739_django_python.txt
Q: how to make multi url in a line of '- url:' ,on google-app-engine like this: handlers: - url: /media static_dir: media - url: /form;/items.html script: validate.py /form;/items.html i want /form and /item.html use validate.py thanks A: URL patterns are regular expressions, so you can simply provide a regular expression that matches both: - url: /(form|items\.html) script: validate.py Alternately, you can use multiple handlers, as Adam suggests, or just make validate.html your catchall (with an expression of '.*'). A: List the handler twice in your app.yaml, e.g.: handlers: - url: /media static_dir: media - url: /form\.html script: validate.py - url: /items\.html script: validate.py Link to documentation. Also note that you need to escape a full-stop (.) with a backslash (\), since "URL and file path patterns use POSIX extended regular expression syntax...".
how to make multi url in a line of '- url:' ,on google-app-engine
like this: handlers: - url: /media static_dir: media - url: /form;/items.html script: validate.py /form;/items.html i want /form and /item.html use validate.py thanks
[ "URL patterns are regular expressions, so you can simply provide a regular expression that matches both:\n- url: /(form|items\\.html)\n script: validate.py\n\nAlternately, you can use multiple handlers, as Adam suggests, or just make validate.html your catchall (with an expression of '.*').\n", "List the handler twice in your app.yaml, e.g.:\n\nhandlers:\n- url: /media\n static_dir: media\n\n- url: /form\\.html\n script: validate.py\n\n- url: /items\\.html\n script: validate.py\n\nLink to documentation.\nAlso note that you need to escape a full-stop (.) with a backslash (\\), since \"URL and file path patterns use POSIX extended regular expression syntax...\". \n" ]
[ 2, 1 ]
[]
[]
[ "google_app_engine", "python", "url" ]
stackoverflow_0002710755_google_app_engine_python_url.txt
Q: Python/C "defs" file - what is it? In the nautilus-python bindings, there is a file "nautilus.defs". It contains stanzas like (define-interface MenuProvider (in-module "Nautilus") (c-name "NautilusMenuProvider") (gtype-id "NAUTILUS_TYPE_MENU_PROVIDER") ) or (define-method get_mime_type (of-object "NautilusFileInfo") (c-name "nautilus_file_info_get_mime_type") (return-type "char*") ) Now I can see what most of these do (eg. that last one means that I can call the method "get_mime_type" on a "FileInfo" object). But I'd like to know: what is this file, exactly (ie. what do I search the web for to find out more info)? Is it a common thing to find in Python/C bindings? What is the format, and where is it documented? What program actually processes it? (So far, I've managed to glean that it gets transformed into a C source file, and it looks a bit like lisp to me.) A: All you need to create Python bindings for C code is to use the Python / C API. However, the API can be somewhat repetitive and redundant, and so various forms of automation may be used to create them. For example, you may have heard of swig. The LISP-like (Scheme) code that you see is simply a configuration file for PyGTK-Codegen, which is a similar automation program for creating bindings to Python. A: To answer your "What program actually processes it?" question: From Makefile.in in the src directory, the command that translates the .defs file into C is PYGTK_CODEGEN. To find out what PYGTK_CODEGEN is, look in the top-level configure.in file, which contains these lines: AC_MSG_CHECKING(for pygtk codegen) PYGTK_CODEGEN="$PYTHON `$PKG_CONFIG --variable=codegendir pygtk-2.0`/codegen.py" AC_SUBST(PYGTK_CODEGEN) AC_MSG_RESULT($PYGTK_CODEGEN) So the program that processes it is a Python script called codegen.py, that apparently has some link with PyGTK. Now a Google search for PyGTK codegen gives me this link as the first hit, which says: "PyGTK-Codegen is a system for automatically generating wrappers for interfacing GTK code with Python." and also gives some examples. As for: "What is the format, and where is it documented?". As others have said, the code looks a lot like simple Scheme. I couldn't find any documentation at all on codegen on the PyGTK site; this looks like one of those many dark corners of open source that isn't well documented. Your best bet would probably be to download a recent tarball for PyGTK, look through the sources for the codegen.py file and see if the file itself contains sufficient documentation.
Python/C "defs" file - what is it?
In the nautilus-python bindings, there is a file "nautilus.defs". It contains stanzas like (define-interface MenuProvider (in-module "Nautilus") (c-name "NautilusMenuProvider") (gtype-id "NAUTILUS_TYPE_MENU_PROVIDER") ) or (define-method get_mime_type (of-object "NautilusFileInfo") (c-name "nautilus_file_info_get_mime_type") (return-type "char*") ) Now I can see what most of these do (eg. that last one means that I can call the method "get_mime_type" on a "FileInfo" object). But I'd like to know: what is this file, exactly (ie. what do I search the web for to find out more info)? Is it a common thing to find in Python/C bindings? What is the format, and where is it documented? What program actually processes it? (So far, I've managed to glean that it gets transformed into a C source file, and it looks a bit like lisp to me.)
[ "All you need to create Python bindings for C code is to use the Python / C API. However, the API can be somewhat repetitive and redundant, and so various forms of automation may be used to create them. For example, you may have heard of swig. The LISP-like (Scheme) code that you see is simply a configuration file for PyGTK-Codegen, which is a similar automation program for creating bindings to Python.\n", "To answer your \"What program actually processes it?\" question:\nFrom Makefile.in in the src directory, the command that translates the .defs file into C is PYGTK_CODEGEN. To find out what PYGTK_CODEGEN is, look in the top-level configure.in file, which contains these lines:\nAC_MSG_CHECKING(for pygtk codegen)\nPYGTK_CODEGEN=\"$PYTHON `$PKG_CONFIG --variable=codegendir pygtk-2.0`/codegen.py\"\nAC_SUBST(PYGTK_CODEGEN)\nAC_MSG_RESULT($PYGTK_CODEGEN)\n\nSo the program that processes it is a Python script called codegen.py, that apparently has some link with PyGTK. Now a Google search for PyGTK codegen gives me this link as the first hit, which says:\n\"PyGTK-Codegen is a system for automatically generating wrappers for interfacing GTK code with Python.\"\nand also gives some examples.\nAs for: \"What is the format, and where is it documented?\". As others have said, the code looks a lot like simple Scheme. I couldn't find any documentation at all on codegen on the PyGTK site; this looks like one of those many dark corners of open source that isn't well documented. Your best bet would probably be to download a recent tarball for PyGTK, look through the sources for the codegen.py file and see if the file itself contains sufficient documentation.\n" ]
[ 3, 3 ]
[]
[]
[ "c", "python" ]
stackoverflow_0002712054_c_python.txt
Q: Fetch Facebook ID with PyFacebook, "Session key is required" I'm trying to fetch the logged in user's ID with Facebook + PyFacebook via: #Establish connection to Facebook via API f = Facebook(config['app_conf']['pyfacebook.apikey'], config['app_conf']['pyfacebook.secret']) #Get the current Facebook ID facebook_id = f.users.getLoggedInUser() But I keep getting the error: FacebookError: Error 453: A session key is required for calling this method What am I doing wrong? Thanks. A: A look at the source shows an example app, and in there it calls f.auth.createToken() followed by f.login() before doing anything else. If you're not logged in, you won't get a session key.
Fetch Facebook ID with PyFacebook, "Session key is required"
I'm trying to fetch the logged in user's ID with Facebook + PyFacebook via: #Establish connection to Facebook via API f = Facebook(config['app_conf']['pyfacebook.apikey'], config['app_conf']['pyfacebook.secret']) #Get the current Facebook ID facebook_id = f.users.getLoggedInUser() But I keep getting the error: FacebookError: Error 453: A session key is required for calling this method What am I doing wrong? Thanks.
[ "A look at the source shows an example app, and in there it calls f.auth.createToken() followed by f.login() before doing anything else. If you're not logged in, you won't get a session key.\n" ]
[ 0 ]
[]
[]
[ "facebook", "pyfacebook", "pylons", "python" ]
stackoverflow_0002710146_facebook_pyfacebook_pylons_python.txt
Q: which is better to send mail on google-app-engine this: http://code.google.com/intl/en/appengine/docs/python/tools/devserver.html The web server can use an SMTP server, or it can use a local installation of Sendmail. i download the Sendmail lib,and find it is so big, and so many doc, i want to know which way is better, and if the Sendmail way is better, how to use it simplely, thanks updated: if can't setup the sendmail lib,can't use this method (mail.send_mail) ,yes?: from google.appengine.api import mail mail.send_mail(sender="support@example.com", to="Albert Johnson <Albert.Johnson@example.com>", subject="Your account has been approved", body=""" Dear Albert: Your example.com account has been approved. You can now visit http://www.example.com/ and sign in using your Google Account to access new features. Please let us know if you have any questions. The example.com Team """) A: As Wooble points out, this only applies to sending email from the development environment - so pick whichever option is easiest. If you can't get any of them working, email sent on the development server will still show up in your logs, so you can debug it there.
which is better to send mail on google-app-engine
this: http://code.google.com/intl/en/appengine/docs/python/tools/devserver.html The web server can use an SMTP server, or it can use a local installation of Sendmail. i download the Sendmail lib,and find it is so big, and so many doc, i want to know which way is better, and if the Sendmail way is better, how to use it simplely, thanks updated: if can't setup the sendmail lib,can't use this method (mail.send_mail) ,yes?: from google.appengine.api import mail mail.send_mail(sender="support@example.com", to="Albert Johnson <Albert.Johnson@example.com>", subject="Your account has been approved", body=""" Dear Albert: Your example.com account has been approved. You can now visit http://www.example.com/ and sign in using your Google Account to access new features. Please let us know if you have any questions. The example.com Team """)
[ "As Wooble points out, this only applies to sending email from the development environment - so pick whichever option is easiest. If you can't get any of them working, email sent on the development server will still show up in your logs, so you can debug it there.\n" ]
[ 2 ]
[]
[]
[ "email", "google_app_engine", "python" ]
stackoverflow_0002703885_email_google_app_engine_python.txt
Q: Google App Engine getting verbose_name of a property from an instance Given a model like so: from google.appengine.ext import db class X(db.Model): p = db.StringProperty(verbose_name="Like π, but more modern.") How does one access verbose_name from x=X() (an instance of X)? One might expect that x.p.verbose_name would work, or alternatively x.properties()['p'].verbose_name, but neither seems to work. Thanks! EDIT: x.name.verbose_name => x.p.verbose_name A: x.properties()['p'].verbose_name definitely works - you can verify for yourself on http://shell.appspot.com/ A: x = X(p="Foo!") print x.p.verbose_name Does that work?
Google App Engine getting verbose_name of a property from an instance
Given a model like so: from google.appengine.ext import db class X(db.Model): p = db.StringProperty(verbose_name="Like π, but more modern.") How does one access verbose_name from x=X() (an instance of X)? One might expect that x.p.verbose_name would work, or alternatively x.properties()['p'].verbose_name, but neither seems to work. Thanks! EDIT: x.name.verbose_name => x.p.verbose_name
[ "x.properties()['p'].verbose_name definitely works - you can verify for yourself on http://shell.appspot.com/\n", "x = X(p=\"Foo!\")\nprint x.p.verbose_name\n\nDoes that work?\n" ]
[ 3, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002702554_django_google_app_engine_python.txt
Q: How do I send an email in Django with a certain mimetype? MYMESSAGE = "<div>Hello</div><p></p>Hello" send_mail("testing",MYMESSAGE,"noreply@mydomain.com",['assdf@gmail.com'],fail_silently=False) However, this message doesn't get the HTML mime type when it is sent. In my outlook, I see the code... A: From the docs: msg = EmailMessage(subject, html_content, from_email, [to]) msg.content_subtype = "html" # Main content is now text/html msg.send() You can only change the subtype of the mimetype it seems. So it will always be "text/%s" % msg.content_subtype
How do I send an email in Django with a certain mimetype?
MYMESSAGE = "<div>Hello</div><p></p>Hello" send_mail("testing",MYMESSAGE,"noreply@mydomain.com",['assdf@gmail.com'],fail_silently=False) However, this message doesn't get the HTML mime type when it is sent. In my outlook, I see the code...
[ "From the docs:\nmsg = EmailMessage(subject, html_content, from_email, [to])\nmsg.content_subtype = \"html\" # Main content is now text/html\nmsg.send()\n\nYou can only change the subtype of the mimetype it seems. So it will always be\n\"text/%s\" % msg.content_subtype\n" ]
[ 5 ]
[]
[]
[ "django", "email", "mime", "python", "smtp" ]
stackoverflow_0002712484_django_email_mime_python_smtp.txt
Q: Optimizing BeautifulSoup (Python) code I have code that uses the BeautifulSoup library for parsing, but it is very slow. The code is written in such a way that threads cannot be used. Can anyone help me with this? I am using BeautifulSoup for parsing and than save into a DB. If I comment out the save statement, it still takes a long time, so there is no problem with the database. def parse(self,text): soup = BeautifulSoup(text) arr = soup.findAll('tbody') for i in range(0,len(arr)-1): data=Data() soup2 = BeautifulSoup(str(arr[i])) arr2 = soup2.findAll('td') c=0 for j in arr2: if str(j).find("<a href=") > 0: data.sourceURL = self.getAttributeValue(str(j),'<a href="') else: if c == 2: data.Hits=j.renderContents() #and few others... c = c+1 data.save() Any suggestions? Note: I already ask this question here but that was closed due to incomplete information. A: soup2 = BeautifulSoup(str(arr[i])) arr2 = soup2.findAll('td') Don't do this: Just call arr2 = arr[i].findAll('td') instead. This will also be slow: if str(j).find("<a href=") > 0: data.sourceURL = self.getAttributeValue(str(j),'<a href="') Assuming that getAttributeValue gives you the href attribute, use this instead: a = j.find('a', href=True) #find first <a> with href attribute if a: data.sourceURL = a['href'] else: #.... In general, you shouldn't need to convert the BeautifulSoup object back into a string if all you want to do is parse it and extract values. Since the find and findAll methods give you back searchable objects, you can keep searching by invoking the find/findAll/etc. methods on the results.
Optimizing BeautifulSoup (Python) code
I have code that uses the BeautifulSoup library for parsing, but it is very slow. The code is written in such a way that threads cannot be used. Can anyone help me with this? I am using BeautifulSoup for parsing and than save into a DB. If I comment out the save statement, it still takes a long time, so there is no problem with the database. def parse(self,text): soup = BeautifulSoup(text) arr = soup.findAll('tbody') for i in range(0,len(arr)-1): data=Data() soup2 = BeautifulSoup(str(arr[i])) arr2 = soup2.findAll('td') c=0 for j in arr2: if str(j).find("<a href=") > 0: data.sourceURL = self.getAttributeValue(str(j),'<a href="') else: if c == 2: data.Hits=j.renderContents() #and few others... c = c+1 data.save() Any suggestions? Note: I already ask this question here but that was closed due to incomplete information.
[ "soup2 = BeautifulSoup(str(arr[i]))\narr2 = soup2.findAll('td')\n\nDon't do this: Just call arr2 = arr[i].findAll('td') instead.\n\nThis will also be slow:\nif str(j).find(\"<a href=\") > 0:\n data.sourceURL = self.getAttributeValue(str(j),'<a href=\"')\n\nAssuming that getAttributeValue gives you the href attribute, use this instead:\na = j.find('a', href=True) #find first <a> with href attribute\nif a:\n data.sourceURL = a['href']\nelse:\n #....\n\n\nIn general, you shouldn't need to convert the BeautifulSoup object back into a string if all you want to do is parse it and extract values. Since the find and findAll methods give you back searchable objects, you can keep searching by invoking the find/findAll/etc. methods on the results.\n" ]
[ 7 ]
[]
[]
[ "beautifulsoup", "optimization", "python" ]
stackoverflow_0002712498_beautifulsoup_optimization_python.txt
Q: How to detect identical part(s) inside string? I try to break down the decoding algorithm wanted question into smaller questions. This is Part I. Question: two strings: s1 and s2 part of s1 is identical to part of s2 space is separator how to extract the identical part(s)? example 1: s1 = "12 November 2010 - 1 visitor" s2 = "6 July 2010 - 100 visitors" the identical parts are "2010", "-", "1" and "visitor" example 2: s1 = "Welcome, John!" s2 = "Welcome, Peter!" the identical parts are "Welcome," and "!" example 3: (to clarify the "!" example) s1 = "Welcome, Sam!" s2 = "Welcome, Tom!" the identical parts are "Welcome," and "m!" Python and Ruby preferred. Thanks A: For example 1 >>> s1 = 'November 2010 - 1 visitor' >>> s2 = '6 July 2010 - 100 visitors' >>> >>> [i for i in s1.split() if any(j for j in s2.split() if i in j)] ['2010', '-', '1', 'visitor'] >>> For both >>> s1 = "Welcome, John!" >>> s2 = "Welcome, Peter!" >>> [i for i in s1.replace('!',' !').split() if any(j for j in s2.replace('!',' !').split() if i in j)] ['Welcome,', '!'] >>> Note: Above codes will not work for example 3, which is OP just added A: EDIT: Updated this example to work with all the examples, including #1: def scan(s1, s2): # Find the longest match where s1 starts with s2 # Returns None if no matches l = len(s1) while 1: if not l: return None elif s1[:l] == s2[:l]: return s1[:l] else: l -= 1 def contains(s1, s2): D = {} # Remove duplicates using a dict L1 = s1.split(' ') L2 = s2.split(' ') # Don't add results which have already # been processed to satisfy example #1! DProcessed = {} for x in L1: yy = 0 for y in L2: if yy in DProcessed: yy += 1 continue # Scan from the start to the end of the words a = scan(x, y) if a: DProcessed[yy] = None D[a] = None break # Scan from the end to the start of the words a = scan(x[::-1], y[::-1]) if a: DProcessed[yy] = None D[a[::-1]] = None break yy += 1 return list(D.keys()) print contains("12 November 2010 - 1 visitor", "6 July 2010 - 100 visitors") print contains("Welcome, John!", "Welcome, Peter!") print contains("Welcome, Sam!", "Welcome, Tom!") Which outputs: ['1', 'visitor', '-', '2010'] ['Welcome,', '!'] ['Welcome,', 'm!'] A: s1 = "12 November 2010 - 1 visitor" s2 = "6 July 2010 - 100 visitors" l1 = s1.split() for item in l1: if item in s2: print item This splits on whitespace. A solution that also splits on word boundaries (in order to catch the ! in example 2) doesn't work in Python because re.split() won't split on zero-length matches. The third example, making even any substring of the words a potential match, is making things a lot more complicated because of the many possible variations (for 1234, I'd have to check against 1234, 123, 234, 12, 23, 34, 1, 2, 3 and 4, and with each extra digit, the number of permutations increases exponentially. A: The complete Ruby solution: def start_similar(i, j) front = '' for ix in (0...([i.size, j.size].min)) if i[ix] == j[ix] then front += i[ix].chr else break end end return front end def back_similar(i, j) back = '' for ix in (0...([i.size, j.size].min)).to_a.reverse dif = i.size < j.size ? j.size - i.size : i.size - j.size ci = i[ i.size < j.size ? ix : ix + dif ] cj = j[ i.size > j.size ? ix : ix + dif ] if ci == cj then back = ci.chr + back else break end end return back end def scan(x, y) a, b = x.split(' '), y.split(' ') result = [] for i in a do for j in b do result << start_similar(i, j) result << back_similar(i, j) end end return result.uniq.select do |r| not r.empty? end end puts scan( "12 November 2010 - 1 visitor", "6 July 2010 - 100 visitors" ).inspect # ["1", "2010", "0", "-", "visitor"] puts scan( "Welcome, John!", "Welcome, Peter!" ).inspect # ["Welcome,", "!"] puts scan( "Welcome, Sam!", "Welcome, Tom!" ).inspect # ["Welcome,", "m!"]
How to detect identical part(s) inside string?
I try to break down the decoding algorithm wanted question into smaller questions. This is Part I. Question: two strings: s1 and s2 part of s1 is identical to part of s2 space is separator how to extract the identical part(s)? example 1: s1 = "12 November 2010 - 1 visitor" s2 = "6 July 2010 - 100 visitors" the identical parts are "2010", "-", "1" and "visitor" example 2: s1 = "Welcome, John!" s2 = "Welcome, Peter!" the identical parts are "Welcome," and "!" example 3: (to clarify the "!" example) s1 = "Welcome, Sam!" s2 = "Welcome, Tom!" the identical parts are "Welcome," and "m!" Python and Ruby preferred. Thanks
[ "For example 1\n>>> s1 = 'November 2010 - 1 visitor'\n>>> s2 = '6 July 2010 - 100 visitors'\n>>> \n>>> [i for i in s1.split() if any(j for j in s2.split() if i in j)]\n['2010', '-', '1', 'visitor']\n>>>\n\nFor both\n>>> s1 = \"Welcome, John!\"\n>>> s2 = \"Welcome, Peter!\"\n>>> [i for i in s1.replace('!',' !').split() if any(j for j in s2.replace('!',' !').split() if i in j)]\n['Welcome,', '!']\n>>>\n\nNote: Above codes will not work for example 3, which is OP just added\n", "EDIT: Updated this example to work with all the examples, including #1: \ndef scan(s1, s2):\n # Find the longest match where s1 starts with s2\n # Returns None if no matches\n l = len(s1)\n while 1:\n if not l:\n return None\n elif s1[:l] == s2[:l]:\n return s1[:l]\n else:\n l -= 1\n\ndef contains(s1, s2):\n D = {} # Remove duplicates using a dict\n L1 = s1.split(' ')\n L2 = s2.split(' ')\n\n # Don't add results which have already \n # been processed to satisfy example #1!\n DProcessed = {}\n\n for x in L1:\n yy = 0\n for y in L2:\n if yy in DProcessed:\n yy += 1\n continue\n\n # Scan from the start to the end of the words\n a = scan(x, y)\n if a: \n DProcessed[yy] = None\n D[a] = None\n break\n\n # Scan from the end to the start of the words\n a = scan(x[::-1], y[::-1])\n if a: \n DProcessed[yy] = None\n D[a[::-1]] = None\n break\n yy += 1\n\n return list(D.keys())\n\nprint contains(\"12 November 2010 - 1 visitor\",\n \"6 July 2010 - 100 visitors\")\nprint contains(\"Welcome, John!\",\n \"Welcome, Peter!\")\nprint contains(\"Welcome, Sam!\",\n \"Welcome, Tom!\")\n\nWhich outputs:\n['1', 'visitor', '-', '2010']\n['Welcome,', '!']\n['Welcome,', 'm!']\n\n", "s1 = \"12 November 2010 - 1 visitor\"\ns2 = \"6 July 2010 - 100 visitors\"\nl1 = s1.split()\nfor item in l1:\n if item in s2:\n print item\n\nThis splits on whitespace. \nA solution that also splits on word boundaries (in order to catch the ! in example 2) doesn't work in Python because re.split() won't split on zero-length matches. \nThe third example, making even any substring of the words a potential match, is making things a lot more complicated because of the many possible variations (for 1234, I'd have to check against 1234, 123, 234, 12, 23, 34, 1, 2, 3 and 4, and with each extra digit, the number of permutations increases exponentially.\n", "The complete Ruby solution:\ndef start_similar(i, j)\n front = ''\n for ix in (0...([i.size, j.size].min))\n if i[ix] == j[ix] then\n front += i[ix].chr\n else\n break\n end\n end\n return front\nend\n\ndef back_similar(i, j)\n back = ''\n for ix in (0...([i.size, j.size].min)).to_a.reverse\n dif = i.size < j.size ? j.size - i.size : i.size - j.size\n ci = i[ i.size < j.size ? ix : ix + dif ]\n cj = j[ i.size > j.size ? ix : ix + dif ]\n if ci == cj then\n back = ci.chr + back\n else\n break\n end\n end\n return back\nend\n\ndef scan(x, y)\n a, b = x.split(' '), y.split(' ')\n result = []\n for i in a do\n for j in b do\n result << start_similar(i, j)\n result << back_similar(i, j)\n end\n end\n return result.uniq.select do |r| not r.empty? end\nend\n\nputs scan(\n \"12 November 2010 - 1 visitor\",\n \"6 July 2010 - 100 visitors\"\n).inspect\n# [\"1\", \"2010\", \"0\", \"-\", \"visitor\"]\n\nputs scan(\n \"Welcome, John!\",\n \"Welcome, Peter!\"\n).inspect\n# [\"Welcome,\", \"!\"]\n\nputs scan(\n \"Welcome, Sam!\",\n \"Welcome, Tom!\"\n).inspect\n# [\"Welcome,\", \"m!\"]\n\n" ]
[ 3, 3, 1, 1 ]
[]
[]
[ "pattern_matching", "python", "regex", "ruby" ]
stackoverflow_0002712466_pattern_matching_python_regex_ruby.txt
Q: Make the Move to Python 3 - Best practices We think about whether we should convert a quite large python web application to Python 3 in the near future. All experiences, possible challenges or guidelines are highly appreciated. A: My suggestion is that you stick with Python 2.6+, but simply add the -3 flag to warn you about incompatibilities with Python 3.0. Then you can make sure your Python 2.6 can be easily upgraded to Python 3.0 via 2to3, without actually making that jump quite yet. I would suggest you hold back at the moment, because you may at some point want to use a library and find out that it is only available for 2.6 and not 3.0; if you make sure to cleanup things flagged by -3, then you will be easily able to make the jump, but you will also be able to take advantage of the code that is only available for 2.6+ and which is not yet ready for 3.0. A: For each third-party library that you use, make sure it has Python 3 support. A lot of the major Python libraries are migrated to 3 now. Check the docs and mailing lists for the libraries. When all the libraries you depend on are supported, I suggest you go for it.
Make the Move to Python 3 - Best practices
We think about whether we should convert a quite large python web application to Python 3 in the near future. All experiences, possible challenges or guidelines are highly appreciated.
[ "My suggestion is that you stick with Python 2.6+, but simply add the -3 flag to warn you about incompatibilities with Python 3.0. Then you can make sure your Python 2.6 can be easily upgraded to Python 3.0 via 2to3, without actually making that jump quite yet. I would suggest you hold back at the moment, because you may at some point want to use a library and find out that it is only available for 2.6 and not 3.0; if you make sure to cleanup things flagged by -3, then you will be easily able to make the jump, but you will also be able to take advantage of the code that is only available for 2.6+ and which is not yet ready for 3.0.\n", "For each third-party library that you use, make sure it has Python 3 support. A lot of the major Python libraries are migrated to 3 now. Check the docs and mailing lists for the libraries.\nWhen all the libraries you depend on are supported, I suggest you go for it.\n" ]
[ 13, 4 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0002712283_python_python_3.x.txt
Q: Log Unittest output to a text file I am trying to log the output of tests to a text file. I am using the unittest module and want to log results into a text file instead of the screen. I have some script here to explain what has been tryied so far. This is the test script. import unittest, sys class TestOne(unittest.TestCase): def setUp(self): self.var = 'Tuesday' def tearDown(self): self.var = None class BasicTestOne(TestOne): def runTest(self): TestOne.setUp(self) self.assertEqual(self.var, 'Tuesday') class AbsoluteMoveTestSuite(unittest.TestSuite): # Tests to be tested by test suite def makeAbsoluteMoveTestSuite(): suite = unittest.TestSuite() suite.addTest(TestOne("BasicTestOne")) return suite def suite(): return unittest.makeSuite(TestOne) if __name__ == '__main__': unittest.main() I have added this to the file but it doesn't seem to work. log_file = 'log_file.txt' sys.stout = sys.sterr = open(log_file, 'w') return suite >> sys.stout and also: log_file = 'log_file.txt' return suite >> open(log_file, 'w') I have tried several different versions of this command. if __name__ == '__main__': unittest.main() >> open(log_file, 'w') I have tried this. I want the log file to be stored and created inside the python script. I do not want to have to call python tests.py >> log_file.txt. Thanks for any help A: You can pass the text runner into the main method. The text runner must be set up to write to a file rather than the std.err as it wraps the stream in a decorator. The following worked for me in python 2.6 if __name__ == '__main__': log_file = 'log_file.txt' with open(log_file, "w") as f: runner = unittest.TextTestRunner(f) unittest.main(testRunner=runner)
Log Unittest output to a text file
I am trying to log the output of tests to a text file. I am using the unittest module and want to log results into a text file instead of the screen. I have some script here to explain what has been tryied so far. This is the test script. import unittest, sys class TestOne(unittest.TestCase): def setUp(self): self.var = 'Tuesday' def tearDown(self): self.var = None class BasicTestOne(TestOne): def runTest(self): TestOne.setUp(self) self.assertEqual(self.var, 'Tuesday') class AbsoluteMoveTestSuite(unittest.TestSuite): # Tests to be tested by test suite def makeAbsoluteMoveTestSuite(): suite = unittest.TestSuite() suite.addTest(TestOne("BasicTestOne")) return suite def suite(): return unittest.makeSuite(TestOne) if __name__ == '__main__': unittest.main() I have added this to the file but it doesn't seem to work. log_file = 'log_file.txt' sys.stout = sys.sterr = open(log_file, 'w') return suite >> sys.stout and also: log_file = 'log_file.txt' return suite >> open(log_file, 'w') I have tried several different versions of this command. if __name__ == '__main__': unittest.main() >> open(log_file, 'w') I have tried this. I want the log file to be stored and created inside the python script. I do not want to have to call python tests.py >> log_file.txt. Thanks for any help
[ "You can pass the text runner into the main method. The text runner must be set up to write to a file rather than the std.err as it wraps the stream in a decorator. The following worked for me in python 2.6\nif __name__ == '__main__':\n log_file = 'log_file.txt'\n with open(log_file, \"w\") as f:\n runner = unittest.TextTestRunner(f)\n unittest.main(testRunner=runner)\n\n" ]
[ 30 ]
[]
[]
[ "logging", "python", "unit_testing" ]
stackoverflow_0002712831_logging_python_unit_testing.txt
Q: python dict function on enumerate object If I have an enumerate object x, why does doing the following: dict(x) clear all the items in the enumerate sequence? A: enumerate creates an iterator. A iterator is a python object that only knows about the current item of a sequence and how to get the next, but there is no way to restart it. Therefore, once you have used a iterator in a loop, it cannot give you any more items and appears to be empty. If you want to create a real sequence from a iterator you can call list on it. stuff = range(5,0,-1) it = enumerate(stuff) print dict(it), dict(it) # first consumes all items, so there are none left for the 2nd call seq = list(enumerate(stuff)) # creates a list of all the items print dict(seq), dict(seq) # you can use it as often as you want
python dict function on enumerate object
If I have an enumerate object x, why does doing the following: dict(x) clear all the items in the enumerate sequence?
[ "enumerate creates an iterator. A iterator is a python object that only knows about the current item of a sequence and how to get the next, but there is no way to restart it. Therefore, once you have used a iterator in a loop, it cannot give you any more items and appears to be empty.\nIf you want to create a real sequence from a iterator you can call list on it.\nstuff = range(5,0,-1)\nit = enumerate(stuff)\nprint dict(it), dict(it) # first consumes all items, so there are none left for the 2nd call\n\nseq = list(enumerate(stuff)) # creates a list of all the items\nprint dict(seq), dict(seq) # you can use it as often as you want\n\n" ]
[ 19 ]
[]
[]
[ "dictionary", "enumerate", "python" ]
stackoverflow_0002713712_dictionary_enumerate_python.txt
Q: When to use buildout:eggs and when to install via zc.recipe.egg? There seem to be more than one way to install eggs into a buildout. Way 1: [buildout] ... eggs = eggname othereggname ... Way 2: [buildout] ... parts = eggs [eggs] recipe = zc.recipe.egg eggs = eggname = othereggname Both ways work. ( variation on way 2 would be to install each requirement as a separate part. ) What is the difference between these 2 methods? For my projects, I'm using buildout with djangorecipe and mr.developer. A: In both cases, the "eggs=" makes those eggs available to that part, which means they're getting installed. The buildout eggs don't get any additional treatment. The big difference is that "recipe = zc.recipe.egg" ALSO tries to create scripts for all the eggs defined there. (Scripts meaning the "console_scripts" entry points, not the old distutils "scripts=", btw) The way I normally work: I use the eggs in [buildout] to list my most important eggs ("myproject"). In the djangorecipe part, I have basically an "eggs = ${buildout:eggs}". And a [console_scripts] part with the zc.recipe.egg recipe to make clear that I want console scripts out of the eggs there. I put extra tools like pep8 in there.
When to use buildout:eggs and when to install via zc.recipe.egg?
There seem to be more than one way to install eggs into a buildout. Way 1: [buildout] ... eggs = eggname othereggname ... Way 2: [buildout] ... parts = eggs [eggs] recipe = zc.recipe.egg eggs = eggname = othereggname Both ways work. ( variation on way 2 would be to install each requirement as a separate part. ) What is the difference between these 2 methods? For my projects, I'm using buildout with djangorecipe and mr.developer.
[ "In both cases, the \"eggs=\" makes those eggs available to that part, which means they're getting installed.\nThe buildout eggs don't get any additional treatment.\nThe big difference is that \"recipe = zc.recipe.egg\" ALSO tries to create scripts for all the eggs defined there. (Scripts meaning the \"console_scripts\" entry points, not the old distutils \"scripts=\", btw)\nThe way I normally work: I use the eggs in [buildout] to list my most important eggs (\"myproject\"). In the djangorecipe part, I have basically an \"eggs = ${buildout:eggs}\".\nAnd a [console_scripts] part with the zc.recipe.egg recipe to make clear that I want console scripts out of the eggs there. I put extra tools like pep8 in there.\n" ]
[ 2 ]
[]
[]
[ "buildout", "python" ]
stackoverflow_0002712514_buildout_python.txt
Q: More compact layout In the following code, I'd like to get rid of the margin around the buttons. I'd like to have the buttons stretch all the way to the edge of the frame. How can I do that? import sys from PyQt4.QtGui import * from PyQt4.QtCore import * app = QApplication(sys.argv) window = QWidget() layout = QVBoxLayout() layout.setSpacing(0) window.setLayout(layout) for i in range(2): layout.addWidget(QPushButton()) window.show() app.exec_() A: layout.setContentsMargin(0, 0, 0, 0) should do the trick A: Unfortunately I don't have a working Qt at hand to try right now, but I believe you might get your wish by using style sheets with both margins and padding set to 0 (you might also need to tweak the size policy, as it might otherwise block the widgets from some kind of stretching your style requires).
More compact layout
In the following code, I'd like to get rid of the margin around the buttons. I'd like to have the buttons stretch all the way to the edge of the frame. How can I do that? import sys from PyQt4.QtGui import * from PyQt4.QtCore import * app = QApplication(sys.argv) window = QWidget() layout = QVBoxLayout() layout.setSpacing(0) window.setLayout(layout) for i in range(2): layout.addWidget(QPushButton()) window.show() app.exec_()
[ "layout.setContentsMargin(0, 0, 0, 0)\n\nshould do the trick\n", "Unfortunately I don't have a working Qt at hand to try right now, but I believe you might get your wish by using style sheets with both margins and padding set to 0 (you might also need to tweak the size policy, as it might otherwise block the widgets from some kind of stretching your style requires).\n" ]
[ 4, 1 ]
[]
[]
[ "layout", "pyqt", "pyqt4", "python", "qt" ]
stackoverflow_0002712355_layout_pyqt_pyqt4_python_qt.txt
Q: python decorator to modify variable in current scope Goal: Make a decorator which can modify the scope that it is used in. If it worked: class Blah(): # or perhaps class Blah(ParentClassWhichMakesThisPossible) def one(self): pass @decorated def two(self): pass >>> Blah.decorated ["two"] Why? I essentially want to write classes which can maintain specific dictionaries of methods, so that I can retrieve lists of available methods of different types on a per class basis. errr..... I want to do this: class RuleClass(ParentClass): @rule def blah(self): pass @rule def kapow(self): pass def shazam(self): class OtherRuleClass(ParentClass): @rule def foo(self): pass def bar(self): pass >>> RuleClass.rules.keys() ["blah", "kapow"] >>> OtherRuleClass.rules.keys() ["foo"] A: You can do what you want with a class decorator (in Python 2.6) or a metaclass. The class decorator version: def rule(f): f.rule = True return f def getRules(cls): cls.rules = {} for attr, value in cls.__dict__.iteritems(): if getattr(value, 'rule', False): cls.rules[attr] = value return cls @getRules class RuleClass: @rule def foo(self): pass The metaclass version would be: def rule(f): f.rule = True return f class RuleType(type): def __init__(self, name, bases, attrs): self.rules = {} for attr, value in attrs.iteritems(): if getattr(value, 'rule', False): self.rules[attr] = value super(RuleType, self).__init__(name, bases, attrs) class RuleBase(object): __metaclass__ = RuleType class RuleClass(RuleBase): @rule def foo(self): pass Notice that neither of these do what you ask for (modify the calling namespace) because it's fragile, hard and often impossible. Instead they both post-process the class -- through the class decorator or the metaclass's __init__ method -- by inspecting all the attributes and filling the rules attribute. The difference between the two is that the metaclass solution works in Python 2.5 and earlier (down to 2.2), and that the metaclass is inherited. With the decorator, subclasses have to each apply the decorator individually (if they want to set the rules attribute.) Both solutions do not take inheritance into account -- they don't look at the parent class when looking for methods marked as rules, nor do they look at the parent class rules attribute. It's not hard to extend either to do that, if that's what you want. A: Problem is, at the time the decorated decorator is called, there is no object Blah yet: the class object is built after the class body finishes executing. Simplest is to have decorated stash the info "somewhere else", e.g. a function attribute, then a final pass (a class decorator or metaclass) reaps that info into the dictionary you desire. Class decorators are simpler, but they don't get inherited (so they wouldn't come from a parent class), while metaclasses are inherited -- so if you insist on inheritance, a metaclass it will have to be. Simplest-first, with a class decorator and the "list" variant you have at the start of your Q rather than the "dict" variant you have later: import inspect def classdecorator(aclass): decorated = [] for name, value in inspect.getmembers(aclass, inspect.ismethod): if hasattr(value, '_decorated'): decorated.append(name) del value._decorated aclass.decorated = decorated return aclass def decorated(afun): afun._decorated = True return afun now, @classdecorator class Blah(object): def one(self): pass @decorated def two(self): pass gives you the Blah.decorated list you request in the first part of your Q. Building a dict instead, as you request in the second part of your Q, just means changing decorated.append(name) to decorated[name] = value in the code above, and of course initializing decorated in the class decorator to an empty dict rather than an empty list. The metaclass variant would use the metaclass's __init__ to perform essentially the same post-processing after the class body is built -- a metaclass's __init__ gets a dict corresponding to the class body as its last argument (but you'll have to support inheritance yourself by appropriately dealing with any base class's analogous dict or list). So the metaclass approach is only "somewhat" more complex in practice than a class decorator, but conceptually it's felt to be much more difficult by most people. I'll give all the details for the metaclass if you need them, but I'd recommend sticking with the simpler class decorator if feasible.
python decorator to modify variable in current scope
Goal: Make a decorator which can modify the scope that it is used in. If it worked: class Blah(): # or perhaps class Blah(ParentClassWhichMakesThisPossible) def one(self): pass @decorated def two(self): pass >>> Blah.decorated ["two"] Why? I essentially want to write classes which can maintain specific dictionaries of methods, so that I can retrieve lists of available methods of different types on a per class basis. errr..... I want to do this: class RuleClass(ParentClass): @rule def blah(self): pass @rule def kapow(self): pass def shazam(self): class OtherRuleClass(ParentClass): @rule def foo(self): pass def bar(self): pass >>> RuleClass.rules.keys() ["blah", "kapow"] >>> OtherRuleClass.rules.keys() ["foo"]
[ "You can do what you want with a class decorator (in Python 2.6) or a metaclass. The class decorator version:\ndef rule(f):\n f.rule = True\n return f\n\ndef getRules(cls):\n cls.rules = {}\n for attr, value in cls.__dict__.iteritems():\n if getattr(value, 'rule', False):\n cls.rules[attr] = value\n return cls\n\n@getRules\nclass RuleClass:\n @rule\n def foo(self):\n pass\n\nThe metaclass version would be:\ndef rule(f):\n f.rule = True\n return f\n\nclass RuleType(type):\n def __init__(self, name, bases, attrs):\n self.rules = {}\n for attr, value in attrs.iteritems():\n if getattr(value, 'rule', False):\n self.rules[attr] = value\n super(RuleType, self).__init__(name, bases, attrs)\n\nclass RuleBase(object):\n __metaclass__ = RuleType\n\nclass RuleClass(RuleBase):\n @rule\n def foo(self):\n pass\n\nNotice that neither of these do what you ask for (modify the calling namespace) because it's fragile, hard and often impossible. Instead they both post-process the class -- through the class decorator or the metaclass's __init__ method -- by inspecting all the attributes and filling the rules attribute. The difference between the two is that the metaclass solution works in Python 2.5 and earlier (down to 2.2), and that the metaclass is inherited. With the decorator, subclasses have to each apply the decorator individually (if they want to set the rules attribute.)\nBoth solutions do not take inheritance into account -- they don't look at the parent class when looking for methods marked as rules, nor do they look at the parent class rules attribute. It's not hard to extend either to do that, if that's what you want.\n", "Problem is, at the time the decorated decorator is called, there is no object Blah yet: the class object is built after the class body finishes executing. Simplest is to have decorated stash the info \"somewhere else\", e.g. a function attribute, then a final pass (a class decorator or metaclass) reaps that info into the dictionary you desire.\nClass decorators are simpler, but they don't get inherited (so they wouldn't come from a parent class), while metaclasses are inherited -- so if you insist on inheritance, a metaclass it will have to be. Simplest-first, with a class decorator and the \"list\" variant you have at the start of your Q rather than the \"dict\" variant you have later:\nimport inspect\n\ndef classdecorator(aclass):\n decorated = []\n for name, value in inspect.getmembers(aclass, inspect.ismethod):\n if hasattr(value, '_decorated'):\n decorated.append(name)\n del value._decorated\n aclass.decorated = decorated\n return aclass\n\ndef decorated(afun):\n afun._decorated = True\n return afun\n\nnow,\n@classdecorator\nclass Blah(object):\n\n def one(self):\n pass\n\n @decorated\n def two(self):\n pass\n\ngives you the Blah.decorated list you request in the first part of your Q. Building a dict instead, as you request in the second part of your Q, just means changing decorated.append(name) to decorated[name] = value in the code above, and of course initializing decorated in the class decorator to an empty dict rather than an empty list.\nThe metaclass variant would use the metaclass's __init__ to perform essentially the same post-processing after the class body is built -- a metaclass's __init__ gets a dict corresponding to the class body as its last argument (but you'll have to support inheritance yourself by appropriately dealing with any base class's analogous dict or list). So the metaclass approach is only \"somewhat\" more complex in practice than a class decorator, but conceptually it's felt to be much more difficult by most people. I'll give all the details for the metaclass if you need them, but I'd recommend sticking with the simpler class decorator if feasible.\n" ]
[ 9, 4 ]
[]
[]
[ "decorator", "python", "scope" ]
stackoverflow_0002714244_decorator_python_scope.txt
Q: Python, implementing proxy support for a socket based application (not urllib2) I am little stumped: I have a simple messenger client program (pure python, sockets), and I wanted to add proxy support (http/s, socks), however I am a little confused on how to go about it. I am assuming that the connection on the socket level will be done to the proxy server, at which point the headers should contain a CONNECT + destination IP (of the chat server) and authentication, (if proxy requires so), however the rest is a little beyond me. How is the subsequent connection handled, specifically the reading/writing, etc... Are there any guides on proxy support implementation for socket based (tcp) programming in Python? Thank you A: Maybe use something like SocksiPy which does all the protocol details for you and would let you connect through a SOCKS proxy as you would without it? A: It is pretty simple - after you send the HTTP request: CONNECT example.com:1234 HTTP/1.0\r\nHost: example.com:1234\r\n<additional headers incl. authentication>\r\n\r\n, the server responds with HTTP/1.0 200 Connection established\r\n\r\n and then (after the double line ends) you can communicate just as you would communicate with example.com port 1234 without the proxy (as I understand you already have the client-server communication part done). A: Have a look at stunnel. Stunnel can allow you to secure non-SSL aware daemons and protocols (like POP, IMAP, LDAP, etc) by having Stunnel provide the encryption, requiring no changes to the daemon's code
Python, implementing proxy support for a socket based application (not urllib2)
I am little stumped: I have a simple messenger client program (pure python, sockets), and I wanted to add proxy support (http/s, socks), however I am a little confused on how to go about it. I am assuming that the connection on the socket level will be done to the proxy server, at which point the headers should contain a CONNECT + destination IP (of the chat server) and authentication, (if proxy requires so), however the rest is a little beyond me. How is the subsequent connection handled, specifically the reading/writing, etc... Are there any guides on proxy support implementation for socket based (tcp) programming in Python? Thank you
[ "Maybe use something like SocksiPy which does all the protocol details for you and would let you connect through a SOCKS proxy as you would without it?\n", "It is pretty simple - after you send the HTTP request: CONNECT example.com:1234 HTTP/1.0\\r\\nHost: example.com:1234\\r\\n<additional headers incl. authentication>\\r\\n\\r\\n, the server responds with HTTP/1.0 200 Connection established\\r\\n\\r\\n and then (after the double line ends) you can communicate just as you would communicate with example.com port 1234 without the proxy (as I understand you already have the client-server communication part done).\n", "Have a look at stunnel. \n\nStunnel can allow you to secure\n non-SSL aware daemons and protocols\n (like POP, IMAP, LDAP, etc) by having\n Stunnel provide the encryption,\n requiring no changes to the daemon's\n code\n\n" ]
[ 3, 2, 0 ]
[]
[]
[ "proxy", "python", "sockets", "socks", "tcp" ]
stackoverflow_0002646983_proxy_python_sockets_socks_tcp.txt
Q: User Crontab + Python + Random wallpapers = Not working? I have a python script that correctly sets the desktop wallpaper via gconf to a random picture in a given folder. I then have the following entry in my crontab * * * * * python /home/bolster/bin/change-background.py And syslog correctly reports execution Apr 26 14:11:01 bolster-desktop CRON[9751]: (bolster) CMD (python /home/bolster/bin/change-background.py) Apr 26 14:12:01 bolster-desktop CRON[9836]: (bolster) CMD (python /home/bolster/bin/change-background.py) Apr 26 14:13:01 bolster-desktop CRON[9860]: (bolster) CMD (python /home/bolster/bin/change-background.py) Apr 26 14:14:01 bolster-desktop CRON[9905]: (bolster) CMD (python /home/bolster/bin/change-background.py) Apr 26 14:15:01 bolster-desktop CRON[9948]: (bolster) CMD (python /home/bolster/bin/change-background.py) Apr 26 14:16:01 bolster-desktop CRON[9983]: (bolster) CMD (python /home/bolster/bin/change-background.py) But no desktopy changey, Any ideas? A: Your script depends on the DISPLAY environment variable, which is set when you execute the script from the shell in an X session, but unset when the script is run from cron. A: As per Bolo's observation, I forgot about building in the DISPLAY into either the script or the crontab. Easiest solution is to prepend the crontab with env DISPLAY=:0.0 so: * * * * * env DISPLAY=:0.0 python /home/bolster/bin/change-background.py A: To set the DISPLAY environment variable, I would put it directly in the crontab. Also, I would make the script executable and give it a proper header (#!/usr/bin/env python) so that it can be executed directly. Additionally, you can rely on the PWD being set to HOME when the crontab runs. My crontab would look like this: DISPLAY=:0.0 * * * * * bin/change-background.py You can also set the PATH (in the same manner as DISPLAY) so that the bin/ is not even needed. The main gotcha for setting environment in the crontab is that values are not variable-interpolated. For example, this not give the expected results: PATH=$HOME/bin:$PATH
User Crontab + Python + Random wallpapers = Not working?
I have a python script that correctly sets the desktop wallpaper via gconf to a random picture in a given folder. I then have the following entry in my crontab * * * * * python /home/bolster/bin/change-background.py And syslog correctly reports execution Apr 26 14:11:01 bolster-desktop CRON[9751]: (bolster) CMD (python /home/bolster/bin/change-background.py) Apr 26 14:12:01 bolster-desktop CRON[9836]: (bolster) CMD (python /home/bolster/bin/change-background.py) Apr 26 14:13:01 bolster-desktop CRON[9860]: (bolster) CMD (python /home/bolster/bin/change-background.py) Apr 26 14:14:01 bolster-desktop CRON[9905]: (bolster) CMD (python /home/bolster/bin/change-background.py) Apr 26 14:15:01 bolster-desktop CRON[9948]: (bolster) CMD (python /home/bolster/bin/change-background.py) Apr 26 14:16:01 bolster-desktop CRON[9983]: (bolster) CMD (python /home/bolster/bin/change-background.py) But no desktopy changey, Any ideas?
[ "Your script depends on the DISPLAY environment variable, which is set when you execute the script from the shell in an X session, but unset when the script is run from cron.\n", "As per Bolo's observation, I forgot about building in the DISPLAY into either the script or the crontab. \nEasiest solution is to prepend the crontab with env DISPLAY=:0.0\nso:\n* * * * * env DISPLAY=:0.0 python /home/bolster/bin/change-background.py\n\n", "To set the DISPLAY environment variable, I would put it directly in the crontab. Also, I would make the script executable and give it a proper header (#!/usr/bin/env python) so that it can be executed directly. Additionally, you can rely on the PWD being set to HOME when the crontab runs. \nMy crontab would look like this:\nDISPLAY=:0.0\n* * * * * bin/change-background.py\n\nYou can also set the PATH (in the same manner as DISPLAY) so that the bin/ is not even needed.\n\nThe main gotcha for setting environment in the crontab is that values are not variable-interpolated. For example, this not give the expected results:\nPATH=$HOME/bin:$PATH\n\n" ]
[ 6, 2, 2 ]
[]
[]
[ "cron", "gconf", "gnome", "python", "ubuntu" ]
stackoverflow_0002713724_cron_gconf_gnome_python_ubuntu.txt
Q: How to get the content of "Google Dictionary" by python script Thank to the script, I've logged in google successfully. But I replaced the value of "gv_home_page_url" with http:// www.google.com.tw/dictionary/wordlist?hl=zh-TW, the error occured. The message is " urllib2.HTTPError: HTTP Error 500: Internal Server Error" Any idea will be appreciated, thanks. A: That's not a valid URL. If you try to enter it in your bar, you'll get redirected to Google search results. Using urllib2, you'll get an error. See here for another way to get data from Google Dictionary: http://googlesystem.blogspot.com/2009/12/on-googles-unofficial-dictionary-api.html A: Does Google require an SSL url? You're using "http://" but the example script uses "https://"
How to get the content of "Google Dictionary" by python script
Thank to the script, I've logged in google successfully. But I replaced the value of "gv_home_page_url" with http:// www.google.com.tw/dictionary/wordlist?hl=zh-TW, the error occured. The message is " urllib2.HTTPError: HTTP Error 500: Internal Server Error" Any idea will be appreciated, thanks.
[ "That's not a valid URL. If you try to enter it in your bar, you'll get redirected to Google search results. Using urllib2, you'll get an error.\nSee here for another way to get data from Google Dictionary:\nhttp://googlesystem.blogspot.com/2009/12/on-googles-unofficial-dictionary-api.html\n", "Does Google require an SSL url? You're using \"http://\" but the example script uses \"https://\" \n" ]
[ 1, 0 ]
[]
[]
[ "python", "web_applications", "web_services" ]
stackoverflow_0002711048_python_web_applications_web_services.txt
Q: Cant fetch production db results using Google app engine remote_api Hey, I'm trying to work out with /remote_api with a django-patch app engine app i got running. i want to select a few rows from my online production app locally. i cant seem to manage to do so, everything authenticates fine, it doesnt breaks on imports, but when i try to fetch something it just doesnt print anything. Placed the test python inside my local app dir. #!/usr/bin/env python # import os import sys # Hardwire in appengine modules to PYTHONPATH # or use wrapper to do it more elegantly appengine_dirs = ['myworkingpath'] sys.path.extend(appengine_dirs) # Add your models to path my_root_dir = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, my_root_dir) from google.appengine.ext import db from google.appengine.ext.remote_api import remote_api_stub import getpass APP_NAME = 'Myappname' os.environ['AUTH_DOMAIN'] = 'gmail.com' os.environ['USER_EMAIL'] = 'myuser@gmail.com' def auth_func(): return (raw_input('Username:'), getpass.getpass('Password:')) # Use local dev server by passing in as parameter: # servername='localhost:8080' # Otherwise, remote_api assumes you are targeting APP_NAME.appspot.com remote_api_stub.ConfigureRemoteDatastore(APP_NAME, '/remote_api', auth_func) # Do stuff like your code was running on App Engine from channel.models import Channel, Channel2Operator myresults = mymodel.all().fetch(10) for result in myresults: print result.key() it doesn't give any error or print anything. so does the remote_api console example google got. when i print the myresults i get []. A: App Engine patch monkeypatches the ext.db module, mutilating the kind names. You need to make sure you import App Engine patch from your script, to give it the opportunity to mangle things as per usual, or you won't see any data returned.
Cant fetch production db results using Google app engine remote_api
Hey, I'm trying to work out with /remote_api with a django-patch app engine app i got running. i want to select a few rows from my online production app locally. i cant seem to manage to do so, everything authenticates fine, it doesnt breaks on imports, but when i try to fetch something it just doesnt print anything. Placed the test python inside my local app dir. #!/usr/bin/env python # import os import sys # Hardwire in appengine modules to PYTHONPATH # or use wrapper to do it more elegantly appengine_dirs = ['myworkingpath'] sys.path.extend(appengine_dirs) # Add your models to path my_root_dir = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, my_root_dir) from google.appengine.ext import db from google.appengine.ext.remote_api import remote_api_stub import getpass APP_NAME = 'Myappname' os.environ['AUTH_DOMAIN'] = 'gmail.com' os.environ['USER_EMAIL'] = 'myuser@gmail.com' def auth_func(): return (raw_input('Username:'), getpass.getpass('Password:')) # Use local dev server by passing in as parameter: # servername='localhost:8080' # Otherwise, remote_api assumes you are targeting APP_NAME.appspot.com remote_api_stub.ConfigureRemoteDatastore(APP_NAME, '/remote_api', auth_func) # Do stuff like your code was running on App Engine from channel.models import Channel, Channel2Operator myresults = mymodel.all().fetch(10) for result in myresults: print result.key() it doesn't give any error or print anything. so does the remote_api console example google got. when i print the myresults i get [].
[ "App Engine patch monkeypatches the ext.db module, mutilating the kind names. You need to make sure you import App Engine patch from your script, to give it the opportunity to mangle things as per usual, or you won't see any data returned.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002708695_google_app_engine_python.txt
Q: Why would it be necessary to subclass from object in Python? I've been using Python for quite a while now, and I'm still unsure as to why you would subclass from object. What is the difference between this: class MyClass(): pass And this: class MyClass(object): pass As far as I understand, object is the base class for all classes and the subclassing is implied. Do you get anything from explicitly subclassing from it? What is the most "Pythonic" thing to do? A: This is oldstyle and new style classes in python 2.x. The second form is the up to date version and exist from python 2.2 and above. For new code you should only use new style classes. In Python 3.x you can again use both form indifferently as the new style is the only one left and both form are truly equivalent. However I believe you should continue to use the MyClass(object) form even for 3.x code at least until python 3.x is widely adopted to avoid any misunderstanding with potential readers of your code used to 2.x. Behavior between old style and new style classes is very different regarding to certain features like use of super(). See here : New Style classes You can also see here on SO. A: Agree with @kriss, @Noctis, and @Carson, plus more color from me: class X: pass and class X(): pass are synonyms for classic classes while class X(object): pass is for new-style classes, as you can see here: >>> class X:pass ... >>> class Y(): pass ... >>> class Z(object): pass ... >>> >>> type(X), type(Y), type(Z) (<type 'classobj'>, <type 'classobj'>, <type 'type'>) Look at the reference provided by @kriss for more details into the differences. What is invalid in Python 3 is the concept of the classic class... the reason is because classic classes have been deprecated. All three idioms create only new-style classes in any 3.x: >>> class X:pass ... >>> class Y(): pass ... >>> class Z(object): pass ... >>> >>> type(X), type(Y), type(Z) (<class 'type'>, <class 'type'>, <class 'type'>) Bottom-line? If you're coding in Python 2, try to use new-style classes as much as possible. This way, you've built in your migration path already, plus new-style classes offer more features than classic classes do. (This is somewhat subjective, but if your [classic] classes are relatively simple, then it's possible you won't need to do anything to get them working in Python 3.)
Why would it be necessary to subclass from object in Python?
I've been using Python for quite a while now, and I'm still unsure as to why you would subclass from object. What is the difference between this: class MyClass(): pass And this: class MyClass(object): pass As far as I understand, object is the base class for all classes and the subclassing is implied. Do you get anything from explicitly subclassing from it? What is the most "Pythonic" thing to do?
[ "This is oldstyle and new style classes in python 2.x. The second form is the up to date version and exist from python 2.2 and above. For new code you should only use new style classes.\nIn Python 3.x you can again use both form indifferently as the new style is the only one left and both form are truly equivalent. However I believe you should continue to use the MyClass(object) form even for 3.x code at least until python 3.x is widely adopted to avoid any misunderstanding with potential readers of your code used to 2.x.\nBehavior between old style and new style classes is very different regarding to certain features like use of super().\nSee here : New Style classes\nYou can also see here on SO.\n", "Agree with @kriss, @Noctis, and @Carson, plus more color from me:\nclass X: pass and class X(): pass are synonyms for classic classes while\nclass X(object): pass is for new-style classes, as you can see here:\n>>> class X:pass\n... \n>>> class Y(): pass\n... \n>>> class Z(object): pass\n... \n>>> \n>>> type(X), type(Y), type(Z)\n(<type 'classobj'>, <type 'classobj'>, <type 'type'>)\n\nLook at the reference provided by @kriss for more details into the differences. What is invalid in Python 3 is the concept of the classic class... the reason is because classic classes have been deprecated. All three idioms create only new-style classes in any 3.x:\n>>> class X:pass\n... \n>>> class Y(): pass\n... \n>>> class Z(object): pass\n... \n>>> \n>>> type(X), type(Y), type(Z)\n(<class 'type'>, <class 'type'>, <class 'type'>)\n\nBottom-line? If you're coding in Python 2, try to use new-style classes as much as possible. This way, you've built in your migration path already, plus new-style classes offer more features than classic classes do. (This is somewhat subjective, but if your [classic] classes are relatively simple, then it's possible you won't need to do anything to get them working in Python 3.)\n" ]
[ 12, 9 ]
[]
[]
[ "python" ]
stackoverflow_0002715186_python.txt
Q: Voting on Hacker News stories programmatically? I decided to write an app like: http://michaelgrinich.com/hackernews/ but for Android devices, my idea will use a web application backend (because I rather code in Python and for the web than completely in Java for Android devices). What I have right now implemented is something like this: $ curl -i http://localhost:8080/stories.json?page=1\&stories=1 HTTP/1.0 200 OK Date: Sun, 25 Apr 2010 07:59:37 GMT Server: WSGIServer/0.1 Python/2.6.5 Content-Length: 296 Content-Type: application/json [{"title": "Don\u2019t talk to aliens, warns Stephen Hawking", "url": "http://www.timesonline.co.uk/tol/news/science/space/article7107207.ece?", "unix_time": 1272175177, "comments": 15, "score": 38, "user": "chaostheory", "position": 1, "human_time": "Sun Apr 25 01:59:37 2010", "id": "1292241"}] The next step (and final I think) is voting, my design is doing something like this: $ curl -i http://localhost:8080/stories/1 -d "vote=up" -u username:password Will vote up and: $ curl -i http://localhost:8080/stories/1 -d "vote=down" -u username:password Vote down. I have no idea how to do it though... I was planning to use Twill but the login link is always different, e.g.: http://news.ycombinator.com/x?fnid=7u89ccHKln Later the Android app will consume this API. Any experience with programmatically browsing Hacker News? A: Twill has a way to list all the links, and you get the links as an objects: login_url = '' for link in showlinks(): if link.text == "login": login_url = link.url go(login_url) So link will be something like: http://news.ycombinator.com/x?fnid=SvdNlGQoqo
Voting on Hacker News stories programmatically?
I decided to write an app like: http://michaelgrinich.com/hackernews/ but for Android devices, my idea will use a web application backend (because I rather code in Python and for the web than completely in Java for Android devices). What I have right now implemented is something like this: $ curl -i http://localhost:8080/stories.json?page=1\&stories=1 HTTP/1.0 200 OK Date: Sun, 25 Apr 2010 07:59:37 GMT Server: WSGIServer/0.1 Python/2.6.5 Content-Length: 296 Content-Type: application/json [{"title": "Don\u2019t talk to aliens, warns Stephen Hawking", "url": "http://www.timesonline.co.uk/tol/news/science/space/article7107207.ece?", "unix_time": 1272175177, "comments": 15, "score": 38, "user": "chaostheory", "position": 1, "human_time": "Sun Apr 25 01:59:37 2010", "id": "1292241"}] The next step (and final I think) is voting, my design is doing something like this: $ curl -i http://localhost:8080/stories/1 -d "vote=up" -u username:password Will vote up and: $ curl -i http://localhost:8080/stories/1 -d "vote=down" -u username:password Vote down. I have no idea how to do it though... I was planning to use Twill but the login link is always different, e.g.: http://news.ycombinator.com/x?fnid=7u89ccHKln Later the Android app will consume this API. Any experience with programmatically browsing Hacker News?
[ "Twill has a way to list all the links, and you get the links as an objects:\nlogin_url = ''\nfor link in showlinks():\n if link.text == \"login\":\n login_url = link.url\n\ngo(login_url)\n\nSo link will be something like: http://news.ycombinator.com/x?fnid=SvdNlGQoqo\n" ]
[ 2 ]
[]
[]
[ "api", "python", "web_scraping" ]
stackoverflow_0002707575_api_python_web_scraping.txt
Q: Passing list and dictionary type parameter with Python When I run this code def func(x, y, *w, **z): print x print y if w: print w if z: print z else: print "None" func(10,20, 1,2,3,{'k':'a'}) I get the result as follows. 10 20 (1, 2, 3, {'k': 'a'}) None But, I expected as follows, I mean the list parameters (1,2,3) matching *w, and dictionary matching **z. 10 20 (1,2,3) {'k':'a'} Q : What went wrong? How can I pass the list and dictionary as parameters? Added func(10,20, 10,20,30, k='a') seems to be working A: Put two asterisks before the dictionary: func(10,20, 1,2,3,**{'k':'a'}) A: I'm not sure what the "input" format is, but this will work: func(10,20, 1,2,3, k='a') With this, you don't even need to put the k=a out there at the end, it can be anywhere after the first two arguments. Then the 1,2,3 and other "unnamed" arguments get stuffed into a tuple (I think?) for the single-star arg. A: If you want to be extra explicit, you can do func(10,20,*[1,2,3],**{'k':'a'}) to specify (to the reader) which argument you want to go with each special-form parameter.
Passing list and dictionary type parameter with Python
When I run this code def func(x, y, *w, **z): print x print y if w: print w if z: print z else: print "None" func(10,20, 1,2,3,{'k':'a'}) I get the result as follows. 10 20 (1, 2, 3, {'k': 'a'}) None But, I expected as follows, I mean the list parameters (1,2,3) matching *w, and dictionary matching **z. 10 20 (1,2,3) {'k':'a'} Q : What went wrong? How can I pass the list and dictionary as parameters? Added func(10,20, 10,20,30, k='a') seems to be working
[ "Put two asterisks before the dictionary:\nfunc(10,20, 1,2,3,**{'k':'a'})\n\n", "I'm not sure what the \"input\" format is, but this will work:\nfunc(10,20, 1,2,3, k='a')\n\nWith this, you don't even need to put the k=a out there at the end, it can be anywhere after the first two arguments. Then the 1,2,3 and other \"unnamed\" arguments get stuffed into a tuple (I think?) for the single-star arg.\n", "If you want to be extra explicit, you can do\nfunc(10,20,*[1,2,3],**{'k':'a'})\n\nto specify (to the reader) which argument you want to go with each special-form parameter.\n" ]
[ 7, 2, 1 ]
[]
[]
[ "parameter_passing", "python" ]
stackoverflow_0002715751_parameter_passing_python.txt
Q: pyinotify file deletion user I'm trying to use pyinotify to alert me whenever files are deleted, but I want to know what user deleted the files. Is there a way to find this information? A: That information isn't exposed by the underlying inotify system. This is the main change notification API for the Linux kernel, so you aren't going to find another notification system that provides this. If you want to track who deleted the file, it would be easiest to make the deleter announce what it is going to do. If you don't have control over the deleter (that is, you still have to maintain a POSIX interface for deleting the file), you could look at writing a custom file system wrapper in FUSE, which might expose the UID of the process that called unlink().
pyinotify file deletion user
I'm trying to use pyinotify to alert me whenever files are deleted, but I want to know what user deleted the files. Is there a way to find this information?
[ "That information isn't exposed by the underlying inotify system. This is the main change notification API for the Linux kernel, so you aren't going to find another notification system that provides this.\nIf you want to track who deleted the file, it would be easiest to make the deleter announce what it is going to do. If you don't have control over the deleter (that is, you still have to maintain a POSIX interface for deleting the file), you could look at writing a custom file system wrapper in FUSE, which might expose the UID of the process that called unlink().\n" ]
[ 3 ]
[]
[]
[ "delete_file", "pyinotify", "python" ]
stackoverflow_0002715819_delete_file_pyinotify_python.txt
Q: Reading a Delphi binary file in Python I have a file that was written with the following Delphi declaration ... Type Tfulldata = Record dpoints, dloops : integer; dtime, bT, sT, hI, LI : real; tm : real; data : array[1..armax] Of Real; End; ... Var: fh: File Of Tfulldata; I want to analyse the data in the files (many MB in size) using Python if possible - is there an easy way to read in the data and cast the data into Python objects similar in form to the Delphi records? Does anyone know of a library perhaps that does this? This is compiled on Delphi 7 with the following options which may (or may not) be pertinent, Record Field Alignment: 8 Pentium Safe FDIV: False Stack Frames: False Optimization: True A: Here is the full solutions thanks to hints from KillianDS and Ritsaert Hornstra import struct fh = open('my_file.dat', 'rb') s = fh.read(40256) vals = struct.unpack('iidddddd5025d', s) dpoints, dloops, dtime, bT, sT, hI, LI, tm = vals[:8] data = vals[8:] A: I do not know how Delphi internally stores data, but if it is as simple byte-wise data (so not serialized and mangled), use struct. This way you can treat a string from a python file as binary data. Also, open files as binary file(open,'rb'). A: Please note that when you define a record in Delphi (like struct in C) the fields are layed out in order and in binary given the current alignment (eg Bytes are aligned on 1 byte boundaries, Words on 2 byte, Integers on 4 byte etc, but it may vary given the compiler settings. When serialized to a file, you probably mean that this record is written in binary to the file and the next record is written after the first one starting at position sizeof( structure) etc etc. Delphi does not specify how thing should be serialized to/from file, So the information you give leaves us guessing. If you want to make sure it is always the same without interference of any compiler setings, use packed record. Real can have multiple meanings (it is an 48 bit float type for older Delphi versions and later on a 64 bit float (IEEE double)). If you cannot access the Delphi code or compile it yourself, just ty to check the data with a HEX editor, you should see the boundaries of the records clearly since they start with Integers and only floats follow.
Reading a Delphi binary file in Python
I have a file that was written with the following Delphi declaration ... Type Tfulldata = Record dpoints, dloops : integer; dtime, bT, sT, hI, LI : real; tm : real; data : array[1..armax] Of Real; End; ... Var: fh: File Of Tfulldata; I want to analyse the data in the files (many MB in size) using Python if possible - is there an easy way to read in the data and cast the data into Python objects similar in form to the Delphi records? Does anyone know of a library perhaps that does this? This is compiled on Delphi 7 with the following options which may (or may not) be pertinent, Record Field Alignment: 8 Pentium Safe FDIV: False Stack Frames: False Optimization: True
[ "Here is the full solutions thanks to hints from KillianDS and Ritsaert Hornstra\nimport struct\nfh = open('my_file.dat', 'rb')\ns = fh.read(40256)\nvals = struct.unpack('iidddddd5025d', s)\ndpoints, dloops, dtime, bT, sT, hI, LI, tm = vals[:8]\ndata = vals[8:]\n", "I do not know how Delphi internally stores data, but if it is as simple byte-wise data (so not serialized and mangled), use struct. This way you can treat a string from a python file as binary data. Also, open files as binary file(open,'rb').\n", "Please note that when you define a record in Delphi (like struct in C) the fields are layed out in order and in binary given the current alignment (eg Bytes are aligned on 1 byte boundaries, Words on 2 byte, Integers on 4 byte etc, but it may vary given the compiler settings. \nWhen serialized to a file, you probably mean that this record is written in binary to the file and the next record is written after the first one starting at position sizeof( structure) etc etc. Delphi does not specify how thing should be serialized to/from file, So the information you give leaves us guessing.\nIf you want to make sure it is always the same without interference of any compiler setings, use packed record.\nReal can have multiple meanings (it is an 48 bit float type for older Delphi versions and later on a 64 bit float (IEEE double)). \nIf you cannot access the Delphi code or compile it yourself, just ty to check the data with a HEX editor, you should see the boundaries of the records clearly since they start with Integers and only floats follow. \n" ]
[ 6, 2, 2 ]
[]
[]
[ "delphi", "file_io", "python" ]
stackoverflow_0002700155_delphi_file_io_python.txt
Q: Open source equivelants to wsdl.exe? (how to autogen a web reference proxy class) As an ASP.NET developer, I'm used to working with how VS/C# transparently autogens proxy classes for web references via wsdl.exe (yes, I know, we're spoiled), but now that I'm creating documentation for more than one coding platform I'm trying to discover what the equivelant to that is in any other framework. So is there a similar way to work transparently with web reference proxy classes for say, RoR, PHP, and Python? And if there's nothing integrated, are there tools you recommend to autogen the proxy classes, or do you recommend to roll custom classes? A: I've had (limited) success with ZSI http://pywebsvcs.sourceforge.net/ for Python. Try at your own risk. If it would be possible to run IronPython or IronRuby I would check that out. I definitely know how VS can spoil you.
Open source equivelants to wsdl.exe? (how to autogen a web reference proxy class)
As an ASP.NET developer, I'm used to working with how VS/C# transparently autogens proxy classes for web references via wsdl.exe (yes, I know, we're spoiled), but now that I'm creating documentation for more than one coding platform I'm trying to discover what the equivelant to that is in any other framework. So is there a similar way to work transparently with web reference proxy classes for say, RoR, PHP, and Python? And if there's nothing integrated, are there tools you recommend to autogen the proxy classes, or do you recommend to roll custom classes?
[ "I've had (limited) success with ZSI http://pywebsvcs.sourceforge.net/ for Python. Try at your own risk.\nIf it would be possible to run IronPython or IronRuby I would check that out.\nI definitely know how VS can spoil you.\n" ]
[ 1 ]
[]
[]
[ "c#", "python", "ruby_on_rails", "web_services" ]
stackoverflow_0002703331_c#_python_ruby_on_rails_web_services.txt
Q: python function parameter evaluation model I was looking at an article on Peter Norvig's website, where he's trying to answer the following question (this is not my question, btw) "Can I do the equivalent of (test ? result : alternative) in Python?" here's one of the options listed by him, def if_(test, result, alternative=None): "If test is true, 'do' result, else alternative. 'Do' means call if callable." if test: if callable(result): result = result() return result else: if callable(alternative): alternative = alternative() return alternative And here's a usage example. >>> fact = lambda n: if_(n <= 1, 1, lambda: n * fact(n-1)) >>> fact(6) 720 I understand how this works (I think), but I was just playing with the code, and decided to see what happens when I change the third argument in the definition of 'fact' above to n * fact(n-1), that is, change it to a non-callable expression. On running it, the interpreter goes into a never ending loop. I have a pretty good idea of why that is happening, that is, the if_ function is returning back the same expression that it is receiving. But what is the type of that expression? What exactly is going on here? I am not looking for a detailed explanation , but just for some pointers to python's evaluation model which might help my understanding. Thanks! A: The reason the loop never terminates when you change fact to n * fact(n-1) is that n * fact(n-1) has to evaluate first (as the third argument to if). Evaluating it leads to another call to fact, ad infinitum (since there is no longer any base case to stop it). Previously, you were passing a function object (lambda), which would not be evaluated until the body of if, and its result would be checked via test. This is known (I believe) as eager evaluation, where function arguments are evaluated before they are passed to the function. In a lazy-evaluation scheme, the arguments would not be evaluated until they were used in the function body.
python function parameter evaluation model
I was looking at an article on Peter Norvig's website, where he's trying to answer the following question (this is not my question, btw) "Can I do the equivalent of (test ? result : alternative) in Python?" here's one of the options listed by him, def if_(test, result, alternative=None): "If test is true, 'do' result, else alternative. 'Do' means call if callable." if test: if callable(result): result = result() return result else: if callable(alternative): alternative = alternative() return alternative And here's a usage example. >>> fact = lambda n: if_(n <= 1, 1, lambda: n * fact(n-1)) >>> fact(6) 720 I understand how this works (I think), but I was just playing with the code, and decided to see what happens when I change the third argument in the definition of 'fact' above to n * fact(n-1), that is, change it to a non-callable expression. On running it, the interpreter goes into a never ending loop. I have a pretty good idea of why that is happening, that is, the if_ function is returning back the same expression that it is receiving. But what is the type of that expression? What exactly is going on here? I am not looking for a detailed explanation , but just for some pointers to python's evaluation model which might help my understanding. Thanks!
[ "The reason the loop never terminates when you change fact to n * fact(n-1) is that n * fact(n-1) has to evaluate first (as the third argument to if). Evaluating it leads to another call to fact, ad infinitum (since there is no longer any base case to stop it).\nPreviously, you were passing a function object (lambda), which would not be evaluated until the body of if, and its result would be checked via test.\nThis is known (I believe) as eager evaluation, where function arguments are evaluated before they are passed to the function. In a lazy-evaluation scheme, the arguments would not be evaluated until they were used in the function body.\n" ]
[ 4 ]
[]
[]
[ "callable", "evaluation", "lambda", "python" ]
stackoverflow_0002716228_callable_evaluation_lambda_python.txt
Q: Bitwise Operations on Rows of lil_matrix How can I quickly extract two rows of a scipy.sparse.lil_matrix and apply bitwise operations on them? I've tried: np.bitwise_and(A[1,:], A[2,:]) but NumPy seems to want an array type according to the documentation. A: By "lil_matrix", do you mean a scipy.sparse.lil_matrix? If so, you'll have to convert your sparse array to a normal dense array to do bitwise operations on it, I believe. a = np.asarray(A.todense()) np.bitwise_and(a[1,:], a[2,:]) Should do the trick, I think... EDIT: Forgot an "asarray" there...
Bitwise Operations on Rows of lil_matrix
How can I quickly extract two rows of a scipy.sparse.lil_matrix and apply bitwise operations on them? I've tried: np.bitwise_and(A[1,:], A[2,:]) but NumPy seems to want an array type according to the documentation.
[ "By \"lil_matrix\", do you mean a scipy.sparse.lil_matrix? If so, you'll have to convert your sparse array to a normal dense array to do bitwise operations on it, I believe.\na = np.asarray(A.todense())\nnp.bitwise_and(a[1,:], a[2,:])\n\nShould do the trick, I think...\nEDIT: Forgot an \"asarray\" there...\n" ]
[ 3 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0002716237_numpy_python_scipy.txt
Q: How to plot non-numeric data in Matplotlib I wish to plot the time variation of my y-axis variable using Matplotlib. This is no problem for continuously discrete data, however how should this be tackled for non-continuous data. I.e. if I wanted to visualise the times at which my car was stationary on the way to work the x-axis would be time and the y-axis would be comprised of the variables 'stationary' and 'moving' (pretty useless example i know) The non-continuous data would need to be indexed somehow, but i don't know how to proceed...any ideas? A: Is this the type of thing you want? (If not, you might want to check out the matplotlib gallery page to give yourself some ideas, or maybe just draw a picture and post it.) import matplotlib.pyplot as plt data = [0]*5 + [1]*10 + [0]*3 +[1]*2 print data fig = plt.figure() ax = fig.add_subplot(111) ax.plot(data) ax.set_yticks((0, 1.)) ax.set_yticklabels(('stopped', 'moving')) ax.set_ybound((-.2, 1.2)) ax.set_xlabel("time (minutes)") plt.show()
How to plot non-numeric data in Matplotlib
I wish to plot the time variation of my y-axis variable using Matplotlib. This is no problem for continuously discrete data, however how should this be tackled for non-continuous data. I.e. if I wanted to visualise the times at which my car was stationary on the way to work the x-axis would be time and the y-axis would be comprised of the variables 'stationary' and 'moving' (pretty useless example i know) The non-continuous data would need to be indexed somehow, but i don't know how to proceed...any ideas?
[ "Is this the type of thing you want? (If not, you might want to check out the matplotlib gallery page to give yourself some ideas, or maybe just draw a picture and post it.)\nimport matplotlib.pyplot as plt\n\ndata = [0]*5 + [1]*10 + [0]*3 +[1]*2\n\nprint data\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(data)\nax.set_yticks((0, 1.))\nax.set_yticklabels(('stopped', 'moving'))\nax.set_ybound((-.2, 1.2))\nax.set_xlabel(\"time (minutes)\")\n\nplt.show()\n\n\n" ]
[ 7 ]
[]
[]
[ "matplotlib", "python", "visualization" ]
stackoverflow_0002715535_matplotlib_python_visualization.txt
Q: BeautifulSoup, but for CSS? BeautifulSoup parses HTML and offers various ways to manipulate and search within HTML. Is there something similar for CSS? Specifically, I'd like to know if a given HTML text is rendered as bold. Either it has an ancestor that is the <strong> or the <bold> tag (which can be done with BeautifulSoup), or it has an ancestor (or itself) that has CSS attributes with font-weight: bold. Is this possible without resulting to writing my own library? A: Have a look to CSSParser class of cssutils package. A: You might have some luck using some of the CSS parsing packages available for python. One in particular that can take CSS blocks and turn them into inline styles is the premailer package. That might make it easier to work with the tool you're already using.
BeautifulSoup, but for CSS?
BeautifulSoup parses HTML and offers various ways to manipulate and search within HTML. Is there something similar for CSS? Specifically, I'd like to know if a given HTML text is rendered as bold. Either it has an ancestor that is the <strong> or the <bold> tag (which can be done with BeautifulSoup), or it has an ancestor (or itself) that has CSS attributes with font-weight: bold. Is this possible without resulting to writing my own library?
[ "Have a look to CSSParser class of cssutils package.\n", "You might have some luck using some of the CSS parsing packages available for python.\nOne in particular that can take CSS blocks and turn them into inline styles is the premailer package. That might make it easier to work with the tool you're already using.\n" ]
[ 3, 0 ]
[]
[]
[ "beautifulsoup", "css", "python" ]
stackoverflow_0002716181_beautifulsoup_css_python.txt
Q: Python comparing string against several regular expressions I'm pretty experienced with Perl and Ruby but new to Python so I'm hoping someone can show me the Pythonic way to accomplish the following task. I want to compare several lines against multiple regular expressions and retrieve the matching group. In Ruby it would be something like this: # Revised to show variance in regex and related action. data, foo, bar = [], nil, nil input_lines.each do |line| if line =~ /Foo(\d+)/ foo = $1.to_i elsif line =~ /Bar=(.*)$/ bar = $1 elsif bar data.push(line.to_f) end end My attempts in Python are turning out pretty ugly because the matching group is returned from a call to match/search on a regular expression and Python has no assignment in conditionals or switch statements. What's the Pythonic way to do (or think!) about this problem? A: Something like this, but prettier: regexs = [re.compile('...'), ...] for regex in regexes: m = regex.match(s) if m: print m.groups() break else: print 'No match' A: There are several ways to "bind a name on the fly" in Python, such as my old recipe for "assign and test"; in this case I'd probably choose another such way (assuming Python 2.6, needs some slight changes if you're working with an old version of Python), something like: import re pats_marks = (r'^A:(.*)$', 'FOO'), (r'^B:(.*)$', 'BAR') for line in lines: mo, m = next(((mo, m) for p, m in pats_mark for mo in [re.match(p, line)] if mo), (None, None)) if mo: print '%s: %s' % (m, mo.group(1)) else: print 'NO MATCH: %s' % line Many minor details can be adjusted, of course (for example, I just chose (.*) rather than (.*?) as the matching group -- they're equivalent given the immediately-following $ so I chose the shorter form;-) -- you could precompile the REs, factor things out differently than the pats_mark tuple (e.g., with a dict indexed by RE patterns), etc. But the substantial ideas, I think, are to make the structure data-driven, and to bind the match object to a name on the fly with the subexpression for mo in [re.match(p, line)], a "loop" over a single-item list (genexps bind names only by loop, not by assignment -- some consider using this part of genexps' specs to be "tricky", but I consider it a perfectly acceptable Python idiom, esp. since it was considered back in the time when listcomps, genexps' "ancestors" in a sense, were being designed). A: Paul McGuire's solution of using an intermediate class REMatcher which performs the match, stores the match group, and returns a boolean for success/fail turned out to produce the most legible code for this purpose.
Python comparing string against several regular expressions
I'm pretty experienced with Perl and Ruby but new to Python so I'm hoping someone can show me the Pythonic way to accomplish the following task. I want to compare several lines against multiple regular expressions and retrieve the matching group. In Ruby it would be something like this: # Revised to show variance in regex and related action. data, foo, bar = [], nil, nil input_lines.each do |line| if line =~ /Foo(\d+)/ foo = $1.to_i elsif line =~ /Bar=(.*)$/ bar = $1 elsif bar data.push(line.to_f) end end My attempts in Python are turning out pretty ugly because the matching group is returned from a call to match/search on a regular expression and Python has no assignment in conditionals or switch statements. What's the Pythonic way to do (or think!) about this problem?
[ "Something like this, but prettier:\nregexs = [re.compile('...'), ...]\n\nfor regex in regexes:\n m = regex.match(s)\n if m:\n print m.groups()\n break\nelse:\n print 'No match'\n\n", "There are several ways to \"bind a name on the fly\" in Python, such as my old recipe for \"assign and test\"; in this case I'd probably choose another such way (assuming Python 2.6, needs some slight changes if you're working with an old version of Python), something like:\nimport re\npats_marks = (r'^A:(.*)$', 'FOO'), (r'^B:(.*)$', 'BAR')\nfor line in lines:\n mo, m = next(((mo, m) for p, m in pats_mark for mo in [re.match(p, line)] if mo),\n (None, None))\n if mo: print '%s: %s' % (m, mo.group(1))\n else: print 'NO MATCH: %s' % line\n\nMany minor details can be adjusted, of course (for example, I just chose (.*) rather than (.*?) as the matching group -- they're equivalent given the immediately-following $ so I chose the shorter form;-) -- you could precompile the REs, factor things out differently than the pats_mark tuple (e.g., with a dict indexed by RE patterns), etc.\nBut the substantial ideas, I think, are to make the structure data-driven, and to bind the match object to a name on the fly with the subexpression for mo in [re.match(p, line)], a \"loop\" over a single-item list (genexps bind names only by loop, not by assignment -- some consider using this part of genexps' specs to be \"tricky\", but I consider it a perfectly acceptable Python idiom, esp. since it was considered back in the time when listcomps, genexps' \"ancestors\" in a sense, were being designed).\n", "Paul McGuire's solution of using an intermediate class REMatcher which performs the match, stores the match group, and returns a boolean for success/fail turned out to produce the most legible code for this purpose.\n" ]
[ 1, 1, 0 ]
[ "your regex simply takes whatever is after the 3rd character onwards.\nfor line in open(\"file\"):\n if line.startswith(\"A:\"):\n print \"FOO #{\"+line[2:]+\"}\"\n elif line.startswith(\"B:\"):\n print \"BAR #{\"+line[2:]+\"}\"\n else:\n print \"No match\"\n\n" ]
[ -1 ]
[ "python", "regex", "switch_statement" ]
stackoverflow_0002633738_python_regex_switch_statement.txt
Q: Hashing a python function to regenerate output when the function is modified I have a python function that has a deterministic result. It takes a long time to run and generates a large output: def time_consuming_function(): # lots_of_computing_time to come up with the_result return the_result I modify time_consuming_function from time to time, but I would like to avoid having it run again while it's unchanged. [time_consuming_function only depends on functions that are immutable for the purposes considered here; i.e. it might have functions from Python libraries but not from other pieces of my code that I'd change.] The solution that suggests itself to me is to cache the output and also cache some "hash" of the function. If the hash changes, the function will have been modified, and we have to re-generate the output. Is this possible or ridiculous? Updated: based on the answers, it looks like what I want to do is to "memoize" time_consuming_function, except instead of (or in addition to) arguments passed into an invariant function, I want to account for a function that itself will change. A: If I understand your problem, I think I'd tackle it like this. It's a touch evil, but I think it's more reliable and on-point than the other solutions I see here. import inspect import functools import json def memoize_zeroadic_function_to_disk(memo_filename): def decorator(f): try: with open(memo_filename, 'r') as fp: cache = json.load(fp) except IOError: # file doesn't exist yet cache = {} source = inspect.getsource(f) @functools.wraps(f) def wrapper(): if source not in cache: cache[source] = f() with open(memo_filename, 'w') as fp: json.dump(cache, fp) return cache[source] return wrapper return decorator @memoize_zeroadic_function_to_disk(...SOME PATH HERE...) def time_consuming_function(): # lots_of_computing_time to come up with the_result return the_result A: Rather than putting the function in a string, I would put the function in its own file. Call it time_consuming.py, for example. It would look something like this: def time_consuming_method(): # your existing method here # Is the cached data older than this file? if (not os.path.exists(data_file_name) or os.stat(data_file_name).st_mtime < os.stat(__file__).st_mtime): data = time_consuming_method() save_data(data_file_name, data) else: data = load_data(data_file_name) # redefine method def time_consuming_method(): return data While testing the infrastructure for this to work, I'd comment out the slow parts. Make a simple function that just returns 0, get all of the save/load stuff working to your satisfaction, then put the slow bits back in. A: So, here is a really neat trick using decorators: def memoize(f): cache={}; def result(*args): if args not in cache: cache[args]=f(*args); return cache[args]; return result; With the above, you can then use: @memoize def myfunc(x,y,z): # Some really long running computation When you invoke myfunc, you will actually be invoking the memoized version of it. Pretty neat, huh? Whenever you want to redefine your function, simply use "@memoize" again, or explicitly write: myfunc = memoize(new_definition_for_myfunc); Edit I didn't realize that you wanted to cache between multiple runs. In that case, you can do the following: import os; import os.path; import cPickle; class MemoizedFunction(object): def __init__(self,f): self.function=f; self.filename=str(hash(f))+".cache"; self.cache={}; if os.path.exists(self.filename): with open(filename,'rb') as file: self.cache=cPickle.load(file); def __call__(self,*args): if args not in self.cache: self.cache[args]=self.function(*args); return self.cache[args]; def __del__(self): with open(self.filename,'wb') as file: cPickle.dump(self.cache,file,cPickle.HIGHEST_PROTOCOL); def memoize(f): return MemoizedFunction(f); A: The first part is memoization and serialization of your lookup table. That should be straightforward enough based on some python serialization library. The second part is that you want to delete your serialized lookup table when the source code changes. Perhaps this is being overthought into some fancy solution. Presumably when you change the code you check it in somewhere? Why not add a hook to your checkin routine that deletes your serialized table? Or if this is not research data and is in production, make it part of your release process that if the revision number of your file (put this function in it's own file) has changed, your release script deletes the serialzed lookup table.
Hashing a python function to regenerate output when the function is modified
I have a python function that has a deterministic result. It takes a long time to run and generates a large output: def time_consuming_function(): # lots_of_computing_time to come up with the_result return the_result I modify time_consuming_function from time to time, but I would like to avoid having it run again while it's unchanged. [time_consuming_function only depends on functions that are immutable for the purposes considered here; i.e. it might have functions from Python libraries but not from other pieces of my code that I'd change.] The solution that suggests itself to me is to cache the output and also cache some "hash" of the function. If the hash changes, the function will have been modified, and we have to re-generate the output. Is this possible or ridiculous? Updated: based on the answers, it looks like what I want to do is to "memoize" time_consuming_function, except instead of (or in addition to) arguments passed into an invariant function, I want to account for a function that itself will change.
[ "If I understand your problem, I think I'd tackle it like this. It's a touch evil, but I think it's more reliable and on-point than the other solutions I see here.\nimport inspect\nimport functools\nimport json\n\ndef memoize_zeroadic_function_to_disk(memo_filename):\n def decorator(f):\n try:\n with open(memo_filename, 'r') as fp:\n cache = json.load(fp)\n except IOError:\n # file doesn't exist yet\n cache = {}\n\n source = inspect.getsource(f)\n\n @functools.wraps(f)\n def wrapper():\n if source not in cache:\n cache[source] = f()\n with open(memo_filename, 'w') as fp:\n json.dump(cache, fp)\n\n return cache[source]\n return wrapper\n return decorator\n\n@memoize_zeroadic_function_to_disk(...SOME PATH HERE...)\ndef time_consuming_function():\n # lots_of_computing_time to come up with the_result\n return the_result\n\n", "Rather than putting the function in a string, I would put the function in its own file. Call it time_consuming.py, for example. It would look something like this:\ndef time_consuming_method():\n # your existing method here\n\n# Is the cached data older than this file?\nif (not os.path.exists(data_file_name) \n or os.stat(data_file_name).st_mtime < os.stat(__file__).st_mtime):\n data = time_consuming_method()\n save_data(data_file_name, data)\nelse:\n data = load_data(data_file_name)\n\n# redefine method\ndef time_consuming_method():\n return data\n\nWhile testing the infrastructure for this to work, I'd comment out the slow parts. Make a simple function that just returns 0, get all of the save/load stuff working to your satisfaction, then put the slow bits back in.\n", "So, here is a really neat trick using decorators:\n\ndef memoize(f):\n cache={};\n def result(*args):\n if args not in cache:\n cache[args]=f(*args);\n return cache[args];\n return result;\n\nWith the above, you can then use:\n\n@memoize\ndef myfunc(x,y,z):\n # Some really long running computation\n\nWhen you invoke myfunc, you will actually be invoking the memoized version of it. Pretty neat, huh? Whenever you want to redefine your function, simply use \"@memoize\" again, or explicitly write:\n\nmyfunc = memoize(new_definition_for_myfunc);\n\nEdit\nI didn't realize that you wanted to cache between multiple runs. In that case, you can do the following:\n\nimport os;\nimport os.path;\nimport cPickle;\n\nclass MemoizedFunction(object):\n def __init__(self,f):\n self.function=f;\n self.filename=str(hash(f))+\".cache\";\n self.cache={};\n if os.path.exists(self.filename):\n with open(filename,'rb') as file:\n self.cache=cPickle.load(file);\n\n def __call__(self,*args):\n if args not in self.cache:\n self.cache[args]=self.function(*args);\n return self.cache[args];\n\n def __del__(self):\n with open(self.filename,'wb') as file:\n cPickle.dump(self.cache,file,cPickle.HIGHEST_PROTOCOL);\n\ndef memoize(f):\n return MemoizedFunction(f);\n\n", "The first part is memoization and serialization of your lookup table. That should be straightforward enough based on some python serialization library. The second part is that you want to delete your serialized lookup table when the source code changes. Perhaps this is being overthought into some fancy solution. Presumably when you change the code you check it in somewhere? Why not add a hook to your checkin routine that deletes your serialized table? Or if this is not research data and is in production, make it part of your release process that if the revision number of your file (put this function in it's own file) has changed, your release script deletes the serialzed lookup table. \n" ]
[ 6, 1, 0, 0 ]
[ "What you describe is effectively memoization. Most common functions can be memoized by defining a decorator.\nA (overly simplified) example:\ndef memoized(f):\n cache={}\n def memo(*args):\n if args in cache:\n return cache[args]\n else:\n ret=f(*args)\n cache[args]=ret\n return ret\n return memo\n\n@memoized\ndef time_consuming_method():\n # lots_of_computing_time to come up with the_result\n return the_result\n\nEdit:\nFrom Mike Graham's comment and the OP's update, it is now clear that values need to be cached over different runs of the program. This can be done by using some of of persistent storage for the cache (e.g. something as simple as using Pickle or a simple text file, or maybe using a full blown database, or anything in between). The choice of which method to use depends on what the OP needs. Several other answers already give some solutions to this, so I'm not going to repeat that here. \n" ]
[ -1 ]
[ "caching", "hash", "python" ]
stackoverflow_0002716710_caching_hash_python.txt
Q: Making an asynchronous interface appear synchronous to mod_python users I have a Python-driven web interface powered by Apache 2.2 with mod_python and Python 2.4. I need to make an asynchronous process appear synchronous to users of this web interface. When users access one module on this website: An external SOAP interface will be contacted with a unique identifier and will respond with a number N The external interface will respond asynchronously by contacting a SOAP server on my machine between 1 and 10 times (the number N tells us how many responses we will receive) I need to somehow aggregate these responses and pass them to the original module which will display the information back to the user. The goal is to make the process appear synchronous to the user. What is the best way to handle this synchronization issue? Is this something Twisted would be well-suited for? I am not restricting myself to Python for the solution, though it is preferred because everything else on the server is in Python. I prefer a solution that is both scalable and will take a minimal amount of programming time (though I understand that these attributes are somewhat at odds). A: Maybe you can use Orbited to get ajax push with long-lived HTTP connections to your web clients. Orbited is based on Twisted, so I think it makes sense to look at if you already know Twisted. Have a look at this tutorial to get started.
Making an asynchronous interface appear synchronous to mod_python users
I have a Python-driven web interface powered by Apache 2.2 with mod_python and Python 2.4. I need to make an asynchronous process appear synchronous to users of this web interface. When users access one module on this website: An external SOAP interface will be contacted with a unique identifier and will respond with a number N The external interface will respond asynchronously by contacting a SOAP server on my machine between 1 and 10 times (the number N tells us how many responses we will receive) I need to somehow aggregate these responses and pass them to the original module which will display the information back to the user. The goal is to make the process appear synchronous to the user. What is the best way to handle this synchronization issue? Is this something Twisted would be well-suited for? I am not restricting myself to Python for the solution, though it is preferred because everything else on the server is in Python. I prefer a solution that is both scalable and will take a minimal amount of programming time (though I understand that these attributes are somewhat at odds).
[ "Maybe you can use Orbited to get ajax push with long-lived HTTP connections to your web clients. Orbited is based on Twisted, so I think it makes sense to look at if you already know Twisted. Have a look at this tutorial to get started.\n" ]
[ 2 ]
[]
[]
[ "asynchronous", "mod_python", "python", "synchronization", "twisted" ]
stackoverflow_0002717279_asynchronous_mod_python_python_synchronization_twisted.txt
Q: Python stdout, \r progress bar and sshd with Putty not updating regularly I have a dead simple progress "bar" using something like the following: import sys from time import sleep current = 0 limit = 50 while current <= limit: sys.stdout.write('\rSynced %s/%s orders' % (current, limit)) current_order += 1 sleep(1) Works fine, except over ssh with Putty. Putty only updates every 3 minutes or if a line ends with \n. Is this a Putty setting, sshd_config, or can I code around it? A: Try doing sys.stdout.flush() after sys.stdout.write call. A: You can use flush() to force an update. sys.stdout.write('\r[%s%s]' % ('=' * completed, ' ' * (total-completed))) sys.stdout.flush() A: Use sys.stderr.write instead, which is not buffered as sys.stdout is, and this way you separate progress indicator from the (presumably) useful process output.
Python stdout, \r progress bar and sshd with Putty not updating regularly
I have a dead simple progress "bar" using something like the following: import sys from time import sleep current = 0 limit = 50 while current <= limit: sys.stdout.write('\rSynced %s/%s orders' % (current, limit)) current_order += 1 sleep(1) Works fine, except over ssh with Putty. Putty only updates every 3 minutes or if a line ends with \n. Is this a Putty setting, sshd_config, or can I code around it?
[ "Try doing sys.stdout.flush() after sys.stdout.write call.\n", "You can use flush() to force an update.\nsys.stdout.write('\\r[%s%s]' % ('=' * completed, ' ' * (total-completed)))\nsys.stdout.flush()\n\n", "Use sys.stderr.write instead, which is not buffered as sys.stdout is, and this way you separate progress indicator from the (presumably) useful process output.\n" ]
[ 3, 1, 0 ]
[]
[]
[ "putty", "python", "ssh" ]
stackoverflow_0002712166_putty_python_ssh.txt
Q: Dealing with Windows line-endings in Python I've got a 700MB XML file coming from a Windows provider. As one might expect, the line endings are '\r\n' (or ^M in vi). What is the most efficient way to deal with this situation aside from getting the supplier to send over '\n' :-) Use os.linesep Use rstrip() (requiring opening the file ... which seems crazy) Using Universal newline support is not standard on my Mac Snow Leopard - so isn't an option. I'm open to anything that requires Python 2.6+ but it needs to work on Snow Leopard and Ubuntu 9.10 with minimal external requirements. I don't mind a small performance penalty but I am looking for the standard best way to deal with this. ----edit---- The line endings are in the middle of the tag descriptors, otherwise they wouldn't be such a problem. I know this is bad form and that they shouldn't be sending this to me, but this is how I have the file and the vendor is mostly incompetent. A: Why are the DOS line-endings a problem? Most things can deal with them just fine, including XML parsers. If you really want to get rid of them, open the file in universal line-endings mode: open(filename, 'rU') Python will convert all line-endings to UNIX line-endings for you. If you really can't use that (which I find a little surprising), there's no way to get Python to do the work for you. You will have to open the file regardless, though, so your objection to #2 seems a little odd. A: Are you opening the file in text mode or binary mode? I'm pretty sure I've counted on universal newlines on my Leopard install, but maybe I got an updated Python from somewhere too... Anyway- I've seen this sort of thing biting many programmers in the bum, because they just reach for the 'b' key. Use a 't' if you're opening text files known to be created on your platform, 'U' instead of 't' if you need universal newlines. with file(filename, 'rt') as f: content = f.read() Edit: The comments note that 'rt' is the default. Fair point, but Python style tends to prefer explicit over implicit, so I'm going with that. A: Allegedly: """This guy has \r\n right in the middle of tag descriptors like so: <ParentRedirec tSequenceID>""". I see no \r\n here. Perhaps you mean repr(xml) contains things like "<ParentRedirec\r\ntSequenceID>" If not, try to say precisely what you mean, with repr-fashion examples. The following should work: >>> import re >>> guff = """<atag>\r\n<bt\r\nag c="2">""" >>> re.sub(r"(<[^>]*)\r\n([^>]*>)", r"\1\2", guff) '<atag>\r\n<btag c="2">' >>> If there is more than one line break in a tag e.g. <foo\r\nbar\r\nzot> this will fix only the first. Alternatives (1) loop until the guff stops shrinking (2) write a smarter regexp yourself :-) A: What are you trying to do with this file? Whitespace between tags is usually ignored in XML, so the only place where line endings matter tags' content.
Dealing with Windows line-endings in Python
I've got a 700MB XML file coming from a Windows provider. As one might expect, the line endings are '\r\n' (or ^M in vi). What is the most efficient way to deal with this situation aside from getting the supplier to send over '\n' :-) Use os.linesep Use rstrip() (requiring opening the file ... which seems crazy) Using Universal newline support is not standard on my Mac Snow Leopard - so isn't an option. I'm open to anything that requires Python 2.6+ but it needs to work on Snow Leopard and Ubuntu 9.10 with minimal external requirements. I don't mind a small performance penalty but I am looking for the standard best way to deal with this. ----edit---- The line endings are in the middle of the tag descriptors, otherwise they wouldn't be such a problem. I know this is bad form and that they shouldn't be sending this to me, but this is how I have the file and the vendor is mostly incompetent.
[ "Why are the DOS line-endings a problem? Most things can deal with them just fine, including XML parsers. If you really want to get rid of them, open the file in universal line-endings mode:\nopen(filename, 'rU')\n\nPython will convert all line-endings to UNIX line-endings for you. If you really can't use that (which I find a little surprising), there's no way to get Python to do the work for you. You will have to open the file regardless, though, so your objection to #2 seems a little odd.\n", "Are you opening the file in text mode or binary mode? I'm pretty sure I've counted on universal newlines on my Leopard install, but maybe I got an updated Python from somewhere too...\nAnyway- I've seen this sort of thing biting many programmers in the bum, because they just reach for the 'b' key. Use a 't' if you're opening text files known to be created on your platform, 'U' instead of 't' if you need universal newlines.\nwith file(filename, 'rt') as f:\n content = f.read()\n\nEdit: The comments note that 'rt' is the default. Fair point, but Python style tends to prefer explicit over implicit, so I'm going with that.\n", "Allegedly: \"\"\"This guy has \\r\\n right in the middle of tag descriptors like so: <ParentRedirec tSequenceID>\"\"\".\nI see no \\r\\n here. Perhaps you mean repr(xml) contains things like\n\"<ParentRedirec\\r\\ntSequenceID>\"\n\nIf not, try to say precisely what you mean, with repr-fashion examples.\nThe following should work:\n>>> import re\n>>> guff = \"\"\"<atag>\\r\\n<bt\\r\\nag c=\"2\">\"\"\"\n>>> re.sub(r\"(<[^>]*)\\r\\n([^>]*>)\", r\"\\1\\2\", guff)\n'<atag>\\r\\n<btag c=\"2\">'\n>>>\n\nIf there is more than one line break in a tag e.g. <foo\\r\\nbar\\r\\nzot> this will fix only the first. Alternatives (1) loop until the guff stops shrinking (2) write a smarter regexp yourself :-)\n", "What are you trying to do with this file? Whitespace between tags is usually ignored in XML, so the only place where line endings matter tags' content.\n" ]
[ 6, 2, 1, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0002717086_file_python.txt
Q: How to display a page in my browser with python code that is run locally on my computer with "GAE" SDK? When I run this code on my computer with the help of "Google App Engine SDK", it displays (in my browser) the HTML code of the Google home page: from google.appengine.api import urlfetch url = "http://www.google.com/" result = urlfetch.fetch(url) print result.content How can I make it display the page itself? I mean I want to see that page in my browser the way it would normally be seen by any user of the internet. Update 1: I see I have received a few questions that look a bit complicated to me, although I definitely remember I was able to do it, and it was very simple, except i don't remember what exactly i changed then in this code. Perhaps, I didn't give You all enough details on how I run this code and where I found it. So, let me tell You what I did. I only installed Python 2.5 on my computer and then downloaded "Google App Engine SDK" and installed it, too. Following the instructions on "GAE" page (http://code.google.com/appengine/docs/python/gettingstarted/helloworld.html) I created a directory and named it “My_test”, then I created a “my_test.py” in it containing that small piece of the code that I mentioned in my question. Then, continuing to follow on the said instructions, I created an “app.yaml” file in it, in which my “my_test.py” file was mentioned. After that in “Google App Engine Launcher” I found “My_test” directory and clicked on Run button, and then on Browse. Then, having visited this URL http://localhost:8080/ in my web browser, I saw the results. I definitely remember I was able to display any page in my browser in this way, and it was very simple, except I don’t remember what exactly I changed in the code (it was a slight change). Now, all I can see is a raw HTML code of a page, but not a page itself. Update 2: (this update is my response to wescpy) Hello, wescpy!!! I've tried Your updated code and something didn't work well there. Perhaps, it's because I am not using a certain framework that I am supposed to use for this code. Please, take a look at this screen shot (I guess You'll need to right-click this image to see it in better resolution): (source: narod.ru) A: Is not that easy, you have to parse content and adjust relative to absolute paths for images and javascripts. Anyway, give it a try adding the correct Content-Type: from google.appengine.api import urlfetch url = "http://www.google.com/" result = urlfetch.fetch(url) print 'Content-Type: text/html' print '' print result.content A: a more complete example would look something like this: from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.api import urlfetch class MainHandler(webapp.RequestHandler): def get(self): url = "http://www.google.com/" result = urlfetch.fetch(url) self.response.out.write(result.content) application = webapp.WSGIApplication([ ('/', MainHandler), ], debug=True) def main(): run_wsgi_app(application) if __name__ == '__main__': main() but as others' have said, it's not that easy to do because you're not in the server's domain, meaning the pages will likely not look correct due to missing static content (JS, CSS, and/or images)... unless full pathnames are used or everything that's needed is embedded into the page itself. UPDATE 1: as mentioned before, you cannot just download the HTML source and expect things to render correctly because you don't necessarily have access to the static data. if you really want to render it as it was meant to be seen, you have to just redirect... here's the modified piece of code: from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.api import urlfetch class MainHandler(webapp.RequestHandler): def get(self): url = "http://www.google.com/" self.redirect(url) application = webapp.WSGIApplication([ ('/', MainHandler), ], debug=True) def main(): run_wsgi_app(application) if __name__ == '__main__': main() UPDATE 2: sorry! it was a cut-n-paste error. now try it. A: special characters such as <> etc are likely encoded, you'd have to decode them again for the browser to interpet it as code.
How to display a page in my browser with python code that is run locally on my computer with "GAE" SDK?
When I run this code on my computer with the help of "Google App Engine SDK", it displays (in my browser) the HTML code of the Google home page: from google.appengine.api import urlfetch url = "http://www.google.com/" result = urlfetch.fetch(url) print result.content How can I make it display the page itself? I mean I want to see that page in my browser the way it would normally be seen by any user of the internet. Update 1: I see I have received a few questions that look a bit complicated to me, although I definitely remember I was able to do it, and it was very simple, except i don't remember what exactly i changed then in this code. Perhaps, I didn't give You all enough details on how I run this code and where I found it. So, let me tell You what I did. I only installed Python 2.5 on my computer and then downloaded "Google App Engine SDK" and installed it, too. Following the instructions on "GAE" page (http://code.google.com/appengine/docs/python/gettingstarted/helloworld.html) I created a directory and named it “My_test”, then I created a “my_test.py” in it containing that small piece of the code that I mentioned in my question. Then, continuing to follow on the said instructions, I created an “app.yaml” file in it, in which my “my_test.py” file was mentioned. After that in “Google App Engine Launcher” I found “My_test” directory and clicked on Run button, and then on Browse. Then, having visited this URL http://localhost:8080/ in my web browser, I saw the results. I definitely remember I was able to display any page in my browser in this way, and it was very simple, except I don’t remember what exactly I changed in the code (it was a slight change). Now, all I can see is a raw HTML code of a page, but not a page itself. Update 2: (this update is my response to wescpy) Hello, wescpy!!! I've tried Your updated code and something didn't work well there. Perhaps, it's because I am not using a certain framework that I am supposed to use for this code. Please, take a look at this screen shot (I guess You'll need to right-click this image to see it in better resolution): (source: narod.ru)
[ "Is not that easy, you have to parse content and adjust relative to absolute paths for images and javascripts.\nAnyway, give it a try adding the correct Content-Type:\nfrom google.appengine.api import urlfetch\nurl = \"http://www.google.com/\"\nresult = urlfetch.fetch(url)\nprint 'Content-Type: text/html'\nprint ''\nprint result.content\n\n", "a more complete example would look something like this:\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom google.appengine.api import urlfetch\n\nclass MainHandler(webapp.RequestHandler):\n def get(self):\n url = \"http://www.google.com/\"\n result = urlfetch.fetch(url)\n self.response.out.write(result.content)\n\napplication = webapp.WSGIApplication([\n ('/', MainHandler),\n], debug=True)\n\ndef main():\n run_wsgi_app(application)\n\nif __name__ == '__main__':\n main()\n\nbut as others' have said, it's not that easy to do because you're not in the server's domain, meaning the pages will likely not look correct due to missing static content (JS, CSS, and/or images)... unless full pathnames are used or everything that's needed is embedded into the page itself.\nUPDATE 1:\nas mentioned before, you cannot just download the HTML source and expect things to render correctly because you don't necessarily have access to the static data. if you really want to render it as it was meant to be seen, you have to just redirect... here's the modified piece of code:\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom google.appengine.api import urlfetch\n\nclass MainHandler(webapp.RequestHandler):\n def get(self):\n url = \"http://www.google.com/\"\n self.redirect(url)\n\napplication = webapp.WSGIApplication([\n ('/', MainHandler),\n], debug=True)\n\ndef main():\n run_wsgi_app(application)\n\nif __name__ == '__main__':\n main()\n\nUPDATE 2:\nsorry! it was a cut-n-paste error. now try it.\n", "special characters such as <> etc are likely encoded, you'd have to decode them again for the browser to interpet it as code.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002717370_google_app_engine_python.txt
Q: Multiple range product in Python Is there a better way to do this: perms = product(range(1,7),range(1,7),range(1,7)) so that I can choose how many ranges I use? I want it to be equivalent to this, but scalable. def dice(num) if num == 1: perms = ((i,) for i in range(1,7)) elif num == 2: perms = product(range(1,7),range(1,7)) elif num == 3: perms = product(range(1,7),range(1,7),range(1,7)) #... and so on but I know there has to be a better way. I'm using it for counting dice outcomes. The actual code def dice(selection= lambda d: d[2]): perms = itertools.product(range(1,7),range(1,7),range(1,7)) return collections.Counter(((selection(sorted(i)) for i in perms))) where I can call it with a variety of selectors, like sum(d[0:2]) for the sum of the lowest 2 dice or d[1] to get the middle dice. A: Yes. Use the repeat keyword argument: perms = product(range(1, 7), repeat=3) See the docs for more. A: I think perms = itertools.product(*([xrange(1,7)]*num)) should work for you.
Multiple range product in Python
Is there a better way to do this: perms = product(range(1,7),range(1,7),range(1,7)) so that I can choose how many ranges I use? I want it to be equivalent to this, but scalable. def dice(num) if num == 1: perms = ((i,) for i in range(1,7)) elif num == 2: perms = product(range(1,7),range(1,7)) elif num == 3: perms = product(range(1,7),range(1,7),range(1,7)) #... and so on but I know there has to be a better way. I'm using it for counting dice outcomes. The actual code def dice(selection= lambda d: d[2]): perms = itertools.product(range(1,7),range(1,7),range(1,7)) return collections.Counter(((selection(sorted(i)) for i in perms))) where I can call it with a variety of selectors, like sum(d[0:2]) for the sum of the lowest 2 dice or d[1] to get the middle dice.
[ "Yes. Use the repeat keyword argument:\nperms = product(range(1, 7), repeat=3)\n\nSee the docs for more.\n", "I think\nperms = itertools.product(*([xrange(1,7)]*num))\n\nshould work for you.\n" ]
[ 10, 0 ]
[]
[]
[ "generator", "permutation", "python", "range" ]
stackoverflow_0002718029_generator_permutation_python_range.txt
Q: How do I pass a lot of parameters to views in Django? I'm very new to Django and I'm trying to build an application to present my data in tables and charts. Till now my learning process went very smooth, but now I'm a bit stuck. My pageview retrieves large amounts of data from a database and puts it in the context. The template then generates different html-tables. So far so good. Now I want to add different charts to the template. I manage to do this by defining <img src=".../> tags. The Matplotlib chart is generate in my chartview an returned via: response=HttpResponse(content_type='image/png') canvas.print_png(response) return response Now I have different questions: the data is retrieved twice from the database. Once in the pageview to render the tables, and again in the chartview for making the charts. What is the best way to pass the data, already in the context of the page to the chartview? I need a lot of charts, each with different datasets. I could make a chartview for each chart, but probably there is a better way. How do I pass the different dataset names to the chartview? Some charts have 20 datasets, so I don't think that passing these dataset parameters via the url (like: <imgm src="chart/dataset1/dataset2/.../dataset20/chart.png />) is the right way. Any advice? A: You can't pass the data from the page view to the chart view, since they are separate HTTP requests. You have a few options: Pass all the data in the URL of the chart. This may sound crazy, but this is just what Google Charts does: http://code.google.com/apis/chart/docs/making_charts.html Store the data in the session. The page view will stuff the data in the session, and the chart view will use it to create a chart. Cache your db queries in memcache. Since the page and the chart will both reference the same query, you are likely to hit the cache. This is a nice solution because your chart will still work even without the page getting rendered first. Just query the database again. Your DBMS likely has good caching, the performance may not be the problem you imagine. For your second question, 20 words in a URL doesn't seem like such a big deal. Of course, you could perhaps find some pattern to the datasets chosen so that you don't need to specify them all every time, but if you need to, just make long URLs. A: Using template tags would probably be the route I would take here. I've had a similar situation to this, whereby I had calendar information being rendered multiple times in different formats on the same page. The way I handled it was by passing the queried data into the request context, then simply using that queryset as an argument of a template tag. The result is that you can end up with template syntax like this: View def my_view(request, *args, **kwargs): yearly_sales_qs = SaleRecord.objects.filter(param=value) monthly_sales_qs = SalesRecord.objects.filter(param=foo) return render_to_response( ..., locals(), ... ) Template {% load data_tags %} <div class="year"> {% render_data_table for yearly_sales_qs %} {% render_bar_chart for yearly_sales_qs %} </div> <div class="month"> {% render_data_table for monthly_sales_qs %} {% render_bar_chart for monthly_sales_qs %} </div> So how do you make something like that? Start by checking out the Django doc on Custom template tags and filters. It's a little more difficult to get started than the rest of Django, but once you get it, it's pretty easy. Start by creating a folder "templatetags" in your app's folder. Make a blank file "init.py" in that new folder Add the location of that templatetags folder to the TEMPLATE_DIRS setting in settings.py (if it's not already there) Because we'll be making several of these, we can make a base template tag that we'll inherit off of that encapsulates our basic functionality... data_tags.py (stored inside of templatetags folder) class DataForTag(tempalte.Node): @classmethod def handle_token(cls, parser, token, template): tokens = token.contents.split() if tokens[1] != 'for': raise template.TemplateSyntaxError("First argument in %r must be 'for'" % tokens[0]) if len(tokens) == 3: return cls(queryset=parser.compile_filter(tokens[2]), template=template) else: raise template.TemplateSyntaxError("%r tag requires 2 arguments" % tokens[0]) def __init__(self, queryset=None, template=None): self.queryset = queryset self.template = template def render(self, context): return render_to_string(self.template, {'queryset':self.queryset}) Then we can make individual tags that handle whatever we need them to... @register.tag def render_bar_chart(parser, token): return DataForTag.handle_token(parser, token, 'data/charts/barchart.html') @register.tag def render_pie_chart(parser, token): return DataForTag.handle_token(parser, token, 'data/charts/piechart.html') @register.tag def render_data_table(parser, token): return DataForTag.handle_token(parser, token, 'data/table.html')
How do I pass a lot of parameters to views in Django?
I'm very new to Django and I'm trying to build an application to present my data in tables and charts. Till now my learning process went very smooth, but now I'm a bit stuck. My pageview retrieves large amounts of data from a database and puts it in the context. The template then generates different html-tables. So far so good. Now I want to add different charts to the template. I manage to do this by defining <img src=".../> tags. The Matplotlib chart is generate in my chartview an returned via: response=HttpResponse(content_type='image/png') canvas.print_png(response) return response Now I have different questions: the data is retrieved twice from the database. Once in the pageview to render the tables, and again in the chartview for making the charts. What is the best way to pass the data, already in the context of the page to the chartview? I need a lot of charts, each with different datasets. I could make a chartview for each chart, but probably there is a better way. How do I pass the different dataset names to the chartview? Some charts have 20 datasets, so I don't think that passing these dataset parameters via the url (like: <imgm src="chart/dataset1/dataset2/.../dataset20/chart.png />) is the right way. Any advice?
[ "You can't pass the data from the page view to the chart view, since they are separate HTTP requests. You have a few options:\n\nPass all the data in the URL of the chart. This may sound crazy, but this is just what Google Charts does: http://code.google.com/apis/chart/docs/making_charts.html\nStore the data in the session. The page view will stuff the data in the session, and the chart view will use it to create a chart.\nCache your db queries in memcache. Since the page and the chart will both reference the same query, you are likely to hit the cache. This is a nice solution because your chart will still work even without the page getting rendered first.\nJust query the database again. Your DBMS likely has good caching, the performance may not be the problem you imagine.\n\nFor your second question, 20 words in a URL doesn't seem like such a big deal. Of course, you could perhaps find some pattern to the datasets chosen so that you don't need to specify them all every time, but if you need to, just make long URLs.\n", "Using template tags would probably be the route I would take here. I've had a similar situation to this, whereby I had calendar information being rendered multiple times in different formats on the same page. The way I handled it was by passing the queried data into the request context, then simply using that queryset as an argument of a template tag. The result is that you can end up with template syntax like this:\nView\ndef my_view(request, *args, **kwargs):\n yearly_sales_qs = SaleRecord.objects.filter(param=value)\n monthly_sales_qs = SalesRecord.objects.filter(param=foo)\n\n return render_to_response( ..., locals(), ... )\n\nTemplate\n{% load data_tags %}\n\n<div class=\"year\">\n {% render_data_table for yearly_sales_qs %}\n {% render_bar_chart for yearly_sales_qs %}\n</div>\n\n<div class=\"month\">\n {% render_data_table for monthly_sales_qs %}\n {% render_bar_chart for monthly_sales_qs %}\n</div>\n\nSo how do you make something like that? Start by checking out the Django doc on Custom template tags and filters. It's a little more difficult to get started than the rest of Django, but once you get it, it's pretty easy.\n\nStart by creating a folder \"templatetags\" in your app's folder.\nMake a blank file \"init.py\" in that new folder\nAdd the location of that templatetags folder to the TEMPLATE_DIRS setting in settings.py (if it's not already there)\n\nBecause we'll be making several of these, we can make a base template tag that we'll inherit off of that encapsulates our basic functionality...\ndata_tags.py (stored inside of templatetags folder)\nclass DataForTag(tempalte.Node):\n @classmethod\n def handle_token(cls, parser, token, template):\n tokens = token.contents.split()\n if tokens[1] != 'for':\n raise template.TemplateSyntaxError(\"First argument in %r must be 'for'\" % tokens[0])\n\n if len(tokens) == 3:\n return cls(queryset=parser.compile_filter(tokens[2]), template=template)\n else:\n raise template.TemplateSyntaxError(\"%r tag requires 2 arguments\" % tokens[0])\n\n def __init__(self, queryset=None, template=None):\n self.queryset = queryset\n self.template = template\n\n def render(self, context):\n return render_to_string(self.template, {'queryset':self.queryset})\n\nThen we can make individual tags that handle whatever we need them to...\n@register.tag\ndef render_bar_chart(parser, token):\n return DataForTag.handle_token(parser, token, 'data/charts/barchart.html')\n\n@register.tag\ndef render_pie_chart(parser, token):\n return DataForTag.handle_token(parser, token, 'data/charts/piechart.html') \n\n@register.tag\ndef render_data_table(parser, token):\n return DataForTag.handle_token(parser, token, 'data/table.html') \n\n" ]
[ 6, 1 ]
[]
[]
[ "charts", "django", "parameters", "python" ]
stackoverflow_0002717824_charts_django_parameters_python.txt
Q: While trying to set up Django on Windows: AttributeError: 'Settings' object has no attribute 'DATABASES' I'm following these instructions in order to set up Django on Windows. I have installed Python 2.6, PostgreSQL 8.4, Psycopg 2.0.14 for Python 2.6 and the latest version of Django from SVN. I'm now following these instructions to run a test project (copied from the page linked to above): C:\Documents and Settings\John>cd C:\ C:\>mkdir django C:\>cd django C:\django>django-admin.py startproject testproject C:\django>cd testproject C:\django\testproject>python manage.py runserver When I run the last line, this is the output: Validating models... Unhandled exception in thread started by <function inner_run at 0x01ECB930> Traceback (most recent call last): File "J:\Python26\lib\site-packages\django\core\management\commands\runserver.py", line 48, in inn er_run self.validate(display_num_errors=True) File "J:\Python26\lib\site-packages\django\core\management\base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "J:\Python26\lib\site-packages\django\core\management\validation.py", line 22, in get_validat ion_errors from django.db import models, connection File "J:\Python26\lib\site-packages\django\db\__init__.py", line 14, in <module> if not settings.DATABASES: File "J:\Python26\lib\site-packages\django\utils\functional.py", line 273, in __getattr__ return getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'DATABASES' Did I forget to do something with the database? Any help will be appreciated. Thank you! EDIT: Seems like all my problems (including this one) were caused because I used the development version of Django from SVN. I removed the development version and installed Django 1.1.1, and finally there are no more strange error messages and the server is running! A: The SVN checkout version of Django is looking for a setting like this in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase' } } This is slightly different than the way it's shown in the Django book and many tutorials. Checkout the online doc.
While trying to set up Django on Windows: AttributeError: 'Settings' object has no attribute 'DATABASES'
I'm following these instructions in order to set up Django on Windows. I have installed Python 2.6, PostgreSQL 8.4, Psycopg 2.0.14 for Python 2.6 and the latest version of Django from SVN. I'm now following these instructions to run a test project (copied from the page linked to above): C:\Documents and Settings\John>cd C:\ C:\>mkdir django C:\>cd django C:\django>django-admin.py startproject testproject C:\django>cd testproject C:\django\testproject>python manage.py runserver When I run the last line, this is the output: Validating models... Unhandled exception in thread started by <function inner_run at 0x01ECB930> Traceback (most recent call last): File "J:\Python26\lib\site-packages\django\core\management\commands\runserver.py", line 48, in inn er_run self.validate(display_num_errors=True) File "J:\Python26\lib\site-packages\django\core\management\base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "J:\Python26\lib\site-packages\django\core\management\validation.py", line 22, in get_validat ion_errors from django.db import models, connection File "J:\Python26\lib\site-packages\django\db\__init__.py", line 14, in <module> if not settings.DATABASES: File "J:\Python26\lib\site-packages\django\utils\functional.py", line 273, in __getattr__ return getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'DATABASES' Did I forget to do something with the database? Any help will be appreciated. Thank you! EDIT: Seems like all my problems (including this one) were caused because I used the development version of Django from SVN. I removed the development version and installed Django 1.1.1, and finally there are no more strange error messages and the server is running!
[ "The SVN checkout version of Django is looking for a setting like this in settings.py:\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': 'mydatabase'\n }\n}\n\nThis is slightly different than the way it's shown in the Django book and many tutorials.\nCheckout the online doc.\n" ]
[ 4 ]
[]
[]
[ "django", "postgresql", "psycopg2", "python" ]
stackoverflow_0002717704_django_postgresql_psycopg2_python.txt
Q: python script to download xml files on my server I need a python script that will do the following: connect to a URL, and that URL will return a number like 1200. Use the number, to download xml files named: 1 to x where x is the number from #1. store the files in a particular directory. Sorry I've never written a python script, so if you could guide me along that would be great (maybe with a some comments). I will be running this as a cron job if that matters. A: Example using urllib: import urllib import os URL = 'http://someurl.com/foo/bar' DIRECTORY = '/some/local/folder' # connect to a URL, and that URL will return a number like 1200. number = int(urllib.urlopen(URL).read()) # Use the number, to download xml files named: # 1 to x where x is the number from #1. # store the files in a particular directory. for n in xrange(1, number + 1): filename = '%d.xml' % (n,) destination = os.path.join(DIRECTORY, filename) urllib2.urlretrieve(URL + '/' + filename, destination) A: If you're never written a python script, you would do better to look for a python tutorial first. Once you have a small grasp of things, check out http://docs.python.org/library/ For question #1, you'll want to look at http://docs.python.org/library/internet.html For question #2, you can do something like max = 10 # assume from #1 for x in range(1, max+1): filename = 'some_file-' + str(x) + '.xml' # download the file - see above url for internet protocols # see http://docs.python.org/library/stdtypes.html#file-objects # for help on files This question is very vague on details and while it doesn't smell like a homework assignment, it would not be a good idea to do it in a language you don't know at all, in particular if you are running it in cron.
python script to download xml files on my server
I need a python script that will do the following: connect to a URL, and that URL will return a number like 1200. Use the number, to download xml files named: 1 to x where x is the number from #1. store the files in a particular directory. Sorry I've never written a python script, so if you could guide me along that would be great (maybe with a some comments). I will be running this as a cron job if that matters.
[ "Example using urllib:\nimport urllib\nimport os\n\nURL = 'http://someurl.com/foo/bar'\nDIRECTORY = '/some/local/folder'\n\n# connect to a URL, and that URL will return a number like 1200.\nnumber = int(urllib.urlopen(URL).read())\n\n# Use the number, to download xml files named: \n# 1 to x where x is the number from #1.\n# store the files in a particular directory.\nfor n in xrange(1, number + 1):\n filename = '%d.xml' % (n,)\n destination = os.path.join(DIRECTORY, filename)\n urllib2.urlretrieve(URL + '/' + filename, destination)\n\n", "If you're never written a python script, you would do better to look for a python tutorial first.\nOnce you have a small grasp of things, check out\nhttp://docs.python.org/library/\nFor question #1, you'll want to look at\nhttp://docs.python.org/library/internet.html\nFor question #2, you can do something like\nmax = 10 # assume from #1\nfor x in range(1, max+1):\n filename = 'some_file-' + str(x) + '.xml'\n # download the file - see above url for internet protocols\n # see http://docs.python.org/library/stdtypes.html#file-objects\n # for help on files\n\nThis question is very vague on details and while it doesn't smell like a homework assignment, it would not be a good idea to do it in a language you don't know at all, in particular if you are running it in cron.\n" ]
[ 2, 1 ]
[]
[]
[ "cron", "python", "scripting" ]
stackoverflow_0002718176_cron_python_scripting.txt
Q: Find all Chinese text in a string using Python and Regex I needed to strip the Chinese out of a bunch of strings today and was looking for a simple Python regex. Any suggestions? A: Python 2: #!/usr/bin/env python # -*- encoding: utf8 -*- import re sample = u'I am from 美国。We should be friends. 朋友。' for n in re.findall(ur'[\u4e00-\u9fff]+',sample): print n Python 3: sample = 'I am from 美国。We should be friends. 朋友。' for n in re.findall(r'[\u4e00-\u9fff]+', sample): print(n) Output: 美国 朋友 About Unicode code blocks: The 4E00—9FFF range covers CJK Unified Ideographs (CJK=Chinese, Japanese and Korean). There are a number of lower ranges that relate, to some degree, to CJK: 31C0—31EF CJK Strokes 31F0—31FF Katakana Phonetic Extensions 3200—32FF Enclosed CJK Letters and Months 3300—33FF CJK Compatibility 3400—4DBF CJK Unified Ideographs Extension A 4DC0—4DFF Yijing Hexagram Symbols 4E00—9FFF CJK Unified Ideographs A: The short, but relatively comprehensive answer for narrow Unicode builds of python (excluding ordinals > 65535 which can only be represented in narrow Unicode builds via surrogate pairs): RE = re.compile(u'[⺀-⺙⺛-⻳⼀-⿕々〇〡-〩〸-〺〻㐀-䶵一-鿃豈-鶴侮-頻並-龎]', re.UNICODE) nochinese = RE.sub('', mystring) The code for building the RE, and if you need to detect Chinese characters in the supplementary plane for wide builds: # -*- coding: utf-8 -*- import re LHan = [[0x2E80, 0x2E99], # Han # So [26] CJK RADICAL REPEAT, CJK RADICAL RAP [0x2E9B, 0x2EF3], # Han # So [89] CJK RADICAL CHOKE, CJK RADICAL C-SIMPLIFIED TURTLE [0x2F00, 0x2FD5], # Han # So [214] KANGXI RADICAL ONE, KANGXI RADICAL FLUTE 0x3005, # Han # Lm IDEOGRAPHIC ITERATION MARK 0x3007, # Han # Nl IDEOGRAPHIC NUMBER ZERO [0x3021, 0x3029], # Han # Nl [9] HANGZHOU NUMERAL ONE, HANGZHOU NUMERAL NINE [0x3038, 0x303A], # Han # Nl [3] HANGZHOU NUMERAL TEN, HANGZHOU NUMERAL THIRTY 0x303B, # Han # Lm VERTICAL IDEOGRAPHIC ITERATION MARK [0x3400, 0x4DB5], # Han # Lo [6582] CJK UNIFIED IDEOGRAPH-3400, CJK UNIFIED IDEOGRAPH-4DB5 [0x4E00, 0x9FC3], # Han # Lo [20932] CJK UNIFIED IDEOGRAPH-4E00, CJK UNIFIED IDEOGRAPH-9FC3 [0xF900, 0xFA2D], # Han # Lo [302] CJK COMPATIBILITY IDEOGRAPH-F900, CJK COMPATIBILITY IDEOGRAPH-FA2D [0xFA30, 0xFA6A], # Han # Lo [59] CJK COMPATIBILITY IDEOGRAPH-FA30, CJK COMPATIBILITY IDEOGRAPH-FA6A [0xFA70, 0xFAD9], # Han # Lo [106] CJK COMPATIBILITY IDEOGRAPH-FA70, CJK COMPATIBILITY IDEOGRAPH-FAD9 [0x20000, 0x2A6D6], # Han # Lo [42711] CJK UNIFIED IDEOGRAPH-20000, CJK UNIFIED IDEOGRAPH-2A6D6 [0x2F800, 0x2FA1D]] # Han # Lo [542] CJK COMPATIBILITY IDEOGRAPH-2F800, CJK COMPATIBILITY IDEOGRAPH-2FA1D def build_re(): L = [] for i in LHan: if isinstance(i, list): f, t = i try: f = unichr(f) t = unichr(t) L.append('%s-%s' % (f, t)) except: pass # A narrow python build, so can't use chars > 65535 without surrogate pairs! else: try: L.append(unichr(i)) except: pass RE = '[%s]' % ''.join(L) print 'RE:', RE.encode('utf-8') return re.compile(RE, re.UNICODE) RE = build_re() print RE.sub('', u'美国').encode('utf-8') print RE.sub('', u'blah').encode('utf-8')
Find all Chinese text in a string using Python and Regex
I needed to strip the Chinese out of a bunch of strings today and was looking for a simple Python regex. Any suggestions?
[ "Python 2:\n#!/usr/bin/env python\n# -*- encoding: utf8 -*-\n\n\nimport re\n\nsample = u'I am from 美国。We should be friends. 朋友。'\nfor n in re.findall(ur'[\\u4e00-\\u9fff]+',sample):\n print n\n\nPython 3:\nsample = 'I am from 美国。We should be friends. 朋友。'\nfor n in re.findall(r'[\\u4e00-\\u9fff]+', sample):\n print(n)\n\nOutput:\n美国\n朋友\n\nAbout Unicode code blocks:\nThe 4E00—9FFF range covers CJK Unified Ideographs (CJK=Chinese, Japanese and Korean). There are a number of lower ranges that relate, to some degree, to CJK:\n31C0—31EF CJK Strokes\n31F0—31FF Katakana Phonetic Extensions\n3200—32FF Enclosed CJK Letters and Months\n3300—33FF CJK Compatibility\n3400—4DBF CJK Unified Ideographs Extension A\n4DC0—4DFF Yijing Hexagram Symbols\n4E00—9FFF CJK Unified Ideographs \n\n", "The short, but relatively comprehensive answer for narrow Unicode builds of python (excluding ordinals > 65535 which can only be represented in narrow Unicode builds via surrogate pairs):\nRE = re.compile(u'[⺀-⺙⺛-⻳⼀-⿕々〇〡-〩〸-〺〻㐀-䶵一-鿃豈-鶴侮-頻並-龎]', re.UNICODE)\nnochinese = RE.sub('', mystring)\n\nThe code for building the RE, and if you need to detect Chinese characters in the supplementary plane for wide builds:\n# -*- coding: utf-8 -*-\nimport re\n\nLHan = [[0x2E80, 0x2E99], # Han # So [26] CJK RADICAL REPEAT, CJK RADICAL RAP\n [0x2E9B, 0x2EF3], # Han # So [89] CJK RADICAL CHOKE, CJK RADICAL C-SIMPLIFIED TURTLE\n [0x2F00, 0x2FD5], # Han # So [214] KANGXI RADICAL ONE, KANGXI RADICAL FLUTE\n 0x3005, # Han # Lm IDEOGRAPHIC ITERATION MARK\n 0x3007, # Han # Nl IDEOGRAPHIC NUMBER ZERO\n [0x3021, 0x3029], # Han # Nl [9] HANGZHOU NUMERAL ONE, HANGZHOU NUMERAL NINE\n [0x3038, 0x303A], # Han # Nl [3] HANGZHOU NUMERAL TEN, HANGZHOU NUMERAL THIRTY\n 0x303B, # Han # Lm VERTICAL IDEOGRAPHIC ITERATION MARK\n [0x3400, 0x4DB5], # Han # Lo [6582] CJK UNIFIED IDEOGRAPH-3400, CJK UNIFIED IDEOGRAPH-4DB5\n [0x4E00, 0x9FC3], # Han # Lo [20932] CJK UNIFIED IDEOGRAPH-4E00, CJK UNIFIED IDEOGRAPH-9FC3\n [0xF900, 0xFA2D], # Han # Lo [302] CJK COMPATIBILITY IDEOGRAPH-F900, CJK COMPATIBILITY IDEOGRAPH-FA2D\n [0xFA30, 0xFA6A], # Han # Lo [59] CJK COMPATIBILITY IDEOGRAPH-FA30, CJK COMPATIBILITY IDEOGRAPH-FA6A\n [0xFA70, 0xFAD9], # Han # Lo [106] CJK COMPATIBILITY IDEOGRAPH-FA70, CJK COMPATIBILITY IDEOGRAPH-FAD9\n [0x20000, 0x2A6D6], # Han # Lo [42711] CJK UNIFIED IDEOGRAPH-20000, CJK UNIFIED IDEOGRAPH-2A6D6\n [0x2F800, 0x2FA1D]] # Han # Lo [542] CJK COMPATIBILITY IDEOGRAPH-2F800, CJK COMPATIBILITY IDEOGRAPH-2FA1D\n\ndef build_re():\n L = []\n for i in LHan:\n if isinstance(i, list):\n f, t = i\n try: \n f = unichr(f)\n t = unichr(t)\n L.append('%s-%s' % (f, t))\n except: \n pass # A narrow python build, so can't use chars > 65535 without surrogate pairs!\n\n else:\n try:\n L.append(unichr(i))\n except:\n pass\n\n RE = '[%s]' % ''.join(L)\n print 'RE:', RE.encode('utf-8')\n return re.compile(RE, re.UNICODE)\n\nRE = build_re()\nprint RE.sub('', u'美国').encode('utf-8')\nprint RE.sub('', u'blah').encode('utf-8')\n\n" ]
[ 43, 31 ]
[]
[]
[ "cjk", "python", "regex" ]
stackoverflow_0002718196_cjk_python_regex.txt
Q: How can I set the line style of a specific cell in a QTableView? I am working with a QT GUI. I am implementing a simple hex edit control using a QTableView. My initial idea is to use a table with seventeen columns. Each row of the table will have 16 hex bytes and then an ASCII representation of that data in the seventeenth column. Ideally, I would like to edit/set the style of the seventeenth column to have no lines on the top and bottom of each cell to give the text a free flowing appearance. What is the best way to approach this using the QTableView? A: I could think about a couple of ways of doing what you need; both would include drawing custom grid as it looks like there is no straight forward way of hooking into the grid painting routine of QTableView class: 1.Switch off the standard grid for your treeview grid by calling setShowGrid(false) and draw grid lines for cells which need them using item delegate. Below is an example: // custom item delegate to draw grid lines around cells class CustomDelegate : public QStyledItemDelegate { public: CustomDelegate(QTableView* tableView); protected: void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; private: QPen _gridPen; }; CustomDelegate::CustomDelegate(QTableView* tableView) { // create grid pen int gridHint = tableView->style()->styleHint(QStyle::SH_Table_GridLineColor, new QStyleOptionViewItemV4()); QColor gridColor = static_cast<QRgb>(gridHint); _gridPen = QPen(gridColor, 0, tableView->gridStyle()); } void CustomDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { QStyledItemDelegate::paint(painter, option, index); QPen oldPen = painter->pen(); painter->setPen(_gridPen); // paint vertical lines painter->drawLine(option.rect.topRight(), option.rect.bottomRight()); // paint horizontal lines if (index.column()!=1) //<-- check if column need horizontal grid lines painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight()); painter->setPen(oldPen); } // set up for your tree view: ui->tableView->setShowGrid(false); ui->tableView->setItemDelegate(new CustomDelegate(ui->tableView)); 2.Create a QTableView descendant and override the paintEvent method. There you could either draw your own grid or let base class to draw it and then paint horizontal lines on top of the grid with using tableview's background color. hope this helps, regards
How can I set the line style of a specific cell in a QTableView?
I am working with a QT GUI. I am implementing a simple hex edit control using a QTableView. My initial idea is to use a table with seventeen columns. Each row of the table will have 16 hex bytes and then an ASCII representation of that data in the seventeenth column. Ideally, I would like to edit/set the style of the seventeenth column to have no lines on the top and bottom of each cell to give the text a free flowing appearance. What is the best way to approach this using the QTableView?
[ "I could think about a couple of ways of doing what you need; both would include drawing custom grid as it looks like there is no straight forward way of hooking into the grid painting routine of QTableView class:\n1.Switch off the standard grid for your treeview grid by calling setShowGrid(false) and draw grid lines for cells which need them using item delegate. Below is an example:\n// custom item delegate to draw grid lines around cells\nclass CustomDelegate : public QStyledItemDelegate\n{\npublic:\n CustomDelegate(QTableView* tableView);\nprotected:\n void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;\nprivate:\n QPen _gridPen;\n};\n\nCustomDelegate::CustomDelegate(QTableView* tableView)\n{\n // create grid pen\n int gridHint = tableView->style()->styleHint(QStyle::SH_Table_GridLineColor, new QStyleOptionViewItemV4());\n QColor gridColor = static_cast<QRgb>(gridHint);\n _gridPen = QPen(gridColor, 0, tableView->gridStyle());\n}\n\nvoid CustomDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const\n{\n QStyledItemDelegate::paint(painter, option, index);\n\n QPen oldPen = painter->pen();\n painter->setPen(_gridPen);\n\n // paint vertical lines\n painter->drawLine(option.rect.topRight(), option.rect.bottomRight());\n // paint horizontal lines \n if (index.column()!=1) //<-- check if column need horizontal grid lines\n painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight());\n\n painter->setPen(oldPen);\n}\n\n// set up for your tree view:\nui->tableView->setShowGrid(false);\nui->tableView->setItemDelegate(new CustomDelegate(ui->tableView));\n\n2.Create a QTableView descendant and override the paintEvent method. There you could either draw your own grid or let base class to draw it and then paint horizontal lines on top of the grid with using tableview's background color.\nhope this helps, regards\n" ]
[ 4 ]
[]
[]
[ "c++", "pyqt4", "python", "qt", "qtableview" ]
stackoverflow_0002717318_c++_pyqt4_python_qt_qtableview.txt
Q: Why can't I display a unicode character in the Python Interpreter on Mac OS X Terminal.app? If I try to paste a unicode character such as the middle dot: · in my python interpreter it does nothing. I'm using Terminal.app on Mac OS X and when I'm simply in in bash I have no trouble: :~$ · But in the interpreter: :~$ python Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> ^^ I get nothing, it just ignores that I just pasted the character. If I use the escape \xNN\xNN representation of the middle dot '\xc2\xb7', and try to convert to unicode, trying to show the dot causes the interpreter to throw an error: >>> unicode('\xc2\xb7') Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128) I have setup 'utf-8' as my default encoding in sitecustomize.py so: >>> sys.getdefaultencoding() 'utf-8' What gives? It's not the Terminal. It's not Python, what am I doing wrong?! This question is not related to this question, as that indivdiual is able to paste unicode into his Terminal. A: unicode('\xc2\xb7') means to decode the byte string in question with the default codec, which is ascii -- and that of course fails (trying to set a different default encoding has never worked well, and in particular doesn't apply to "pasted literals" -- that would require a different setting anyway). You could use instead u'\xc2\xb7', and see: >>> print(u'\xc2\xb7') · since those are two unicode characters of course. While: >>> print(u'\uc2b7') 슷 gives you a single unicode character (of some oriental persuasion -- sorry, I'm ignorant about these things). BTW, neither of these is the "middle dot" you were looking for. Maybe you mean >>> print('\xc2\xb7'.decode('utf8')) · which is the middle dot. BTW, for me (python 2.6.4 from python.org on a Mac Terminal.app): >>> print('슷') 슷 which kind of surprised me (I expected an error...!-).
Why can't I display a unicode character in the Python Interpreter on Mac OS X Terminal.app?
If I try to paste a unicode character such as the middle dot: · in my python interpreter it does nothing. I'm using Terminal.app on Mac OS X and when I'm simply in in bash I have no trouble: :~$ · But in the interpreter: :~$ python Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> ^^ I get nothing, it just ignores that I just pasted the character. If I use the escape \xNN\xNN representation of the middle dot '\xc2\xb7', and try to convert to unicode, trying to show the dot causes the interpreter to throw an error: >>> unicode('\xc2\xb7') Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128) I have setup 'utf-8' as my default encoding in sitecustomize.py so: >>> sys.getdefaultencoding() 'utf-8' What gives? It's not the Terminal. It's not Python, what am I doing wrong?! This question is not related to this question, as that indivdiual is able to paste unicode into his Terminal.
[ "unicode('\\xc2\\xb7') means to decode the byte string in question with the default codec, which is ascii -- and that of course fails (trying to set a different default encoding has never worked well, and in particular doesn't apply to \"pasted literals\" -- that would require a different setting anyway). You could use instead u'\\xc2\\xb7', and see:\n>>> print(u'\\xc2\\xb7')\n·\n\nsince those are two unicode characters of course. While:\n>>> print(u'\\uc2b7')\n슷\n\ngives you a single unicode character (of some oriental persuasion -- sorry, I'm ignorant about these things). BTW, neither of these is the \"middle dot\" you were looking for. Maybe you mean\n>>> print('\\xc2\\xb7'.decode('utf8'))\n·\n\nwhich is the middle dot. BTW, for me (python 2.6.4 from python.org on a Mac Terminal.app):\n>>> print('슷')\n슷\n\nwhich kind of surprised me (I expected an error...!-).\n" ]
[ 6 ]
[]
[]
[ "macos", "python", "terminal", "unicode" ]
stackoverflow_0002718491_macos_python_terminal_unicode.txt
Q: get city, state or zip from a string in python I'd like to be able to parse out the city, state or zip from a string in python. So, if I entered Boulder, Co 80303 Boulder, Colorado Boulder, Co 80303 ... any variation of these it would return the city, state or zip. This is all going to be user inputted data and inputted in one text field. A: Just ask for their zip only, then give a (short) list of applicable cities by using a geocode database. That way you get nice clean 5-digit input, they save time, and you all go home happy. If you already have the data, look just for the zip, find a list of possible cities (there will only be one applicable state) and match for the city name after making everything lowercase. A: You could use a geocoding web service or something similar. For example, on the Yahoo geocoding API page, it shows how you can specify the address in a number of ways: This free field lets users enter any of the following: city, state city, state, zip zip street, city, state street, city, state, zip street, zip and the XML results provide the parsed address, for example with this test URL specified on the page. A: I would use ([^\d]+)?(\d{5})? as my regular expression, and use match so it only matches the beginning of the string. This way it won't fail on bad input and will make its best guess as to what was intended. Then you can split the first capture group on ",". A: easy_install ngram build file with all the city and state names one per line, place in citystate.data Redwood City, CA Redwood, VA etc Experiment ( the .2 threshold is a little lax ) import string import ngram cityStateParser = ngram.NGram( items = (line.strip() for line in open('citystate.data')) , N=3, iconv=string.lower, qconv=string.lower, threshold=.2 ) Example: cityStateParser.search('redwood') [('Redwood VA', 0.5), ('Redwood NY', 0.5), ('Redwood MS', 0.5), ('Redwood City CA', 0.36842105263157893), ... ] Notes: Because these are NGrams you might get overmatch when the state is part of a ngram in the city i.e. search for "washington" would yield Washington IN with a bette score than "Washington OK" You might also want read Using Superimposed Coding Of N-Gram Lists For Efficient Inexact Matching (PDF Download) A: This code seems to do what you want: text = """ Boulder, Co 80303 Boulder, Colorado Boulder, Co 80303 """ lines = text.splitlines() ABBREV = dict(co="Colorado", ca="California") STATES = ABBREV.values() def parse_addr(line): addr = {} # normalize commas parts = line.replace(",", " ").split() for part in parts: if part.capitalize() in STATES: addr["state"] = part elif part.lower() in ABBREV: addr["state"] = ABBREV[part.lower()] else: try: zip = int(part) addr["zip"] = part except ValueError: addr["city"] = part return addr for line in lines: print line, parse_addr(line) Output: Boulder, Co {'city': 'Boulder', 'state': 'Colorado'} 80303 {'zip': '80303'} Boulder, Colorado {'city': 'Boulder', 'state': 'Colorado'} Boulder, Co 80303 {'city': 'Boulder', 'state': 'Colorado', 'zip': '80303'} Handling of "South Dakota" and other two-word states/cities left as an exercise for the reader :) As the other posters suggested, you can get smart and use the zip code to narrow in on the city/state as well.
get city, state or zip from a string in python
I'd like to be able to parse out the city, state or zip from a string in python. So, if I entered Boulder, Co 80303 Boulder, Colorado Boulder, Co 80303 ... any variation of these it would return the city, state or zip. This is all going to be user inputted data and inputted in one text field.
[ "Just ask for their zip only, then give a (short) list of applicable cities by using a geocode database. That way you get nice clean 5-digit input, they save time, and you all go home happy.\nIf you already have the data, look just for the zip, find a list of possible cities (there will only be one applicable state) and match for the city name after making everything lowercase.\n", "You could use a geocoding web service or something similar. For example, on the Yahoo geocoding API page, it shows how you can specify the address in a number of ways:\nThis free field lets users enter any of the following:\n city, state\n city, state, zip\n zip\n street, city, state\n street, city, state, zip\n street, zip\n\nand the XML results provide the parsed address, for example with this test URL specified on the page.\n", "I would use ([^\\d]+)?(\\d{5})? as my regular expression, and use match so it only matches the beginning of the string. This way it won't fail on bad input and will make its best guess as to what was intended. Then you can split the first capture group on \",\".\n", "\neasy_install ngram\nbuild file with all the city and state names one per line, place in citystate.data\nRedwood City, CA\nRedwood, VA\netc\nExperiment ( the .2 threshold is a little lax )\n\n\nimport string\nimport ngram\ncityStateParser = ngram.NGram(\n items = (line.strip() for line in open('citystate.data')) ,\n N=3, iconv=string.lower, qconv=string.lower, threshold=.2\n)\n\nExample:\ncityStateParser.search('redwood')\n[('Redwood VA', 0.5),\n('Redwood NY', 0.5),\n('Redwood MS', 0.5),\n('Redwood City CA', 0.36842105263157893),\n...\n]\n\nNotes:\nBecause these are NGrams you might get overmatch when the state is part of a ngram in the city\ni.e. search for \"washington\" would yield Washington IN with a bette score than \"Washington OK\" \nYou might also want read Using Superimposed Coding Of N-Gram Lists For Efficient Inexact Matching (PDF Download)\n", "This code seems to do what you want:\ntext = \"\"\"\nBoulder, Co\n80303\nBoulder, Colorado\nBoulder, Co 80303\n\"\"\"\n\nlines = text.splitlines()\n\nABBREV = dict(co=\"Colorado\", ca=\"California\")\nSTATES = ABBREV.values()\n\ndef parse_addr(line):\n addr = {}\n # normalize commas\n parts = line.replace(\",\", \" \").split()\n for part in parts:\n if part.capitalize() in STATES:\n addr[\"state\"] = part\n elif part.lower() in ABBREV:\n addr[\"state\"] = ABBREV[part.lower()]\n else:\n try:\n zip = int(part)\n addr[\"zip\"] = part\n except ValueError:\n addr[\"city\"] = part\n return addr\n\nfor line in lines:\n print line, parse_addr(line)\n\nOutput:\nBoulder, Co {'city': 'Boulder', 'state': 'Colorado'}\n80303 {'zip': '80303'}\nBoulder, Colorado {'city': 'Boulder', 'state': 'Colorado'}\nBoulder, Co 80303 {'city': 'Boulder', 'state': 'Colorado', 'zip': '80303'}\n\nHandling of \"South Dakota\" and other two-word states/cities left as an exercise for the reader :)\nAs the other posters suggested, you can get smart and use the zip code to narrow in on the city/state as well.\n" ]
[ 3, 3, 1, 1, 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0002054422_python_regex_string.txt
Q: How do I create a type of compression that my software can read / write? My software only I am working on a project that requires programmatically distributing a compressed file that in a format that is associated with my software. I am writing the software in Python. I would use .zip, but I don't want to overwrite any previouse filetype associations. ( with zip utilities ) A: You could create new file extension other than .zip and associate that file extension with your program. A: Do what Java does: use zip format[*] file, but use a different filename extension. [*] or a standard compression format of your choosing. A: If you are looking to be able to associate an extension with your application, just use your own unique file extension and leverage existing zip processes. If you are looking to be able to ensure that your own application is the ONLY application that can read the file as well, even if the user changed the extension you will have to do a LOT more work.
How do I create a type of compression that my software can read / write? My software only
I am working on a project that requires programmatically distributing a compressed file that in a format that is associated with my software. I am writing the software in Python. I would use .zip, but I don't want to overwrite any previouse filetype associations. ( with zip utilities )
[ "You could create new file extension other than .zip and associate that file extension with your program.\n", "Do what Java does: use zip format[*] file, but use a different filename extension.\n[*] or a standard compression format of your choosing.\n", "If you are looking to be able to associate an extension with your application, just use your own unique file extension and leverage existing zip processes.\nIf you are looking to be able to ensure that your own application is the ONLY application that can read the file as well, even if the user changed the extension you will have to do a LOT more work.\n" ]
[ 4, 0, 0 ]
[]
[]
[ "associations", "compression", "format", "python" ]
stackoverflow_0002718933_associations_compression_format_python.txt
Q: filter queryset based on list, including None I dont know if its a django bug or a feature but i have a strange ORM behaviour with MySQL. class Status(models.Model): name = models.CharField(max_length = 50) class Article(models.Model) status = models.ForeignKey(status, blank = True, null=True) filters = Q(status__in =[0, 1,2] ) | Q(status=None) items = Article.objects.filter(filters) this returns Article items but some have other status than requested [0,1,2,None] looking at the sql query : SELECT [..] FROM `app_article` LEFT OUTER JOIN `app_status` ON (`app_article`.`status_id` = `app_status`.`id`) WHERE (`app_article`.`status_id` IN (1, 2) OR `app_status`.`id` IS NULL) ORDER BY [...] the OR app_status.id IS NULL part seems to be the cause. if i change it to OR app_article.status_id IS NULL it works correctly. How to deal with this ? Thanx. A: Try using this query instead: filters = Q(status__in =[0, 1,2] ) | Q(status__isnull=True) A: In your foreign key attribute for the Article model, you're referencing status with a lowercase 's'. But your Status model has an uppercase 'S'. Not sure where your typo is, but in case your model is actually defined with a lower case 's', then that might explain the strange SQL you're seeing.
filter queryset based on list, including None
I dont know if its a django bug or a feature but i have a strange ORM behaviour with MySQL. class Status(models.Model): name = models.CharField(max_length = 50) class Article(models.Model) status = models.ForeignKey(status, blank = True, null=True) filters = Q(status__in =[0, 1,2] ) | Q(status=None) items = Article.objects.filter(filters) this returns Article items but some have other status than requested [0,1,2,None] looking at the sql query : SELECT [..] FROM `app_article` LEFT OUTER JOIN `app_status` ON (`app_article`.`status_id` = `app_status`.`id`) WHERE (`app_article`.`status_id` IN (1, 2) OR `app_status`.`id` IS NULL) ORDER BY [...] the OR app_status.id IS NULL part seems to be the cause. if i change it to OR app_article.status_id IS NULL it works correctly. How to deal with this ? Thanx.
[ "Try using this query instead:\nfilters = Q(status__in =[0, 1,2] ) | Q(status__isnull=True) \n\n", "In your foreign key attribute for the Article model, you're referencing status with a lowercase 's'. But your Status model has an uppercase 'S'. Not sure where your typo is, but in case your model is actually defined with a lower case 's', then that might explain the strange SQL you're seeing. \n" ]
[ 1, 0 ]
[]
[]
[ "django", "mysql", "orm", "python", "sql" ]
stackoverflow_0002717282_django_mysql_orm_python_sql.txt
Q: how to diff / align Python lists using arbitrary matching function? I'd like to align two lists in a similar way to what difflib.Differ would do except I want to be able to define a match function for comparing items, not just use string equality, and preferably a match function that can return a number between 0.0 and 1.0, not just a boolean. So, for example, say I had the two lists: L1 = [('A', 1), ('B', 3), ('C', 7)] L2 = ['A', 'b', 'C'] and I want to be able to write a match function like this: def match(item1, item2): if item1[0] == item2: return 1.0 elif item1[0].lower() == item2.lower(): return 0.5 else: return 0.0 and then do: d = Differ(match_func=match) d.compare(L1, L2) and have it diff using the match function. Like difflib, I'd rather the algorithm gave more intuitive Ratcliff-Obershelp type results rather than a purely minimal Levenshtein distance. A: I just wrote this implementation of Needleman-Wunsch and it seems to do what I want: def nw_align(a, b, replace_func, insert, delete): ZERO, LEFT, UP, DIAGONAL = 0, 1, 2, 3 len_a = len(a) len_b = len(b) matrix = [[(0, ZERO) for x in range(len_b + 1)] for y in range(len_a + 1)] for i in range(len_a + 1): matrix[i][0] = (insert * i, UP) for j in range(len_b + 1): matrix[0][j] = (delete * j, LEFT) for i in range(1, len_a + 1): for j in range(1, len_b + 1): replace = replace_func(a[i - 1], b[j - 1]) matrix[i][j] = max([ (matrix[i - 1][j - 1][0] + replace, DIAGONAL), (matrix[i][j - 1][0] + insert, LEFT), (matrix[i - 1][j][0] + delete, UP) ]) i, j = len_a, len_b align_a = "" align_b = "" while (i, j) != (0, 0): if matrix[i][j][1] == DIAGONAL: align_a += a[i - 1] align_b += b[j - 1] i -= 1 j -= 1 elif matrix[i][j][1] == LEFT: align_a += "-" align_b += b[j - 1] j -= 1 else: # UP align_a += a[i - 1] align_b += "-" i -= 1 return align_a[::-1], align_b[::-1] A: I recently ran across a discussion of an algorithm called patience diff that sounds rather simple. You could try implementing that yourself, and then of course you can have it use whatever comparison algorithm you like.
how to diff / align Python lists using arbitrary matching function?
I'd like to align two lists in a similar way to what difflib.Differ would do except I want to be able to define a match function for comparing items, not just use string equality, and preferably a match function that can return a number between 0.0 and 1.0, not just a boolean. So, for example, say I had the two lists: L1 = [('A', 1), ('B', 3), ('C', 7)] L2 = ['A', 'b', 'C'] and I want to be able to write a match function like this: def match(item1, item2): if item1[0] == item2: return 1.0 elif item1[0].lower() == item2.lower(): return 0.5 else: return 0.0 and then do: d = Differ(match_func=match) d.compare(L1, L2) and have it diff using the match function. Like difflib, I'd rather the algorithm gave more intuitive Ratcliff-Obershelp type results rather than a purely minimal Levenshtein distance.
[ "I just wrote this implementation of Needleman-Wunsch and it seems to do what I want:\ndef nw_align(a, b, replace_func, insert, delete):\n\n ZERO, LEFT, UP, DIAGONAL = 0, 1, 2, 3\n\n len_a = len(a)\n len_b = len(b)\n\n matrix = [[(0, ZERO) for x in range(len_b + 1)] for y in range(len_a + 1)]\n\n for i in range(len_a + 1):\n matrix[i][0] = (insert * i, UP)\n\n for j in range(len_b + 1):\n matrix[0][j] = (delete * j, LEFT)\n\n for i in range(1, len_a + 1):\n for j in range(1, len_b + 1):\n replace = replace_func(a[i - 1], b[j - 1])\n matrix[i][j] = max([\n (matrix[i - 1][j - 1][0] + replace, DIAGONAL),\n (matrix[i][j - 1][0] + insert, LEFT),\n (matrix[i - 1][j][0] + delete, UP)\n ])\n\n i, j = len_a, len_b\n align_a = \"\"\n align_b = \"\"\n\n while (i, j) != (0, 0):\n if matrix[i][j][1] == DIAGONAL:\n align_a += a[i - 1]\n align_b += b[j - 1]\n i -= 1\n j -= 1\n elif matrix[i][j][1] == LEFT:\n align_a += \"-\"\n align_b += b[j - 1]\n j -= 1\n else: # UP\n align_a += a[i - 1]\n align_b += \"-\"\n i -= 1\n\n return align_a[::-1], align_b[::-1]\n\n", "I recently ran across a discussion of an algorithm called patience diff that sounds rather simple. You could try implementing that yourself, and then of course you can have it use whatever comparison algorithm you like.\n" ]
[ 8, 0 ]
[]
[]
[ "diff", "python" ]
stackoverflow_0002718809_diff_python.txt
Q: python packaging problem hi develop code in python to scan wifi and send to the server, its working fine when execute manually, but i packaged it via http://www.python-packager.com by uploading my .py file and they create package for me as deb file for linux, and i download it and install the package but nothing happen when i click the .exe or set it as startup application, why this happen, nothing is printed in the terminal in .py file i'm having print statement to check manually to list out the wifi scan value, data to post to the server, response from the server once send how this can be solve thanks A: I'm the maintainer of the project, I thought I'd chime in and give my 2c. I had a look at your program. With .deb's, it installs everything to /opt/application-name. So to debug-it, run it from the command line. eg. "/opt/Jemapoh_Wifi/Jemapoh_Wifi". I just ran it myself and your programs gives the error "IOError: [Errno 2] No such file or directory: '/opt/Jemapoh_Wifi/config.txt'". So your program's looking for config.txt but you didn't upload it with the program. :-) If you have any further problems, please email me or report a bug on Launchpad - http://launchpad.net/python-packager. There'll be a re-vamped version coming out soon, hopefully it'll make things easier to understand. Hope that helps/makes sense. Cheers, Jackson A: "How this can be solved?" Use a standard packager. Read this: http://docs.python.org/distutils/introduction.html and this: http://pypi.python.org/pypi/pip and this: http://pypi.python.org/pypi/zc.buildout
python packaging problem
hi develop code in python to scan wifi and send to the server, its working fine when execute manually, but i packaged it via http://www.python-packager.com by uploading my .py file and they create package for me as deb file for linux, and i download it and install the package but nothing happen when i click the .exe or set it as startup application, why this happen, nothing is printed in the terminal in .py file i'm having print statement to check manually to list out the wifi scan value, data to post to the server, response from the server once send how this can be solve thanks
[ "I'm the maintainer of the project, I thought I'd chime in and give my 2c.\nI had a look at your program. With .deb's, it installs everything to /opt/application-name. So to debug-it, run it from the command line. eg. \"/opt/Jemapoh_Wifi/Jemapoh_Wifi\".\nI just ran it myself and your programs gives the error \"IOError: [Errno 2] No such file or directory: '/opt/Jemapoh_Wifi/config.txt'\". So your program's looking for config.txt but you didn't upload it with the program. :-)\nIf you have any further problems, please email me or report a bug on Launchpad - http://launchpad.net/python-packager. There'll be a re-vamped version coming out soon, hopefully it'll make things easier to understand.\nHope that helps/makes sense.\nCheers,\nJackson\n", "\"How this can be solved?\" \nUse a standard packager. Read this: http://docs.python.org/distutils/introduction.html and this: http://pypi.python.org/pypi/pip and this: http://pypi.python.org/pypi/zc.buildout\n" ]
[ 4, 2 ]
[]
[]
[ "package", "python" ]
stackoverflow_0002711462_package_python.txt
Q: Break nested loop in Django views.py with a function I have a nested loop that I would like to break out of. After searching this site it seems the best practice is to put the nested loop into a function and use return to break out of it. Is it acceptable to have functions inside the views.py file that are not a view? What is the best practice for the location of this function? Here's the example code from inside my views.py @login_required def save_bookmark(request): if request.method == 'POST': form = BookmarkSaveForm(request.POST) if form.is_valid(): bookmark_list = Bookmark.objects.all() for bookmark in bookmark_list: for link in bookmark.link_set.all(): if link.url == form.cleaned_data['url']: # Do something. break else: # Do something else. else: form = BookmarkSaveForm() return render_to_response('save_bookmark_form.html', {'form': form}) A: Yes. it's fine to have functions in views.py that are not views - (I do this all the time). This is particularly appropriate if the function is only for use within that module (i.e. by views in that views.py), or by just a single view function. You could always make it a private function if you're worried about exposing it to the outside world. Also, try avoid giving it a parameter called request, I tend to subconsciously parse functions which take a request as view functions when reading code. A: You shouldn't think of Django views as being in any way special. It's just Python. As such, you can have whatever functions you like in views.py. The only limitation is that views themselves have to take a request object and return a subclass of HttpResponse. Other than that, you can do what you like in that module, including having functions, classes or constants that are used by your views. If you have a lot of utility functions, you may want to consider extracting them into eg a lib.py in your app directory for the sake of tidiness. But there's no need to do that if you've just got one or two.
Break nested loop in Django views.py with a function
I have a nested loop that I would like to break out of. After searching this site it seems the best practice is to put the nested loop into a function and use return to break out of it. Is it acceptable to have functions inside the views.py file that are not a view? What is the best practice for the location of this function? Here's the example code from inside my views.py @login_required def save_bookmark(request): if request.method == 'POST': form = BookmarkSaveForm(request.POST) if form.is_valid(): bookmark_list = Bookmark.objects.all() for bookmark in bookmark_list: for link in bookmark.link_set.all(): if link.url == form.cleaned_data['url']: # Do something. break else: # Do something else. else: form = BookmarkSaveForm() return render_to_response('save_bookmark_form.html', {'form': form})
[ "Yes. it's fine to have functions in views.py that are not views - (I do this all the time). This is particularly appropriate if the function is only for use within that module (i.e. by views in that views.py), or by just a single view function.\nYou could always make it a private function if you're worried about exposing it to the outside world. Also, try avoid giving it a parameter called request, I tend to subconsciously parse functions which take a request as view functions when reading code.\n", "You shouldn't think of Django views as being in any way special. It's just Python. As such, you can have whatever functions you like in views.py. The only limitation is that views themselves have to take a request object and return a subclass of HttpResponse. Other than that, you can do what you like in that module, including having functions, classes or constants that are used by your views.\nIf you have a lot of utility functions, you may want to consider extracting them into eg a lib.py in your app directory for the sake of tidiness. But there's no need to do that if you've just got one or two.\n" ]
[ 2, 2 ]
[]
[]
[ "django", "django_views", "loops", "python" ]
stackoverflow_0002718890_django_django_views_loops_python.txt
Q: Posting messages in two RabbitMQ queue, instead of one (using py-amqp) I've got this strange problem using py-amqp and the Flopsy module. I have written a publisher that sends messages to a RabbitMQ server, and I wanted to be able to send it to a specified queue. On the Flopsy module that is not possible, so I tweaked it adding a parameter and a line to declare the queue on the _init__ method of the Publisher object def __init__(self, routing_key=DEFAULT_ROUTING_KEY, exchange=DEFAULT_EXCHANGE, connection=None, delivery_mode=DEFAULT_DELIVERY_MODE, queue=DEFAULT_QUEUE): self.connection = connection or Connection() self.channel = self.connection.connection.channel() self.channel.queue_declare(queue) # ADDED TO SET UP QUEUE self.exchange = exchange self.routing_key = routing_key self.delivery_mode = delivery_mode The channel object is part of the py-amqplib library The problem I've got it's that, even if it's sending the messages to the specified queue, it's ALSO sending the messages to the default queue. AS in this system we expect to send quite a lot of messages, we don't want to stress the system making useless duplicates... I've tried to debug the code and go inside the py-amqplib library, but I'm not able figure out any error or lacking step. Also, I'm not able to find any documentation form py-amqplib outside the code. Any ideas on why is this happening and how to correct it? A: OK, I've think I've got it. unless anybody else have a better idea. I've check this tutorial on AMQP I was assuming that the publisher should know the queue, but that's not the case, you need to send the message to a exchange, and the consumer will declare that the queue is related to the exchange. That allow different options on sending and receiving, as you can see on the tutorial. So, I've been including the exchange information on both the publisher and the consumer, not making use of the call to queue_declare and it appears to be working just fine.
Posting messages in two RabbitMQ queue, instead of one (using py-amqp)
I've got this strange problem using py-amqp and the Flopsy module. I have written a publisher that sends messages to a RabbitMQ server, and I wanted to be able to send it to a specified queue. On the Flopsy module that is not possible, so I tweaked it adding a parameter and a line to declare the queue on the _init__ method of the Publisher object def __init__(self, routing_key=DEFAULT_ROUTING_KEY, exchange=DEFAULT_EXCHANGE, connection=None, delivery_mode=DEFAULT_DELIVERY_MODE, queue=DEFAULT_QUEUE): self.connection = connection or Connection() self.channel = self.connection.connection.channel() self.channel.queue_declare(queue) # ADDED TO SET UP QUEUE self.exchange = exchange self.routing_key = routing_key self.delivery_mode = delivery_mode The channel object is part of the py-amqplib library The problem I've got it's that, even if it's sending the messages to the specified queue, it's ALSO sending the messages to the default queue. AS in this system we expect to send quite a lot of messages, we don't want to stress the system making useless duplicates... I've tried to debug the code and go inside the py-amqplib library, but I'm not able figure out any error or lacking step. Also, I'm not able to find any documentation form py-amqplib outside the code. Any ideas on why is this happening and how to correct it?
[ "OK, I've think I've got it. unless anybody else have a better idea. I've check this tutorial on AMQP I was assuming that the publisher should know the queue, but that's not the case, you need to send the message to a exchange, and the consumer will declare that the queue is related to the exchange. That allow different options on sending and receiving, as you can see on the tutorial.\nSo, I've been including the exchange information on both the publisher and the consumer, not making use of the call to queue_declare and it appears to be working just fine.\n" ]
[ 0 ]
[]
[]
[ "amqp", "flopsy", "py_amqplib", "python" ]
stackoverflow_0002719638_amqp_flopsy_py_amqplib_python.txt
Q: best framework on gae(python) ,like jquery on javascript ? has it? i want to find a framework to make my work simple on gae , has it ? thanks i found one, but not very good http://code.google.com/p/appengine-framework/ A: There are a large number of frameworks you can use on App Engine - both those custom designed for it, and those that are general purpose and work fine on App Engine. If you've used a Python framework in the past, some small amount of searching will tell you if it will work on App Engine with or without modifications. Common frameworks that do work on App Engine include Django, web2py and Pylons. There's a fairly comprehensive list or open source tools here.
best framework on gae(python) ,like jquery on javascript ? has it?
i want to find a framework to make my work simple on gae , has it ? thanks i found one, but not very good http://code.google.com/p/appengine-framework/
[ "There are a large number of frameworks you can use on App Engine - both those custom designed for it, and those that are general purpose and work fine on App Engine. If you've used a Python framework in the past, some small amount of searching will tell you if it will work on App Engine with or without modifications. Common frameworks that do work on App Engine include Django, web2py and Pylons.\nThere's a fairly comprehensive list or open source tools here.\n" ]
[ 1 ]
[]
[]
[ "frameworks", "google_app_engine", "python" ]
stackoverflow_0002719752_frameworks_google_app_engine_python.txt
Q: JQuery cookie access has stopped working for GAE app I have a google app engine app that has been running for some time, and some javascript code that checks for a login cookie has suddenly stopped working. As far as I can tell, NO code has changed. The relevant code uses the jquery cookies plugin (jquery.cookies.2.2.0.min.js)... // control the default screen depending // if someone is logged in if( $.cookies.get('dev_appserver_login') != null || $.cookies.get('ACSID') != null ) { alert("valid cookie!") $("#inventory-container").show(); } else { alert("INvalid cookie!") $("#welcome-container").show(); } The reason for the two checks is that in the GAE SDK, the cookies are named differently. The production system uses 'ACSID'. This if statement works in the SDK and now fails 100% of the time in production. I have verified that the cookie is, in fact, present when I inspect the page. Thoughts? A: Possibly the ACSID cookie is now being marked as 'secure', and hence unavailable to Javascript. Why the devil are you doing this in the first place, though?
JQuery cookie access has stopped working for GAE app
I have a google app engine app that has been running for some time, and some javascript code that checks for a login cookie has suddenly stopped working. As far as I can tell, NO code has changed. The relevant code uses the jquery cookies plugin (jquery.cookies.2.2.0.min.js)... // control the default screen depending // if someone is logged in if( $.cookies.get('dev_appserver_login') != null || $.cookies.get('ACSID') != null ) { alert("valid cookie!") $("#inventory-container").show(); } else { alert("INvalid cookie!") $("#welcome-container").show(); } The reason for the two checks is that in the GAE SDK, the cookies are named differently. The production system uses 'ACSID'. This if statement works in the SDK and now fails 100% of the time in production. I have verified that the cookie is, in fact, present when I inspect the page. Thoughts?
[ "Possibly the ACSID cookie is now being marked as 'secure', and hence unavailable to Javascript. Why the devil are you doing this in the first place, though?\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "javascript", "jquery", "python" ]
stackoverflow_0002716892_google_app_engine_javascript_jquery_python.txt
Q: multi-line pattern matching in python A periodic computer generated message (simplified): Hello user123, - (604)7080900 - 152 - minutes Regards Using python, how can I extract "(604)7080900", "152", "minutes" (i.e. any text following a leading "- " pattern) between the two empty lines (empty line is the \n\n after "Hello user123" and the \n\n before "Regards"). Even better if the result string list are stored in an array. Thanks! edit: the number of lines between two blank lines are not fixed. 2nd edit: e.g. hello - x1 - x2 - x3 - x4 - x6 morning - x7 world x1 x2 x3 are good, as all lines are surrounded by 2 empty lines, x4 is also good for the same reason. x6 is not good because no blank line follows it, x7 is not good as no blank in front of it. x2 is good (not like x6, x7) because the line ahead is a good line and the line following it is also good. this conditions might be not clear when I posted the question: a continuous of good lines between 2 empty lines good line must have leading "- " good line must follow an empty line or follow another good line good line must be followed by an empty line or followed by another good line thanks A: >>> import re >>> >>> x="""Hello user123, ... ... - (604)7080900 ... - 152 ... - minutes ... ... Regards ... """ >>> >>> re.findall("\n+\n-\s*(.*)\n-\s*(.*)\n-\s*(minutes)\s*\n\n+",x) [('(604)7080900', '152', 'minutes')] >>> A: The simplest approach is to go over these lines (assuming you have a list of lines, or a file, or split the string into a list of lines) until you see a line that's just '\n', then check that each line starts with '- ' (using the startswith string method) and slicing it off, storing the result, until you find another empty line. For example: # if you have a single string, split it into lines. L = s.splitlines() # if you (now) have a list of lines, grab an iterator so we can continue # iteration where it left off. it = iter(L) # Alternatively, if you have a file, just use that directly. it = open(....) # Find the first empty line: for line in it: # Treat lines of just whitespace as empty lines too. If you don't want # that, do 'if line == ""'. if not line.strip(): break # Now starts data. for line in it: if not line.rstrip(): # End of data. break if line.startswith('- '): data.append(line[:2].rstrip()) else: # misformed data? raise ValueError, "misformed line %r" % (line,) Edited: Since you elaborate on what you want to do, here's an updated version of the loops. It no longer loops twice, but instead collects data until it encounters a 'bad' line, and either saves or discards the collected lines when it encounters a block separator. It doesn't need an explicit iterator, because it doesn't restart iteration, so you can just pass it a list (or any iterable) of lines: def getblocks(L): # The list of good blocks (as lists of lines.) You can also make this # a flat list if you prefer. data = [] # The list of good lines encountered in the current block # (but the block may still become bad.) block = [] # Whether the current block is bad. bad = 1 for line in L: # Not in a 'good' block, and encountering the block separator. if bad and not line.rstrip(): bad = 0 block = [] continue # In a 'good' block and encountering the block separator. if not bad and not line.rstrip(): # Save 'good' data. Or, if you want a flat list of lines, # use 'extend' instead of 'append' (also below.) data.append(block) block = [] continue if not bad and line.startswith('- '): # A good line in a 'good' (not 'bad' yet) block; save the line, # minus # '- ' prefix and trailing whitespace. block.append(line[2:].rstrip()) continue else: # A 'bad' line, invalidating the current block. bad = 1 # Don't forget to handle the last block, if it's good # (and if you want to handle the last block.) if not bad and block: data.append(block) return data And here it is in action: >>> L = """hello ... ... - x1 ... - x2 ... - x3 ... ... - x4 ... ... - x6 ... morning ... - x7 ... ... world""".splitlines() >>> print getblocks(L) [['x1', 'x2', 'x3'], ['x4']] A: >>> s = """Hello user123, - (604)7080900 - 152 - minutes Regards """ >>> import re >>> re.findall(r'^- (.*)', s, re.M) ['(604)7080900', '152', 'minutes'] A: l = """Hello user123, - (604)7080900 - 152 - minutes Regards Hello user124, - (604)8576576 - 345 - minutes - seconds - bla Regards""" do this: result = [] for data in s.split('Regards'): result.append([v.strip() for v in data.split('-')[1:]]) del result[-1] # remove empty list at end and have this: >>> result [['(604)7080900', '152', 'minutes'], ['(604)8576576', '345', 'minutes', 'seconds', 'bla']]
multi-line pattern matching in python
A periodic computer generated message (simplified): Hello user123, - (604)7080900 - 152 - minutes Regards Using python, how can I extract "(604)7080900", "152", "minutes" (i.e. any text following a leading "- " pattern) between the two empty lines (empty line is the \n\n after "Hello user123" and the \n\n before "Regards"). Even better if the result string list are stored in an array. Thanks! edit: the number of lines between two blank lines are not fixed. 2nd edit: e.g. hello - x1 - x2 - x3 - x4 - x6 morning - x7 world x1 x2 x3 are good, as all lines are surrounded by 2 empty lines, x4 is also good for the same reason. x6 is not good because no blank line follows it, x7 is not good as no blank in front of it. x2 is good (not like x6, x7) because the line ahead is a good line and the line following it is also good. this conditions might be not clear when I posted the question: a continuous of good lines between 2 empty lines good line must have leading "- " good line must follow an empty line or follow another good line good line must be followed by an empty line or followed by another good line thanks
[ ">>> import re\n>>>\n>>> x=\"\"\"Hello user123,\n...\n... - (604)7080900\n... - 152\n... - minutes\n...\n... Regards\n... \"\"\"\n>>>\n>>> re.findall(\"\\n+\\n-\\s*(.*)\\n-\\s*(.*)\\n-\\s*(minutes)\\s*\\n\\n+\",x)\n[('(604)7080900', '152', 'minutes')]\n>>>\n\n", "The simplest approach is to go over these lines (assuming you have a list of lines, or a file, or split the string into a list of lines) until you see a line that's just '\\n', then check that each line starts with '- ' (using the startswith string method) and slicing it off, storing the result, until you find another empty line. For example:\n# if you have a single string, split it into lines.\nL = s.splitlines()\n# if you (now) have a list of lines, grab an iterator so we can continue\n# iteration where it left off.\nit = iter(L)\n# Alternatively, if you have a file, just use that directly.\nit = open(....)\n\n# Find the first empty line:\nfor line in it:\n # Treat lines of just whitespace as empty lines too. If you don't want\n # that, do 'if line == \"\"'.\n if not line.strip():\n break\n# Now starts data.\nfor line in it:\n if not line.rstrip():\n # End of data.\n break\n if line.startswith('- '):\n data.append(line[:2].rstrip())\n else:\n # misformed data?\n raise ValueError, \"misformed line %r\" % (line,)\n\nEdited: Since you elaborate on what you want to do, here's an updated version of the loops. It no longer loops twice, but instead collects data until it encounters a 'bad' line, and either saves or discards the collected lines when it encounters a block separator. It doesn't need an explicit iterator, because it doesn't restart iteration, so you can just pass it a list (or any iterable) of lines:\ndef getblocks(L):\n # The list of good blocks (as lists of lines.) You can also make this\n # a flat list if you prefer.\n data = []\n # The list of good lines encountered in the current block\n # (but the block may still become bad.)\n block = []\n # Whether the current block is bad.\n bad = 1\n for line in L:\n # Not in a 'good' block, and encountering the block separator.\n if bad and not line.rstrip():\n bad = 0\n block = []\n continue\n # In a 'good' block and encountering the block separator.\n if not bad and not line.rstrip():\n # Save 'good' data. Or, if you want a flat list of lines,\n # use 'extend' instead of 'append' (also below.)\n data.append(block)\n block = []\n continue\n if not bad and line.startswith('- '):\n # A good line in a 'good' (not 'bad' yet) block; save the line,\n # minus\n # '- ' prefix and trailing whitespace.\n block.append(line[2:].rstrip())\n continue\n else:\n # A 'bad' line, invalidating the current block.\n bad = 1\n # Don't forget to handle the last block, if it's good\n # (and if you want to handle the last block.)\n if not bad and block:\n data.append(block)\n return data\n\nAnd here it is in action:\n>>> L = \"\"\"hello\n...\n... - x1\n... - x2\n... - x3\n...\n... - x4\n...\n... - x6\n... morning\n... - x7\n...\n... world\"\"\".splitlines()\n>>> print getblocks(L)\n[['x1', 'x2', 'x3'], ['x4']]\n\n", ">>> s = \"\"\"Hello user123,\n\n- (604)7080900\n- 152\n- minutes\n\nRegards\n\"\"\"\n>>> import re\n>>> re.findall(r'^- (.*)', s, re.M)\n['(604)7080900', '152', 'minutes']\n\n", "l = \"\"\"Hello user123,\n\n- (604)7080900\n- 152\n- minutes\n\nRegards \n\nHello user124,\n\n- (604)8576576\n- 345\n- minutes\n- seconds\n- bla\n\nRegards\"\"\"\n\ndo this:\nresult = []\nfor data in s.split('Regards'): \n result.append([v.strip() for v in data.split('-')[1:]])\ndel result[-1] # remove empty list at end\n\nand have this:\n>>> result\n[['(604)7080900', '152', 'minutes'],\n['(604)8576576', '345', 'minutes', 'seconds', 'bla']]\n\n" ]
[ 4, 3, 1, 1 ]
[]
[]
[ "multiline", "python", "regex" ]
stackoverflow_0002720022_multiline_python_regex.txt
Q: Why are my two date fields not identical when I copy them? I use django, and have two models with a models.DateTimeField(). Sometimes I need a copy of a date - but look at this: >>>myobject.date = datetime.datetime.now() >>>print myobject.date >>>2010-04-27 12:10:43.526277 >>>other_object.date_copy = myobject.date >>>print other_object.date_copy >>>2010-04-27 12:10:43 Why are these two dates not identical, and how do I make an excact copy of myobject.date? Edit: I made the mistake of oversimplifying the code I used. The following code will replicate the weirdness: >>>myobject.date = datetime.datetime.now() >>>print myobject.date >>>2010-04-27 12:10:43.526277 >>>myobject.save() >>>myobject_retrieved_from_db = Myobject.objects.get(id=myobject.id) >>>other_object.date_copy = myobject_retrieved_from_db.date >>>print other_object.date_copy >>>2010-04-27 12:10:43 As Petriborg suggested, the difference in time is caused by storing to the database: >>>print myobject_retrieved_from_db.date >>>2010-04-27 12:10:43 Mystery solved. A: What version of python are you using? Seems to work for me... In [3]: s = datetime.datetime.now() In [4]: x = s In [5]: print s ------> print(s) 2010-04-27 06:37:02.303067 In [6]: print x ------> print(x) 2010-04-27 06:37:02.303067 Are you storing the datetime into a 3rd party structure like an sqldb via django? A time struct is usually of the form { int seconds; int fractional_seconds; } or as a long milliseconds, so it might be that the second part is getting dropped, either by structure, or by down casting...
Why are my two date fields not identical when I copy them?
I use django, and have two models with a models.DateTimeField(). Sometimes I need a copy of a date - but look at this: >>>myobject.date = datetime.datetime.now() >>>print myobject.date >>>2010-04-27 12:10:43.526277 >>>other_object.date_copy = myobject.date >>>print other_object.date_copy >>>2010-04-27 12:10:43 Why are these two dates not identical, and how do I make an excact copy of myobject.date? Edit: I made the mistake of oversimplifying the code I used. The following code will replicate the weirdness: >>>myobject.date = datetime.datetime.now() >>>print myobject.date >>>2010-04-27 12:10:43.526277 >>>myobject.save() >>>myobject_retrieved_from_db = Myobject.objects.get(id=myobject.id) >>>other_object.date_copy = myobject_retrieved_from_db.date >>>print other_object.date_copy >>>2010-04-27 12:10:43 As Petriborg suggested, the difference in time is caused by storing to the database: >>>print myobject_retrieved_from_db.date >>>2010-04-27 12:10:43 Mystery solved.
[ "What version of python are you using?\nSeems to work for me...\nIn [3]: s = datetime.datetime.now()\nIn [4]: x = s\nIn [5]: print s\n------> print(s)\n2010-04-27 06:37:02.303067\nIn [6]: print x\n------> print(x)\n2010-04-27 06:37:02.303067\n\nAre you storing the datetime into a 3rd party structure like an sqldb via django? A time struct is usually of the form { int seconds; int fractional_seconds; } or as a long milliseconds, so it might be that the second part is getting dropped, either by structure, or by down casting...\n" ]
[ 3 ]
[]
[]
[ "datetime", "django", "python" ]
stackoverflow_0002720414_datetime_django_python.txt
Q: Simple check authentication decorator in Python + Pylons I'd like to write a simple decorator that I can put above functions in my controller to check authentication and re-direct to the login page if the current user is not authenticated. What is the best way to do this? Where should the decorator go? How should I pass cookie info to the decorator? Sample code is greatly appreciated. Thank you! A: Another approach for authorization in pylons (decorator based, repoze.what like) How should I pass cookie info to the decorator? Use a global request object and get cookie or use wsgi environ of the request
Simple check authentication decorator in Python + Pylons
I'd like to write a simple decorator that I can put above functions in my controller to check authentication and re-direct to the login page if the current user is not authenticated. What is the best way to do this? Where should the decorator go? How should I pass cookie info to the decorator? Sample code is greatly appreciated. Thank you!
[ "Another approach for authorization in pylons (decorator based, repoze.what like)\n\nHow should I pass cookie info to the\n decorator?\n\nUse a global request object and get cookie or use wsgi environ of the request\n" ]
[ 2 ]
[]
[]
[ "decorator", "pylons", "python" ]
stackoverflow_0002718716_decorator_pylons_python.txt
Q: making binned boxplot in matplotlib with numpy and scipy in Python I have a 2-d array containing pairs of values and I'd like to make a boxplot of the y-values by different bins of the x-values. I.e. if the array is: my_array = array([[1, 40.5], [4.5, 60], ...]]) then I'd like to bin my_array[:, 0] and then for each of the bins, produce a boxplot of the corresponding my_array[:, 1] values that fall into each box. So in the end I want the plot to contain number of bins-many box plots. I tried the following: min_x = min(my_array[:, 0]) max_x = max(my_array[:, 1]) num_bins = 3 bins = linspace(min_x, max_x, num_bins) elts_to_bins = digitize(my_array[:, 0], bins) However, this gives me values in elts_to_bins that range from 1 to 3. I thought I should get 0-based indices for the bins, and I only wanted 3 bins. I'm assuming this is due to some trickyness with how bins are represented in linspace vs. digitize. What is the easiest way to achieve this? I want num_bins-many equally spaced bins, with the first bin containing the lower half of the data and the upper bin containing the upper half... i.e., I want each data point to fall into some bin, so that I can make a boxplot. thanks. A: You're getting the 3rd bin for the maximum value in the array (I'm assuming you have a typo there, and max_x should be "max(my_array[:,0])" instead of "max(my_array[:,1])"). You can avoid this by adding 1 (or any positive number) to the last bin. Also, if I'm understanding you correctly, you want to bin one variable by another, so my example below shows that. If you're using recarrays (which are much slower) there are also several functions in matplotlib.mlab (e.g. mlab.rec_groupby, etc) that do this sort of thing. Anyway, in the end, you might have something like this (to bin x by the values in y, assuming x and y are the same length) def bin_by(x, y, nbins=30): """ Bin x by y. Returns the binned "x" values and the left edges of the bins """ bins = np.linspace(y.min(), y.max(), nbins+1) # To avoid extra bin for the max value bins[-1] += 1 indicies = np.digitize(y, bins) output = [] for i in xrange(1, len(bins)): output.append(x[indicies==i]) # Just return the left edges of the bins bins = bins[:-1] return output, bins As a quick example: In [3]: x = np.random.random((100, 2)) In [4]: binned_values, bins = bin_by(x[:,0], x[:,1], 2) In [5]: binned_values Out[5]: [array([ 0.59649575, 0.07082605, 0.7191498 , 0.4026375 , 0.06611863, 0.01473529, 0.45487203, 0.39942696, 0.02342408, 0.04669615, 0.58294003, 0.59510434, 0.76255006, 0.76685052, 0.26108928, 0.7640156 , 0.01771553, 0.38212975, 0.74417014, 0.38217517, 0.73909022, 0.21068663, 0.9103707 , 0.83556636, 0.34277006, 0.38007865, 0.18697416, 0.64370535, 0.68292336, 0.26142583, 0.50457354, 0.63071319, 0.87525221, 0.86509534, 0.96382375, 0.57556343, 0.55860405, 0.36392931, 0.93638048, 0.66889756, 0.46140831, 0.01675165, 0.15401495, 0.10813141, 0.03876953, 0.65967335, 0.86803192, 0.94835281, 0.44950182]), array([ 0.9249993 , 0.02682873, 0.89439141, 0.26415792, 0.42771144, 0.12292614, 0.44790357, 0.64692616, 0.14871052, 0.55611472, 0.72340179, 0.55335053, 0.07967047, 0.95725514, 0.49737279, 0.99213794, 0.7604765 , 0.56719713, 0.77828727, 0.77046566, 0.15060196, 0.39199123, 0.78904624, 0.59974575, 0.6965413 , 0.52664095, 0.28629324, 0.21838664, 0.47305751, 0.3544522 , 0.57704906, 0.1023201 , 0.76861237, 0.88862359, 0.29310836, 0.22079126, 0.84966201, 0.9376939 , 0.95449215, 0.10856864, 0.86655289, 0.57835533, 0.32831162, 0.1673871 , 0.55742108, 0.02436965, 0.45261232, 0.31552715, 0.56666458, 0.24757898, 0.8674747 ])] Hope that helps a bit! A: Numpy has a dedicated function for creating histograms the way you need to: histogram(a, bins=10, range=None, normed=False, weights=None, new=None) which you can use like: (hist_data, bin_edges) = histogram(my_array[:,0], weights=my_array[:,1]) The key point here is to use the weights argument: each value a[i] will contribute weights[i] to the histogram. Example: a = [0, 1] weights = [10, 2] describes 10 points at x = 0 and 2 points at x = 1. You can set the number of bins, or the bin limits, with the bins argument (see the official documentation for more details). The histogram can then be plotted with something like: bar(bin_edges[:-1], hist_data) If you only need to do a histogram plot, the similar hist() function can directly plot the histogram: hist(my_array[:,0], weights=my_array[:,1])
making binned boxplot in matplotlib with numpy and scipy in Python
I have a 2-d array containing pairs of values and I'd like to make a boxplot of the y-values by different bins of the x-values. I.e. if the array is: my_array = array([[1, 40.5], [4.5, 60], ...]]) then I'd like to bin my_array[:, 0] and then for each of the bins, produce a boxplot of the corresponding my_array[:, 1] values that fall into each box. So in the end I want the plot to contain number of bins-many box plots. I tried the following: min_x = min(my_array[:, 0]) max_x = max(my_array[:, 1]) num_bins = 3 bins = linspace(min_x, max_x, num_bins) elts_to_bins = digitize(my_array[:, 0], bins) However, this gives me values in elts_to_bins that range from 1 to 3. I thought I should get 0-based indices for the bins, and I only wanted 3 bins. I'm assuming this is due to some trickyness with how bins are represented in linspace vs. digitize. What is the easiest way to achieve this? I want num_bins-many equally spaced bins, with the first bin containing the lower half of the data and the upper bin containing the upper half... i.e., I want each data point to fall into some bin, so that I can make a boxplot. thanks.
[ "You're getting the 3rd bin for the maximum value in the array (I'm assuming you have a typo there, and max_x should be \"max(my_array[:,0])\" instead of \"max(my_array[:,1])\"). You can avoid this by adding 1 (or any positive number) to the last bin.\nAlso, if I'm understanding you correctly, you want to bin one variable by another, so my example below shows that. If you're using recarrays (which are much slower) there are also several functions in matplotlib.mlab (e.g. mlab.rec_groupby, etc) that do this sort of thing. \nAnyway, in the end, you might have something like this (to bin x by the values in y, assuming x and y are the same length)\ndef bin_by(x, y, nbins=30):\n \"\"\"\n Bin x by y.\n Returns the binned \"x\" values and the left edges of the bins\n \"\"\"\n bins = np.linspace(y.min(), y.max(), nbins+1)\n # To avoid extra bin for the max value\n bins[-1] += 1 \n\n indicies = np.digitize(y, bins)\n\n output = []\n for i in xrange(1, len(bins)):\n output.append(x[indicies==i])\n\n # Just return the left edges of the bins\n bins = bins[:-1]\n\n return output, bins\n\nAs a quick example:\nIn [3]: x = np.random.random((100, 2))\n\nIn [4]: binned_values, bins = bin_by(x[:,0], x[:,1], 2)\n\nIn [5]: binned_values\nOut[5]: \n[array([ 0.59649575, 0.07082605, 0.7191498 , 0.4026375 , 0.06611863,\n 0.01473529, 0.45487203, 0.39942696, 0.02342408, 0.04669615,\n 0.58294003, 0.59510434, 0.76255006, 0.76685052, 0.26108928,\n 0.7640156 , 0.01771553, 0.38212975, 0.74417014, 0.38217517,\n 0.73909022, 0.21068663, 0.9103707 , 0.83556636, 0.34277006,\n 0.38007865, 0.18697416, 0.64370535, 0.68292336, 0.26142583,\n 0.50457354, 0.63071319, 0.87525221, 0.86509534, 0.96382375,\n 0.57556343, 0.55860405, 0.36392931, 0.93638048, 0.66889756,\n 0.46140831, 0.01675165, 0.15401495, 0.10813141, 0.03876953,\n 0.65967335, 0.86803192, 0.94835281, 0.44950182]),\n array([ 0.9249993 , 0.02682873, 0.89439141, 0.26415792, 0.42771144,\n 0.12292614, 0.44790357, 0.64692616, 0.14871052, 0.55611472,\n 0.72340179, 0.55335053, 0.07967047, 0.95725514, 0.49737279,\n 0.99213794, 0.7604765 , 0.56719713, 0.77828727, 0.77046566,\n 0.15060196, 0.39199123, 0.78904624, 0.59974575, 0.6965413 ,\n 0.52664095, 0.28629324, 0.21838664, 0.47305751, 0.3544522 ,\n 0.57704906, 0.1023201 , 0.76861237, 0.88862359, 0.29310836,\n 0.22079126, 0.84966201, 0.9376939 , 0.95449215, 0.10856864,\n 0.86655289, 0.57835533, 0.32831162, 0.1673871 , 0.55742108,\n 0.02436965, 0.45261232, 0.31552715, 0.56666458, 0.24757898,\n 0.8674747 ])]\n\nHope that helps a bit!\n", "Numpy has a dedicated function for creating histograms the way you need to:\nhistogram(a, bins=10, range=None, normed=False, weights=None, new=None)\n\nwhich you can use like:\n(hist_data, bin_edges) = histogram(my_array[:,0], weights=my_array[:,1])\n\nThe key point here is to use the weights argument: each value a[i] will contribute weights[i] to the histogram. Example:\na = [0, 1]\nweights = [10, 2]\n\ndescribes 10 points at x = 0 and 2 points at x = 1.\nYou can set the number of bins, or the bin limits, with the bins argument (see the official documentation for more details).\nThe histogram can then be plotted with something like:\nbar(bin_edges[:-1], hist_data)\n\nIf you only need to do a histogram plot, the similar hist() function can directly plot the histogram:\nhist(my_array[:,0], weights=my_array[:,1])\n\n" ]
[ 7, 4 ]
[]
[]
[ "matplotlib", "numpy", "plot", "python", "scipy" ]
stackoverflow_0002716894_matplotlib_numpy_plot_python_scipy.txt
Q: QPluginLoader with PyQt modules as plugins: possible? I have a C++ application that loads externals plugins thanks to QPluginloader. QPluginLoader provides access to a Qt plugin. A Qt plugin is stored in a shared library (a DLL). The plugins have to inherit from a pure virtual class ( and Q_DECLARE_INTERFACE ) and QObject. I would like to create plugins by using python and PyQt. Is this possible without too much work? For instance if I have to convert the modules to C++ with boost::python, this could be nonsense, as PyQt is already a conversion from C++ to Python... Thanks! Edit: I have looked into the doc of pyqt regarding plugins: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#writing-qt-designer-plugins PyQT has a specific class QPyDesignerCustomWidgetPlugin for qt designer plugins. But this class is in the QtDesigner.pyd module, so I can not see the code in order to replicate the same architecture. Edit2: http://www.boddie.org.uk/david/Projects/Python/Qt/ File pyqt4-embedded-examples-2008-02-13.tar.gz Contains code sample to integrate PyQt Widget in C++. But you don't use QPluginLoader and have to integrate the python interpretor headers in your C++ main code. Thanks again A: Well, I don't think it's possible without too much work. If you write a module in PyQt, chances are that you would have to add the entire Python interpreter to your executable in order to be able to interpret those modules. Even if you translate those modules into C++, the translated functions will have to call the Python API at some point, thus introducing a dependency on Python itself.
QPluginLoader with PyQt modules as plugins: possible?
I have a C++ application that loads externals plugins thanks to QPluginloader. QPluginLoader provides access to a Qt plugin. A Qt plugin is stored in a shared library (a DLL). The plugins have to inherit from a pure virtual class ( and Q_DECLARE_INTERFACE ) and QObject. I would like to create plugins by using python and PyQt. Is this possible without too much work? For instance if I have to convert the modules to C++ with boost::python, this could be nonsense, as PyQt is already a conversion from C++ to Python... Thanks! Edit: I have looked into the doc of pyqt regarding plugins: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#writing-qt-designer-plugins PyQT has a specific class QPyDesignerCustomWidgetPlugin for qt designer plugins. But this class is in the QtDesigner.pyd module, so I can not see the code in order to replicate the same architecture. Edit2: http://www.boddie.org.uk/david/Projects/Python/Qt/ File pyqt4-embedded-examples-2008-02-13.tar.gz Contains code sample to integrate PyQt Widget in C++. But you don't use QPluginLoader and have to integrate the python interpretor headers in your C++ main code. Thanks again
[ "Well, I don't think it's possible without too much work. If you write a module in PyQt, chances are that you would have to add the entire Python interpreter to your executable in order to be able to interpret those modules. Even if you translate those modules into C++, the translated functions will have to call the Python API at some point, thus introducing a dependency on Python itself.\n" ]
[ 2 ]
[]
[]
[ "c++", "plugins", "pyqt", "python", "qt" ]
stackoverflow_0002691724_c++_plugins_pyqt_python_qt.txt
Q: Python: Traffic-Simulation (cars on a road) I want to create a traffic simulator like here: http://www.doobybrain.com/wp-content/uploads/2008/03/traffic-simulation.gif But I didn't thougt very deep about this. I would create the class car. Every car has his own color, position and so on. And I could create the road with an array. But how to tell the car where to go? Could I hear your ideas? EDIT: Is it forbidden to get new ideas from good programmers? Why do some people want to close this thread? Or were to ask such questions? I dont understand them. :( EDIT2: Next time I will go to a gamer-forum. I like the ideas until now. Thanks! A: You don't tell a car where to go. It goes anyway due to its velocity. By looking ahead (where will it be a few timesteps from now, and is there still a road?) you can see whether you need to adjust the velocity. And a road isn't an array; it's a matrix or bitmap. You can't go all that fast in the corner or you'll fly from the road. It's always a good idea to clearly formulate the goals and scope first. In this case, you would be thinking about the extent of the modeling (the physics involved) and the complexity of the car movements (collisions, following bend roads, and so on). I find that if you can state your concept clearly in plain English (or Dutch in my case), writing the code becomes much easier, almost trivial sometimes. EDIT For clarity, when I'm talking about velocity I'm talking about a vector, which has both magnitude (10MPH) and direction. Your vectors would have 2 elements, x and y, unless you also want airplanes, or want to model hills and such (you don't want hills 'cause you'd also have to take gravity into account:) where a z position and velocity are used. A: Each car has a position, speed, direction/trajectory/destination. Based in this information and, relative position of the other cars and (eventually) the presence of "road signs", you can calculate the next position of each car and if the car will be slowing down or accelerating. When you add a new car to the simulation, just set its initial position, speed and destination. A: You'll also need to consider collision detection, not necessarily collisions between cars themselves but you'll need a way of telling the agents (the AI) when it's appropriate to brake when in the vicinity of of other vehicles. You could do this with bounding spheres around each car. A: I encourage you to use my own project for this. It's called GarlicSim, it's a platform for making simulations, and it will work great for the kind of simulation you have in mind. (Incidentally, just yesterday I made a big release, version 0.4). It's all Python, and it'll give you a nice GUI too. If you'll be serious about it, I could help you write your simpack. If you want to do it, send a mail on the mailing list. A: The theory behind the simulator is Queing Theory. I found a page on a course on my alma mater that will show you some keywords, that can help you - https://www.erasmus.cvut.cz/prospectus/FTS/11THO-E.html. Simulator itself will be "easier". A: There is a Java-based package called processing that is targetted at artists and non- or beginner-programmers that includes some very nice visualization features, while presenting a simplified development environment (no "public static void main(String[] args)", for instance). Look at the demos that show particle systems to get an idea on how to model your individual cars. There is a Python rendition of this code call pyprocessing that follows much of the same simple programming idiom. Here is my little "tesla" applet - move the mouse between the two spherical electrodes. A: First question: What is the scope of the simulation? You can do it as much as simple as a one dimensional cellular automata in discrete time or as complex as a full fledged physical system (you can model even the chemical reactions in the engine!) with a sophisticated AI and advanced photorealistic graphics and sound effects. In between, there are lots of possibilities. Think about what you can do and what you want to learn.
Python: Traffic-Simulation (cars on a road)
I want to create a traffic simulator like here: http://www.doobybrain.com/wp-content/uploads/2008/03/traffic-simulation.gif But I didn't thougt very deep about this. I would create the class car. Every car has his own color, position and so on. And I could create the road with an array. But how to tell the car where to go? Could I hear your ideas? EDIT: Is it forbidden to get new ideas from good programmers? Why do some people want to close this thread? Or were to ask such questions? I dont understand them. :( EDIT2: Next time I will go to a gamer-forum. I like the ideas until now. Thanks!
[ "You don't tell a car where to go. It goes anyway due to its velocity. By looking ahead (where will it be a few timesteps from now, and is there still a road?) you can see whether you need to adjust the velocity.\nAnd a road isn't an array; it's a matrix or bitmap. You can't go all that fast in the corner or you'll fly from the road.\nIt's always a good idea to clearly formulate the goals and scope first. In this case, you would be thinking about the extent of the modeling (the physics involved) and the complexity of the car movements (collisions, following bend roads, and so on).\nI find that if you can state your concept clearly in plain English (or Dutch in my case), writing the code becomes much easier, almost trivial sometimes.\nEDIT\nFor clarity, when I'm talking about velocity I'm talking about a vector, which has both magnitude (10MPH) and direction. Your vectors would have 2 elements, x and y, unless you also want airplanes, or want to model hills and such (you don't want hills 'cause you'd also have to take gravity into account:) where a z position and velocity are used.\n", "Each car has a position, speed, direction/trajectory/destination. Based in this information and, relative position of the other cars and (eventually) the presence of \"road signs\", you can calculate the next position of each car and if the car will be slowing down or accelerating. \nWhen you add a new car to the simulation, just set its initial position, speed and destination.\n", "You'll also need to consider collision detection, not necessarily collisions between cars themselves but you'll need a way of telling the agents (the AI) when it's appropriate to brake when in the vicinity of of other vehicles. You could do this with bounding spheres around each car. \n", "I encourage you to use my own project for this. It's called GarlicSim, it's a platform for making simulations, and it will work great for the kind of simulation you have in mind. (Incidentally, just yesterday I made a big release, version 0.4).\nIt's all Python, and it'll give you a nice GUI too.\nIf you'll be serious about it, I could help you write your simpack. If you want to do it, send a mail on the mailing list.\n", "The theory behind the simulator is Queing Theory. I found a page on a course on my alma mater that will show you some keywords, that can help you - https://www.erasmus.cvut.cz/prospectus/FTS/11THO-E.html. \nSimulator itself will be \"easier\".\n", "There is a Java-based package called processing that is targetted at artists and non- or beginner-programmers that includes some very nice visualization features, while presenting a simplified development environment (no \"public static void main(String[] args)\", for instance). Look at the demos that show particle systems to get an idea on how to model your individual cars. There is a Python rendition of this code call pyprocessing that follows much of the same simple programming idiom.\nHere is my little \"tesla\" applet - move the mouse between the two spherical electrodes.\n", "First question: What is the scope of the simulation?\nYou can do it as much as simple as a one dimensional cellular automata in discrete time or as complex as a full fledged physical system (you can model even the chemical reactions in the engine!) with a sophisticated AI and advanced photorealistic graphics and sound effects.\nIn between, there are lots of possibilities. Think about what you can do and what you want to learn.\n" ]
[ 5, 2, 2, 2, 2, 1, 0 ]
[]
[]
[ "python", "simulation", "traffic" ]
stackoverflow_0002720378_python_simulation_traffic.txt
Q: Django ModelFormSet with Google app engine I'm using Django with google app engine. I'm using the google furnished django app engine helper project. I'm attempting to create a Django modelformset like this: #MyModel inherits from BaseModel MyFormSet = modelformset_factory(models.MyModel) However, it's failing with this error: 'ModelOptions' object has no attribute 'fields' Apparently modelformset_factory() is expecting MyModel to implement a 'fields' accessor. Anybody successfully used a modelformset with GAE datastore? Or is this a fundamental incompatibility between Django and GAE? A: It is a fundamental incompatibility between Django and GAE, because they do not share the same interface for their models. The django helper does not include a patch for the modelformsets, but django-nonrel probably does, or will eventually. Since the google team does not spend much time on the django helper any more, you are probably better off looking at django-nonrel http://www.allbuttonspressed.com/projects/django-nonrel unless you want to patch the helper yourself.
Django ModelFormSet with Google app engine
I'm using Django with google app engine. I'm using the google furnished django app engine helper project. I'm attempting to create a Django modelformset like this: #MyModel inherits from BaseModel MyFormSet = modelformset_factory(models.MyModel) However, it's failing with this error: 'ModelOptions' object has no attribute 'fields' Apparently modelformset_factory() is expecting MyModel to implement a 'fields' accessor. Anybody successfully used a modelformset with GAE datastore? Or is this a fundamental incompatibility between Django and GAE?
[ "It is a fundamental incompatibility between Django and GAE, because they do not share the same interface for their models. The django helper does not include a patch for the modelformsets, but django-nonrel probably does, or will eventually.\nSince the google team does not spend much time on the django helper any more, you are probably better off looking at django-nonrel http://www.allbuttonspressed.com/projects/django-nonrel unless you want to patch the helper yourself.\n" ]
[ 0 ]
[]
[]
[ "django", "django_forms", "google_app_engine", "python" ]
stackoverflow_0002526394_django_django_forms_google_app_engine_python.txt
Q: How to create Python module distribution to gracefully fall-back to pure Python code I have written a Python module, and I have two versions: a pure Python implementation and a C extension. I've written the __init__.py file so that it tries to import the C extension, and if that fails, it imports the pure Python code (is that reasonable?). Now, I'd like to know what is the best way to distribute this module (e.g. write setup.py) so it can be easily used by people with or without the facility to build, or use, the C extension, just by running: python setup.py install My experience is limited, but I see two possible cases: User does not have MS Visual Studio, or the GCC compiler suite, installed on their machine, to build the C extension User is running IronPython, Jython, or anything other than CPython. I only have used CPython. So I'm not sure how I could distribute this module so that it would work smoothly and be easy to install on those platforms, if they're unable to use the C extension. A: (is that reasonable?). Yep, perfectly sensible. To catch the "no suitable C compiler case": the call to setup(...) will do a sys.exit in case of problems. So, first try it with the ext_modules argument set as desired, within a try: try: setup(..., ext_modules=...) except SystemExit: ... and in the except clause, call setup(...) again without the ext_modules (so it gives up on building and installing the extensions). The user who's installing will still see messages like "unable to execute gcc-4.0: No such file or directory", but you can appropriately add your own messages to inform the user that it's no big deal and that you're trying again without the extension modules. To support non-CPython implementations, in your setup.py you can test sys.version (I'm not sure what the value will be for each non-CPython implementation, but IronPython has an 'IronPython' substring there, for example), to avoid even trying the ext_modules part. If you miss some such implementation in your checks, the try/except should probably catch most others anyway, just with a modest amount of wasted work;-). A: "tries to import the C extension, and if that fails, it imports the pure Python code (is that reasonable?)." Almost. Read about cStringIO and StringIO. Also read about cPickle and Pickle. Also read about cElementTree and ElementTree. If the C version can't be built, that's one use case. The pure Python version is the only one available. If the C version can be built, however, I still have good reasons for declining it. Primary, I would consider declining the C version because it may not allow the depth of subclass that I require for my application. I don't want to be forced to use the C version, just because I happened to have the correct compiler. I prefer to make those decisions on my own. Consequently, I don't like the idea of some part of your module making my architecture decisions for me. I prefer to choose which to import. If the C version doesn't exist, that doesn't change my decision process, because I may still be creating subclasses of the pure Python version. Bottom line. Automate less. Provide the two modules. I prefer to choose which one to import. A: According to the documentation for Planar, you can make the setup.py file for building the C extensions as normal, and then: To build and install Planar from the source distribution or repository use: python setup.py install To install only the pure-Python modules without compiling, use: python setup.py build_py install --skip-build
How to create Python module distribution to gracefully fall-back to pure Python code
I have written a Python module, and I have two versions: a pure Python implementation and a C extension. I've written the __init__.py file so that it tries to import the C extension, and if that fails, it imports the pure Python code (is that reasonable?). Now, I'd like to know what is the best way to distribute this module (e.g. write setup.py) so it can be easily used by people with or without the facility to build, or use, the C extension, just by running: python setup.py install My experience is limited, but I see two possible cases: User does not have MS Visual Studio, or the GCC compiler suite, installed on their machine, to build the C extension User is running IronPython, Jython, or anything other than CPython. I only have used CPython. So I'm not sure how I could distribute this module so that it would work smoothly and be easy to install on those platforms, if they're unable to use the C extension.
[ "\n(is that reasonable?).\n\nYep, perfectly sensible.\nTo catch the \"no suitable C compiler case\": the call to setup(...) will do a sys.exit in case of problems. So, first try it with the ext_modules argument set as desired, within a try:\ntry:\n setup(..., ext_modules=...)\nexcept SystemExit: ...\n\nand in the except clause, call setup(...) again without the ext_modules (so it gives up on building and installing the extensions). The user who's installing will still see messages like \"unable to execute gcc-4.0: No such file or directory\", but you can appropriately add your own messages to inform the user that it's no big deal and that you're trying again without the extension modules.\nTo support non-CPython implementations, in your setup.py you can test sys.version (I'm not sure what the value will be for each non-CPython implementation, but IronPython has an 'IronPython' substring there, for example), to avoid even trying the ext_modules part. If you miss some such implementation in your checks, the try/except should probably catch most others anyway, just with a modest amount of wasted work;-).\n", "\"tries to import the C extension, and if that fails, it imports the pure Python code (is that reasonable?).\"\nAlmost. Read about cStringIO and StringIO. Also read about cPickle and Pickle. Also read about cElementTree and ElementTree.\nIf the C version can't be built, that's one use case. The pure Python version is the only one available. \nIf the C version can be built, however, I still have good reasons for declining it. Primary, I would consider declining the C version because it may not allow the depth of subclass that I require for my application.\nI don't want to be forced to use the C version, just because I happened to have the correct compiler. I prefer to make those decisions on my own. \nConsequently, I don't like the idea of some part of your module making my architecture decisions for me. I prefer to choose which to import. If the C version doesn't exist, that doesn't change my decision process, because I may still be creating subclasses of the pure Python version.\nBottom line. Automate less. Provide the two modules. I prefer to choose which one to import. \n", "According to the documentation for Planar, you can make the setup.py file for building the C extensions as normal, and then:\n\nTo build and install Planar from the source distribution or repository use:\n\npython setup.py install\n\n\nTo install only the pure-Python modules without compiling, use:\n\npython setup.py build_py install --skip-build\n\n" ]
[ 7, 0, 0 ]
[]
[]
[ "python", "software_distribution" ]
stackoverflow_0002398699_python_software_distribution.txt
Q: How does large text file viewer work? How to build a large text reader how does large text file viewer work? I'm assuming that: Threading is used to handle the file The TextBox is updated line by line Effective memory handling is used Are these assumptions correct? if someone were to develop their own, what are the mustsand don'ts? I'm looking to implement one using a DataGrid instead of a TextBox I'm comfortable with C++ and python. I'll probably use QT/PyQT EDIT The files, I have are usually between 1.5 to 2 GB. I'm looking at editing and viewing these files A: I believe that the trick is not loading the entire file into memory, but using seek and such to just load the part which is viewed (possibly with a block before and after to handle a bit of scrolling). Perhaps even using memory-mapped buffers, though I have no experience with those. Do realize that modifying a large file (fast) is different from just viewing it. You might need to copy the gigabytes of data surrounding the edit to a new file, which may be slow. A: In Kernighan and Plaugher's classic (antique?) book "Software Tools in Pascal" they cover the development and design choices of a version of ed(1) and note "A warning: edit is a big program (excluding contributions from translit, find, and change; at 950 lines, it is fifty percent bigger than anything else in this book." And they (literally) didn't even have string types to use. Since they note that the file to be edited may exist on tape which doesn't support arbitrary writes in the middle, they had to keep an index of line positions in memory and work with a scratch file to store changes, deletions and additions, merging the whole together upon a "save" command. They, like you, were concerned about memory constraining the size of their editable file. The general structure of this approach is preserved in the GNU ed project, particularly in buffer.c
How does large text file viewer work? How to build a large text reader
how does large text file viewer work? I'm assuming that: Threading is used to handle the file The TextBox is updated line by line Effective memory handling is used Are these assumptions correct? if someone were to develop their own, what are the mustsand don'ts? I'm looking to implement one using a DataGrid instead of a TextBox I'm comfortable with C++ and python. I'll probably use QT/PyQT EDIT The files, I have are usually between 1.5 to 2 GB. I'm looking at editing and viewing these files
[ "I believe that the trick is not loading the entire file into memory, but using seek and such to just load the part which is viewed (possibly with a block before and after to handle a bit of scrolling). Perhaps even using memory-mapped buffers, though I have no experience with those.\nDo realize that modifying a large file (fast) is different from just viewing it. You might need to copy the gigabytes of data surrounding the edit to a new file, which may be slow.\n", "In Kernighan and Plaugher's classic (antique?) book \"Software Tools in Pascal\" they cover the development and design choices of a version of ed(1) and note \n\n\"A warning: edit is a big\n program (excluding contributions from\n translit, find, and change; at\n 950 lines, it is fifty percent bigger\n than anything else in this book.\"\n\nAnd they (literally) didn't even have string types to use. Since they note that the file to be edited may exist on tape which doesn't support arbitrary writes in the middle, they had to keep an index of line positions in memory and work with a scratch file to store changes, deletions and additions, merging the whole together upon a \"save\" command. They, like you, were concerned about memory constraining the size of their editable file.\nThe general structure of this approach is preserved in the GNU ed project, particularly in buffer.c\n" ]
[ 6, 4 ]
[]
[]
[ "c++", "multithreading", "pyqt", "python", "qt" ]
stackoverflow_0002720752_c++_multithreading_pyqt_python_qt.txt
Q: Using PyLab to create a 2D graph from two separate lists This seems like a basic problem with an easy answer but I simply cannot figure it out no matter how much I try. I am trying to create a line graph based on two lists. For my x-axis, I want my list to be a set of strings. x_axis_list = ["Jan-06","Jul-06","Jan-07","Jul-07","Jan-08"] y_axis_list = [5,7,6,8,9] Any suggestions on how to best graph these items? A: from pylab import * from matplotlib.font_manager import FontProperties dates = ["Jan-06","Jul-06","Jan-07","Jul-07","Jan-08"] x_axis_list = range(len(dates)) y_axis_list = [5,7,6,8,9] figure() plot(x_axis_list, y_axis_list, "k") xticks(x_axis_list, dates, rotation=45) show()
Using PyLab to create a 2D graph from two separate lists
This seems like a basic problem with an easy answer but I simply cannot figure it out no matter how much I try. I am trying to create a line graph based on two lists. For my x-axis, I want my list to be a set of strings. x_axis_list = ["Jan-06","Jul-06","Jan-07","Jul-07","Jan-08"] y_axis_list = [5,7,6,8,9] Any suggestions on how to best graph these items?
[ "from pylab import *\nfrom matplotlib.font_manager import FontProperties\n\ndates = [\"Jan-06\",\"Jul-06\",\"Jan-07\",\"Jul-07\",\"Jan-08\"]\nx_axis_list = range(len(dates))\ny_axis_list = [5,7,6,8,9]\n\nfigure()\nplot(x_axis_list, y_axis_list, \"k\")\nxticks(x_axis_list, dates, rotation=45)\nshow()\n\n" ]
[ 5 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0002722216_matplotlib_python.txt
Q: optimize pymssql code i am inserting records to sql server from python using pymssql. The database takes 2 milliseconds to execute a query, yet it insert 6 rows per second. The only problem is at code side. how to optimize following code or what is the fastest method to insert records. def save(self): conn = pymssql.connect(host=dbHost, user=dbUser, password=dbPassword, database=dbName, as_dict=True) cur = conn.cursor() self.pageURL = self.pageURL.replace("'","''") query = "my query is there" cur.execute(query) conn.commit() conn.close() A: It looks like you're creating a new connection per insert there. That's probably the major reason for the slowdown: building new connections is typically quite slow. Create the connection outside the method and you should see a large improvement. You can also create a cursor outside function and re-use it, which will be another speedup. Depending on your situation, you may also want to use the same transaction for more than a single insertion. This changes the behaviour a little -- since a transaction is supposed to be atomic and either completely succeeds or completely fails -- but committing a transaction is typically a slow operation, because it has to be certain the whole operation succeeded. A: In addition to Thomas' great advice, I'd suggest you look into executemany()*, e.g.: cur.executemany("INSERT INTO persons VALUES(%d, %s)", [ (1, 'John Doe'), (2, 'Jane Doe') ]) ...where the second argument of executemany() should be a sequence of rows to insert. This brings up another point: You probably want to send your query and query parameters as separate arguments to either execute() or executemany(). This will allow the PyMSSQL module to handle any quoting issues for you. *executemany() as described in the Python DB-API: .executemany(operation,seq_of_parameters) Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters.
optimize pymssql code
i am inserting records to sql server from python using pymssql. The database takes 2 milliseconds to execute a query, yet it insert 6 rows per second. The only problem is at code side. how to optimize following code or what is the fastest method to insert records. def save(self): conn = pymssql.connect(host=dbHost, user=dbUser, password=dbPassword, database=dbName, as_dict=True) cur = conn.cursor() self.pageURL = self.pageURL.replace("'","''") query = "my query is there" cur.execute(query) conn.commit() conn.close()
[ "It looks like you're creating a new connection per insert there. That's probably the major reason for the slowdown: building new connections is typically quite slow. Create the connection outside the method and you should see a large improvement. You can also create a cursor outside function and re-use it, which will be another speedup.\nDepending on your situation, you may also want to use the same transaction for more than a single insertion. This changes the behaviour a little -- since a transaction is supposed to be atomic and either completely succeeds or completely fails -- but committing a transaction is typically a slow operation, because it has to be certain the whole operation succeeded.\n", "In addition to Thomas' great advice,\nI'd suggest you look into executemany()*, e.g.:\ncur.executemany(\"INSERT INTO persons VALUES(%d, %s)\", \n [ (1, 'John Doe'), (2, 'Jane Doe') ])\n\n...where the second argument of executemany() should be a sequence of rows to insert.\nThis brings up another point:\nYou probably want to send your query and query parameters as separate arguments to either execute() or executemany(). This will allow the PyMSSQL module to handle any quoting issues for you.\n*executemany() as described in the Python DB-API:\n\n.executemany(operation,seq_of_parameters)\n Prepare a database operation (query or\n command) and then execute it against\n all parameter sequences or mappings\n found in the sequence\n seq_of_parameters.\n\n" ]
[ 4, 3 ]
[]
[]
[ "optimization", "pymssql", "python" ]
stackoverflow_0002721063_optimization_pymssql_python.txt
Q: Various way to send data to the web server Client Environment : Windows XP , Internet connection Available, PHP Not installed. Server Environment : CentOS , Internet connection Available, PHP , MYsql installed. Data are stored in files at client machine , suggest better ways to send data fetched from the file to the server. Normally i would be using HTTP request using Curl to send the data to the server but client machine doesnt have php installed. What all are the ways to send data to the server and the comparisons? Note: In client machine the data are to be taken from the file and to be sent in background as a daemon. A: Unless you want to install some sort of software on the client machine to make the data available to the server, there is really no other simple way that I can think of other than writing a web app to upload the files (which may not be practical, and certainly requires manual labor). Otherwise, you could setup an sFTP server (or something that accomplishes the same thing) on the client machine, and use PHP to connect to the sFTP service on the client machine.
Various way to send data to the web server
Client Environment : Windows XP , Internet connection Available, PHP Not installed. Server Environment : CentOS , Internet connection Available, PHP , MYsql installed. Data are stored in files at client machine , suggest better ways to send data fetched from the file to the server. Normally i would be using HTTP request using Curl to send the data to the server but client machine doesnt have php installed. What all are the ways to send data to the server and the comparisons? Note: In client machine the data are to be taken from the file and to be sent in background as a daemon.
[ "Unless you want to install some sort of software on the client machine to make the data available to the server, there is really no other simple way that I can think of other than writing a web app to upload the files (which may not be practical, and certainly requires manual labor).\nOtherwise, you could setup an sFTP server (or something that accomplishes the same thing) on the client machine, and use PHP to connect to the sFTP service on the client machine.\n" ]
[ 0 ]
[]
[]
[ "http", "php", "python", "web_services" ]
stackoverflow_0002718932_http_php_python_web_services.txt
Q: One letter game Issue? Recently at a job interview I was given the following problem: Write a script capable of running on the command line as python It should take in two words on the command line (or optionally if you'd prefer it can query the user to supply the two words via the console). Given those two words: a. Ensure they are of equal length b. Ensure they are both words present in the dictionary of valid words in the English language that you downloaded. If so compute whether you can reach the second word from the first by a series of steps as follows a. You can change one letter at a time b. Each time you change a letter the resulting word must also exist in the dictionary c. You cannot add or remove letters If the two words are reachable, the script should print out the path which leads as a single, shortest path from one word to the other. You can /usr/share/dict/words for your dictionary of words. My solution consisted of using breadth first search to find a shortest path between two words. But apparently that wasn't good enough to get the job :( Would you guys know what I could have done wrong? Thank you so much. import collections import functools import re def time_func(func): import time def wrapper(*args, **kwargs): start = time.time() res = func(*args, **kwargs) timed = time.time() - start setattr(wrapper, 'time_taken', timed) return res functools.update_wrapper(wrapper, func) return wrapper class OneLetterGame: def __init__(self, dict_path): self.dict_path = dict_path self.words = set() def run(self, start_word, end_word): '''Runs the one letter game with the given start and end words. ''' assert len(start_word) == len(end_word), \ 'Start word and end word must of the same length.' self.read_dict(len(start_word)) path = self.shortest_path(start_word, end_word) if not path: print 'There is no path between %s and %s (took %.2f sec.)' % ( start_word, end_word, find_shortest_path.time_taken) else: print 'The shortest path (found in %.2f sec.) is:\n=> %s' % ( self.shortest_path.time_taken, ' -- '.join(path)) def _bfs(self, start): '''Implementation of breadth first search as a generator. The portion of the graph to explore is given on demand using get_neighboors. Care was taken so that a vertex / node is explored only once. ''' queue = collections.deque([(None, start)]) inqueue = set([start]) while queue: parent, node = queue.popleft() yield parent, node new = set(self.get_neighbours(node)) - inqueue inqueue = inqueue | new queue.extend([(node, child) for child in new]) @time_func def shortest_path(self, start, end): '''Returns the shortest path from start to end using bfs. ''' assert start in self.words, 'Start word not in dictionnary.' assert end in self.words, 'End word not in dictionnary.' paths = {None: []} for parent, child in self._bfs(start): paths[child] = paths[parent] + [child] if child == end: return paths[child] return None def get_neighbours(self, word): '''Gets every word one letter away from the a given word. We do not keep these words in memory because bfs accesses a given vertex only once. ''' neighbours = [] p_word = ['^' + word[0:i] + '\w' + word[i+1:] + '$' for i, w in enumerate(word)] p_word = '|'.join(p_word) for w in self.words: if w != word and re.match(p_word, w, re.I|re.U): neighbours += [w] return neighbours def read_dict(self, size): '''Loads every word of a specific size from the dictionnary into memory. ''' for l in open(self.dict_path): l = l.decode('latin-1').strip().lower() if len(l) == size: self.words.add(l) if __name__ == '__main__': import sys if len(sys.argv) not in [3, 4]: print 'Usage: python one_letter_game.py start_word end_word' else: g = OneLetterGame(dict_path = '/usr/share/dict/words') try: g.run(*sys.argv[1:]) except AssertionError, e: print e Thank you for all the great answers. I think what really got me is the fact that I do iterate over ALL words in the dictionary each time to consider possible word neighbors. Instead I could have used an inverted index as pointed by Duncan and Matt Anderson. A* approach would definitely have helped too. Thanks a lot, now I know what I have done wrong. Here is the same code with inverted index: import collections import functools import re def time_func(func): import time def wrapper(*args, **kwargs): start = time.time() res = func(*args, **kwargs) timed = time.time() - start setattr(wrapper, 'time_taken', timed) return res functools.update_wrapper(wrapper, func) return wrapper class OneLetterGame: def __init__(self, dict_path): self.dict_path = dict_path self.words = {} def run(self, start_word, end_word): '''Runs the one letter game with the given start and end words. ''' assert len(start_word) == len(end_word), \ 'Start word and end word must of the same length.' self.read_dict(len(start_word)) path = self.shortest_path(start_word, end_word) if not path: print 'There is no path between %s and %s (took %.2f sec.)' % ( start_word, end_word, self.shortest_path.time_taken) else: print 'The shortest path (found in %.2f sec.) is:\n=> %s' % ( self.shortest_path.time_taken, ' -- '.join(path)) def _bfs(self, start): '''Implementation of breadth first search as a generator. The portion of the graph to explore is given on demand using get_neighboors. Care was taken so that a vertex / node is explored only once. ''' queue = collections.deque([(None, start)]) inqueue = set([start]) while queue: parent, node = queue.popleft() yield parent, node new = set(self.get_neighbours(node)) - inqueue inqueue = inqueue | new queue.extend([(node, child) for child in new]) @time_func def shortest_path(self, start, end): '''Returns the shortest path from start to end using bfs. ''' assert self.in_dictionnary(start), 'Start word not in dictionnary.' assert self.in_dictionnary(end), 'End word not in dictionnary.' paths = {None: []} for parent, child in self._bfs(start): paths[child] = paths[parent] + [child] if child == end: return paths[child] return None def in_dictionnary(self, word): for s in self.get_steps(word): if s in self.words: return True return False def get_neighbours(self, word): '''Gets every word one letter away from the a given word. ''' for step in self.get_steps(word): for neighbour in self.words[step]: yield neighbour def get_steps(self, word): return (word[0:i] + '*' + word[i+1:] for i, w in enumerate(word)) def read_dict(self, size): '''Loads every word of a specific size from the dictionnary into an inverted index. ''' for w in open(self.dict_path): w = w.decode('latin-1').strip().lower() if len(w) != size: continue for step in self.get_steps(w): if step not in self.words: self.words[step] = [] self.words[step].append(w) if __name__ == '__main__': import sys if len(sys.argv) not in [3, 4]: print 'Usage: python one_letter_game.py start_word end_word' else: g = OneLetterGame(dict_path = '/usr/share/dict/words') try: g.run(*sys.argv[1:]) except AssertionError, e: print e And a timing comparison: % python one_letter_game_old.py happy hello The shortest path (found in 91.57 sec.) is: => happy -- harpy -- harps -- harts -- halts -- halls -- hells -- hello % python one_letter_game.py happy hello The shortest path (found in 1.71 sec.) is: => happy -- harpy -- harps -- harts -- halts -- halls -- hells -- hello A: I wouldn't say your solution is wrong, but it is a little slow. For two reasons. Breadth-first-search is going to visit all paths of length one shorter than is needed, plus some-to-all of paths of length needed, before it can give you an answer. A best-first-search (A*) will ideally skip most irrelevant paths. You're checking every word in the dictionary for candidacy as a neighbor each time you look for neighbors. As Duncan suggests, you can build a data structure to essentially look up the neighbors instead of searching for them. Here is another solution to your problem: import collections import heapq import time def distance(start, end): steps = 0 for pos in range(len(start)): if start[pos] != end[pos]: steps += 1 return steps class SearchHeap(object): def __init__(self): self.on_heap = set() self.heap = [] def push(self, distance, word, path): if word in self.on_heap: return self.on_heap.add(word) heapq.heappush(self.heap, ((distance, len(path)), word, path)) def __len__(self): return len(self.heap) def pop(self): return heapq.heappop(self.heap) class OneLetterGame(object): _word_data = None def __init__(self, dict_path): self.dict_path = dict_path def run(self, start_word, end_word): start_time = time.time() self._word_data = collections.defaultdict(list) if len(start_word) != len(end_word): print 'words of different length; no path' return found_start, found_end = self._load_words(start_word, end_word) if not found_start: print 'start word %r not found in dictionary' % start_word return if not found_end: print 'end word %r not found in dictionary' % end_word return search_start_time = time.time() path = self._shortest_path(start_word, end_word) search_time = time.time() - search_start_time print 'search time was %.4f seconds' % search_time if path: print path else: print 'no path found from %r to %r' % (start_word, end_word) run_time = time.time() - start_time print 'total run time was %.4f seconds' % run_time def _load_words(self, start_word, end_word): found_start, found_end = False, False length = len(start_word) with open(self.dict_path) as words: for word in words: word = word.strip() if len(word) == length: if start_word == word: found_start = True if end_word == word: found_end = True for bucket in self._buckets_for(word): self._word_data[bucket].append(word) return found_start, found_end def _shortest_path(self, start_word, end_word): heap = SearchHeap() heap.push(distance(start_word, end_word), start_word, (start_word,)) while len(heap): dist, word, path = heap.pop() if word == end_word: return path for neighbor in self._neighbors_of(word): heap.push( distance(neighbor, end_word), neighbor, path + (neighbor,)) return () def _buckets_for(self, word): buckets = [] for pos in range(len(word)): front, back = word[:pos], word[pos+1:] buckets.append(front+'*'+back) return buckets def _neighbors_of(self, word): for bucket in self._buckets_for(word): for word in self._word_data[bucket]: yield word if __name__ == '__main__': import sys if len(sys.argv) not in [3, 4]: print 'Usage: python one_letter_game.py start_word end_word' else: matt = OneLetterGame(dict_path = '/usr/share/dict/words') matt.run(*sys.argv[1:]) And, a timing comparison: % python /tmp/one_letter_alex.py canoe happy The shortest path (found in 51.98 sec.) is: => canoe -- canon -- caxon -- taxon -- taxor -- taxer -- taper -- paper -- papey -- pappy -- happy % python /tmp/one_letter_matt.py canoe happy search time was 0.0020 seconds ('canoe', 'canon', 'caxon', 'taxon', 'taxor', 'taxer', 'taper', 'paper', 'papey', 'pappy', 'happy') total run time was 0.2416 seconds A: I agree that it would be odd to expect your answer to this programming test to be the sole reason why they chose someone else, but there are actually problems with your code. You do a linear search through the dictionary for every step of the path, or every potential path. That could take a long time for a large dictionary and lots of potential paths. Also it is pretty obvious you didn't test it thoroughly as it fails when there is no path. If I were coding this I'd create a dictionary when loading the words that would remove the linear search by letting you pick out the next words pretty well directly. This code isn't the complete solution but should indicate what I mean: words = {} def get_keys(word): """Generate keys from a word by replacing each letter in turn by an asterisk""" for i in range(len(word)): yield word[:i]+'*'+word[i+1:] def get_steps(word): """Find the set of all words that can link to the given word.""" steps = [] for key in get_keys(word): steps.extend(words[key]) steps = set(steps) - set([word]) return steps # Load the dictionary for word in ('start', 'stare', 'spare', 'spore'): for key in get_keys(word): if key not in words: words[key] = [] words[key].append(word) print(words) print(get_steps('stare')) A: Maybe they expected the A* search with the edit distance as the estimate? A: Maybe you did not want to work at a jerk company like that to begin with. I personally do not believe in code reviews. I think if you do a good enough job with checking out the portfolio and past references that there is no need for such at the spot code tests. Companies with stringent policies like these are the ones that never make it eventually as all they employ is one track code nerds that are thinking code 24/7. Just my 2 cents. A: Maybe you forgot to add the shebang? >-| Or maybe they just didn't like your coding style... For example, I wouldn't have made a class for such a simple problem, it's over-engineering the solution (although I'm not that picky to base the hiring decision only on that, of course).
One letter game Issue?
Recently at a job interview I was given the following problem: Write a script capable of running on the command line as python It should take in two words on the command line (or optionally if you'd prefer it can query the user to supply the two words via the console). Given those two words: a. Ensure they are of equal length b. Ensure they are both words present in the dictionary of valid words in the English language that you downloaded. If so compute whether you can reach the second word from the first by a series of steps as follows a. You can change one letter at a time b. Each time you change a letter the resulting word must also exist in the dictionary c. You cannot add or remove letters If the two words are reachable, the script should print out the path which leads as a single, shortest path from one word to the other. You can /usr/share/dict/words for your dictionary of words. My solution consisted of using breadth first search to find a shortest path between two words. But apparently that wasn't good enough to get the job :( Would you guys know what I could have done wrong? Thank you so much. import collections import functools import re def time_func(func): import time def wrapper(*args, **kwargs): start = time.time() res = func(*args, **kwargs) timed = time.time() - start setattr(wrapper, 'time_taken', timed) return res functools.update_wrapper(wrapper, func) return wrapper class OneLetterGame: def __init__(self, dict_path): self.dict_path = dict_path self.words = set() def run(self, start_word, end_word): '''Runs the one letter game with the given start and end words. ''' assert len(start_word) == len(end_word), \ 'Start word and end word must of the same length.' self.read_dict(len(start_word)) path = self.shortest_path(start_word, end_word) if not path: print 'There is no path between %s and %s (took %.2f sec.)' % ( start_word, end_word, find_shortest_path.time_taken) else: print 'The shortest path (found in %.2f sec.) is:\n=> %s' % ( self.shortest_path.time_taken, ' -- '.join(path)) def _bfs(self, start): '''Implementation of breadth first search as a generator. The portion of the graph to explore is given on demand using get_neighboors. Care was taken so that a vertex / node is explored only once. ''' queue = collections.deque([(None, start)]) inqueue = set([start]) while queue: parent, node = queue.popleft() yield parent, node new = set(self.get_neighbours(node)) - inqueue inqueue = inqueue | new queue.extend([(node, child) for child in new]) @time_func def shortest_path(self, start, end): '''Returns the shortest path from start to end using bfs. ''' assert start in self.words, 'Start word not in dictionnary.' assert end in self.words, 'End word not in dictionnary.' paths = {None: []} for parent, child in self._bfs(start): paths[child] = paths[parent] + [child] if child == end: return paths[child] return None def get_neighbours(self, word): '''Gets every word one letter away from the a given word. We do not keep these words in memory because bfs accesses a given vertex only once. ''' neighbours = [] p_word = ['^' + word[0:i] + '\w' + word[i+1:] + '$' for i, w in enumerate(word)] p_word = '|'.join(p_word) for w in self.words: if w != word and re.match(p_word, w, re.I|re.U): neighbours += [w] return neighbours def read_dict(self, size): '''Loads every word of a specific size from the dictionnary into memory. ''' for l in open(self.dict_path): l = l.decode('latin-1').strip().lower() if len(l) == size: self.words.add(l) if __name__ == '__main__': import sys if len(sys.argv) not in [3, 4]: print 'Usage: python one_letter_game.py start_word end_word' else: g = OneLetterGame(dict_path = '/usr/share/dict/words') try: g.run(*sys.argv[1:]) except AssertionError, e: print e Thank you for all the great answers. I think what really got me is the fact that I do iterate over ALL words in the dictionary each time to consider possible word neighbors. Instead I could have used an inverted index as pointed by Duncan and Matt Anderson. A* approach would definitely have helped too. Thanks a lot, now I know what I have done wrong. Here is the same code with inverted index: import collections import functools import re def time_func(func): import time def wrapper(*args, **kwargs): start = time.time() res = func(*args, **kwargs) timed = time.time() - start setattr(wrapper, 'time_taken', timed) return res functools.update_wrapper(wrapper, func) return wrapper class OneLetterGame: def __init__(self, dict_path): self.dict_path = dict_path self.words = {} def run(self, start_word, end_word): '''Runs the one letter game with the given start and end words. ''' assert len(start_word) == len(end_word), \ 'Start word and end word must of the same length.' self.read_dict(len(start_word)) path = self.shortest_path(start_word, end_word) if not path: print 'There is no path between %s and %s (took %.2f sec.)' % ( start_word, end_word, self.shortest_path.time_taken) else: print 'The shortest path (found in %.2f sec.) is:\n=> %s' % ( self.shortest_path.time_taken, ' -- '.join(path)) def _bfs(self, start): '''Implementation of breadth first search as a generator. The portion of the graph to explore is given on demand using get_neighboors. Care was taken so that a vertex / node is explored only once. ''' queue = collections.deque([(None, start)]) inqueue = set([start]) while queue: parent, node = queue.popleft() yield parent, node new = set(self.get_neighbours(node)) - inqueue inqueue = inqueue | new queue.extend([(node, child) for child in new]) @time_func def shortest_path(self, start, end): '''Returns the shortest path from start to end using bfs. ''' assert self.in_dictionnary(start), 'Start word not in dictionnary.' assert self.in_dictionnary(end), 'End word not in dictionnary.' paths = {None: []} for parent, child in self._bfs(start): paths[child] = paths[parent] + [child] if child == end: return paths[child] return None def in_dictionnary(self, word): for s in self.get_steps(word): if s in self.words: return True return False def get_neighbours(self, word): '''Gets every word one letter away from the a given word. ''' for step in self.get_steps(word): for neighbour in self.words[step]: yield neighbour def get_steps(self, word): return (word[0:i] + '*' + word[i+1:] for i, w in enumerate(word)) def read_dict(self, size): '''Loads every word of a specific size from the dictionnary into an inverted index. ''' for w in open(self.dict_path): w = w.decode('latin-1').strip().lower() if len(w) != size: continue for step in self.get_steps(w): if step not in self.words: self.words[step] = [] self.words[step].append(w) if __name__ == '__main__': import sys if len(sys.argv) not in [3, 4]: print 'Usage: python one_letter_game.py start_word end_word' else: g = OneLetterGame(dict_path = '/usr/share/dict/words') try: g.run(*sys.argv[1:]) except AssertionError, e: print e And a timing comparison: % python one_letter_game_old.py happy hello The shortest path (found in 91.57 sec.) is: => happy -- harpy -- harps -- harts -- halts -- halls -- hells -- hello % python one_letter_game.py happy hello The shortest path (found in 1.71 sec.) is: => happy -- harpy -- harps -- harts -- halts -- halls -- hells -- hello
[ "I wouldn't say your solution is wrong, but it is a little slow. For two reasons. \n\nBreadth-first-search is going to visit all paths of length one shorter than is needed, plus some-to-all of paths of length needed, before it can give you an answer. A best-first-search (A*) will ideally skip most irrelevant paths.\nYou're checking every word in the dictionary for candidacy as a neighbor each time you look for neighbors. As Duncan suggests, you can build a data structure to essentially look up the neighbors instead of searching for them.\n\nHere is another solution to your problem:\nimport collections\nimport heapq\nimport time\n\ndef distance(start, end):\n steps = 0\n for pos in range(len(start)):\n if start[pos] != end[pos]:\n steps += 1\n return steps\n\n\nclass SearchHeap(object):\n def __init__(self):\n self.on_heap = set()\n self.heap = []\n\n def push(self, distance, word, path):\n if word in self.on_heap:\n return\n self.on_heap.add(word)\n heapq.heappush(self.heap, ((distance, len(path)), word, path))\n\n def __len__(self):\n return len(self.heap)\n\n def pop(self):\n return heapq.heappop(self.heap)\n\n\nclass OneLetterGame(object):\n _word_data = None\n\n def __init__(self, dict_path):\n self.dict_path = dict_path\n\n def run(self, start_word, end_word):\n start_time = time.time()\n self._word_data = collections.defaultdict(list)\n if len(start_word) != len(end_word):\n print 'words of different length; no path'\n return\n\n found_start, found_end = self._load_words(start_word, end_word)\n if not found_start:\n print 'start word %r not found in dictionary' % start_word\n return\n if not found_end:\n print 'end word %r not found in dictionary' % end_word\n return\n\n search_start_time = time.time()\n path = self._shortest_path(start_word, end_word)\n search_time = time.time() - search_start_time\n print 'search time was %.4f seconds' % search_time\n\n if path:\n print path\n else:\n print 'no path found from %r to %r' % (start_word, end_word)\n\n run_time = time.time() - start_time\n print 'total run time was %.4f seconds' % run_time\n\n def _load_words(self, start_word, end_word):\n found_start, found_end = False, False\n length = len(start_word)\n with open(self.dict_path) as words:\n for word in words:\n word = word.strip()\n if len(word) == length:\n if start_word == word: found_start = True\n if end_word == word: found_end = True\n for bucket in self._buckets_for(word):\n self._word_data[bucket].append(word)\n return found_start, found_end\n\n def _shortest_path(self, start_word, end_word):\n heap = SearchHeap()\n heap.push(distance(start_word, end_word), start_word, (start_word,))\n while len(heap):\n dist, word, path = heap.pop()\n if word == end_word:\n return path\n for neighbor in self._neighbors_of(word):\n heap.push(\n distance(neighbor, end_word), \n neighbor, \n path + (neighbor,))\n return ()\n\n def _buckets_for(self, word):\n buckets = []\n for pos in range(len(word)):\n front, back = word[:pos], word[pos+1:]\n buckets.append(front+'*'+back)\n return buckets\n\n def _neighbors_of(self, word):\n for bucket in self._buckets_for(word):\n for word in self._word_data[bucket]:\n yield word\n\nif __name__ == '__main__':\n import sys\n if len(sys.argv) not in [3, 4]:\n print 'Usage: python one_letter_game.py start_word end_word'\n else:\n matt = OneLetterGame(dict_path = '/usr/share/dict/words')\n matt.run(*sys.argv[1:])\n\nAnd, a timing comparison:\n% python /tmp/one_letter_alex.py canoe happy\nThe shortest path (found in 51.98 sec.) is:\n=> canoe -- canon -- caxon -- taxon -- taxor -- taxer -- taper -- paper -- papey -- pappy -- happy\n\n% python /tmp/one_letter_matt.py canoe happy\nsearch time was 0.0020 seconds\n('canoe', 'canon', 'caxon', 'taxon', 'taxor', 'taxer', 'taper', 'paper', 'papey', 'pappy', 'happy')\ntotal run time was 0.2416 seconds\n\n", "I agree that it would be odd to expect your answer to this programming test to be the sole reason why they chose someone else, but there are actually problems with your code. You do a linear search through the dictionary for every step of the path, or every potential path. That could take a long time for a large dictionary and lots of potential paths. Also it is pretty obvious you didn't test it thoroughly as it fails when there is no path.\nIf I were coding this I'd create a dictionary when loading the words that would remove the linear search by letting you pick out the next words pretty well directly. This code isn't the complete solution but should indicate what I mean:\nwords = {}\n\ndef get_keys(word):\n \"\"\"Generate keys from a word by replacing each letter in turn by an asterisk\"\"\"\n for i in range(len(word)):\n yield word[:i]+'*'+word[i+1:]\n\ndef get_steps(word):\n \"\"\"Find the set of all words that can link to the given word.\"\"\"\n steps = []\n for key in get_keys(word):\n steps.extend(words[key])\n steps = set(steps) - set([word])\n return steps\n\n# Load the dictionary\nfor word in ('start', 'stare', 'spare', 'spore'):\n for key in get_keys(word):\n if key not in words:\n words[key] = []\n words[key].append(word)\n\nprint(words)\nprint(get_steps('stare'))\n\n", "Maybe they expected the A* search with the edit distance as the estimate?\n", "Maybe you did not want to work at a jerk company like that to begin with. I personally do not believe in code reviews. I think if you do a good enough job with checking out the portfolio and past references that there is no need for such at the spot code tests. Companies with stringent policies like these are the ones that never make it eventually as all they employ is one track code nerds that are thinking code 24/7. Just my 2 cents. \n", "Maybe you forgot to add the shebang? >-|\nOr maybe they just didn't like your coding style... For example, I wouldn't have made a class for such a simple problem, it's over-engineering the solution (although I'm not that picky to base the hiring decision only on that, of course).\n" ]
[ 10, 3, 1, 1, 0 ]
[]
[]
[ "letter", "optimization", "python" ]
stackoverflow_0002721514_letter_optimization_python.txt
Q: Use Twisted's getPage as urlopen? I would like to use Twisted non-blocking getPage method within a webapp, but it feels quite complicated to use such function compared to urlopen. This is an example of what I'm trying to achive: def web_request(request): response = urllib.urlopen('http://www.example.org') return HttpResponse(len(response.read())) Is it so hard to have something similar with getPage? A: The thing to realize about non-blocking operations (which you seem to explicitly want) is that you can't really write sequential code with them. The operations don't block because they don't wait for a result. They start the operation and return control to your function. So, getPage doesn't return a file-like object you can read from like urllib.urlopen does. And even if it did, you couldn't read from it until the data was available (or it would block.) And so you can't call len() on it, since that needs to read all the data first (which would block.) The way to deal with non-blocking operations in Twisted is through Deferreds, which are objects for managing callbacks. getPage returns a Deferred, which means "you will get this result later". You can't do anything with the result until you get it, so you add callbacks to the Deferred, and the Deferred will call these callbacks when the result is available. That callback can then do what you want it to: def web_request(request) def callback(data): HttpResponse(len(data)) d = getPage("http://www.example.org") d.addCallback(callback) return d An additional problem with your example is that your web_request function itself is blocking. What do you want to do while you wait for the result of getPage to become available? Do something else within web_request, or just wait? Or do you want to turn web_request itself non-blocking? If so, how do you want to produce the result? (The obvious choice in Twisted is to return another Deferred -- or even the same one as getPage returns, as in the example above. This may not always be appropriate if you're writing code in another framework, though.) There is a way to write sequential code using Deferreds, although it's somewhat restrictive, harder to debug, and core Twisted people cry when you use it: twisted.internet.defer.inlineCallbacks. It uses the new generator feature in Python 2.5 where you can send data into a generator, and the code would look somewhat like this: @defer.inlineCallbacks def web_request(request) data = yield getPage("http://www.example.org") HttpResponse(len(data)) Like the example that explicitly returned the d Deferred, this'll only work if the caller expects web_request to be non-blocking -- the defer.inlineCallbacks decorator turns the generator into a function that returns a Deferred. A: I posted a response to a similar question recently that provides the minimal amount of code required to get the contents from a URL using getPage. Here it is for completeness: from twisted.web.client import getPage from twisted.internet import reactor url = 'http://aol.com' def print_and_stop(output): print output if reactor.running: reactor.stop() if __name__ == '__main__': print 'fetching', url d = getPage(url) d.addCallback(print_and_stop) reactor.run() Keep in mind that you'll probably need a more in-depth understanding of the reactor pattern used by Twisted to handle events (getPage firing being an event in this instance).
Use Twisted's getPage as urlopen?
I would like to use Twisted non-blocking getPage method within a webapp, but it feels quite complicated to use such function compared to urlopen. This is an example of what I'm trying to achive: def web_request(request): response = urllib.urlopen('http://www.example.org') return HttpResponse(len(response.read())) Is it so hard to have something similar with getPage?
[ "The thing to realize about non-blocking operations (which you seem to explicitly want) is that you can't really write sequential code with them. The operations don't block because they don't wait for a result. They start the operation and return control to your function. So, getPage doesn't return a file-like object you can read from like urllib.urlopen does. And even if it did, you couldn't read from it until the data was available (or it would block.) And so you can't call len() on it, since that needs to read all the data first (which would block.)\nThe way to deal with non-blocking operations in Twisted is through Deferreds, which are objects for managing callbacks. getPage returns a Deferred, which means \"you will get this result later\". You can't do anything with the result until you get it, so you add callbacks to the Deferred, and the Deferred will call these callbacks when the result is available. That callback can then do what you want it to:\ndef web_request(request)\n def callback(data):\n HttpResponse(len(data))\n d = getPage(\"http://www.example.org\")\n d.addCallback(callback)\n return d\n\nAn additional problem with your example is that your web_request function itself is blocking. What do you want to do while you wait for the result of getPage to become available? Do something else within web_request, or just wait? Or do you want to turn web_request itself non-blocking? If so, how do you want to produce the result? (The obvious choice in Twisted is to return another Deferred -- or even the same one as getPage returns, as in the example above. This may not always be appropriate if you're writing code in another framework, though.)\nThere is a way to write sequential code using Deferreds, although it's somewhat restrictive, harder to debug, and core Twisted people cry when you use it: twisted.internet.defer.inlineCallbacks. It uses the new generator feature in Python 2.5 where you can send data into a generator, and the code would look somewhat like this:\n@defer.inlineCallbacks\ndef web_request(request)\n data = yield getPage(\"http://www.example.org\")\n HttpResponse(len(data))\n\nLike the example that explicitly returned the d Deferred, this'll only work if the caller expects web_request to be non-blocking -- the defer.inlineCallbacks decorator turns the generator into a function that returns a Deferred.\n", "I posted a response to a similar question recently that provides the minimal amount of code required to get the contents from a URL using getPage. Here it is for completeness:\nfrom twisted.web.client import getPage\nfrom twisted.internet import reactor\n\nurl = 'http://aol.com'\n\ndef print_and_stop(output):\n print output\n if reactor.running:\n reactor.stop()\n\nif __name__ == '__main__':\n print 'fetching', url\n d = getPage(url)\n d.addCallback(print_and_stop)\n reactor.run()\n\nKeep in mind that you'll probably need a more in-depth understanding of the reactor pattern used by Twisted to handle events (getPage firing being an event in this instance).\n" ]
[ 20, 4 ]
[]
[]
[ "django", "python", "twisted", "urllib", "urllib2" ]
stackoverflow_0002720484_django_python_twisted_urllib_urllib2.txt
Q: writing a fast parser in python I've written a hands-on recursive pure python parser for a some file format (ARFF) we use in one lecture. Now running my exercise submission is awfully slow. Turns out by far the most time is spent in my parser. It's consuming a lot of CPU time, the HD is not the bottleneck. I wonder what performant ways are there to write a parser in python? I'd rather not rewrite it in C. I tried to use jython, but that decreased performance a lot! The files I parse are partially huge (> 150 MB) with very long lines. My current parser only needs a look-ahead of one character. I'd post the source here but I don't know if that's such a good idea. After all the submission deadline has not ended yet. But then, the focus in this exercise is not the parser. You can choose whatever language you want to use and there already is a parser for Java. Note: I've a x86_64 system so psyco (and it seems also PyPy) is no option. Update: I now uploaded my parser/writer to bitbucket. A: You could use ANTLR or pyparsing, they might speed up your parsing process. And if you want to keep your current code, you might want to look at Cython/PyPy, which increases your perfomance (sometimes upto 4x). A: The most general tip I'd give without further information would be to read the entire file, or at least a substantial section of it, into memory at once. You don't want to be reading it one character at a time and seeking here and there; regardless of the buffering that's going on under the hood it's probably a good idea just to have the whole thing in memory so you can operate on it however you want. I have written parsers in Python and there's no particular requirement for them to be particularly slower than a parser written in any other language. As it is with these sorts of things, it's more likely that you're doing work you don't need to do. Of those class of item, creating and destroying and recreating the same object is more costly than just storing it off somewhere. Recomputing a value over and over again is more costly than just storing it somewhere. Etc., etc. In Python specifically, one trap that people fall into is doing a lot of unnecessary string manipulation. Don't append to strings one character at a time; when you're building up your tokens do your work on the "master" string and strip out the token in one fell swoop. (In other words, index into the "master" string, figure out the start and end points, and then grab it with token = master[start:end].) Doing string concatenation one character at a time is a short path to performance misery. I suspect even if you want/need for some reason to do for c in master: newstr += c you might have better luck stuffing the 'c's into a list and then newstr = ''.join(newstr_charlist).
writing a fast parser in python
I've written a hands-on recursive pure python parser for a some file format (ARFF) we use in one lecture. Now running my exercise submission is awfully slow. Turns out by far the most time is spent in my parser. It's consuming a lot of CPU time, the HD is not the bottleneck. I wonder what performant ways are there to write a parser in python? I'd rather not rewrite it in C. I tried to use jython, but that decreased performance a lot! The files I parse are partially huge (> 150 MB) with very long lines. My current parser only needs a look-ahead of one character. I'd post the source here but I don't know if that's such a good idea. After all the submission deadline has not ended yet. But then, the focus in this exercise is not the parser. You can choose whatever language you want to use and there already is a parser for Java. Note: I've a x86_64 system so psyco (and it seems also PyPy) is no option. Update: I now uploaded my parser/writer to bitbucket.
[ "You could use ANTLR or pyparsing, they might speed up your parsing process.\nAnd if you want to keep your current code, you might want to look at Cython/PyPy, which increases your perfomance (sometimes upto 4x).\n", "The most general tip I'd give without further information would be to read the entire file, or at least a substantial section of it, into memory at once. You don't want to be reading it one character at a time and seeking here and there; regardless of the buffering that's going on under the hood it's probably a good idea just to have the whole thing in memory so you can operate on it however you want.\nI have written parsers in Python and there's no particular requirement for them to be particularly slower than a parser written in any other language. As it is with these sorts of things, it's more likely that you're doing work you don't need to do. Of those class of item, creating and destroying and recreating the same object is more costly than just storing it off somewhere. Recomputing a value over and over again is more costly than just storing it somewhere. Etc., etc.\nIn Python specifically, one trap that people fall into is doing a lot of unnecessary string manipulation. Don't append to strings one character at a time; when you're building up your tokens do your work on the \"master\" string and strip out the token in one fell swoop. (In other words, index into the \"master\" string, figure out the start and end points, and then grab it with token = master[start:end].) Doing string concatenation one character at a time is a short path to performance misery. I suspect even if you want/need for some reason to do for c in master: newstr += c you might have better luck stuffing the 'c's into a list and then newstr = ''.join(newstr_charlist).\n" ]
[ 10, 10 ]
[]
[]
[ "arff", "parsing", "python" ]
stackoverflow_0002722995_arff_parsing_python.txt
Q: Tokenize a command string I have string like this: command ". / * or any other char like this" some_param="string param" some_param2=50 I want to tokenize this string into: command ". / * or any other char like this" some_param="string param" some_param2=50 I know it's possible to split with spaces but these parameters can also be seperated by commas, like: command ". / * or any other char like this", some_param="string param", some_param2=50 I tried to do it like this: \w+\=?\"?.+\"? but it didn't work. A: The stdlib module shlex is designed for parsing shell-like command syntax: >>> import shlex >>> s = 'command ". / * or any other char like this" some_param="string param" some_param2=50' >>> shlex.split(s) ['command', '. / * or any other char like this', 'some_param=string param', 'some_param2=50'] The only difference from your desired result is that the quoted string is returned as the string value, not as the quoted string literal. A: Something like this? >>> x='command ". / * or any other char like this" some_param="string param" some_param2=50' >>> >>> re.findall('\w+\=\d+|\w+\="[^"]+"|"[^"]+"|\w+',x) ['command', '". / * or any other char like this"', 'some_param="string param"', 'some_param2=50'] >>>
Tokenize a command string
I have string like this: command ". / * or any other char like this" some_param="string param" some_param2=50 I want to tokenize this string into: command ". / * or any other char like this" some_param="string param" some_param2=50 I know it's possible to split with spaces but these parameters can also be seperated by commas, like: command ". / * or any other char like this", some_param="string param", some_param2=50 I tried to do it like this: \w+\=?\"?.+\"? but it didn't work.
[ "The stdlib module shlex is designed for parsing shell-like command syntax:\n>>> import shlex\n>>> s = 'command \". / * or any other char like this\" some_param=\"string param\" some_param2=50'\n>>> shlex.split(s)\n['command', '. / * or any other char like this', 'some_param=string param', 'some_param2=50']\n\nThe only difference from your desired result is that the quoted string is returned as the string value, not as the quoted string literal.\n", "Something like this?\n>>> x='command \". / * or any other char like this\" some_param=\"string param\" some_param2=50'\n>>>\n>>> re.findall('\\w+\\=\\d+|\\w+\\=\"[^\"]+\"|\"[^\"]+\"|\\w+',x)\n['command', '\". / * or any other char like this\"', 'some_param=\"string param\"', 'some_param2=50']\n>>>\n\n" ]
[ 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002723040_python_regex.txt
Q: python: list manipulation I have a list L of objects (for what it's worth this is in scons). I would like to create two lists L1 and L2 where L1 is L with an item I1 appended, and L2 is L with an item I2 appended. I would use append but that modifies the original list. How can I do this in Python? (sorry for the beginner question, I don't use the language much, just for scons) A: L1 = L + [i1] L2 = L + [i2] That is probably the simplest way. Another option is to copy the list and then append: L1 = L[:] #make a copy of L L1.append(i1) A: L1=list(L) duplicates the list. I guess you can figure out the rest :) A: You can make a copy of your list >>> x = [1, 2, 3] >>> y = list(x) >>> y.append(4) >>> y [1, 2, 3, 4] >>> z = list(x) >>> z.append(5) >>> z [1, 2, 3, 5] or use concatenation, which will make a new list >>> x = [1, 2, 3] >>> y = x + [4] >>> z = x + [5] >>> y [1, 2, 3, 4] >>> z [1, 2, 3, 5] The former is probably a touch more idiomatic/common, but the latter works fine in this case. Some people also copy using slicing (x[:] makes a new list with all the elements of the original list x referred to) or the copy module. Neither of these are awful, but I find the former a touch cryptic and the latter a bit silly.
python: list manipulation
I have a list L of objects (for what it's worth this is in scons). I would like to create two lists L1 and L2 where L1 is L with an item I1 appended, and L2 is L with an item I2 appended. I would use append but that modifies the original list. How can I do this in Python? (sorry for the beginner question, I don't use the language much, just for scons)
[ "L1 = L + [i1]\nL2 = L + [i2]\n\nThat is probably the simplest way. Another option is to copy the list and then append:\nL1 = L[:] #make a copy of L\nL1.append(i1)\n\n", "L1=list(L)\n\nduplicates the list. I guess you can figure out the rest :)\n", "You can make a copy of your list\n>>> x = [1, 2, 3]\n>>> y = list(x)\n>>> y.append(4)\n>>> y\n[1, 2, 3, 4]\n>>> z = list(x)\n>>> z.append(5)\n>>> z\n[1, 2, 3, 5]\n\nor use concatenation, which will make a new list\n>>> x = [1, 2, 3]\n>>> y = x + [4]\n>>> z = x + [5]\n>>> y\n[1, 2, 3, 4]\n>>> z\n[1, 2, 3, 5]\n\nThe former is probably a touch more idiomatic/common, but the latter works fine in this case. Some people also copy using slicing (x[:] makes a new list with all the elements of the original list x referred to) or the copy module. Neither of these are awful, but I find the former a touch cryptic and the latter a bit silly.\n" ]
[ 8, 3, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002723404_list_python.txt
Q: Why doesn't my QsciLexerCustom subclass work in PyQt4 using QsciScintilla? My end goal is to get Erlang syntax highlighting in QsciScintilla using PyQt4 and Python 2.6. I'm running on Windows 7, but will also need Ubuntu support. PyQt4 is missing the necessary wrapper code for the Erlang lexer/highlighter that "base" scintilla has, so I figured I'd write a lightweight one on top of QsciLexerCustom. It's a little bit problematic, because the Qsci wrapper seems to really want to talk about line+index rather than offset-from-start when getting/setting subranges of text. Meanwhile, the lexer gets arguments as offset-from-start. For now, I get a copy of the entire text, and split that up as appropriate. I have the following lexer, and I apply it with setLexer(). It gets all the appropriate calls when I open a new file and sets this as the lexer, and prints a bunch of appropriate lines based on what it's doing... but there is no styling in the document. I tried making all the defined styles red, and the document is still stubbornly black-on-white, so apparently the styles don't really "take effect" What am I doing wrong? If nobody here knows, what's the appropriate discussion forum where people might actually know these things? (It's an interesting intersection between Python, Qt and Scintilla, so I imagine the set of people who would know is small) Let's assume prefs.declare() just sets up a dict that returns the value for the given key (I've verified this -- it's not the problem). Let's assume scintilla is reasonably properly constructed into its host window QWidget. Specifically, if I apply a bundled lexer (such as QsciLexerPython), it takes effect and does show styled text. prefs.declare('font.name.margin', "MS Dlg") prefs.declare('font.size.margin', 8) prefs.declare('font.name.code', "Courier New") prefs.declare('font.size.code', 10) prefs.declare('color.editline', "#d0e0ff") class LexerErlang(Qsci.QsciLexerCustom): def __init__(self, obj = None): Qsci.QsciLexerCustom.__init__(self, obj) self.sci = None self.plainFont = QtGui.QFont() self.plainFont.setPointSize(int(prefs.get('font.size.code'))) self.plainFont.setFamily(prefs.get('font.name.code')) self.marginFont = QtGui.QFont() self.marginFont.setPointSize(int(prefs.get('font.size.code'))) self.marginFont.setFamily(prefs.get('font.name.margin')) self.boldFont = QtGui.QFont() self.boldFont.setPointSize(int(prefs.get('font.size.code'))) self.boldFont.setFamily(prefs.get('font.name.code')) self.boldFont.setBold(True) self.styles = [ Qsci.QsciStyle(0, QtCore.QString("base"), QtGui.QColor("#000000"), QtGui.QColor("#ffffff"), self.plainFont, True), Qsci.QsciStyle(1, QtCore.QString("comment"), QtGui.QColor("#008000"), QtGui.QColor("#eeffee"), self.marginFont, True), Qsci.QsciStyle(2, QtCore.QString("keyword"), QtGui.QColor("#000080"), QtGui.QColor("#ffffff"), self.boldFont, True), Qsci.QsciStyle(3, QtCore.QString("string"), QtGui.QColor("#800000"), QtGui.QColor("#ffffff"), self.marginFont, True), Qsci.QsciStyle(4, QtCore.QString("atom"), QtGui.QColor("#008080"), QtGui.QColor("#ffffff"), self.plainFont, True), Qsci.QsciStyle(5, QtCore.QString("macro"), QtGui.QColor("#808000"), QtGui.QColor("#ffffff"), self.boldFont, True), Qsci.QsciStyle(6, QtCore.QString("error"), QtGui.QColor("#000000"), QtGui.QColor("#ffd0d0"), self.plainFont, True), ] print("LexerErlang created") def description(self, ix): for i in self.styles: if i.style() == ix: return QtCore.QString(i.description()) return QtCore.QString("") def setEditor(self, sci): self.sci = sci Qsci.QsciLexerCustom.setEditor(self, sci) print("LexerErlang.setEditor()") def styleText(self, start, end): print("LexerErlang.styleText(%d,%d)" % (start, end)) lines = self.getText(start, end) offset = start self.startStyling(offset, 0) print("startStyling()") for i in lines: if i == "": self.setStyling(1, self.styles[0]) print("setStyling(1)") offset += 1 continue if i[0] == '%': self.setStyling(len(i)+1, self.styles[1]) print("setStyling(%)") offset += len(i)+1 continue self.setStyling(len(i)+1, self.styles[0]) print("setStyling(n)") offset += len(i)+1 def getText(self, start, end): data = self.sci.text() print("LexerErlang.getText(): " + str(len(data)) + " chars") return data[start:end].split('\n') Applied to the QsciScintilla widget as follows: _lexers = { 'erl': (Q.SCLEX_ERLANG, LexerErlang), 'hrl': (Q.SCLEX_ERLANG, LexerErlang), 'html': (Q.SCLEX_HTML, Qsci.QsciLexerHTML), 'css': (Q.SCLEX_CSS, Qsci.QsciLexerCSS), 'py': (Q.SCLEX_PYTHON, Qsci.QsciLexerPython), 'php': (Q.SCLEX_PHP, Qsci.QsciLexerHTML), 'inc': (Q.SCLEX_PHP, Qsci.QsciLexerHTML), 'js': (Q.SCLEX_CPP, Qsci.QsciLexerJavaScript), 'cpp': (Q.SCLEX_CPP, Qsci.QsciLexerCPP), 'h': (Q.SCLEX_CPP, Qsci.QsciLexerCPP), 'cxx': (Q.SCLEX_CPP, Qsci.QsciLexerCPP), 'hpp': (Q.SCLEX_CPP, Qsci.QsciLexerCPP), 'c': (Q.SCLEX_CPP, Qsci.QsciLexerCPP), 'hxx': (Q.SCLEX_CPP, Qsci.QsciLexerCPP), 'tpl': (Q.SCLEX_CPP, Qsci.QsciLexerCPP), 'xml': (Q.SCLEX_XML, Qsci.QsciLexerXML), } ... inside my document window class ... def addContentsDocument(self, contents, title): handler = self.makeScintilla() handler.title = title sci = handler.sci sci.append(contents) self.tabWidget.addTab(sci, title) self.tabWidget.setCurrentWidget(sci) self.applyLexer(sci, title) EventBus.bus.broadcast('command.done', {'text': 'Opened ' + title}) return handler def applyLexer(self, sci, title): (language, lexer) = language_and_lexer_from_title(title) if lexer: l = lexer() print("making lexer: " + str(l)) sci.setLexer(l) else: print("setting lexer by id: " + str(language)) sci.SendScintilla(Qsci.QsciScintillaBase.SCI_SETLEXER, language) linst = sci.lexer() print("lexer: " + str(linst)) def makeScintilla(self): sci = Qsci.QsciScintilla() sci.setUtf8(True) sci.setTabIndents(True) sci.setIndentationsUseTabs(False) sci.setIndentationWidth(4) sci.setMarginsFont(self.smallFont) sci.setMarginWidth(0, self.smallFontMetrics.width('00000')) sci.setFont(self.monoFont) sci.setAutoIndent(True) sci.setBraceMatching(Qsci.QsciScintilla.StrictBraceMatch) handler = SciHandler(sci) self.handlers[sci] = handler sci.setMarginLineNumbers(0, True) sci.setCaretLineVisible(True) sci.setCaretLineBackgroundColor(QtGui.QColor(prefs.get('color.editline'))) return handler Let's assume the rest of the application works, too (because it does :-) A: The answer was that the documentation for QsciLexerCustom is misleading. It's not enough to call setStyling() with a QsciStyle object. Only the numeric index from that object actually seems to matter. Additionally, your custom lexer needs to override the font(), color() and other style-getting functions that take a style index, and return the style you want to have for that index.
Why doesn't my QsciLexerCustom subclass work in PyQt4 using QsciScintilla?
My end goal is to get Erlang syntax highlighting in QsciScintilla using PyQt4 and Python 2.6. I'm running on Windows 7, but will also need Ubuntu support. PyQt4 is missing the necessary wrapper code for the Erlang lexer/highlighter that "base" scintilla has, so I figured I'd write a lightweight one on top of QsciLexerCustom. It's a little bit problematic, because the Qsci wrapper seems to really want to talk about line+index rather than offset-from-start when getting/setting subranges of text. Meanwhile, the lexer gets arguments as offset-from-start. For now, I get a copy of the entire text, and split that up as appropriate. I have the following lexer, and I apply it with setLexer(). It gets all the appropriate calls when I open a new file and sets this as the lexer, and prints a bunch of appropriate lines based on what it's doing... but there is no styling in the document. I tried making all the defined styles red, and the document is still stubbornly black-on-white, so apparently the styles don't really "take effect" What am I doing wrong? If nobody here knows, what's the appropriate discussion forum where people might actually know these things? (It's an interesting intersection between Python, Qt and Scintilla, so I imagine the set of people who would know is small) Let's assume prefs.declare() just sets up a dict that returns the value for the given key (I've verified this -- it's not the problem). Let's assume scintilla is reasonably properly constructed into its host window QWidget. Specifically, if I apply a bundled lexer (such as QsciLexerPython), it takes effect and does show styled text. prefs.declare('font.name.margin', "MS Dlg") prefs.declare('font.size.margin', 8) prefs.declare('font.name.code', "Courier New") prefs.declare('font.size.code', 10) prefs.declare('color.editline', "#d0e0ff") class LexerErlang(Qsci.QsciLexerCustom): def __init__(self, obj = None): Qsci.QsciLexerCustom.__init__(self, obj) self.sci = None self.plainFont = QtGui.QFont() self.plainFont.setPointSize(int(prefs.get('font.size.code'))) self.plainFont.setFamily(prefs.get('font.name.code')) self.marginFont = QtGui.QFont() self.marginFont.setPointSize(int(prefs.get('font.size.code'))) self.marginFont.setFamily(prefs.get('font.name.margin')) self.boldFont = QtGui.QFont() self.boldFont.setPointSize(int(prefs.get('font.size.code'))) self.boldFont.setFamily(prefs.get('font.name.code')) self.boldFont.setBold(True) self.styles = [ Qsci.QsciStyle(0, QtCore.QString("base"), QtGui.QColor("#000000"), QtGui.QColor("#ffffff"), self.plainFont, True), Qsci.QsciStyle(1, QtCore.QString("comment"), QtGui.QColor("#008000"), QtGui.QColor("#eeffee"), self.marginFont, True), Qsci.QsciStyle(2, QtCore.QString("keyword"), QtGui.QColor("#000080"), QtGui.QColor("#ffffff"), self.boldFont, True), Qsci.QsciStyle(3, QtCore.QString("string"), QtGui.QColor("#800000"), QtGui.QColor("#ffffff"), self.marginFont, True), Qsci.QsciStyle(4, QtCore.QString("atom"), QtGui.QColor("#008080"), QtGui.QColor("#ffffff"), self.plainFont, True), Qsci.QsciStyle(5, QtCore.QString("macro"), QtGui.QColor("#808000"), QtGui.QColor("#ffffff"), self.boldFont, True), Qsci.QsciStyle(6, QtCore.QString("error"), QtGui.QColor("#000000"), QtGui.QColor("#ffd0d0"), self.plainFont, True), ] print("LexerErlang created") def description(self, ix): for i in self.styles: if i.style() == ix: return QtCore.QString(i.description()) return QtCore.QString("") def setEditor(self, sci): self.sci = sci Qsci.QsciLexerCustom.setEditor(self, sci) print("LexerErlang.setEditor()") def styleText(self, start, end): print("LexerErlang.styleText(%d,%d)" % (start, end)) lines = self.getText(start, end) offset = start self.startStyling(offset, 0) print("startStyling()") for i in lines: if i == "": self.setStyling(1, self.styles[0]) print("setStyling(1)") offset += 1 continue if i[0] == '%': self.setStyling(len(i)+1, self.styles[1]) print("setStyling(%)") offset += len(i)+1 continue self.setStyling(len(i)+1, self.styles[0]) print("setStyling(n)") offset += len(i)+1 def getText(self, start, end): data = self.sci.text() print("LexerErlang.getText(): " + str(len(data)) + " chars") return data[start:end].split('\n') Applied to the QsciScintilla widget as follows: _lexers = { 'erl': (Q.SCLEX_ERLANG, LexerErlang), 'hrl': (Q.SCLEX_ERLANG, LexerErlang), 'html': (Q.SCLEX_HTML, Qsci.QsciLexerHTML), 'css': (Q.SCLEX_CSS, Qsci.QsciLexerCSS), 'py': (Q.SCLEX_PYTHON, Qsci.QsciLexerPython), 'php': (Q.SCLEX_PHP, Qsci.QsciLexerHTML), 'inc': (Q.SCLEX_PHP, Qsci.QsciLexerHTML), 'js': (Q.SCLEX_CPP, Qsci.QsciLexerJavaScript), 'cpp': (Q.SCLEX_CPP, Qsci.QsciLexerCPP), 'h': (Q.SCLEX_CPP, Qsci.QsciLexerCPP), 'cxx': (Q.SCLEX_CPP, Qsci.QsciLexerCPP), 'hpp': (Q.SCLEX_CPP, Qsci.QsciLexerCPP), 'c': (Q.SCLEX_CPP, Qsci.QsciLexerCPP), 'hxx': (Q.SCLEX_CPP, Qsci.QsciLexerCPP), 'tpl': (Q.SCLEX_CPP, Qsci.QsciLexerCPP), 'xml': (Q.SCLEX_XML, Qsci.QsciLexerXML), } ... inside my document window class ... def addContentsDocument(self, contents, title): handler = self.makeScintilla() handler.title = title sci = handler.sci sci.append(contents) self.tabWidget.addTab(sci, title) self.tabWidget.setCurrentWidget(sci) self.applyLexer(sci, title) EventBus.bus.broadcast('command.done', {'text': 'Opened ' + title}) return handler def applyLexer(self, sci, title): (language, lexer) = language_and_lexer_from_title(title) if lexer: l = lexer() print("making lexer: " + str(l)) sci.setLexer(l) else: print("setting lexer by id: " + str(language)) sci.SendScintilla(Qsci.QsciScintillaBase.SCI_SETLEXER, language) linst = sci.lexer() print("lexer: " + str(linst)) def makeScintilla(self): sci = Qsci.QsciScintilla() sci.setUtf8(True) sci.setTabIndents(True) sci.setIndentationsUseTabs(False) sci.setIndentationWidth(4) sci.setMarginsFont(self.smallFont) sci.setMarginWidth(0, self.smallFontMetrics.width('00000')) sci.setFont(self.monoFont) sci.setAutoIndent(True) sci.setBraceMatching(Qsci.QsciScintilla.StrictBraceMatch) handler = SciHandler(sci) self.handlers[sci] = handler sci.setMarginLineNumbers(0, True) sci.setCaretLineVisible(True) sci.setCaretLineBackgroundColor(QtGui.QColor(prefs.get('color.editline'))) return handler Let's assume the rest of the application works, too (because it does :-)
[ "The answer was that the documentation for QsciLexerCustom is misleading.\nIt's not enough to call setStyling() with a QsciStyle object. Only the numeric index from that object actually seems to matter.\nAdditionally, your custom lexer needs to override the font(), color() and other style-getting functions that take a style index, and return the style you want to have for that index.\n" ]
[ 3 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "scintilla" ]
stackoverflow_0002694593_pyqt_pyqt4_python_qt_scintilla.txt
Q: Why is recordset result being returned in this way for Python database query? I have searched high and low for an answer to why query results returned in this format and how to convert to a list. data = cursor.fetchall() When I print data, it results in: (('car',), ('boat',), ('plane',), ('truck',)) I want to have the results in a list as ["car", "boat", "plane", "truck"] A: It's returning it in that way because a recordset is comprised of many rows of data, not a list of single elements. You can flatten it if you want using a list comprehension: data = [row[0] for row in cursor.fetchall()] A: The result for fetchall() returns an array of rows, where each row is an array with one value per column. Even if you are selecting only one column, you will still get an array of arrays, but only one value for each row. A: x = (('car',), ('boat',), ('plane',), ('truck',)) y = [z[0] for z in x] # ['car', 'boat', 'plane', 'truck']
Why is recordset result being returned in this way for Python database query?
I have searched high and low for an answer to why query results returned in this format and how to convert to a list. data = cursor.fetchall() When I print data, it results in: (('car',), ('boat',), ('plane',), ('truck',)) I want to have the results in a list as ["car", "boat", "plane", "truck"]
[ "It's returning it in that way because a recordset is comprised of many rows of data, not a list of single elements.\nYou can flatten it if you want using a list comprehension:\ndata = [row[0] for row in cursor.fetchall()]\n\n", "The result for fetchall() returns an array of rows, where each row is an array with one value per column.\nEven if you are selecting only one column, you will still get an array of arrays, but only one value for each row.\n", "x = (('car',), ('boat',), ('plane',), ('truck',))\n\ny = [z[0] for z in x] # ['car', 'boat', 'plane', 'truck']\n\n" ]
[ 5, 1, 0 ]
[]
[]
[ "list", "mysql", "python", "recordset" ]
stackoverflow_0002723432_list_mysql_python_recordset.txt
Q: Python Regex To VB.net I made a program in Python and now I whant to transfert it to vb.net. But I have some difficulties with the vb.net regular expression.... Someone can help me please? There are my Python regex: id = re.search('(?<=watch\?v\=)[\w|-]+|(?<=/v/)[\w|-]+', src) id = id.group(0) t = re.search('(?<=\&t\=)[\w|-]+', src) t = t.group() It's supposed to fin the value of ?v=Value&SomeOtherContent and &t=Value&SomeOtherContent Thank you A: An easy way to parse query strings is by using a NameValueCollection, using the HttpUtility.ParseQueryString method. This also takes care of encoding. For example: NameValueCollection parameters = HttpUtility.ParseQueryString("?var1=1&var2=2");
Python Regex To VB.net
I made a program in Python and now I whant to transfert it to vb.net. But I have some difficulties with the vb.net regular expression.... Someone can help me please? There are my Python regex: id = re.search('(?<=watch\?v\=)[\w|-]+|(?<=/v/)[\w|-]+', src) id = id.group(0) t = re.search('(?<=\&t\=)[\w|-]+', src) t = t.group() It's supposed to fin the value of ?v=Value&SomeOtherContent and &t=Value&SomeOtherContent Thank you
[ "An easy way to parse query strings is by using a NameValueCollection, using the HttpUtility.ParseQueryString method. This also takes care of encoding.\nFor example:\nNameValueCollection parameters = HttpUtility.ParseQueryString(\"?var1=1&var2=2\");\n\n" ]
[ 1 ]
[]
[]
[ "python", "regex", "vb.net" ]
stackoverflow_0002723485_python_regex_vb.net.txt
Q: How to convert Selenese (html) to Python programmatically? How would I convert test cases made by Selenium IDE to Python without exporting every test case by hand? Is there any command line converter for that job? In the end I want to use Selenium RC and Pythons build in unittest to test my websites. Thanks a lot. Update: I started to write a converter but its too much work to implement all the commands. Is there any better way? from xml.dom.minidom import parse class SeleneseParser: def __init__(self,selFile): self.dom = parse(selFile) def getTestName(self): return self.dom.getElementsByTagName('title')[0].firstChild.data def getBaseUrl(self): return self.dom.getElementsByTagName('link')[0].getAttribute('href') def getNodes(self): cmds = [] nodes = self.dom.getElementsByTagName('tbody')[0].childNodes for node in nodes: if node.nodeType == node.TEXT_NODE and "\n" in node.data: continue if node.nodeType == node.COMMENT_NODE: cmds.append(node.data) if node.nodeType == node.ELEMENT_NODE: cmd = [] for c in node.childNodes: if c.nodeType == node.ELEMENT_NODE: if len(c.childNodes) == 1: cmd.append(c.childNodes[0].data) else: cmd.append("") cmds.append(cmd) return cmds class PythonConverter: def __init__(self,sourceFile): self.parser = SeleneseParser(sourceFile) self.dest = u'# -*- coding: utf-8 -*-\n\nfrom selenium import selenium\nimport unittest, time, re\n' def getHeader(self): self.dest += u'\nclass %s(unittest.TestCase):\n' % self.parser.getTestName() self.dest += u'\tdef setUp(self):\n\t\tself.verificationErrors = []\n' self.dest += u'\t\tself.selenium = selenium("localhost", 4444, "*chrome", "%s")\n' % self.parser.getBaseUrl() self.dest += u'\t\tself.selenium.start()\n' def getContent(self): self.dest += u'\n\tdef test_%s(self):\n\t\tsel = self.selenium\n' % self.parser.getTestName() nodes = self.parser.getNodes() for node in nodes: if type(node) is list: cmd,target,value = node[0],node[1],node[2] if cmd == 'store': self.dest += u'\t\t%s = "%s"\n' % (value,target) elif cmd == 'clickAndWait': self.dest += u'\t\tsel.click(u"%s")\n\t\tsel.wait_for_page_to_load("30000")\n' % (target) elif cmd == 'type': self.dest += u'\t\tsel.%s(u"%s", u"%s")\n' % (cmd,target,value) elif cmd == 'select': self.dest += u'\t\tsel.select(u"%s", u"%s")\n' % (target,value) elif cmd == 'verifyTextPresent': self.dest += u'\t\ttry: self.failUnless(sel.is_text_present(u"%s"))\n\t\texcept AssertionError, e: self.verificationErrors.append(str(e))\n' % target elif cmd == 'verifySelectedLabel': self.dest += u'\t\ttry: self.assertEqual(u"%s", sel.get_selected_label(u"%s"))\n\t\texcept AssertionError, e: self.verificationErrors.append(str(e))\n' % (value,target) elif cmd == 'verifyValue': self.dest += u'\t\ttry: self.assertEqual(u"%s", sel.get_value(u"%s"))\n\t\texcept AssertionError, e: self.verificationErrors.append(str(e))\n' % (value,target) elif cmd == 'verifyText': self.dest += u'\t\ttry: self.assertEqual(u"%s", sel.get_text(u"%s"))\n\t\texcept AssertionError, e: self.verificationErrors.append(str(e))\n' % (value,target) elif cmd == 'verifyElementPresent': self.dest += u'\t\ttry: self.failUnless(sel.is_element_present(u"%s"))\n\t\texcept AssertionError, e: self.verificationErrors.append(str(e))\n' % (target) else: self.dest += u'\t\tsel.%s(u"%s")\n' % (cmd,target) #print cmd,target,value else: self.dest += u'\t\t#%s\n' % node def getFooter(self): self.dest += u'\n\tdef tearDown(self):\n\t\tself.selenium.stop()\n\t\tself.assertEqual([], self.verificationErrors)\n' self.dest += u'\nif __name__ == "__main__":\n\tunittest.main()' def convert(self): self.getHeader() self.getContent() self.getFooter() return self.dest p = PythonConverter('test_case.html') print p.convert() A: I've started building a Selenese-to-Python parser, PySelenese, which I've posted on Github. Feel free to fork/clone the repository and give it a try: http://github.com/jpstacey/PySelenese . A: No there isn't a way but in theory it shouldn't be too difficult to do as all you need to do is have something that uses the python-rc.js to convert the file.
How to convert Selenese (html) to Python programmatically?
How would I convert test cases made by Selenium IDE to Python without exporting every test case by hand? Is there any command line converter for that job? In the end I want to use Selenium RC and Pythons build in unittest to test my websites. Thanks a lot. Update: I started to write a converter but its too much work to implement all the commands. Is there any better way? from xml.dom.minidom import parse class SeleneseParser: def __init__(self,selFile): self.dom = parse(selFile) def getTestName(self): return self.dom.getElementsByTagName('title')[0].firstChild.data def getBaseUrl(self): return self.dom.getElementsByTagName('link')[0].getAttribute('href') def getNodes(self): cmds = [] nodes = self.dom.getElementsByTagName('tbody')[0].childNodes for node in nodes: if node.nodeType == node.TEXT_NODE and "\n" in node.data: continue if node.nodeType == node.COMMENT_NODE: cmds.append(node.data) if node.nodeType == node.ELEMENT_NODE: cmd = [] for c in node.childNodes: if c.nodeType == node.ELEMENT_NODE: if len(c.childNodes) == 1: cmd.append(c.childNodes[0].data) else: cmd.append("") cmds.append(cmd) return cmds class PythonConverter: def __init__(self,sourceFile): self.parser = SeleneseParser(sourceFile) self.dest = u'# -*- coding: utf-8 -*-\n\nfrom selenium import selenium\nimport unittest, time, re\n' def getHeader(self): self.dest += u'\nclass %s(unittest.TestCase):\n' % self.parser.getTestName() self.dest += u'\tdef setUp(self):\n\t\tself.verificationErrors = []\n' self.dest += u'\t\tself.selenium = selenium("localhost", 4444, "*chrome", "%s")\n' % self.parser.getBaseUrl() self.dest += u'\t\tself.selenium.start()\n' def getContent(self): self.dest += u'\n\tdef test_%s(self):\n\t\tsel = self.selenium\n' % self.parser.getTestName() nodes = self.parser.getNodes() for node in nodes: if type(node) is list: cmd,target,value = node[0],node[1],node[2] if cmd == 'store': self.dest += u'\t\t%s = "%s"\n' % (value,target) elif cmd == 'clickAndWait': self.dest += u'\t\tsel.click(u"%s")\n\t\tsel.wait_for_page_to_load("30000")\n' % (target) elif cmd == 'type': self.dest += u'\t\tsel.%s(u"%s", u"%s")\n' % (cmd,target,value) elif cmd == 'select': self.dest += u'\t\tsel.select(u"%s", u"%s")\n' % (target,value) elif cmd == 'verifyTextPresent': self.dest += u'\t\ttry: self.failUnless(sel.is_text_present(u"%s"))\n\t\texcept AssertionError, e: self.verificationErrors.append(str(e))\n' % target elif cmd == 'verifySelectedLabel': self.dest += u'\t\ttry: self.assertEqual(u"%s", sel.get_selected_label(u"%s"))\n\t\texcept AssertionError, e: self.verificationErrors.append(str(e))\n' % (value,target) elif cmd == 'verifyValue': self.dest += u'\t\ttry: self.assertEqual(u"%s", sel.get_value(u"%s"))\n\t\texcept AssertionError, e: self.verificationErrors.append(str(e))\n' % (value,target) elif cmd == 'verifyText': self.dest += u'\t\ttry: self.assertEqual(u"%s", sel.get_text(u"%s"))\n\t\texcept AssertionError, e: self.verificationErrors.append(str(e))\n' % (value,target) elif cmd == 'verifyElementPresent': self.dest += u'\t\ttry: self.failUnless(sel.is_element_present(u"%s"))\n\t\texcept AssertionError, e: self.verificationErrors.append(str(e))\n' % (target) else: self.dest += u'\t\tsel.%s(u"%s")\n' % (cmd,target) #print cmd,target,value else: self.dest += u'\t\t#%s\n' % node def getFooter(self): self.dest += u'\n\tdef tearDown(self):\n\t\tself.selenium.stop()\n\t\tself.assertEqual([], self.verificationErrors)\n' self.dest += u'\nif __name__ == "__main__":\n\tunittest.main()' def convert(self): self.getHeader() self.getContent() self.getFooter() return self.dest p = PythonConverter('test_case.html') print p.convert()
[ "I've started building a Selenese-to-Python parser, PySelenese, which I've posted on Github. Feel free to fork/clone the repository and give it a try: http://github.com/jpstacey/PySelenese .\n", "No there isn't a way but in theory it shouldn't be too difficult to do as all you need to do is have something that uses the python-rc.js to convert the file.\n" ]
[ 3, 0 ]
[]
[]
[ "python", "selenium", "selenium_ide", "selenium_rc" ]
stackoverflow_0002617684_python_selenium_selenium_ide_selenium_rc.txt
Q: fd.seek() IOError: [Errno 22] Invalid argument My Python Interpreter (v2.6.5) raises the above error in the following codepart: fd = open("some_filename", "r") fd.seek(-2, os.SEEK_END) #same happens if you exchange the second arg. w/ 2 data=fd.read(2); last call is fd.seek() Traceback (most recent call last): File "bot.py", line 250, in <module> fd.seek(iterator, os.SEEK_END); IOError: [Errno 22] Invalid argument The strange thing with this is that the exception occurs just when executing my entire code, not if only the specific part with the file opening. At the runtime of this part of code, the opened file definitely exists, disk is not full, the variable "iterator" contains a correct value like in the first codeblock. What could be my mistake? Thanks in advance A: From lseek(2): EINVAL whence is not one of SEEK_SET, SEEK_CUR, SEEK_END; or the resulting file offset would be negative, or beyond the end of a seekable device. So double-check the value of iterator.
fd.seek() IOError: [Errno 22] Invalid argument
My Python Interpreter (v2.6.5) raises the above error in the following codepart: fd = open("some_filename", "r") fd.seek(-2, os.SEEK_END) #same happens if you exchange the second arg. w/ 2 data=fd.read(2); last call is fd.seek() Traceback (most recent call last): File "bot.py", line 250, in <module> fd.seek(iterator, os.SEEK_END); IOError: [Errno 22] Invalid argument The strange thing with this is that the exception occurs just when executing my entire code, not if only the specific part with the file opening. At the runtime of this part of code, the opened file definitely exists, disk is not full, the variable "iterator" contains a correct value like in the first codeblock. What could be my mistake? Thanks in advance
[ "From lseek(2):\n\nEINVAL \nwhence is not one of SEEK_SET,\n SEEK_CUR, SEEK_END; or the resulting\n file offset would be negative, or\n beyond the end of a seekable device.\n\nSo double-check the value of iterator. \n" ]
[ 8 ]
[]
[]
[ "python", "python_2.6" ]
stackoverflow_0002724015_python_python_2.6.txt
Q: Python recommendation engine Is there a recommendation engine for python similar to Java Taste? A: I haven't found much that runs natively in python, but someone created python wrappers for SUGGEST, which looks like a solid program. SUGGEST overview python wrappers Since python is still fairly slow when compared to C or Java, using wrappers will probably improve performance.
Python recommendation engine
Is there a recommendation engine for python similar to Java Taste?
[ "I haven't found much that runs natively in python, but someone created python wrappers for SUGGEST, which looks like a solid program.\nSUGGEST overview\npython wrappers\nSince python is still fairly slow when compared to C or Java, using wrappers will probably improve performance.\n" ]
[ 0 ]
[]
[]
[ "python", "recommendation_engine" ]
stackoverflow_0002704845_python_recommendation_engine.txt
Q: CAC Client Application Authentication in Python I am building a python application to pull data from a website. The application has to authenticate(HTTPS/SSL) with a CAC card and pin in order to make requests. Am I correct in my assumptions that you can't retrieve the private key from a CAC card, and am therefore stuck using a PKCS #11 Wrapper like PyKCS? Any tips or resources for going about this? A: Authentication and signature keys are usually generated on the card and are not extractable, unlike encryption keys which can/should be escrowed somewhere. See Need help using M2Crypto.Engine to access USB Token for an example with M2Crypto that explains how to use a smart card via PKCS#11 for website access in python. A: You are correct. That's the whole purpose of the smart card to keep the private keys safe. If your application is running in Windows you can try using WININET.DLL for your connectivity, with the correct middleware installed it should handle authentication to the CAC enabled site automatically. A: I would attempt to find out if an ECA cert is a suitable substitute. For example, there sites that accept CAC and ECA certs. For more info: http://iase.disa.mil/pki/eca/certificate.html
CAC Client Application Authentication in Python
I am building a python application to pull data from a website. The application has to authenticate(HTTPS/SSL) with a CAC card and pin in order to make requests. Am I correct in my assumptions that you can't retrieve the private key from a CAC card, and am therefore stuck using a PKCS #11 Wrapper like PyKCS? Any tips or resources for going about this?
[ "Authentication and signature keys are usually generated on the card and are not extractable, unlike encryption keys which can/should be escrowed somewhere.\nSee Need help using M2Crypto.Engine to access USB Token for an example with M2Crypto that explains how to use a smart card via PKCS#11 for website access in python.\n", "You are correct. That's the whole purpose of the smart card to keep the private keys safe. If your application is running in Windows you can try using WININET.DLL for your connectivity, with the correct middleware installed it should handle authentication to the CAC enabled site automatically.\n", "I would attempt to find out if an ECA cert is a suitable substitute. For example, there sites that accept CAC and ECA certs. For more info: http://iase.disa.mil/pki/eca/certificate.html\n" ]
[ 4, 0, 0 ]
[]
[]
[ "cac", "pkcs#11", "python", "smartcard" ]
stackoverflow_0002366636_cac_pkcs#11_python_smartcard.txt
Q: Help with authorization and redirection decorator in python (pylons) I'm trying to write a simple decorator to check the authentication of a user, and to redirect to the login page if s/he is not authenticated: def authenticate(f): try: if user['authenticated'] is True: return f except: redirect_to(controller='login', action='index') class IndexController(BaseController): @authenticate def index(self): return render('/index.mako' ) But this approach doesn't work. When a user is authenticated, everything is fine. But when the user is not authenticated, redirect_to() doesn't work and I am given this error: HTTPFound: 302 Found Content-Type: text/html; charset=UTF-8 Content-Length: 0 location: /login Thank for your help! A: i don't know pylons, but it seems the way you wrote your decorator is not good. a decorator is a callable which must return a callable. the decorator is called at the moment the function is defined, and it should return a callable (generally a function) which will be called in place of the function being decorated. in your sample, your decorator returns a callable only if the user is authenticated at the moment the index() function is defined. try rewriting it this way: def authenticate(func): def call(*args, **kwargs): if user['authenticated'] is True: return func(*args,**kwargs) else: return redirect_to(controller='login', action='index') return call here, authenticate() defines an inner function, which is returned in place of the function it decorates. now when you decorate a function using this decorator: @authenticate def index(self): return render('/index.mako' ) this means that each time you call index(), you are in fact calling the inner function declared in your decorator. you should note that: due to the way functions are defined in python, the function object returned by the decorator still remembers the value of arguments of the function in which it was defined. call() still knows about the argument func which was passed when the decorator was called. (this is called a closure) decorators are difficult to understand although they are not complicated. you should search google for a tutorial on decorators: there are plenty of them which gives a very nice understanding of the concept, far much clearer than the python documentation.
Help with authorization and redirection decorator in python (pylons)
I'm trying to write a simple decorator to check the authentication of a user, and to redirect to the login page if s/he is not authenticated: def authenticate(f): try: if user['authenticated'] is True: return f except: redirect_to(controller='login', action='index') class IndexController(BaseController): @authenticate def index(self): return render('/index.mako' ) But this approach doesn't work. When a user is authenticated, everything is fine. But when the user is not authenticated, redirect_to() doesn't work and I am given this error: HTTPFound: 302 Found Content-Type: text/html; charset=UTF-8 Content-Length: 0 location: /login Thank for your help!
[ "i don't know pylons, but it seems the way you wrote your decorator is not good. \na decorator is a callable which must return a callable. the decorator is called at the moment the function is defined, and it should return a callable (generally a function) which will be called in place of the function being decorated.\nin your sample, your decorator returns a callable only if the user is authenticated at the moment the index() function is defined.\ntry rewriting it this way:\ndef authenticate(func):\n def call(*args, **kwargs):\n if user['authenticated'] is True:\n return func(*args,**kwargs)\n else:\n return redirect_to(controller='login', action='index')\n return call\n\nhere, authenticate() defines an inner function, which is returned in place of the function it decorates. now when you decorate a function using this decorator:\n@authenticate\ndef index(self):\n return render('/index.mako' )\n\nthis means that each time you call index(), you are in fact calling the inner function declared in your decorator. \nyou should note that: due to the way functions are defined in python, the function object returned by the decorator still remembers the value of arguments of the function in which it was defined. call() still knows about the argument func which was passed when the decorator was called. (this is called a closure)\ndecorators are difficult to understand although they are not complicated. you should search google for a tutorial on decorators: there are plenty of them which gives a very nice understanding of the concept, far much clearer than the python documentation.\n" ]
[ 5 ]
[]
[]
[ "decorator", "pylons", "python", "redirect" ]
stackoverflow_0002724057_decorator_pylons_python_redirect.txt
Q: Can python code (say if I used djangno) be obfuscated to the same 'level' as c#/java? If I obfuscated python code, would it provide the same level of 'security' as c#/java obfuscating? i.e it makes things a little hard, but really you can still reverse engineer if you really wanted to, its just a bit cryptic. A: Obfuscation is a form of security through obscurity. All obfuscated code can, if the attacker is determined enough, be reversed. There are no exceptions. A: Python code gets compiled to bytecode (.pyc) files as it is imported. You can distribute those .pyc files instead of the .py source code files, and the Python interpreter should be able to load them. While Python bytecode is more "obfuscated" than Python source code, it's still relatively easy to disassemble Python bytecode -- but, then again, it's not that hard to disassemble Java bytecode, either. A: Obfuscation doesn't provide security. What you describe isn't security. If you distribute your Python program or your Java program or your C program, it is vunerable. What protects you from people using what you distributed unfairly is the law and people not being jerks. Obfuscation not only provides no security, it has the potential of breaking working code, hurting performance, and ruining documentation.
Can python code (say if I used djangno) be obfuscated to the same 'level' as c#/java?
If I obfuscated python code, would it provide the same level of 'security' as c#/java obfuscating? i.e it makes things a little hard, but really you can still reverse engineer if you really wanted to, its just a bit cryptic.
[ "Obfuscation is a form of security through obscurity. All obfuscated code can, if the attacker is determined enough, be reversed. There are no exceptions.\n", "Python code gets compiled to bytecode (.pyc) files as it is imported. You can distribute those .pyc files instead of the .py source code files, and the Python interpreter should be able to load them. While Python bytecode is more \"obfuscated\" than Python source code, it's still relatively easy to disassemble Python bytecode -- but, then again, it's not that hard to disassemble Java bytecode, either.\n", "Obfuscation doesn't provide security. What you describe isn't security.\nIf you distribute your Python program or your Java program or your C program, it is vunerable. What protects you from people using what you distributed unfairly is the law and people not being jerks.\nObfuscation not only provides no security, it has the potential of breaking working code, hurting performance, and ruining documentation.\n" ]
[ 7, 0, 0 ]
[ "Why don't you write something and examine the bytecode? Make some functions that depend on random numbers but are almost complete improbable to execute. This way the compiler can't optimize and you'll see more 'junk'. \ndef myfunc(num):\n if (num > 1):\n return 1\n else:\n return 0\n\n>>> dis.dis(myfunc)\n 2 0 LOAD_FAST 0 (num)\n 3 LOAD_CONST 1 (1)\n 6 COMPARE_OP 4 (>)\n 9 JUMP_IF_FALSE 5 (to 17)\n 12 POP_TOP\n\n 3 13 LOAD_CONST 1 (1)\n 16 RETURN_VALUE\n >> 17 POP_TOP\n\n 5 18 LOAD_CONST 2 (0)\n 21 RETURN_VALUE\n 22 LOAD_CONST 0 (None)\n 25 RETURN_VALUE\n\n" ]
[ -2 ]
[ "c#", "java", "obfuscation", "python" ]
stackoverflow_0002724885_c#_java_obfuscation_python.txt
Q: Search engine recommendation for 100 sites of about 4000 pages I am looking for a search engine that can regularly (daily-ish) scan about 100 pages for changes and index an associated site if changes since the last scan are found. It should be able to handle about 100 sites, each averaging 4000 pages of about 5k average size, each on a different server (but only the one centralized search engine). Each of these sites will have a search form that gets submitted to this search engine. The results that are returned must be specific to the site that submitted them. I create the templates for the external sites, so I can give the search form a hidden field that specifies which site the form is submitted from. What would you recommend I look into? I would love to use a Python-based system for this, if feasible. I am currently using something called iSearch2. It doesn't seem very stable at this scale, the description of the product states it is not really intended to do multiple sites, is in PHP (which is less comfortable to me than Python), and has a few other shortcomings for my specific situation. A: I recommend PyLucene. PyLucene is a Python extension for accessing Java Lucene and works very well and fast. A: If you're looking for a pure python search engine you could look at whoosh. The problem with whoosh is that it's slow and not as full featured. It would be fine if your site doesn't get much traffic, but you might need something more robust for production. With that being said, I like using Xapian with its python bindings. It's pretty fast and easy to set up. You could also use solr which has a python api. Solr is written in Java, but don't let that fool you as it's the best performer out of this bunch. You'll just have to run a java server to get this working. Since I use Django I can integrate haystack into my projects which makes it easy to switch search engines. I'll use Whoosh for development because it's easy and fast to set up (it can install in the virtualenv), but deploy with Xapian or Solr for production depending on my needs. A: +1 for Lucene. If PyLucene seems complex, alternately you could look at Solr (which is a search server based on Lucene with an HTTP interface. Highly scalable, blazing fast and offers very great featureset such faceted browsing, caching etc. OOTB Since Solr is HTTP based you could hook into any language (incl. Python) using its RESTful API.
Search engine recommendation for 100 sites of about 4000 pages
I am looking for a search engine that can regularly (daily-ish) scan about 100 pages for changes and index an associated site if changes since the last scan are found. It should be able to handle about 100 sites, each averaging 4000 pages of about 5k average size, each on a different server (but only the one centralized search engine). Each of these sites will have a search form that gets submitted to this search engine. The results that are returned must be specific to the site that submitted them. I create the templates for the external sites, so I can give the search form a hidden field that specifies which site the form is submitted from. What would you recommend I look into? I would love to use a Python-based system for this, if feasible. I am currently using something called iSearch2. It doesn't seem very stable at this scale, the description of the product states it is not really intended to do multiple sites, is in PHP (which is less comfortable to me than Python), and has a few other shortcomings for my specific situation.
[ "I recommend PyLucene. PyLucene is a Python extension for accessing Java Lucene and works very well and fast.\n", "If you're looking for a pure python search engine you could look at whoosh. The problem with whoosh is that it's slow and not as full featured. It would be fine if your site doesn't get much traffic, but you might need something more robust for production.\nWith that being said, I like using Xapian with its python bindings. It's pretty fast and easy to set up.\nYou could also use solr which has a python api. Solr is written in Java, but don't let that fool you as it's the best performer out of this bunch. You'll just have to run a java server to get this working.\nSince I use Django I can integrate haystack into my projects which makes it easy to switch search engines. I'll use Whoosh for development because it's easy and fast to set up (it can install in the virtualenv), but deploy with Xapian or Solr for production depending on my needs.\n", "+1 for Lucene. If PyLucene seems complex, alternately you could look at Solr (which is a search server based on Lucene with an HTTP interface. Highly scalable, blazing fast and offers very great featureset such faceted browsing, caching etc. OOTB\nSince Solr is HTTP based you could hook into any language (incl. Python) using its RESTful API.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "python", "search_engine" ]
stackoverflow_0002715733_python_search_engine.txt
Q: What's the non brute force way to filter a Python dictionary? I can filter the following dictionary like: data = { 1: {'name': 'stackoverflow', 'traffic': 'high'}, 2: {'name': 'serverfault', 'traffic': 'low'}, 3: {'name': 'superuser', 'traffic': 'low'}, 4: {'name': 'mathoverflow', 'traffic': 'low'}, } traffic = 'low' for k, v in data.items(): if v['traffic'] == traffic: print k, v Is there an alternate way to do the above filtering? A: At some level the filter will have to do exactly what you describe. If you're going to filter on the values, you'll have to process each one, one-by-one. A: If you're doing this a lot, you could have two dictionaries, one for each direction. The new dictionary will map values to lists of values. This is a good idea if you will be doing this reverse lookup more than once. A: In principle — no. You could rewrite the code slightly, but it would still do the same — iterating through all the values. A: Sure, but they're all brute-force. dict((k, v) for (k, v) in data.iteritems() if v['traffic'] == traffic)
What's the non brute force way to filter a Python dictionary?
I can filter the following dictionary like: data = { 1: {'name': 'stackoverflow', 'traffic': 'high'}, 2: {'name': 'serverfault', 'traffic': 'low'}, 3: {'name': 'superuser', 'traffic': 'low'}, 4: {'name': 'mathoverflow', 'traffic': 'low'}, } traffic = 'low' for k, v in data.items(): if v['traffic'] == traffic: print k, v Is there an alternate way to do the above filtering?
[ "At some level the filter will have to do exactly what you describe. If you're going to filter on the values, you'll have to process each one, one-by-one.\n", "If you're doing this a lot, you could have two dictionaries, one for each direction. The new dictionary will map values to lists of values. This is a good idea if you will be doing this reverse lookup more than once.\n", "In principle — no. You could rewrite the code slightly, but it would still do the same — iterating through all the values.\n", "Sure, but they're all brute-force.\ndict((k, v) for (k, v) in data.iteritems() if v['traffic'] == traffic)\n\n" ]
[ 2, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002725248_python.txt
Q: Python: How to extract xml embedded in a html file? I have a html file with xml snipped embedded, the source code is pasted in the pastbin: <html> <head> <title> test֤</title> </head> <body> <form name="acsForm" action="" method="post" > <textarea rows=10 cols=80 name="xmlText"><?xml version="1.0" encoding="UTF-8"?> <samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"> </samlp:Response> </textarea> <textarea name="2nd"> text2....</textarea> </form> </body> </html> My task is to extract the text enclosed in the first textarea, which is a XML snippet, from the HTML. Without any change to the original snippet. I'm able to get it by using the BeautifulSoup, but it changes all the tag names into lower case. A: Try using the BeautifulStoneSoup part of the BeautifulSoup library, which is designed for XML. A: Perhaps lxml would work, although I've never used it myself so I don't know how easy/complicated it would be to do what you want. A: (Ugh! Why do so many authors seem to think <textarea> content doesn't need HTML-escaping? Fools!) Unfortunately BeautifulSoup 3.1 is not applying the (incorrect but common) browser-fixup of treating < and & characters inside <textarea> as text, and is instead creating real XML elements. BeautifulSoup 3.0 copes with it OK though. Why there's a difference. A: Well I just tried beautifulSoup 3.0, and it doesn't work for me: xml ='<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"></samlp:Resonse>' print BeautifulSoup.BeautifulStoneSoup(xml) <samlp:response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" You will notice that the soup has changed Response to response A: Finally I found the pyparsing is the best weapon to accomplish the task: aStart,aEnd = makeHTMLTags("textarea") search = aStart + SkipTo(aEnd)("body")+ aEnd saml_resp_str = search.searchString(doc)[0].body relay_state_str = search.searchString(doc)[1].body
Python: How to extract xml embedded in a html file?
I have a html file with xml snipped embedded, the source code is pasted in the pastbin: <html> <head> <title> test֤</title> </head> <body> <form name="acsForm" action="" method="post" > <textarea rows=10 cols=80 name="xmlText"><?xml version="1.0" encoding="UTF-8"?> <samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"> </samlp:Response> </textarea> <textarea name="2nd"> text2....</textarea> </form> </body> </html> My task is to extract the text enclosed in the first textarea, which is a XML snippet, from the HTML. Without any change to the original snippet. I'm able to get it by using the BeautifulSoup, but it changes all the tag names into lower case.
[ "Try using the BeautifulStoneSoup part of the BeautifulSoup library, which is designed for XML.\n", "Perhaps lxml would work, although I've never used it myself so I don't know how easy/complicated it would be to do what you want.\n", "(Ugh! Why do so many authors seem to think <textarea> content doesn't need HTML-escaping? Fools!)\nUnfortunately BeautifulSoup 3.1 is not applying the (incorrect but common) browser-fixup of treating < and & characters inside <textarea> as text, and is instead creating real XML elements.\nBeautifulSoup 3.0 copes with it OK though. Why there's a difference.\n", "Well I just tried beautifulSoup 3.0, and it doesn't work for me:\nxml ='<samlp:Response xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\"></samlp:Resonse>'\nprint BeautifulSoup.BeautifulStoneSoup(xml)\n<samlp:response xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\"\n\nYou will notice that the soup has changed Response to response\n", "Finally I found the pyparsing is the best weapon to accomplish the task:\naStart,aEnd = makeHTMLTags(\"textarea\")\nsearch = aStart + SkipTo(aEnd)(\"body\")+ aEnd\nsaml_resp_str = search.searchString(doc)[0].body\nrelay_state_str = search.searchString(doc)[1].body\n" ]
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "screen_scraping", "xml" ]
stackoverflow_0002717363_python_screen_scraping_xml.txt
Q: What's the best way to join an array into a readable list? I've got an array listing days of the week: days = ['Monday', 'Tuesday', 'Wednesday'] What's the easiest / best way to output it in a human readable format: Monday, Tuesday and Wednesday The best I have is rather ugly: ', '.join(days[:-2]+['']) + ' and '.join(days[-2:]) A: Here is what I would do: '%s and %s' % (', '.join(days[:-1]), days[-1]) I am not sure it's pretty, but I am not sure it has to be either. :) A: Why is everyone trying to force-fit this into a single expression? def comma_separated(lst): """ >>> comma_separated(['a']) 'a' >>> comma_separated(['a', 'b']) 'a and b' >>> comma_separated(['a', 'b', 'c']) 'a, b and c' """ if len(lst) == 1: return lst[0] comma_part = ", ".join(lst[:-1]) return "%s and %s" % (comma_part, lst[-1]) if __name__ == "__main__": import doctest doctest.testmod() And remember, this is specific to English (and aside from "and", probably some other Western languages). Other languages have entirely different rules. A: I would make a lambda/function once and then just re-use it. def days(*d): ''.join([i + ((n < len(d) - 2 and ', ') or ' and ') for n, i in enumerate(d)])[:-5] + '.' print days('Monday', 'Tuesday', 'Wednesday') >>> Monday, Tuesday and Wednesday. print days('Monday', 'Tuesday') >>> Monday and Tuesday. print days('Monday', 'Tuesday') >>> Monday. Works for every combination too :)
What's the best way to join an array into a readable list?
I've got an array listing days of the week: days = ['Monday', 'Tuesday', 'Wednesday'] What's the easiest / best way to output it in a human readable format: Monday, Tuesday and Wednesday The best I have is rather ugly: ', '.join(days[:-2]+['']) + ' and '.join(days[-2:])
[ "Here is what I would do:\n'%s and %s' % (', '.join(days[:-1]), days[-1])\n\nI am not sure it's pretty, but I am not sure it has to be either. :)\n", "Why is everyone trying to force-fit this into a single expression?\ndef comma_separated(lst):\n \"\"\"\n >>> comma_separated(['a'])\n 'a'\n >>> comma_separated(['a', 'b'])\n 'a and b'\n >>> comma_separated(['a', 'b', 'c'])\n 'a, b and c'\n \"\"\"\n if len(lst) == 1:\n return lst[0]\n comma_part = \", \".join(lst[:-1])\n return \"%s and %s\" % (comma_part, lst[-1])\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n\nAnd remember, this is specific to English (and aside from \"and\", probably some other Western languages). Other languages have entirely different rules.\n", "I would make a lambda/function once and then just re-use it.\ndef days(*d):\n ''.join([i + ((n < len(d) - 2 and ', ') or ' and ') for n, i in enumerate(d)])[:-5] + '.'\n\nprint days('Monday', 'Tuesday', 'Wednesday')\n>>> Monday, Tuesday and Wednesday.\n\nprint days('Monday', 'Tuesday')\n>>> Monday and Tuesday.\n\nprint days('Monday', 'Tuesday')\n>>> Monday.\n\nWorks for every combination too :)\n" ]
[ 6, 2, 0 ]
[ "you really don't need that second join() in your 'best' sample. you can rewrite it this way:\n', '.join(days[:-1])+' and '+days[-1]\n\npersonally, i always prefer calling the class method, because i find the syntax closer to the intent:\nstr.join(', ',days[:-1])+' and '+days[-1]\n\n" ]
[ -1 ]
[ "join", "python", "string" ]
stackoverflow_0002723998_join_python_string.txt
Q: Sending email from an web2py on GAE I am trying to send a mail from my web2py app hosted on GoogleAppEngine. But it is not working. I used the mail function that was given with the web2py. Does anybody how to do this? I read in the GAE Documentation that python mail library would not work with GAE and GAE mail library has to be used. Does it also applies to web2py mail? Thanks A: The web2py gluon.tools.Mail class (that is used by the Auth module too) works on GAE and non-GAE out of the box. You just need to pass the correct settings: mail=Mail() mail.settings.server="smtp.example.com:25" or "gae" mail.settings.sender="you@example.com" mail.settings.tls=True or False mail.settings.login="you:password" It supports multiple encodings, MIME and attachments. A: The web2py gluon.tools.Mail class works on GAE. See code snippet gluon.tools line 310 try: if self.settings.server == 'gae': from google.appengine.api import mail result = mail.send_mail(sender=self.settings.sender, to=to, subject=subject, body=text) This is the correct settings to work on GAE mail=Mail() mail.settings.server="gae" mail.settings.sender="you@example.com" #This must be the email address of a registered #administrator for the application, or the address #of the current signed-in user. mail.settings.login="you:password" See http://code.google.com/intl/en/appengine/docs/python/mail/emailmessagefields.html sender The email address of the sender, the From address. This must be the email address of a registered administrator for the application, or the address of the current signed-in user. Administrators can be added to an application using the Administration Console. The current user's email address can be determined with the Users API. Sorry! My english is very poor. I hope to help. Celso Godinho (celso.gcosta@gmail.com) Brazil World Cup champion soccer 2010
Sending email from an web2py on GAE
I am trying to send a mail from my web2py app hosted on GoogleAppEngine. But it is not working. I used the mail function that was given with the web2py. Does anybody how to do this? I read in the GAE Documentation that python mail library would not work with GAE and GAE mail library has to be used. Does it also applies to web2py mail? Thanks
[ "The web2py gluon.tools.Mail class (that is used by the Auth module too) works on GAE and non-GAE out of the box. You just need to pass the correct settings:\nmail=Mail()\nmail.settings.server=\"smtp.example.com:25\" or \"gae\"\nmail.settings.sender=\"you@example.com\"\nmail.settings.tls=True or False\nmail.settings.login=\"you:password\"\n\nIt supports multiple encodings, MIME and attachments.\n", "The web2py gluon.tools.Mail class works on GAE.\nSee code snippet gluon.tools\nline 310\n try:\n if self.settings.server == 'gae':\n from google.appengine.api import mail\n result = mail.send_mail(sender=self.settings.sender, to=to,\n subject=subject, body=text)\n\nThis is the correct settings to work on GAE\nmail=Mail()\nmail.settings.server=\"gae\"\nmail.settings.sender=\"you@example.com\" #This must be the email address of a registered\n #administrator for the application, or the address \n #of the current signed-in user. \nmail.settings.login=\"you:password\"\n\nSee \nhttp://code.google.com/intl/en/appengine/docs/python/mail/emailmessagefields.html\nsender\n The email address of the sender, the From address. This must be the email address of a registered administrator for the application, or the address of the current signed-in user. Administrators can be added to an application using the Administration Console. The current user's email address can be determined with the Users API. \nSorry! My english is very poor. I hope to help.\nCelso Godinho (celso.gcosta@gmail.com)\nBrazil World Cup champion soccer 2010\n" ]
[ 5, 3 ]
[ "You should use the native App Engine mailer:\nhttp://code.google.com/appengine/docs/python/mail/sendingmail.html\n" ]
[ -1 ]
[ "google_app_engine", "python", "web2py" ]
stackoverflow_0002656068_google_app_engine_python_web2py.txt
Q: Reading colors from a config file with ConfigParser to use with Pygame In the config file I have the variable defined as BackgroundColor = 0,0,0 Which should work for the screen.fill settings for Pygame or any color argument for that matter. Where I can just do screen.fill(0,0,0) The problem I think is with this is that for integers read through a configfile I have to put int() to convert the string to an int. For something like colors int doesnt work and I have no idea what should be used. TypeError: invalid color argument That's the error from python. A: You've got a string representing the color, e.g. '0,0,0'. Use split(',') to split it into separate fields, then convert each one. e.g. color = '255, 255, 255' red, green, blue = color.split(',') red = int(red) green = int(green) blue = int(blue) Or if you want to do it in one step and the comprehensions don't bother you: color = '128, 128, 128' red, green, blue = [int(c) for c in color.split(',')]
Reading colors from a config file with ConfigParser to use with Pygame
In the config file I have the variable defined as BackgroundColor = 0,0,0 Which should work for the screen.fill settings for Pygame or any color argument for that matter. Where I can just do screen.fill(0,0,0) The problem I think is with this is that for integers read through a configfile I have to put int() to convert the string to an int. For something like colors int doesnt work and I have no idea what should be used. TypeError: invalid color argument That's the error from python.
[ "You've got a string representing the color, e.g. '0,0,0'. Use split(',') to split it into separate fields, then convert each one.\ne.g.\ncolor = '255, 255, 255'\nred, green, blue = color.split(',')\nred = int(red)\ngreen = int(green)\nblue = int(blue)\n\nOr if you want to do it in one step and the comprehensions don't bother you:\ncolor = '128, 128, 128'\nred, green, blue = [int(c) for c in color.split(',')]\n\n" ]
[ 2 ]
[]
[]
[ "configparser", "pygame", "python" ]
stackoverflow_0002725806_configparser_pygame_python.txt
Q: Am I correctly extracting JPEG binary data from this mysqldump? I have a very old .sql backup of a vbulletin site that I ran around 8 years ago. I am trying to see the file attachments that are stored in the DB. The script below extracts them all and is verified to be JPEG by hex dumping and checking the SOI (start of image) and EOI (end of image) bytes (FFD8 and FFD9, respectively) according to the JPEG wiki page. But when I try to open them with evince, I get this message "Error interpreting JPEG image file (JPEG datastream contains no image)" What could be going on here? Some background info: sqldump is around 8 years old vbulletin 2.x was the software that stored the info most likely php 4 was used most likely mysql 4.0, possibly even 3.x the column datatype these attachments are stored in is mediumtext My Python 3.1 script: #!/usr/bin/env python3.1 import re trim_l = re.compile(b"""^INSERT INTO attachment VALUES\('\d+', '\d+', '\d+', '(.+)""") trim_r = re.compile(b"""(.+)', '\d+', '\d+'\);$""") extractor = re.compile(b"""^(.*(?:\.jpe?g|\.gif|\.bmp))', '(.+)$""") with open('attachments.sql', 'rb') as fh: for line in fh: data = trim_l.findall(line)[0] data = trim_r.findall(data)[0] data = extractor.findall(data) if data: name, data = data[0] try: filename = 'files/%s' % str(name, 'UTF-8') ah = open(filename, 'wb') ah.write(data) except UnicodeDecodeError: continue finally: ah.close() fh.close() update The JPEG wiki page says FF bytes are section markers, with the next byte indicating the section type. I see some that are not listed in the wiki page (specifically, I see a lot of 5C bytes, so FF5C). But the list is of "common markers" so I'm trying to find a more complete list. Any guidance here would also be appreciated. A: Update your question with a sample SQL statement, including a few lines/bytes of the JPEG string value. Perhaps the data is base64 encoded, or even straight hex values. We'll help you further. Also, it's easier to see the type of a file's contents by issuing a: file yourfile.jpg
Am I correctly extracting JPEG binary data from this mysqldump?
I have a very old .sql backup of a vbulletin site that I ran around 8 years ago. I am trying to see the file attachments that are stored in the DB. The script below extracts them all and is verified to be JPEG by hex dumping and checking the SOI (start of image) and EOI (end of image) bytes (FFD8 and FFD9, respectively) according to the JPEG wiki page. But when I try to open them with evince, I get this message "Error interpreting JPEG image file (JPEG datastream contains no image)" What could be going on here? Some background info: sqldump is around 8 years old vbulletin 2.x was the software that stored the info most likely php 4 was used most likely mysql 4.0, possibly even 3.x the column datatype these attachments are stored in is mediumtext My Python 3.1 script: #!/usr/bin/env python3.1 import re trim_l = re.compile(b"""^INSERT INTO attachment VALUES\('\d+', '\d+', '\d+', '(.+)""") trim_r = re.compile(b"""(.+)', '\d+', '\d+'\);$""") extractor = re.compile(b"""^(.*(?:\.jpe?g|\.gif|\.bmp))', '(.+)$""") with open('attachments.sql', 'rb') as fh: for line in fh: data = trim_l.findall(line)[0] data = trim_r.findall(data)[0] data = extractor.findall(data) if data: name, data = data[0] try: filename = 'files/%s' % str(name, 'UTF-8') ah = open(filename, 'wb') ah.write(data) except UnicodeDecodeError: continue finally: ah.close() fh.close() update The JPEG wiki page says FF bytes are section markers, with the next byte indicating the section type. I see some that are not listed in the wiki page (specifically, I see a lot of 5C bytes, so FF5C). But the list is of "common markers" so I'm trying to find a more complete list. Any guidance here would also be appreciated.
[ "Update your question with a sample SQL statement, including a few lines/bytes of the JPEG string value. Perhaps the data is base64 encoded, or even straight hex values. We'll help you further.\nAlso, it's easier to see the type of a file's contents by issuing a:\nfile yourfile.jpg\n\n" ]
[ 1 ]
[]
[]
[ "jpeg", "mysql", "python" ]
stackoverflow_0002723973_jpeg_mysql_python.txt
Q: mouse rollover event in Python (VPython) Is there something similar to scene.mouse.getclick in the visual module (VPython)? I need it for a rollover. Thanks in advance. EDIT: I need a function for doing something when the mouse moves inside a special area without clicking. A: As mentioned by mathmike, it would seem that you could use scene.mouse.pick to get the object that is currently under the mouse, and as for the 'scene-position', I think scene.mouse.pickpos is what you're looking for - if not, you should be able to calculate it from the global mouse position (through getEvent()). Otherwise, look at getting your information from the getEvent() function, and possibly writing an event loop for yourself. A: Well, do you mean the scene.mouse.getclick() described here in the documentation? I don't know what you mean by Is there something similar... What are you looking for? A: scene.mouse.getclick will tell you where the mouse was when it was last clicked. This is different from scene.mouse.clicked which tells you if someone clicked. There is no correspoding way to see if someone had their mouse over a particular object. One thing you can do is use a while loop that continually checks scene.mouse.pick to see if it is the mouse is currently over an object of interest.
mouse rollover event in Python (VPython)
Is there something similar to scene.mouse.getclick in the visual module (VPython)? I need it for a rollover. Thanks in advance. EDIT: I need a function for doing something when the mouse moves inside a special area without clicking.
[ "As mentioned by mathmike, it would seem that you could use scene.mouse.pick to get the object that is currently under the mouse, and as for the 'scene-position', I think scene.mouse.pickpos is what you're looking for - if not, you should be able to calculate it from the global mouse position (through getEvent()). \nOtherwise, look at getting your information from the getEvent() function, and possibly writing an event loop for yourself.\n", "Well, do you mean the scene.mouse.getclick() described here in the documentation?\nI don't know what you mean by\n\nIs there something similar...\n\nWhat are you looking for?\n", "scene.mouse.getclick will tell you where the mouse was when it was last clicked. This is different from scene.mouse.clicked which tells you if someone clicked.\nThere is no correspoding way to see if someone had their mouse over a particular object. One thing you can do is use a while loop that continually checks scene.mouse.pick to see if it is the mouse is currently over an object of interest.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "mouseevent", "python", "rollover", "vpython" ]
stackoverflow_0002655747_mouseevent_python_rollover_vpython.txt
Q: Can I get the amount of time for which a key is pressed on a keyboard I am working on a project in which I have to develop bio-passwords based on user's keystroke style. Suppose a user types a password for 20 times, his keystrokes are recorded, like holdtime : time for which a particular key is pressed. digraph time : time it takes to press a different key. suppose a user types a password " COMPUTER". I need to know the time for which every key is pressed. something like : holdtime for the above password is C-- 200ms O-- 130ms M-- 150ms P-- 175ms U-- 320ms T-- 230ms E-- 120ms R-- 300ms The rational behind this is , every user will have a different holdtime. Say a old person is typing the password, he will take more time then a student. And it will be unique to a particular person. To do this project, I need to record the time for each key pressed. I would greatly appreciate if anyone can guide me in how to get these times. Editing from here.. Language is not important, but I would prefer it in C. I am more interested in getting the dataset. A: Record the KeyDown and KeyUp events, and do a diff on the timestamps of each. http://code.activestate.com/recipes/203830/ Edit: You may want to check out wxPython, it should help you out: http://www.wxpython.org/onlinedocs.php in particular: http://docs.wxwidgets.org/stable/wx_wxkeyevent.html#wxkeyevent A: You mentioned you'd prefer it in C, but since you tagged it Python... :) Also, since you say you're looking for building a dataset, I assume you'll have to invite users to type in arbitrary text, so you'll need some sort of interface (graphical or otherwise). Here's a quick example using pygame. You can trivially modify it to ask users to type specific words, but, as it is, it'll just let the user type in arbitrary text, record pressing times for all keypresses, and print each hold and digraph times, in the order that the user typed it, when it exits (i.e., when the user presses Esc). As Kibibu noticed, showing the user what he's typing in realtime introduces a delay which might mask real key-pressing times, so this code only displays what the user has typed when he types "Enter". Update: it now calculates digraph as well as hold times (excluding Enter in both cases). Update2: Per Adi's request, changed from displaying average to displaying each individual time, in order. import sys from collections import defaultdict from time import time import pygame from pygame.key import name as keyname from pygame.locals import * # Mapping of a key to a list of holdtimes (from which you can average, etc) holdtimes = defaultdict(list) # Mapping of a key pair to a list of digraph times digraphs = defaultdict(list) # Keys which have been pressed down, but not up yet. pending = {} # Last key to be de-pressed, corresponding time). last_key = None # Text that the user has typed so far (one sublist for every Enter pressed) typed_text = [[]] def show_times(): all_text = [k for line in typed_text for k in line] print "Holdtimes:" for key in all_text: print "%s: %.5f" % (key, holdtimes[key].pop(0)) print "Digraphs:" for key1, key2 in zip(all_text, all_text[1:]): print "(%s, %s): %.5f" % (key1, key2, digraphs[(key1, key2)].pop(0)) def time_keypresses(events): global last_key for event in events: if event.type == KEYDOWN: # ESC exits the program if event.key == K_ESCAPE: show_times() sys.exit(0) t = pending[event.key] = time() if last_key is not None: if event.key != K_RETURN: digraphs[(last_key[0], keyname(event.key))].append(t - last_key[1]) last_key = None elif event.type == KEYUP: if event.key == K_RETURN: update_screen() typed_text.append([]) pending.pop(event.key) last_key = None else: t = time() holdtimes[keyname(event.key)].append(t - pending.pop(event.key)) last_key = [keyname(event.key), t] typed_text[-1].append(keyname(event.key)) # Any other event handling you might have would go here... def update_screen(): global screen screen.fill((255, 255, 255)) header_font = pygame.font.Font(None, 42) header = header_font.render("Type away! Press 'Enter' to show.", True, (0, 0, 0)) header_rect = header.get_rect() header_rect.centerx = screen.get_rect().centerx header_rect.centery = screen.get_rect().centery - 100 text_font = pygame.font.Font(None, 32) user_text = text_font.render("".join(typed_text[-1]) if typed_text[-1] else "...", True, (0, 0, 255)) text_rect = user_text.get_rect() text_rect.centerx = screen.get_rect().centerx text_rect.centery = screen.get_rect().centery screen.blit(header, header_rect) screen.blit(user_text, text_rect) pygame.display.update() if __name__ == '__main__': pygame.init() window = pygame.display.set_mode((800, 600)) screen = pygame.display.get_surface() update_screen() while True: time_keypresses(pygame.event.get()) A: Have a look at ncurses. It is a terrific tool for getting information about keypresses in the terminal. Have a look at this link too. A: If you read from the terminal in conical mode, you can read each keystroke as it's pressed. You won't see keydown keyup events, like you could if you trapped X events, but it's probably easier, especially if you're just running in a console or terminal. A: The answer is conditionally "yes". If your languages/environment has interactive keyboard support that offers Key-Down and Key-Up events, then you catch both events and time the difference between them. This would be trivially easy in JavaScript on a web page, which would also be the easiest way to show off your work to a wider audience.
Can I get the amount of time for which a key is pressed on a keyboard
I am working on a project in which I have to develop bio-passwords based on user's keystroke style. Suppose a user types a password for 20 times, his keystrokes are recorded, like holdtime : time for which a particular key is pressed. digraph time : time it takes to press a different key. suppose a user types a password " COMPUTER". I need to know the time for which every key is pressed. something like : holdtime for the above password is C-- 200ms O-- 130ms M-- 150ms P-- 175ms U-- 320ms T-- 230ms E-- 120ms R-- 300ms The rational behind this is , every user will have a different holdtime. Say a old person is typing the password, he will take more time then a student. And it will be unique to a particular person. To do this project, I need to record the time for each key pressed. I would greatly appreciate if anyone can guide me in how to get these times. Editing from here.. Language is not important, but I would prefer it in C. I am more interested in getting the dataset.
[ "Record the KeyDown and KeyUp events, and do a diff on the timestamps of each.\nhttp://code.activestate.com/recipes/203830/\nEdit:\nYou may want to check out wxPython, it should help you out:\nhttp://www.wxpython.org/onlinedocs.php\nin particular:\nhttp://docs.wxwidgets.org/stable/wx_wxkeyevent.html#wxkeyevent\n", "You mentioned you'd prefer it in C, but since you tagged it Python... :)\nAlso, since you say you're looking for building a dataset, I assume you'll have to invite users to type in arbitrary text, so you'll need some sort of interface (graphical or otherwise).\nHere's a quick example using pygame. You can trivially modify it to ask users to type specific words, but, as it is, it'll just let the user type in arbitrary text, record pressing times for all keypresses, and print each hold and digraph times, in the order that the user typed it, when it exits (i.e., when the user presses Esc).\nAs Kibibu noticed, showing the user what he's typing in realtime introduces a delay which might mask real key-pressing times, so this code only displays what the user has typed when he types \"Enter\".\nUpdate: it now calculates digraph as well as hold times (excluding Enter in both cases).\nUpdate2: Per Adi's request, changed from displaying average to displaying each individual time, in order.\nimport sys\nfrom collections import defaultdict\nfrom time import time\nimport pygame\nfrom pygame.key import name as keyname\nfrom pygame.locals import *\n\n# Mapping of a key to a list of holdtimes (from which you can average, etc)\nholdtimes = defaultdict(list)\n# Mapping of a key pair to a list of digraph times\ndigraphs = defaultdict(list)\n# Keys which have been pressed down, but not up yet.\npending = {}\n# Last key to be de-pressed, corresponding time).\nlast_key = None\n# Text that the user has typed so far (one sublist for every Enter pressed)\ntyped_text = [[]]\n\ndef show_times():\n all_text = [k for line in typed_text for k in line]\n print \"Holdtimes:\"\n for key in all_text:\n print \"%s: %.5f\" % (key, holdtimes[key].pop(0))\n\n print \"Digraphs:\"\n for key1, key2 in zip(all_text, all_text[1:]):\n print \"(%s, %s): %.5f\" % (key1, key2,\n digraphs[(key1, key2)].pop(0))\n\ndef time_keypresses(events):\n global last_key\n for event in events:\n if event.type == KEYDOWN:\n # ESC exits the program\n if event.key == K_ESCAPE:\n show_times()\n sys.exit(0)\n\n t = pending[event.key] = time()\n if last_key is not None:\n if event.key != K_RETURN:\n digraphs[(last_key[0], keyname(event.key))].append(t - last_key[1])\n last_key = None\n elif event.type == KEYUP:\n if event.key == K_RETURN:\n update_screen()\n typed_text.append([])\n pending.pop(event.key)\n last_key = None\n else:\n t = time()\n holdtimes[keyname(event.key)].append(t - pending.pop(event.key))\n last_key = [keyname(event.key), t]\n typed_text[-1].append(keyname(event.key))\n # Any other event handling you might have would go here...\n\ndef update_screen():\n global screen\n screen.fill((255, 255, 255))\n\n header_font = pygame.font.Font(None, 42)\n header = header_font.render(\"Type away! Press 'Enter' to show.\", True, (0, 0, 0))\n header_rect = header.get_rect()\n header_rect.centerx = screen.get_rect().centerx\n header_rect.centery = screen.get_rect().centery - 100\n\n text_font = pygame.font.Font(None, 32)\n user_text = text_font.render(\"\".join(typed_text[-1]) if typed_text[-1] else \"...\",\n True, (0, 0, 255))\n text_rect = user_text.get_rect()\n text_rect.centerx = screen.get_rect().centerx\n text_rect.centery = screen.get_rect().centery \n\n screen.blit(header, header_rect)\n screen.blit(user_text, text_rect)\n\n pygame.display.update()\n\n\nif __name__ == '__main__':\n pygame.init()\n window = pygame.display.set_mode((800, 600))\n screen = pygame.display.get_surface()\n update_screen()\n while True:\n time_keypresses(pygame.event.get())\n\n", "Have a look at ncurses. It is a terrific tool for getting information about keypresses in the terminal.\nHave a look at this link too.\n", "If you read from the terminal in conical mode, you can read each keystroke as it's pressed. You won't see keydown keyup events, like you could if you trapped X events, but it's probably easier, especially if you're just running in a console or terminal.\n", "The answer is conditionally \"yes\".\nIf your languages/environment has interactive keyboard support that offers Key-Down and Key-Up events, then you catch both events and time the difference between them.\nThis would be trivially easy in JavaScript on a web page, which would also be the easiest way to show off your work to a wider audience.\n" ]
[ 6, 3, 2, 0, 0 ]
[]
[]
[ "c", "c++", "linux", "python", "unix" ]
stackoverflow_0002726176_c_c++_linux_python_unix.txt
Q: how to use @ in python.. and the @property and the @classmethod this is my code: def a(): print 'sss' @a() def b(): print 'aaa' b() and the Traceback is: sss Traceback (most recent call last): File "D:\zjm_code\a.py", line 8, in <module> @a() TypeError: 'NoneType' object is not callable so how to use the '@' thanks updated class a: @property def b(x): print 'sss' aa=a() print aa.b it print : sss None how to use @property thanks updated2 and the classmethod: class a: @classmethod def b(x): print 'sss' aa=a() print aa.b the it print : <bound method classobj.b of <class __main__.a at 0x00B2DC00>> A: A decorator needs to be a callable object (either a function or an object implementing __call__), where the parameter is the function that has been decorated, and the result is a function that will replace the function that has been decorated, so, to use your example of printing 'sss' instead of printing 'aaa': >>> def a(f): ... def replacementfunc(): ... print 'sss' ... return replacementfunc; ... >>> @a ... def b(): ... print 'aaa' ... >>> b() sss Or, a more elaborate example: >>> class print_decorator(object): ... def __init__(self,text): ... self.text = text; ... def __call__(self,f): ... def replacement(): ... print self.text; ... return replacement; ... >>> @print_decorator("Hello world!") ... def b(): ... print 'aaa'; ... >>> b() Hello world! Edit As for your updated question, you need to look at the documentation for @property. It's not clear exactly what you are trying to accomplish, although my guess is that you want: class a: @property def b(self): return 'sss' aa=a() print aa.b # prints 'sss', whereas without @property, prints <function ... > A: The line @a() means "a is a callable, returning some other callable, which can be called with a function as its only argument and will return a callable". If you're not familiar with the term callable, it's just a generalization of function: it can be a function, a class, or an instance of a class that has a __call__ method. Your def a is returning None, so you're clearly violating the "decorator contract" that you're requesting with the @a() syntax. If you just used @a, without the (), then a would have to accept the function as its argument and return a callable. I'm not sure what you're trying to accomplish, but if it's just "print something in a decorator for a function, then this would work: def a(): print 'sss' return lambda f: f Now you can use @a() and live happily ever after, since this version does respect the "decorator contract" I explained in the first paragraph.
how to use @ in python.. and the @property and the @classmethod
this is my code: def a(): print 'sss' @a() def b(): print 'aaa' b() and the Traceback is: sss Traceback (most recent call last): File "D:\zjm_code\a.py", line 8, in <module> @a() TypeError: 'NoneType' object is not callable so how to use the '@' thanks updated class a: @property def b(x): print 'sss' aa=a() print aa.b it print : sss None how to use @property thanks updated2 and the classmethod: class a: @classmethod def b(x): print 'sss' aa=a() print aa.b the it print : <bound method classobj.b of <class __main__.a at 0x00B2DC00>>
[ "A decorator needs to be a callable object (either a function or an object implementing __call__), where the parameter is the function that has been decorated, and the result is a function that will replace the function that has been decorated, so, to use your example of printing 'sss' instead of printing 'aaa':\n\n>>> def a(f):\n... def replacementfunc():\n... print 'sss'\n... return replacementfunc;\n... \n>>> @a\n... def b():\n... print 'aaa'\n... \n>>> b()\nsss\n\n\nOr, a more elaborate example:\n\n>>> class print_decorator(object):\n... def __init__(self,text):\n... self.text = text;\n... def __call__(self,f):\n... def replacement():\n... print self.text;\n... return replacement;\n... \n>>> @print_decorator(\"Hello world!\")\n... def b():\n... print 'aaa';\n... \n>>> b()\nHello world!\n\nEdit\nAs for your updated question, you need to look at the documentation for @property. It's not clear exactly what you are trying to accomplish, although my guess is that you want:\n\nclass a:\n @property\n def b(self):\n return 'sss'\n\naa=a()\nprint aa.b # prints 'sss', whereas without @property, prints <function ... >\n\n", "The line @a() means \"a is a callable, returning some other callable, which can be called with a function as its only argument and will return a callable\". If you're not familiar with the term callable, it's just a generalization of function: it can be a function, a class, or an instance of a class that has a __call__ method.\nYour def a is returning None, so you're clearly violating the \"decorator contract\" that you're requesting with the @a() syntax.\nIf you just used @a, without the (), then a would have to accept the function as its argument and return a callable.\nI'm not sure what you're trying to accomplish, but if it's just \"print something in a decorator for a function, then this would work:\ndef a():\n print 'sss'\n return lambda f: f\n\nNow you can use @a() and live happily ever after, since this version does respect the \"decorator contract\" I explained in the first paragraph.\n" ]
[ 8, 4 ]
[]
[]
[ "python" ]
stackoverflow_0002726345_python.txt
Q: Add a value to an element in a list of sets I'm using python, and I have a list of sets, constructed like this: list = [set([])]*n ...where n is the number of sets I want in the list. I want to add a value to a specific set in the list. Say, the second set. I tried list[1].add(value) But this instead adds the value to each set in the list. This behaviour is pretty non-intuitive to me. Through further tests, I think I've found the problem: the list apparently contains 10 instances of the same set, or ten pointers to the same set, or something. Constructing the list through repeated calls of list.append(set([])) allowed me to use the syntax above to add elements to single sets. So my question is this: what exactly is going on in my first list-construction technique? It is clear I don't understand the syntax so well. Also, is there a better way to intialize an n-element list? I've been using this syntax for a while and this is my first problem with it. A: You've pretty much summarized the problem yourself -- the X*n syntax makes one instance of X and includes it n times. It's not a problem for things like 'a'*10 because it doesn't matter if every character in that string happens to point to the same 'a', but it does for mutable constructions like lists and sets. You can make n separate sets using a list comprehension: list = [set() for x in xrange(n)] A: Yes, that is correct. The * syntax is simply copying the reference that many times. Your method works fine, or you can use a list comprehension to construct that many sets as in: list = [set([]) for x in xrange(n)];
Add a value to an element in a list of sets
I'm using python, and I have a list of sets, constructed like this: list = [set([])]*n ...where n is the number of sets I want in the list. I want to add a value to a specific set in the list. Say, the second set. I tried list[1].add(value) But this instead adds the value to each set in the list. This behaviour is pretty non-intuitive to me. Through further tests, I think I've found the problem: the list apparently contains 10 instances of the same set, or ten pointers to the same set, or something. Constructing the list through repeated calls of list.append(set([])) allowed me to use the syntax above to add elements to single sets. So my question is this: what exactly is going on in my first list-construction technique? It is clear I don't understand the syntax so well. Also, is there a better way to intialize an n-element list? I've been using this syntax for a while and this is my first problem with it.
[ "You've pretty much summarized the problem yourself -- the X*n syntax makes one instance of X and includes it n times. It's not a problem for things like 'a'*10 because it doesn't matter if every character in that string happens to point to the same 'a', but it does for mutable constructions like lists and sets. You can make n separate sets using a list comprehension:\nlist = [set() for x in xrange(n)]\n\n", "Yes, that is correct. The * syntax is simply copying the reference that many times. Your method works fine, or you can use a list comprehension to construct that many sets as in:\n\nlist = [set([]) for x in xrange(n)];\n\n" ]
[ 5, 1 ]
[]
[]
[ "mutable", "python" ]
stackoverflow_0002726418_mutable_python.txt
Q: Look of the app - Py2exe / wxPython So my problem is the look and feel from my application, as it looks like an old look app. It is an wxPython application, and on python it runs fine and looks fine, but when I convert it to .exe using py2exe, the look is just bad. Now I know that if you are using XP you need some manifest to correct it but I am in other circumstances. I'm using Windows 7, and I'm using Python 2.6 (Yes, I am including the DLL's and the Microsoft.VC90.CRT.manifest). So my question is how can I solve this under these circumstances? NOTE: I tried to search on google, but the posts I found were rather old with people using XP and older python versions so I assumed it would be different? EDIT: Screenshots Normal (wanted look) : http://img80.imageshack.us/img80/3157/70762988.png Py2exe (unwanted look) : http://img687.imageshack.us/img687/6581/53608742.jpg A: Try use Gui2exe I use gui2exe on win7 running on virtualbox. This make gui look ok on all windows version. upx.exe to compress exe,dll,pyd. And inno-setup,for a setup fil for windows.
Look of the app - Py2exe / wxPython
So my problem is the look and feel from my application, as it looks like an old look app. It is an wxPython application, and on python it runs fine and looks fine, but when I convert it to .exe using py2exe, the look is just bad. Now I know that if you are using XP you need some manifest to correct it but I am in other circumstances. I'm using Windows 7, and I'm using Python 2.6 (Yes, I am including the DLL's and the Microsoft.VC90.CRT.manifest). So my question is how can I solve this under these circumstances? NOTE: I tried to search on google, but the posts I found were rather old with people using XP and older python versions so I assumed it would be different? EDIT: Screenshots Normal (wanted look) : http://img80.imageshack.us/img80/3157/70762988.png Py2exe (unwanted look) : http://img687.imageshack.us/img687/6581/53608742.jpg
[ "Try use Gui2exe\nI use gui2exe on win7 running on virtualbox.\nThis make gui look ok on all windows version.\nupx.exe to compress exe,dll,pyd.\nAnd inno-setup,for a setup fil for windows.\n" ]
[ 4 ]
[]
[]
[ "look_and_feel", "py2exe", "python", "wxpython" ]
stackoverflow_0002725516_look_and_feel_py2exe_python_wxpython.txt
Q: Fastest way to make a dict a single comma-separated string I have a list of uids: ['1234','4321','1111'] and I would like to turn this into a single string of: "uid = '1234' OR uid = '4321' OR uid = '1111'" What's the most efficient way to do this? Thanks! A: ' OR '.join("uid = '%s'" % u for u in uids) This invokes the join function on the string ' OR ', which takes the list passed in and puts the string in between each element, then concatenates them all together. (Used to put the ORs in between each key=val pair.) The part inside the () is a comprehension that says "for each u in the uids list, generate a value equal to the string "uid = '%s'", but substitute in u instead of the %s marker". A: If—as Mike and Thomas mention in the comments—you need this for a database query, you should take Thomas' advice and use the DB-API. Here are two examples: MySQL import MySQLdb conn = MySQLdb.connect(host='localhost', user='u', passwd='p', db='mydb') curs = conn.cursor() uids = [1234,4321,1111] qry = ("""SELECT cheese FROM cheeseshop WHERE id IN (%s)""" % ','.join(['%s']*len(uids))) # 'SELECT cheese FROM cheeseshop WHERE id IN (%s,%s,%s)' curs.execute(qry, uids) curs.fetchone() # ... SQLite import sqlite3 conn = sqlite3.connect(':memory:') curs = conn.cursor() uids = [1234,4321,1111] qry = ("""SELECT cheese FROM cheeseshop WHERE id IN (%s)""" % ','.join('?'*len(uids))) # 'SELECT cheese FROM cheeseshop WHERE id IN (?,?,?)' curs.execute(qry, uids) curs.fetchone() # ...
Fastest way to make a dict a single comma-separated string
I have a list of uids: ['1234','4321','1111'] and I would like to turn this into a single string of: "uid = '1234' OR uid = '4321' OR uid = '1111'" What's the most efficient way to do this? Thanks!
[ "' OR '.join(\"uid = '%s'\" % u for u in uids)\n\nThis invokes the join function on the string ' OR ', which takes the list passed in and puts the string in between each element, then concatenates them all together. (Used to put the ORs in between each key=val pair.)\nThe part inside the () is a comprehension that says \"for each u in the uids list, generate a value equal to the string \"uid = '%s'\", but substitute in u instead of the %s marker\".\n", "If—as Mike and Thomas mention in the comments—you need this for a database query, you should take Thomas' advice and use the DB-API.\nHere are two examples: \nMySQL\nimport MySQLdb\nconn = MySQLdb.connect(host='localhost', user='u', passwd='p', db='mydb')\ncurs = conn.cursor()\nuids = [1234,4321,1111]\nqry = (\"\"\"SELECT cheese \n FROM cheeseshop \n WHERE id IN (%s)\"\"\" % ','.join(['%s']*len(uids)))\n# 'SELECT cheese FROM cheeseshop WHERE id IN (%s,%s,%s)'\ncurs.execute(qry, uids)\ncurs.fetchone()\n# ...\n\nSQLite\nimport sqlite3\nconn = sqlite3.connect(':memory:')\ncurs = conn.cursor()\nuids = [1234,4321,1111]\nqry = (\"\"\"SELECT cheese \n FROM cheeseshop \n WHERE id IN (%s)\"\"\" % ','.join('?'*len(uids)))\n# 'SELECT cheese FROM cheeseshop WHERE id IN (?,?,?)'\ncurs.execute(qry, uids)\ncurs.fetchone()\n# ...\n\n" ]
[ 9, 2 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002725912_python_string.txt
Q: List of objects or parallel arrays of properties? The question is, basically: what would be more preferable, both performance-wise and design-wise - to have a list of objects of a Python class or to have several lists of numerical properties? I am writing some sort of a scientific simulation which involves a rather large system of interacting particles. For simplicity, let's say we have a set of balls bouncing inside a box so each ball has a number of numerical properties, like x-y-z-coordinates, diameter, mass, velocity vector and so on. How to store the system better? Two major options I can think of are: to make a class "Ball" with those properties and some methods, then store a list of objects of the class, e. g. [b1, b2, b3, ...bn, ...], where for each bn we can access bn.x, bn.y, bn.mass and so on; to make an array of numbers for each property, then for each i-th "ball" we can access it's 'x' coordinate as xs[i], 'y' coordinate as ys[i], 'mass' as masses[i] and so on; To me it seems that the first option represents a better design. The second option looks somewhat uglier, but might be better in terms of performance, and it could be easier to use it with numpy and scipy, which I try to use as much as I can. I am still not sure if Python will be fast enough, so it may be necessary to rewrite it in C++ or something, after initial prototyping in Python. Would the choice of data representation be different for C/C++? What about a hybrid approach, e.g. Python with C++ extension? Update: I never expected any performance gain from parallel arrays per se, but in a mixed environment like Python + Numpy (or whatever SlowScriptingLanguage + FastNativeLibrary) using them may (or may not?) let you move more work out of you slow scripting code and into the fast native library. A: Having an object for each ball in this example is certainly better design. Parallel arrays are really a workaround for languages that do not support proper objects. I wouldn't use them in a language with OO capabilities unless it's a tiny case that fits within a function (and maybe not even then) or if I've run out of every other optimization option and the profiler shows that property access is the culprit. This applies twice as much to Python as to C++, as the former places a large emphasis on readability and elegance. A: I agree that parallel arrays are almost always a bad idea, but don't forget that you can use views into a numpy array when you're setting things, up, though... (Yes, I know this is effectively using parallel arrays, but I think it's the best option in this case...) This is great if you know the number of "balls" you're going to create beforehand, as you can allocate an array for the coordinates, and store a view into that array for each ball object. You have to be a bit careful to do operations in-place on the coords array, but it makes updating coordinates for numerous "balls" much, much, much faster. For example... import numpy as np class Ball(object): def __init__(self, coords): self.coords = coords def _set_coord(self, i, value): self.coords[i] = value x = property(lambda self: self.coords[0], lambda self, value: self._set_coord(0, value)) y = property(lambda self: self.coords[1], lambda self, value: self._set_coord(1, value)) def move(self, dx, dy): self.x += dx self.y += dy def main(): n_balls = 10 n_dims = 2 coords = np.zeros((n_balls, n_dims)) balls = [Ball(coords[i,:]) for i in range(n_balls)] # Just to illustrate that that the coords are updating ball = balls[0] # Random walk by updating coords array print 'Moving all the balls randomly by updating coords' for step in xrange(5): # Add a random value to all coordinates coords += 0.5 - np.random.random((n_balls, n_dims)) # Display the coords for a particular ball and the # corresponding row of the coords array print ' Value of ball.x, ball.y:', ball.x, ball.y print ' Value of coords[0,:]:', coords[0,:] # Move an individual ball object print 'Moving a ball individually through Ball.move()' ball.move(0.5, 0.5) print ' Value of ball.x, ball.y:', ball.x, ball.y print ' Value of coords[0,:]:', coords[0,:] main() Just to illustrate, this outputs something like: Moving all the balls randomly by updating coords Value of ball.x, ball.y: -0.125713650677 0.301692195466 Value of coords[0,:]: [-0.12571365 0.3016922 ] Value of ball.x, ball.y: -0.304516863495 -0.0447543559805 Value of coords[0,:]: [-0.30451686 -0.04475436] Value of ball.x, ball.y: -0.171589457954 0.334844443821 Value of coords[0,:]: [-0.17158946 0.33484444] Value of ball.x, ball.y: -0.0452864552743 -0.0297552313656 Value of coords[0,:]: [-0.04528646 -0.02975523] Value of ball.x, ball.y: -0.163829876915 0.0153203173857 Value of coords[0,:]: [-0.16382988 0.01532032] Moving a ball individually through Ball.move() Value of ball.x, ball.y: 0.336170123085 0.515320317386 Value of coords[0,:]: [ 0.33617012 0.51532032] The advantage here is that updating a single numpy array is going to be much, much faster than iterating through all of your ball objects, but you retain a more object-oriented approach. Just my thoughts on it, anyway.. EDIT: To give some idea of the speed difference, with 1,000,000 balls: In [104]: %timeit coords[:,0] += 1.0 100 loops, best of 3: 11.8 ms per loop In [105]: %timeit [item.x + 1.0 for item in balls] 1 loops, best of 3: 1.69 s per loop So, updating the coordinates directly using numpy is roughly 2 orders of magnitude faster when using a large number of balls. (the difference is smaller when using 10 balls, as per the example, roughly a factor of 2x, rather than 150x) A: I think it depends on what you're going to be doing with them, and how often you're going to be working with (all attributes of one particle) vs (one attribute of all particles). The former is better suited to the object approach; the latter is better suited to the array approach. I was facing a similar problem (although in a different domain) a couple of years ago. The project got deprioritized before I actually implemented this phase, but I was leaning towards a hybrid approach, where in addition to the Ball class I would have an Ensemble class. The Ensemble would not be a list or other simple container of Balls, but would have its own attributes (which would be arrays) and its own methods. Whether the Ensemble is created from the Balls, or the Balls from the Ensemble, depends on how you're going to construct them. One of my coworkers was arguing for a solution where the fundamental object was an Ensemble which might contain only one Ball, so that no calling code would ever have to know whether you were operating on just one Ball (do you ever do that for your application?) or on many. A: Will you be having any forces between the balls (hard sphere/collision, gravity, electromagnetic)? I'm guessing so. Will you be having a large enough number of balls to want to use Barnes-Hut simulation ideas? If so, then you should definitely use the Ball class idea so that you can store them easily in octrees or something else along those lines. Also, using the Barnes-Hut simulation will cut down the complexity of the simulation to O(N log N) from O(N^2). Really though, if you don't have forces between the balls or aren't using many balls, you don't need the possible speed gains from using parallel arrays and should go with the Ball class idea for that as well.
List of objects or parallel arrays of properties?
The question is, basically: what would be more preferable, both performance-wise and design-wise - to have a list of objects of a Python class or to have several lists of numerical properties? I am writing some sort of a scientific simulation which involves a rather large system of interacting particles. For simplicity, let's say we have a set of balls bouncing inside a box so each ball has a number of numerical properties, like x-y-z-coordinates, diameter, mass, velocity vector and so on. How to store the system better? Two major options I can think of are: to make a class "Ball" with those properties and some methods, then store a list of objects of the class, e. g. [b1, b2, b3, ...bn, ...], where for each bn we can access bn.x, bn.y, bn.mass and so on; to make an array of numbers for each property, then for each i-th "ball" we can access it's 'x' coordinate as xs[i], 'y' coordinate as ys[i], 'mass' as masses[i] and so on; To me it seems that the first option represents a better design. The second option looks somewhat uglier, but might be better in terms of performance, and it could be easier to use it with numpy and scipy, which I try to use as much as I can. I am still not sure if Python will be fast enough, so it may be necessary to rewrite it in C++ or something, after initial prototyping in Python. Would the choice of data representation be different for C/C++? What about a hybrid approach, e.g. Python with C++ extension? Update: I never expected any performance gain from parallel arrays per se, but in a mixed environment like Python + Numpy (or whatever SlowScriptingLanguage + FastNativeLibrary) using them may (or may not?) let you move more work out of you slow scripting code and into the fast native library.
[ "Having an object for each ball in this example is certainly better design. Parallel arrays are really a workaround for languages that do not support proper objects. I wouldn't use them in a language with OO capabilities unless it's a tiny case that fits within a function (and maybe not even then) or if I've run out of every other optimization option and the profiler shows that property access is the culprit. This applies twice as much to Python as to C++, as the former places a large emphasis on readability and elegance.\n", "I agree that parallel arrays are almost always a bad idea, but don't forget that you can use views into a numpy array when you're setting things, up, though... (Yes, I know this is effectively using parallel arrays, but I think it's the best option in this case...)\nThis is great if you know the number of \"balls\" you're going to create beforehand, as you can allocate an array for the coordinates, and store a view into that array for each ball object.\nYou have to be a bit careful to do operations in-place on the coords array, but it makes updating coordinates for numerous \"balls\" much, much, much faster.\nFor example...\nimport numpy as np\n\nclass Ball(object):\n def __init__(self, coords):\n self.coords = coords\n\n def _set_coord(self, i, value):\n self.coords[i] = value\n x = property(lambda self: self.coords[0],\n lambda self, value: self._set_coord(0, value))\n y = property(lambda self: self.coords[1],\n lambda self, value: self._set_coord(1, value))\n\n def move(self, dx, dy):\n self.x += dx\n self.y += dy\n\ndef main():\n n_balls = 10\n n_dims = 2\n coords = np.zeros((n_balls, n_dims))\n balls = [Ball(coords[i,:]) for i in range(n_balls)]\n\n # Just to illustrate that that the coords are updating\n ball = balls[0]\n\n # Random walk by updating coords array\n print 'Moving all the balls randomly by updating coords'\n for step in xrange(5):\n # Add a random value to all coordinates\n coords += 0.5 - np.random.random((n_balls, n_dims))\n\n # Display the coords for a particular ball and the \n # corresponding row of the coords array\n print ' Value of ball.x, ball.y:', ball.x, ball.y\n print ' Value of coords[0,:]:', coords[0,:]\n\n # Move an individual ball object\n print 'Moving a ball individually through Ball.move()'\n ball.move(0.5, 0.5)\n print ' Value of ball.x, ball.y:', ball.x, ball.y\n print ' Value of coords[0,:]:', coords[0,:]\n\nmain()\n\nJust to illustrate, this outputs something like:\nMoving all the balls randomly by updating coords\n Value of ball.x, ball.y: -0.125713650677 0.301692195466\n Value of coords[0,:]: [-0.12571365 0.3016922 ]\n Value of ball.x, ball.y: -0.304516863495 -0.0447543559805\n Value of coords[0,:]: [-0.30451686 -0.04475436]\n Value of ball.x, ball.y: -0.171589457954 0.334844443821\n Value of coords[0,:]: [-0.17158946 0.33484444]\n Value of ball.x, ball.y: -0.0452864552743 -0.0297552313656\n Value of coords[0,:]: [-0.04528646 -0.02975523]\n Value of ball.x, ball.y: -0.163829876915 0.0153203173857\n Value of coords[0,:]: [-0.16382988 0.01532032]\nMoving a ball individually through Ball.move()\n Value of ball.x, ball.y: 0.336170123085 0.515320317386\n Value of coords[0,:]: [ 0.33617012 0.51532032]\n\nThe advantage here is that updating a single numpy array is going to be much, much faster than iterating through all of your ball objects, but you retain a more object-oriented approach.\nJust my thoughts on it, anyway..\nEDIT: To give some idea of the speed difference, with 1,000,000 balls:\nIn [104]: %timeit coords[:,0] += 1.0\n100 loops, best of 3: 11.8 ms per loop\n\nIn [105]: %timeit [item.x + 1.0 for item in balls]\n1 loops, best of 3: 1.69 s per loop\n\nSo, updating the coordinates directly using numpy is roughly 2 orders of magnitude faster when using a large number of balls. (the difference is smaller when using 10 balls, as per the example, roughly a factor of 2x, rather than 150x)\n", "I think it depends on what you're going to be doing with them, and how often you're going to be working with (all attributes of one particle) vs (one attribute of all particles). The former is better suited to the object approach; the latter is better suited to the array approach.\nI was facing a similar problem (although in a different domain) a couple of years ago. The project got deprioritized before I actually implemented this phase, but I was leaning towards a hybrid approach, where in addition to the Ball class I would have an Ensemble class. The Ensemble would not be a list or other simple container of Balls, but would have its own attributes (which would be arrays) and its own methods. Whether the Ensemble is created from the Balls, or the Balls from the Ensemble, depends on how you're going to construct them. \nOne of my coworkers was arguing for a solution where the fundamental object was an Ensemble which might contain only one Ball, so that no calling code would ever have to know whether you were operating on just one Ball (do you ever do that for your application?) or on many.\n", "Will you be having any forces between the balls (hard sphere/collision, gravity, electromagnetic)? I'm guessing so. Will you be having a large enough number of balls to want to use Barnes-Hut simulation ideas? If so, then you should definitely use the Ball class idea so that you can store them easily in octrees or something else along those lines. Also, using the Barnes-Hut simulation will cut down the complexity of the simulation to O(N log N) from O(N^2). \nReally though, if you don't have forces between the balls or aren't using many balls, you don't need the possible speed gains from using parallel arrays and should go with the Ball class idea for that as well.\n" ]
[ 2, 2, 1, 0 ]
[]
[]
[ "data_structures", "numpy", "performance", "python" ]
stackoverflow_0002723790_data_structures_numpy_performance_python.txt
Q: How to make lists automatically instantiate on use in Python as they do in Perl? In Perl, I can do this: push(@{$h->[x]}, y); Can I simplify the following python codes according to above Perl example? if x not in h: h[x] = [] h[x].append(y) I want to simplify this, because it goes many places in my code, (and I cannot initialize all possible x with []). I do not want to make it a function, because there is no 'inline' keyword. Any ideas? A: A very elegant way (since Python 2.5) is to use defaultdict from the "collections" module: >>> from collections import defaultdict >>> h = defaultdict(list) >>> h['a'].append('b') >>> h defaultdict(<type 'list'>, {'a': ['b']}) defaultdict is like a dict, but provides a default value using whichever constructor you passed to it when you created it (in this example, a list). I particularly like this over the setdefault dict method, because 1) you define the variable as a defaultdict, and generally no other changes are required on the code (except perhaps to remove previous kludges for default values); and 2) setdefault is a terrible name :P A: There are a couple of ways to do this with the dict methods: h.setdefault(x, []).append(y) or h[x] = h.pop(x,[]).append(y) A: You can use setdefault h = {} h.setdefault(x, []).append(y)
How to make lists automatically instantiate on use in Python as they do in Perl?
In Perl, I can do this: push(@{$h->[x]}, y); Can I simplify the following python codes according to above Perl example? if x not in h: h[x] = [] h[x].append(y) I want to simplify this, because it goes many places in my code, (and I cannot initialize all possible x with []). I do not want to make it a function, because there is no 'inline' keyword. Any ideas?
[ "A very elegant way (since Python 2.5) is to use defaultdict from the \"collections\" module:\n>>> from collections import defaultdict\n>>> h = defaultdict(list)\n>>> h['a'].append('b')\n>>> h\ndefaultdict(<type 'list'>, {'a': ['b']})\n\ndefaultdict is like a dict, but provides a default value using whichever constructor you passed to it when you created it (in this example, a list).\nI particularly like this over the setdefault dict method, because 1) you define the variable as a defaultdict, and generally no other changes are required on the code (except perhaps to remove previous kludges for default values); and 2) setdefault is a terrible name :P\n", "There are a couple of ways to do this with the dict methods:\nh.setdefault(x, []).append(y)\n\nor\nh[x] = h.pop(x,[]).append(y)\n\n", "You can use setdefault\nh = {}\nh.setdefault(x, []).append(y)\n\n" ]
[ 9, 4, 3 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0002726632_perl_python.txt
Q: Intersection of two querysets in django I can't do an AND on two querysets. As in, q1 & q2. I get the empty set and I do not know why. I have tested this with the simplest cases. I am using django 1.1.1 I have basically objects like this: item1 name="Joe" color = "blue" item2 name="Jim" color = "blue" color = "white" item3 name="John" color = "red" color = "white" Is there something weird about having a many-to-many relationship or what am I missing? queryset1 = Item.objects.filter(color="blue") this gives (item1, item2) queryset2 = Item.objects.filter(color="white") this gives (item2, item3) queryset1 & queryset2 gives me the empty set [] The OR operator works fine (I'm using "|" ) Why is this so? A: qs = Item.objects.filter(color__in=['blue','white']) A: Item.objects.filter(color="blue").filter(color="white")
Intersection of two querysets in django
I can't do an AND on two querysets. As in, q1 & q2. I get the empty set and I do not know why. I have tested this with the simplest cases. I am using django 1.1.1 I have basically objects like this: item1 name="Joe" color = "blue" item2 name="Jim" color = "blue" color = "white" item3 name="John" color = "red" color = "white" Is there something weird about having a many-to-many relationship or what am I missing? queryset1 = Item.objects.filter(color="blue") this gives (item1, item2) queryset2 = Item.objects.filter(color="white") this gives (item2, item3) queryset1 & queryset2 gives me the empty set [] The OR operator works fine (I'm using "|" ) Why is this so?
[ "qs = Item.objects.filter(color__in=['blue','white'])\n\n", "Item.objects.filter(color=\"blue\").filter(color=\"white\")\n\n" ]
[ 3, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002719128_django_python.txt
Q: Call Python From PHP And Get Return Code I am calling a python script from PHP. The python program has to return some value according to the arguments passed to it. Here is a sample python program, which will give you a basic idea of what i am doing currently: #!/usr/bin/python import sys #get the arguments passed argList = sys.argv #Not enough arguments. Exit with a value of 1. if len(argList) < 3: #Return with a value of 1. sys.exit(1) arg1 = argList[1] arg2 = argList[2] #Check arguments. Exit with the appropriate value. if len(arg1) > 255: #Exit with a value of 4. sys.exit(4) if len(arg2) < 2: #Exit with a value of 8. sys.exit(8) #Do further coding using the arguments------ #If program works successfully, exit with a value of 0 As you can see from the above code, my basic aim is for the python program to return some values (0,1,4,8 etc) depending on the arguments. And then the calling PHP program to access these returned values and do the appropriate operation. Currently i have used "sys.exit(n)", for that purpose. Am i right in using sys.exit, or do I need to use something else? And also what method exists in PHP so that I can access the return code from python? Sorry for the long question, but hopefully it will help in you understanding my dilemma Thanks a ton A: In PHP, you can execute a command and obtain the return code using exec. The manual for exec says the third parameter is a variable in which the return code will be stored, for example exec('python blibble.py', $output, $ret_code); $ret_code will be the shell return code, and $output is an array of the lines of text printed to std. output. This does appear to be an appropriate use for a return code from what you described, i.e. 0 indicating success, and >0 being codes for various types of errors. A: That is correct use of exit(). See also: http://docs.python.org/library/sys.html
Call Python From PHP And Get Return Code
I am calling a python script from PHP. The python program has to return some value according to the arguments passed to it. Here is a sample python program, which will give you a basic idea of what i am doing currently: #!/usr/bin/python import sys #get the arguments passed argList = sys.argv #Not enough arguments. Exit with a value of 1. if len(argList) < 3: #Return with a value of 1. sys.exit(1) arg1 = argList[1] arg2 = argList[2] #Check arguments. Exit with the appropriate value. if len(arg1) > 255: #Exit with a value of 4. sys.exit(4) if len(arg2) < 2: #Exit with a value of 8. sys.exit(8) #Do further coding using the arguments------ #If program works successfully, exit with a value of 0 As you can see from the above code, my basic aim is for the python program to return some values (0,1,4,8 etc) depending on the arguments. And then the calling PHP program to access these returned values and do the appropriate operation. Currently i have used "sys.exit(n)", for that purpose. Am i right in using sys.exit, or do I need to use something else? And also what method exists in PHP so that I can access the return code from python? Sorry for the long question, but hopefully it will help in you understanding my dilemma Thanks a ton
[ "In PHP, you can execute a command and obtain the return code using exec.\nThe manual for exec says the third parameter is a variable in which the return code will be stored, for example\nexec('python blibble.py', $output, $ret_code);\n\n$ret_code will be the shell return code, and $output is an array of the lines of text printed to std. output.\nThis does appear to be an appropriate use for a return code from what you described, i.e. 0 indicating success, and >0 being codes for various types of errors.\n", "That is correct use of exit(). See also: http://docs.python.org/library/sys.html\n" ]
[ 15, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0002726551_php_python.txt
Q: Replace each char in a multi-line string except space and \r \n, how? A multi-line string, e.g. abc 123 456 def wanted result (ordinal + 2): cde 345 678 fgh if I use: text = "abc 123\n456 def" add2=''.join(chr(ord(c)+2) for c in text) print text print add2 the space and \r \n will also be replaced, how can I add the exception of not including space, \r or \n in the 2nd line of code. p.s. it's follow up to this question. A: Your other question suggests that you might be translating a very long string (a PDF file). In that case, using the string translate method will be quicker than doing a character-by-character for-loop over the string: test.py: import string infile='filename.pdf' outfile='newfile.pdf' with open(infile,'r') as f: text=f.read() def using_translate(): start_chars=''.join(chr(n) for n in range(256) if not chr(n).isspace()) end_chars=''.join(chr((ord(c)+2)%256) for c in start_chars) table = string.maketrans(start_chars,end_chars) return text.translate(table) def using_for_c_in_text(): return ''.join(chr((ord(c) + 2)%256) if not c.isspace() else c for c in text) This shows the results of a timeit run using a 1M pdf file: # % python -mtimeit -s"import test" "test.using_for_c_in_text()" # 10 loops, best of 3: 821 msec per loop # % python -mtimeit -s"import test" "test.using_translate()" # 100 loops, best of 3: 4.36 msec per loop PS: Many answers (including mine at one point) used chr(ord(c) + 2). This throws a TypeError if ord(c)+2>=256. To avoid the TypeError, you could use chr((ord(c) + 2)%256). A: You can simply check if the character is alphanumeric and keep the original character otherwise: add2 = ''.join(chr(ord(c)+2) if c.isalnum() else c for c in text) Please note that applying this to some characters (such as 'y', 'z', '9', '0' etc) might not yield what you expect. I.e., 'y' will not become 'a', but '{'. A: slower than @Roger's solution but filters all whitespace: >>> text = "abc 123\n456 def" >>> ''.join(chr(ord(c) + 2) if not c.isspace() else c for c in text) 'cde 345\n678 fgh' same as above but only bumps up alphanumerics: >>> text = "abc 123\n456 def" >>> ''.join(chr(ord(c) + 2) if c.isalnum() else c for c in text) 'cde 345\n678 fgh' A: add2 = ''.join(chr(ord(c) + 2) if c not in "\n\r " else c for c in text)
Replace each char in a multi-line string except space and \r \n, how?
A multi-line string, e.g. abc 123 456 def wanted result (ordinal + 2): cde 345 678 fgh if I use: text = "abc 123\n456 def" add2=''.join(chr(ord(c)+2) for c in text) print text print add2 the space and \r \n will also be replaced, how can I add the exception of not including space, \r or \n in the 2nd line of code. p.s. it's follow up to this question.
[ "Your other question suggests that you might be translating a very long string (a PDF file). In that case, using the string translate method will be quicker than doing a character-by-character for-loop over the string:\ntest.py:\nimport string\n\ninfile='filename.pdf'\noutfile='newfile.pdf'\n\nwith open(infile,'r') as f:\n text=f.read()\n\ndef using_translate():\n start_chars=''.join(chr(n) for n in range(256) if not chr(n).isspace())\n end_chars=''.join(chr((ord(c)+2)%256) for c in start_chars)\n table = string.maketrans(start_chars,end_chars)\n return text.translate(table)\n\ndef using_for_c_in_text():\n return ''.join(chr((ord(c) + 2)%256) if not c.isspace() else c for c in text)\n\nThis shows the results of a timeit run using a 1M pdf file:\n# % python -mtimeit -s\"import test\" \"test.using_for_c_in_text()\"\n# 10 loops, best of 3: 821 msec per loop\n# % python -mtimeit -s\"import test\" \"test.using_translate()\"\n# 100 loops, best of 3: 4.36 msec per loop\n\nPS: Many answers (including mine at one point) used chr(ord(c) + 2). This throws a TypeError if ord(c)+2>=256. To avoid the TypeError, you could use chr((ord(c) + 2)%256).\n", "You can simply check if the character is alphanumeric and keep the original character otherwise:\nadd2 = ''.join(chr(ord(c)+2) if c.isalnum() else c for c in text)\n\nPlease note that applying this to some characters (such as 'y', 'z', '9', '0' etc) might not yield what you expect. I.e., 'y' will not become 'a', but '{'.\n", "slower than @Roger's solution but filters all whitespace:\n>>> text = \"abc 123\\n456 def\"\n>>> ''.join(chr(ord(c) + 2) if not c.isspace() else c for c in text)\n'cde 345\\n678 fgh'\n\nsame as above but only bumps up alphanumerics:\n>>> text = \"abc 123\\n456 def\"\n>>> ''.join(chr(ord(c) + 2) if c.isalnum() else c for c in text)\n'cde 345\\n678 fgh'\n\n", "add2 = ''.join(chr(ord(c) + 2) if c not in \"\\n\\r \" else c for c in text)\n\n" ]
[ 3, 2, 2, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002726688_python_string.txt
Q: Recommendations for a simple 2D graphics python library that can output to screen and pdf? I'm looking for an easy-to-use graphics lib for python that can output to screen as well as pdf. So, I would use code to draw some stuff (simple prims like ovals, rectangles, lines and points) to screen and then when things look good, have it output to pdf. A: If you use Tkinter, you can draw on a Canvas widget, then use its .postscript method to save the contents as a PostScript file, which you can convert to PDF using ps2pdf. postscript(self, cnf={}, **kw) Print the contents of the canvas to a postscript file. Valid options: colormap, colormode, file, fontmap, height, pageanchor, pageheight, pagewidth, pagex, pagey, rotate, witdh, x, y. A: Matplotlib should be able to do it. See event handling here: http://matplotlib.sourceforge.net/examples/event_handling/index.html A: You can use the Python Imaging Library for drawing images which can easily be displayed in various UIs, e.g. by displaying a jpg. Then, use ReportLab. Here's an example which shows how to use ReportLab with an image. I'm not sure what you mean by drawing to "screen", i.e. if you're working with a specific UI toolkit. But if it's acceptable to draw and display PDFs without using an intermediate image (jpg, etc), then you might consider the PyX library, which makes it quite simple to do graphics with PDFs. A: You could look into matplotlib, which is mainly for plotting but you could probably do some basic drawing. Then there is pygame. But I'm not so sure if it can generate a pdf, however you can do 2D graphics with it. There is something called ReportLab that can generate pdf's. Here is a bunch of tutorials using it. A: This is a tricky question, because there are so many libraries available - there is a trade-off between beauty/easiness. What I've done and works great is to produce the Postscript directly, it is not difficult at all, and you can preview it using Ghostview; converting tyo PDF is trivial (ps2pdf). Learning how to tell Postscript to create lines and circles is extremely simple. If you want more extensibility, then go to Matplotlib, but beware of the many times when it will "decide for you what looks best" even if you don't like it. Good luck. A: Creating PDFs is always a pain, it doesn't make sense if you do not aim to lose sanity. With that said, you are aiming to do two completely different things: when you draw to screen you draw into a raster bitmap, while PDFs are mostly dynamic, like HTML. (unlike HTML they are more prone to be the same over different platforms, but that's beside the point) If you really want to do that, the solution might be finding something that outputs PDFs, and then showing the generated PDF on screen at every step. I guess that's the only way to have WYSIWYG results.
Recommendations for a simple 2D graphics python library that can output to screen and pdf?
I'm looking for an easy-to-use graphics lib for python that can output to screen as well as pdf. So, I would use code to draw some stuff (simple prims like ovals, rectangles, lines and points) to screen and then when things look good, have it output to pdf.
[ "If you use Tkinter, you can draw on a Canvas widget, then use its .postscript method to save the contents as a PostScript file, which you can convert to PDF using ps2pdf.\n\npostscript(self, cnf={}, **kw)\n Print the contents of the canvas to a postscript\n file. Valid options: colormap, colormode, file, fontmap,\n height, pageanchor, pageheight, pagewidth, pagex, pagey,\n rotate, witdh, x, y.\n\n", "Matplotlib should be able to do it. See event handling here: http://matplotlib.sourceforge.net/examples/event_handling/index.html\n", "You can use the Python Imaging Library for drawing images which can easily be displayed in various UIs, e.g. by displaying a jpg. Then, use ReportLab. Here's an example which shows how to use ReportLab with an image.\nI'm not sure what you mean by drawing to \"screen\", i.e. if you're working with a specific UI toolkit. But if it's acceptable to draw and display PDFs without using an intermediate image (jpg, etc), then you might consider the PyX library, which makes it quite simple to do graphics with PDFs.\n", "You could look into matplotlib, which is mainly for plotting but you could probably do some basic drawing.\nThen there is pygame. But I'm not so sure if it can generate a pdf, however you can do 2D graphics with it.\nThere is something called ReportLab that can generate pdf's. Here is a bunch of tutorials using it. \n", "This is a tricky question, because there are so many libraries available - there is a trade-off between beauty/easiness.\nWhat I've done and works great is to produce the Postscript directly, it is not difficult at all, and you can preview it using Ghostview; converting tyo PDF is trivial (ps2pdf). Learning how to tell Postscript to create lines and circles is extremely simple.\nIf you want more extensibility, then go to Matplotlib, but beware of the many times when it will \"decide for you what looks best\" even if you don't like it.\nGood luck.\n", "Creating PDFs is always a pain, it doesn't make sense if you do not aim to lose sanity.\nWith that said, you are aiming to do two completely different things: when you draw to screen you draw into a raster bitmap, while PDFs are mostly dynamic, like HTML. (unlike HTML they are more prone to be the same over different platforms, but that's beside the point)\nIf you really want to do that, the solution might be finding something that outputs PDFs, and then showing the generated PDF on screen at every step.\nI guess that's the only way to have WYSIWYG results.\n" ]
[ 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "graphics", "pdf", "python" ]
stackoverflow_0002725735_graphics_pdf_python.txt
Q: How to build an interactive search engine web interface using python I have build a static web interface for searching data from some tables in my PostgreSQL database. The query website consists of a simple textfield for entering the search term, the result website presents the results as a simple html table. The server side code for searching the PostgreSQL database and returning the results is written in python using psycopg2. Now I would like to add some interactive "Ajax features" to my search engine. When entering the search term I would like to be able to see a list of possible search terms like Google does it. On the results page, I would like to be able to sort the table showing the results. What would be the easiest/recommended way to implement these features for my search engine web site? A: I have not had to build a search outside of Django, but Haystack http://haystacksearch.org/ makes things very easy. If you don't want to get into Django you could look at Whoosh. http://bitbucket.org/mchaput/whoosh/wiki/Home A: what you call "Ajax features" are technically known as auto-suggest. Unless you want to reinvent the wheel. I would highly recommend indexing your db tables using Apache Solr. It comes with autosuggest, faceted filtering (like on most ecommerce sites) and spell-check. and since it is HTTP based you can hook into Python very easily using its RESTful API.
How to build an interactive search engine web interface using python
I have build a static web interface for searching data from some tables in my PostgreSQL database. The query website consists of a simple textfield for entering the search term, the result website presents the results as a simple html table. The server side code for searching the PostgreSQL database and returning the results is written in python using psycopg2. Now I would like to add some interactive "Ajax features" to my search engine. When entering the search term I would like to be able to see a list of possible search terms like Google does it. On the results page, I would like to be able to sort the table showing the results. What would be the easiest/recommended way to implement these features for my search engine web site?
[ "I have not had to build a search outside of Django, but Haystack http://haystacksearch.org/ makes things very easy.\nIf you don't want to get into Django you could look at Whoosh. http://bitbucket.org/mchaput/whoosh/wiki/Home\n", "what you call \"Ajax features\" are technically known as auto-suggest. Unless you want to reinvent the wheel. I would highly recommend indexing your db tables using Apache Solr. It comes with autosuggest, faceted filtering (like on most ecommerce sites) and spell-check. and since it is HTTP based you can hook into Python very easily using its RESTful API.\n" ]
[ 1, 0 ]
[]
[]
[ "ajax", "python", "search_engine", "web_frameworks" ]
stackoverflow_0002613316_ajax_python_search_engine_web_frameworks.txt
Q: Help with filetype association! I have the actual association part down, but when I open the file that is associated with my Python program, how do I get the filepath of the file opened? I think it is something like sys.argv? But that just returns the path to the python program, not the associated file. A: The __file__ attribute of your module looks what you're looking for. E.g., save in foo.py: $ cat foo.py print 'Hello', __file__ $ python foo.py Hello foo.py os.path.abspath will help you if you want the absolute rather than relative path, etc, etc. A: The contents of sys.argv are platform-dependent, as noted in sys.argv. I do know that sys.argv[0] is the full path on Windows only when you open .py files using the shell by double-clicking on it. Using the command line just results in the script name. The os module provides platform-independent solutions. The full path to your script should always be available with the following code: import os.path import sys print os.path.abspath(sys.argv[0])
Help with filetype association!
I have the actual association part down, but when I open the file that is associated with my Python program, how do I get the filepath of the file opened? I think it is something like sys.argv? But that just returns the path to the python program, not the associated file.
[ "The __file__ attribute of your module looks what you're looking for. E.g., save in foo.py:\n$ cat foo.py\nprint 'Hello', __file__\n$ python foo.py \nHello foo.py\n\nos.path.abspath will help you if you want the absolute rather than relative path, etc, etc.\n", "The contents of sys.argv are platform-dependent, as noted in sys.argv. I do know that sys.argv[0] is the full path on Windows only when you open .py files using the shell by double-clicking on it. Using the command line just results in the script name.\nThe os module provides platform-independent solutions. The full path to your script should always be available with the following code:\nimport os.path\nimport sys\n\nprint os.path.abspath(sys.argv[0])\n\n" ]
[ 1, 1 ]
[]
[]
[ "filepath", "python" ]
stackoverflow_0002726835_filepath_python.txt
Q: Using M2Crypto to save and load X509 certs in pem files I would expect that if I have a X509 cert as an object in memory, saved it as a pem file, then loaded it back in, I would end up with the same cert I started with. This seems not to be the case however. Let's call the original cert A, and the cert loaded from the pem file B. A.as_text() is identical to B.as_text(), but A.as_pem() differs from B.as_pem(). To say the least, I'm confused by this. As a side note, if A has been signed by another entity C, then A will verify against C's cert, but B will not. I've put together a tiny sample program to demonstrate what I'm seeing. When I run this, the second RuntimeError is raised. Thanks, Brock #!/usr/bin/python2.6 import M2Crypto as m2 import time cur_time = m2.ASN1.ASN1_UTCTIME() cur_time.set_time(int(time.time()) - 60*60*24) expire_time = m2.ASN1.ASN1_UTCTIME() # Expire certs in 1 hour. expire_time.set_time(int(time.time()) + 60 * 60 * 24) cs_rsa = m2.RSA.gen_key(1024, 65537, lambda: None) cs_pk = m2.EVP.PKey() cs_pk.assign_rsa(cs_rsa) cs_cert = m2.X509.X509() # These two seem the minimum necessary to make the as_text function call work # at all cs_cert.set_not_before(cur_time) cs_cert.set_not_after(expire_time) # This seems necessary to fill out the complete cert without errors. cs_cert.set_pubkey(cs_pk) # I've tried with the following set lines commented out and not commented. cs_name = m2.X509.X509_Name() cs_name.C = "US" cs_name.ST = "CA" cs_name.OU = "Fake Org CA 1" cs_name.CN = "www.fakeorg.dex" cs_name.Email = "cs1@www.fakeorg.dex" cs_cert.set_subject(cs_name) cs_cert.set_issuer_name(cs_name) cs_cert.sign(cs_pk, md="sha256") orig_text = cs_cert.as_text() orig_pem = cs_cert.as_pem() print "orig_text:\n%s" % orig_text cs_cert.save_pem("/tmp/foo") tcs = m2.X509.load_cert("/tmp/foo") tcs_text = tcs.as_text() tcs_pem = tcs.as_pem() if orig_text != tcs_text: raise RuntimeError( "Texts were different.\nOrig:\n%s\nAfter load:\n%s" % (orig_text, tcs_text)) if orig_pem != tcs_pem: raise RuntimeError( "Pems were different.\nOrig:\n%s\nAfter load:\n%s" % (orig_pem, tcs_pem)) A: If you try this with a cert that you created with OpenSSL command line tools (for example, the server.pem in tests directory sans the key and text) by loading and saving it with M2Crypto, you should get identical files. I thought SimpleX509Create.py in the contrib directory worked differently, but I tested it and I experience the same issue you found. Apparently there is some step we are missing that OpenSSL command line tools do.
Using M2Crypto to save and load X509 certs in pem files
I would expect that if I have a X509 cert as an object in memory, saved it as a pem file, then loaded it back in, I would end up with the same cert I started with. This seems not to be the case however. Let's call the original cert A, and the cert loaded from the pem file B. A.as_text() is identical to B.as_text(), but A.as_pem() differs from B.as_pem(). To say the least, I'm confused by this. As a side note, if A has been signed by another entity C, then A will verify against C's cert, but B will not. I've put together a tiny sample program to demonstrate what I'm seeing. When I run this, the second RuntimeError is raised. Thanks, Brock #!/usr/bin/python2.6 import M2Crypto as m2 import time cur_time = m2.ASN1.ASN1_UTCTIME() cur_time.set_time(int(time.time()) - 60*60*24) expire_time = m2.ASN1.ASN1_UTCTIME() # Expire certs in 1 hour. expire_time.set_time(int(time.time()) + 60 * 60 * 24) cs_rsa = m2.RSA.gen_key(1024, 65537, lambda: None) cs_pk = m2.EVP.PKey() cs_pk.assign_rsa(cs_rsa) cs_cert = m2.X509.X509() # These two seem the minimum necessary to make the as_text function call work # at all cs_cert.set_not_before(cur_time) cs_cert.set_not_after(expire_time) # This seems necessary to fill out the complete cert without errors. cs_cert.set_pubkey(cs_pk) # I've tried with the following set lines commented out and not commented. cs_name = m2.X509.X509_Name() cs_name.C = "US" cs_name.ST = "CA" cs_name.OU = "Fake Org CA 1" cs_name.CN = "www.fakeorg.dex" cs_name.Email = "cs1@www.fakeorg.dex" cs_cert.set_subject(cs_name) cs_cert.set_issuer_name(cs_name) cs_cert.sign(cs_pk, md="sha256") orig_text = cs_cert.as_text() orig_pem = cs_cert.as_pem() print "orig_text:\n%s" % orig_text cs_cert.save_pem("/tmp/foo") tcs = m2.X509.load_cert("/tmp/foo") tcs_text = tcs.as_text() tcs_pem = tcs.as_pem() if orig_text != tcs_text: raise RuntimeError( "Texts were different.\nOrig:\n%s\nAfter load:\n%s" % (orig_text, tcs_text)) if orig_pem != tcs_pem: raise RuntimeError( "Pems were different.\nOrig:\n%s\nAfter load:\n%s" % (orig_pem, tcs_pem))
[ "If you try this with a cert that you created with OpenSSL command line tools (for example, the server.pem in tests directory sans the key and text) by loading and saving it with M2Crypto, you should get identical files.\nI thought SimpleX509Create.py in the contrib directory worked differently, but I tested it and I experience the same issue you found. Apparently there is some step we are missing that OpenSSL command line tools do.\n" ]
[ 1 ]
[]
[]
[ "cryptography", "m2crypto", "pem", "python", "x509certificate" ]
stackoverflow_0002726003_cryptography_m2crypto_pem_python_x509certificate.txt