title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Python GAE urlfetch credentials | 8,377,298 | 9 | 2011-12-04T17:50:14Z | 8,454,580 | 19 | 2011-12-10T05:14:52Z | [
"python",
"google-app-engine",
"credentials",
"urlfetch"
] | I'd like to know if the Google App Engine [URL Fetch Python API](http://code.google.com/appengine/docs/python/urlfetch/) does not support accessing URLs that have credentials:
```
http://username:password@www.domain.com/
```
It should be a basic feature, but I cannot get it to work and could not find any documentatio... | SOLUTION - here's how it should be done:
```
result = urlfetch.fetch("http://www.domain.com/",
headers={"Authorization":
"Basic %s" % base64.b64encode("username:password")})
``` |
Python have slow db-query, but Perl not | 8,377,603 | 12 | 2011-12-04T18:32:38Z | 8,378,359 | 9 | 2011-12-04T20:28:00Z | [
"python",
"mysql",
"database",
"perl"
] | I use python (Django) for my web-shop.
When I tested high loading (db access) got interesting results:
```
python 10 process = 200sec / 100% CPU utilisation
perl 10 process = 65sec / 35% CPU utilisation
```
Centos 6, python 2.6, mysql 5.5, standard libraries, mysql-server on other server.
Table product\_cars have 7... | In theory, your Perl code should speed up significantly if you execute `$cursor = $db->prepare($sql);` before the loop and simply reexecute the same prepared query repeatedly. I suspect either DBI or MySQL has simply cached and ignored your repeated identical query preparations.
Your Python code, on the other hand, de... |
Python have slow db-query, but Perl not | 8,377,603 | 12 | 2011-12-04T18:32:38Z | 8,379,234 | 9 | 2011-12-04T22:50:59Z | [
"python",
"mysql",
"database",
"perl"
] | I use python (Django) for my web-shop.
When I tested high loading (db access) got interesting results:
```
python 10 process = 200sec / 100% CPU utilisation
perl 10 process = 65sec / 35% CPU utilisation
```
Centos 6, python 2.6, mysql 5.5, standard libraries, mysql-server on other server.
Table product\_cars have 7... | As people have pointed out, the way you're preparing and executing statements between the two is not the same and is not the recommended practice. Both should be taking advantage of prepared statements, and both should be preparing *outside* the loop.
However, it looks like that Python MySQL driver does not take advan... |
python - accessing superclass attributes | 8,377,634 | 6 | 2011-12-04T18:38:47Z | 8,377,759 | 10 | 2011-12-04T18:56:49Z | [
"python",
"inheritance"
] | Hi I want to achieve the following in python, however I cant figure out what to replace the line `super.a = b` with:
```
class Super:
def __init__(self):
self.a = 1
class Sub(Super):
def method(self, b):
super.a = b
``` | An `Sub` *is a* `Super`, i.e. all instances of `Sub` can be treated exactly like instances of `Super`. In your case, that means you simply set `self.a = b`. |
Is there a one line way of saying this? | 8,378,364 | 4 | 2011-12-04T20:29:18Z | 8,378,372 | 8 | 2011-12-04T20:30:37Z | [
"python",
"conditional"
] | Pretty simple probably for someone. Is there a way to say this in one line of code?
```
if word.startswith('^') or word.startswith('@'):
truth = True
else:
truth = False
``` | The boolean expression (`word.startswith('^') or word.startswith('@')`) returns a boolean value, which can then be assigned to a variable, so:
```
truth = (word.startswith('^') or word.startswith('@'))
```
is perfectly valid. |
Is there a one line way of saying this? | 8,378,364 | 4 | 2011-12-04T20:29:18Z | 8,378,484 | 10 | 2011-12-04T20:48:49Z | [
"python",
"conditional"
] | Pretty simple probably for someone. Is there a way to say this in one line of code?
```
if word.startswith('^') or word.startswith('@'):
truth = True
else:
truth = False
``` | I think this will be the shortest one:
```
truth = word.startswith(('^','@'))
```
From docs (look at the last line):
```
startswith(...)
S.startswith(prefix[, start[, end]]) -> bool
Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position... |
Problems with running cherrypy's hello world example | 8,379,747 | 8 | 2011-12-05T00:27:47Z | 8,380,152 | 11 | 2011-12-05T01:38:45Z | [
"python",
"cherrypy"
] | I'm trying to test cherrypy framework by using example from their site:
```
import cherrypy
class HelloWorld(object):
def index(self):
return "Hello World!"
index.exposed = True
cherrypy.quickstart(HelloWorld())
```
When I run it I get this response in the console:
```
[05/Dec/2011:00:15:11] ENGINE List... | By default `cherrypy.quickstart` is only going to bind to localhost `127.0.0.1`, which can be access from the serving computer but not from computers connected to it through the network.
If you want to be able to access the site from another computer, you need to set the configuration, like documented in here: <http:... |
File Open Function with Try & Except Python 2.7.1 | 8,380,006 | 3 | 2011-12-05T01:14:49Z | 8,380,019 | 8 | 2011-12-05T01:17:14Z | [
"python",
"file",
"function",
"try-catch",
"except"
] | ```
def FileCheck(fn):
try:
fn=open("TestFile.txt","U")
except IOError:
print "Error: File does not appear to exist."
return 0
```
I'm trying to make a function that checks to see if a file exists and if doesn't then it should print the error message and return 0 . W... | You'll need to indent the return 0 if you want to return from within the except block.
Also, your argument isn't doing much of anything. Instead of assigning it the filehandle, I assume you want this function to be able to test any file? If not, you don't need any arguments.
```
def FileCheck(fn):
try:
open(... |
How do you capitalize the first word and every word after a period? | 8,380,061 | 3 | 2011-12-05T01:24:09Z | 8,380,085 | 8 | 2011-12-05T01:27:09Z | [
"python"
] | So far I'm able to capitalize the first word of the sentence, but I need every first letter after a period to be capitalized.
This is what I have:
```
def main():
input1 = input('Enter your input here: ')
capitalize = str.capitalize(input1)
print("The capitalized version:", capitalize)
main()
``` | Use [Sentence Case](http://packages.python.org/tl.rename/tl/rename/case.html#sentence-case) of the [rename package](http://packages.python.org/tl.rename/index.html).
```
>>> from tl.rename.case import transform_sentence_case
>>> transform_sentence_case(['foo bar baz', 'FOO bar. baz Asdf'])
['Foo bar baz', 'Foo bar. Ba... |
Default key for Python builtin max/min functions | 8,380,179 | 7 | 2011-12-05T01:43:40Z | 8,380,293 | 22 | 2011-12-05T02:10:26Z | [
"python"
] | The documentation for the built-in functions `max` and `min` in Python indicate that the `key` parameter should operate like it does in the `sort` function. In other words, I should be able to do this:
```
a = [1, 2, 3, 4]
max(a, key=None)
```
However, this raises an error:
`TypeError: 'NoneType' object is not callab... | You've stumbled on to a difference in the implementation of `.sort` and `max` more than a problem with the language.
`list.sort()` takes a keyword argument "key" which happens to default to None. This means that the sort method can't tell the difference between you supplying a `key=None` argument or it just taking on ... |
Default key for Python builtin max/min functions | 8,380,179 | 7 | 2011-12-05T01:43:40Z | 8,380,642 | 7 | 2011-12-05T03:15:17Z | [
"python"
] | The documentation for the built-in functions `max` and `min` in Python indicate that the `key` parameter should operate like it does in the `sort` function. In other words, I should be able to do this:
```
a = [1, 2, 3, 4]
max(a, key=None)
```
However, this raises an error:
`TypeError: 'NoneType' object is not callab... | @David's answer is perfect. Just adding, in case you're wondering, the default `key` value (both in `sort` and in `max`/`min` functions) is something like:
```
lambda x: x
``` |
customizing admin of django to have dependent select fields | 8,380,241 | 9 | 2011-12-05T01:55:45Z | 8,390,892 | 10 | 2011-12-05T19:45:08Z | [
"python",
"django",
"django-admin"
] | I am new in django , I am developing admin panel first for my site. I need to have dependent select fields, so that after selecting country, user will be able to select city. I want that when I select country then cities of that country options load in city select box but I don't know how to customize django admin. I h... | You probably want to use the feature Grouped Selects in [django smart selects](https://github.com/digi604/django-smart-selects). From the README:
If you have the following model:
```
class Location(models.Model)
continent = models.ForeignKey(Continent)
country = models.ForeignKey(Country)
```
And you want th... |
The way to make namespace packages in Python | 8,380,381 | 13 | 2011-12-05T02:25:45Z | 8,380,524 | 37 | 2011-12-05T02:51:25Z | [
"python",
"setuptools",
"module-packaging"
] | From [Namespace Packages in distribute](http://packages.python.org/distribute/setuptools.html#namespace-packages), I know I can make use of namespace packages to separate a big Python package into several smaller ones. It is really awesome. The document also mentions:
> Note, by the way, that your projectâs source t... | A namespace package mainly has a particular effect when it comes time to import a sub-package. Basically, here's what happens, when importing `foo.bar`
* the importer scans through `sys.path` looking for something that looks like `foo`.
* when it finds something, it will look inside of the discovered `foo` for `bar`.
... |
how to get day name in datetime in python | 8,380,389 | 21 | 2011-12-05T02:27:09Z | 8,380,402 | 53 | 2011-12-05T02:29:42Z | [
"python",
"django",
"datetime",
"django-piston"
] | how can I get the day name (such as : Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday) in datetime in python?...
here is my code in my handlers.py
```
from django.utils.xmlutils import SimplerXMLGenerator
from piston.handler import BaseHandler
from booking.models import *
from djang... | ```
import datetime
now = datetime.datetime.now()
print now.strftime("%A")
```
See the Python docs for [datetime.now](http://docs.python.org/py3k/library/datetime.html#datetime.datetime.now), [datetime.strftime](http://docs.python.org/py3k/library/datetime.html#datetime.datetime.strftime) and [more on strftime](http:/... |
how to get day name in datetime in python | 8,380,389 | 21 | 2011-12-05T02:27:09Z | 8,380,435 | 14 | 2011-12-05T02:36:09Z | [
"python",
"django",
"datetime",
"django-piston"
] | how can I get the day name (such as : Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday) in datetime in python?...
here is my code in my handlers.py
```
from django.utils.xmlutils import SimplerXMLGenerator
from piston.handler import BaseHandler
from booking.models import *
from djang... | ```
>>> date.today().strftime("%A")
'Monday'
``` |
Python: Handle JSON Decode Error when nothing returned | 8,381,193 | 18 | 2011-12-05T04:58:54Z | 8,381,223 | 44 | 2011-12-05T05:05:31Z | [
"python",
"json"
] | I am parsing json data. I don't have an issue with parsing and I am using `simplejson` module. But some api requests returns empty value. Here is my example:
```
{
"all" : {
"count" : 0,
"questions" : [ ]
}
}
```
This is the segment of my code where I parse the json object:
```
qByUser = byUsrUrlObj... | There is a rule in Python programming called "it is Easier to Ask for Forgiveness than for Permission" (in short: EAFP). It means that you should catch exceptions instead of checking values for validity.
Thus, try the following:
```
try:
qByUser = byUsrUrlObj.read()
qUserData = json.loads(qByUser).decode('utf... |
How do I update/redraw a GTK Widget (GTKLabel) internally without a key press event using python? | 8,381,631 | 3 | 2011-12-05T06:14:22Z | 8,383,141 | 9 | 2011-12-05T09:22:42Z | [
"python",
"gtk",
"pygtk"
] | I have some code below that is attempting to update a GTK Label element. I'm including two files: the ui file and the py file.
UI file:
```
<glade-interface>
<widget class="GtkWindow" id="ApplicationFrame">
<property name="width_request">320</property>
<property name="height_request">240</property>
<pro... | You'll want to use the Widget's [`queue_draw`](http://www.pygtk.org/docs/pygtk/class-gtkwidget.html#method-gtkwidget--queue-draw) function:
> *The queue\_draw\_area() method invalidates the rectangular area of the widget (...) by calling the* `gtk.gdk.Window.invalidate_rect()` *method on the widget's window and all it... |
toggle a value in Python | 8,381,735 | 38 | 2011-12-05T06:30:15Z | 8,381,743 | 13 | 2011-12-05T06:31:20Z | [
"python"
] | What is the most efficient way to toggle between `0` and `1`? | The `not` operator negates your variable (converting it into a boolean if it isn't already one). You can *probably* use `1` and `0` interchangeably with `True` and `False`, so just negate it:
```
toggle = not toggle
```
But if you are using two arbitrary values, use an inline `if`:
```
toggle = 'a' if toggle == 'b' ... |
toggle a value in Python | 8,381,735 | 38 | 2011-12-05T06:30:15Z | 8,381,763 | 7 | 2011-12-05T06:33:40Z | [
"python"
] | What is the most efficient way to toggle between `0` and `1`? | Just between 1 and 0, do this
```
1-x
```
x can take 1 or 0 |
toggle a value in Python | 8,381,735 | 38 | 2011-12-05T06:30:15Z | 8,381,848 | 13 | 2011-12-05T06:45:00Z | [
"python"
] | What is the most efficient way to toggle between `0` and `1`? | Here is another non intuitive way. The beauty is you can cycle over multiple values and not just two [0,1]
For Two values (toggling)
```
>>> x=[1,0]
>>> toggle=x[toggle]
```
For Multiple Values (say 4)
```
>>> x=[1,2,3,0]
>>> toggle=x[toggle]
```
I didn't expect this solution to be almost the fastest too
```
>>> ... |
toggle a value in Python | 8,381,735 | 38 | 2011-12-05T06:30:15Z | 8,381,955 | 63 | 2011-12-05T06:59:01Z | [
"python"
] | What is the most efficient way to toggle between `0` and `1`? | If the values are boolean, the fastest approach is to use the *[not](http://docs.python.org/reference/expressions.html#boolean-operations)* operator:
```
>>> x = True
>>> x = not x # toggle
>>> x
False
>>> x = not x # toggle
>>> x
True
>>> x = not x # toggle
>>> x
False
```
If the values are nume... |
toggle a value in Python | 8,381,735 | 38 | 2011-12-05T06:30:15Z | 23,582,571 | 11 | 2014-05-10T14:58:45Z | [
"python"
] | What is the most efficient way to toggle between `0` and `1`? | I always use:
```
p^=True
```
If p is a boolean, this switches between true and false. |
Combining pygame and twisted | 8,381,850 | 3 | 2011-12-05T06:45:01Z | 8,382,006 | 11 | 2011-12-05T07:07:08Z | [
"python",
"twisted",
"pygame"
] | [After yesterdays](http://stackoverflow.com/questions/8379110/i-have-a-twisted-reactor-running-how-do-i-connect-to-it) poorly chosen question I'm trying again.
I have a [tic tac toe program](https://github.com/Teifion/mp_tictactoe) in the works purely for the purpose of learning network play.
My understanding of twis... | The difficulty of combining pygame with twisted is the issue of who controls the mainloop. This usually comes up with wanting to combine any sort of UI (GTK, Tkinter, etc) mainloop with Twisted, and PyGame is no different.
What I would suggest, is that since network latency is important and since twisted has a very go... |
How to ssh connect through python Paramiko with public key | 8,382,847 | 23 | 2011-12-05T08:51:51Z | 8,417,181 | 24 | 2011-12-07T14:46:10Z | [
"python",
"ssh",
"putty",
"paramiko",
"public-key"
] | i'm using [Paramiko](http://www.lag.net/paramiko/) to connect through ssh to a server.
Basic authentication works well, but i can't understand how to connect with public key.
When i connect with putty, the server tell me this:
```
Using username "root".
Authenticating with public key "rsa-key@ddddd.com"
Passphrase f... | Ok @Adam and @Kimvais were right, paramiko cannot parse .ppk files.
So the way to go (thanks to @JimB too) is to convert .ppk file to openssh private key format; this can be achieved using [Puttygen](http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html) as described [here](http://stackoverflow.com/questions... |
Convert '229, 255, 66' to (229, 255, 66) in Python | 8,382,893 | 2 | 2011-12-05T08:57:41Z | 8,382,966 | 15 | 2011-12-05T09:04:01Z | [
"python"
] | I want to do a simple conversion of `u'229, 255, 66'` to `(229, 255, 66)`
Is there a very simple way to do this? Or do I need to split, convert to int, etc... | The easy way is to use the function `ast.literal_eval()` which has none of the security issues of using `eval`:
```
>>> from ast import literal_eval
>>> literal_eval(u'229, 255, 66')
(229, 255, 66)
``` |
pylab ImportError: No module named _thread | 8,383,056 | 7 | 2011-12-05T09:15:08Z | 8,383,183 | 9 | 2011-12-05T09:25:30Z | [
"python",
"ubuntu",
"matplotlib"
] | From ubuntu 10.04, I installed pylab with easy\_install.
After some upgrade, I can import pylab.
First I run ipython installed from easy\_install:
```
$ ipython
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
Type "copyright", "credits" or "license" for more information.
IPython 0.11 -- An enhanced Interactive Pyth... | It is caused by *dateutil*.
As you can see, you have installed dateutil **2.0** using easy\_install, but it's not compatible with python 2.x. You should uninstall (or just delete the whole folder) the **2.0** version and then go to its [homepage](http://labix.org/python-dateutil) and download version **1.5**, then man... |
Python Regex for hyphenated words | 8,383,213 | 7 | 2011-12-05T09:28:47Z | 8,383,339 | 13 | 2011-12-05T09:39:09Z | [
"python",
"regex",
"hyphen"
] | I'm looking for a regex to match hyphenated words in python.
The closest I've managed to get is: '\w+-\w+[-w+]\*'
```
text = "one-hundered-and-three- some text foo-bar some--text"
hyphenated = re.findall(r'\w+-\w+[-\w+]*',text)
```
which returns list ['one-hundered-and-three-', 'foo-bar'].
This is almost perfect ex... | Try this:
```
re.findall(r'\w+(?:-\w+)+',text)
```
Here we consider a hyphenated word to be:
* a number of word chars
* followed by any number of:
+ a single hyphen
+ followed by word chars |
Equivalent function for xticks for an AxesSubplot object | 8,384,120 | 6 | 2011-12-05T10:46:36Z | 8,384,229 | 12 | 2011-12-05T10:56:22Z | [
"python",
"matplotlib",
"tkinter"
] | So I am trying to use Axes objects to control my matlibplot figure. I am not using plt (aka import matlibplot.pyplot as plt) because I am embedding the figure in my tkinter GUI per [this](http://matplotlib.sourceforge.net/examples/user_interfaces/embedding_in_tk.html).
However, I am also using subplots in the figure, ... | you can use instead:
```
axes.set_xticks(ticks, minor=False)
```
and
```
axes.set_xticklabels(labels, fontdict=None, minor=False, **kwargs)
``` |
Non-blocking Thrift Server in Python | 8,384,326 | 4 | 2011-12-05T11:04:21Z | 8,384,885 | 8 | 2011-12-05T11:53:06Z | [
"python",
"nonblocking",
"thrift",
"thrift-protocol"
] | In below code snippet, I am trying to make a non-blocking thrift server in python.
```
# set handler to our implementation
handler = ServiceHandler()
processor = MyService.Processor(handler)
transport = TSocket.TServerSocket(port=port)
tfactory = TTransport.TFramedTransport(transport)
pfacto... | I found some [working Thrift code](http://nullege.com/codes/show/src@t@h@thrift-examples-HEAD@server@PythonServer.py/53/thrift.server.TServer.TThreadedServer.serve/python) and it looks like your tfactory needs to be a TBufferedTransportFactory and not a TBufferedTransport instance.
```
tfactory = TTransport.TBufferedT... |
Is there any available solution to provide xsrf/csrf support for Google app engine? | 8,384,729 | 17 | 2011-12-05T11:39:04Z | 8,545,183 | 11 | 2011-12-17T13:49:15Z | [
"python",
"google-app-engine",
"webapp2"
] | [Cross-site request forgery](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is common on web now a days. I am facing this in my own site deployed on Google App engine. I got to know this by examining access logs. Is there any XSRF/CSRF library or other solution available for App engine that I can use. And, ho... | I use this code called from basehandler's init request function
```
def init_csrf(self):
"""Issue and handle CSRF token as necessary"""
self.csrf_token = self.request.cookies.get('c')
if not self.csrf_token:
self.csrf_token = str(uuid4())[:8]
self.set_cookie('c', self.csrf_token)
if se... |
Python, extract file name from path, no matter what the os/path format | 8,384,737 | 214 | 2011-12-05T11:39:49Z | 8,384,786 | 74 | 2011-12-05T11:45:14Z | [
"python"
] | Which Python library can I use to extract filenames from paths, no matter what the operating system or path format could be?
For example, I'd like all of these paths to return me `c`:
```
a/b/c/
a/b/c
\a\b\c
\a\b\c\
a\b\c
a/b/../../a/b/c/
a/b/../../a/b/c
``` | [os.path.split](http://docs.python.org/library/os.path.html#os.path.split)
is the function you are looking for
```
head, tail = os.path.split("/tmp/d/a.dat")
>>> print tail
a.dat
>>> print head
/tmp/d
``` |
Python, extract file name from path, no matter what the os/path format | 8,384,737 | 214 | 2011-12-05T11:39:49Z | 8,384,787 | 20 | 2011-12-05T11:45:21Z | [
"python"
] | Which Python library can I use to extract filenames from paths, no matter what the operating system or path format could be?
For example, I'd like all of these paths to return me `c`:
```
a/b/c/
a/b/c
\a\b\c
\a\b\c\
a\b\c
a/b/../../a/b/c/
a/b/../../a/b/c
``` | ```
import os
head, tail = os.path.split(p)
print tail
```
Assume p is the input string, tail is what you want.
See [python os module docs](http://docs.python.org/library/os.path.html#os.path.split) for detail |
Python, extract file name from path, no matter what the os/path format | 8,384,737 | 214 | 2011-12-05T11:39:49Z | 8,384,788 | 257 | 2011-12-05T11:45:25Z | [
"python"
] | Which Python library can I use to extract filenames from paths, no matter what the operating system or path format could be?
For example, I'd like all of these paths to return me `c`:
```
a/b/c/
a/b/c
\a\b\c
\a\b\c\
a\b\c
a/b/../../a/b/c/
a/b/../../a/b/c
``` | Using `os.path.split` or `os.path.basename` as others suggest won't work in all cases: if you're running the script on Linux and attempt to process a classic windows-style path, it will fail.
Windows paths can use either backslash or forward slash as path separator. Therefore, the `ntpath` module (which is equivalent ... |
Python, extract file name from path, no matter what the os/path format | 8,384,737 | 214 | 2011-12-05T11:39:49Z | 8,384,838 | 281 | 2011-12-05T11:49:16Z | [
"python"
] | Which Python library can I use to extract filenames from paths, no matter what the operating system or path format could be?
For example, I'd like all of these paths to return me `c`:
```
a/b/c/
a/b/c
\a\b\c
\a\b\c\
a\b\c
a/b/../../a/b/c/
a/b/../../a/b/c
``` | Actually, there's a [function](https://docs.python.org/2/library/os.path.html#os.path.basename) that returns exactly what you want
```
print os.path.basename(your_path)
``` |
Python, extract file name from path, no matter what the os/path format | 8,384,737 | 214 | 2011-12-05T11:39:49Z | 8,384,865 | 8 | 2011-12-05T11:51:21Z | [
"python"
] | Which Python library can I use to extract filenames from paths, no matter what the operating system or path format could be?
For example, I'd like all of these paths to return me `c`:
```
a/b/c/
a/b/c
\a\b\c
\a\b\c\
a\b\c
a/b/../../a/b/c/
a/b/../../a/b/c
``` | In your example you will also need to strip slash from right the right side to return `c`:
```
>>> import os
>>> path = 'a/b/c/'
>>> path = path.rstrip(os.sep) # strip the slash from the right side
>>> os.path.basename(path)
'c'
```
Second level:
```
>>> os.path.filename(os.path.dirname(path))
'b'
```
update: I thi... |
LXML - Sorting Tag Order | 8,385,358 | 3 | 2011-12-05T12:33:00Z | 8,387,132 | 12 | 2011-12-05T14:51:12Z | [
"python",
"xml",
"lxml"
] | I have a legacy file format which I'm converting into XML for processing. The structure can be summarised as:
```
<A>
<A01>X</A01>
<A02>Y</A02>
<A03>Z</A03>
</A>
```
The numerical part of the tags can go from 01 to 99 and there may be gaps. As part of the processing certain records may have additional tag... | It's possible to write a helper function to insert a new element in the correct place, but without knowing more about the structure it's difficult to make it generic.
Here's a short example of sorting child elements across the whole document:
```
from lxml import etree
data = """<X>
<X03>3</X03>
<X02>2</X02>... |
why are numpy arrays so fast | 8,385,602 | 13 | 2011-12-05T12:53:05Z | 8,385,658 | 38 | 2011-12-05T12:57:01Z | [
"python",
"arrays",
"numpy"
] | I just changed a program I am writing to hold my data as numpy arrays as I was having performance issues, and the difference was incredible. It originally took 30 minutes to run and now takes 2.5 seconds!
I was wondering how it does it. I assume it is that the because it removes the need for for loops but beyond that ... | Numpy arrays are densely packed arrays of homogeneous type. Python lists, by contrast, are arrays of pointers to objects, even when all of them are of the same type. So, you get the benefits of [locality of reference](https://en.wikipedia.org/wiki/Locality_of_reference).
Also, many Numpy operations are implemented in ... |
why are numpy arrays so fast | 8,385,602 | 13 | 2011-12-05T12:53:05Z | 8,385,745 | 8 | 2011-12-05T13:04:11Z | [
"python",
"arrays",
"numpy"
] | I just changed a program I am writing to hold my data as numpy arrays as I was having performance issues, and the difference was incredible. It originally took 30 minutes to run and now takes 2.5 seconds!
I was wondering how it does it. I assume it is that the because it removes the need for for loops but beyond that ... | numpy arrays are specialized data structures.
This means you don't only get the benefits of an efficient in-memory representation, but efficient specialized implementations as well.
E.g. if you are summing up two arrays the addition will be performed with the specialized CPU vector operations, instead of calling the p... |
How do I deploy web2py on PythonAnywhere? | 8,386,240 | 11 | 2011-12-05T13:44:55Z | 8,386,751 | 17 | 2011-12-05T14:25:51Z | [
"python",
"web2py",
"pythonanywhere"
] | How do i get a basic web2py server up and running on
[PythonAnywhere](http://www.pythonanywhere.com)? | [update - 29/05] We now have a big button on the web tab that will do all this stuff for you. Just click where it says *Web2Py*, fill in your admin password, and you're good to go.
Here's the old stuff for historical interest...
I'm a PythonAnywhere developer. We're not massive web2py experts (yet?) but I've managed ... |
Web Crawler - Ignore Robots.txt file? | 8,386,481 | 8 | 2011-12-05T14:05:02Z | 8,386,542 | 8 | 2011-12-05T14:09:31Z | [
"python",
"web-crawler",
"mechanize",
"robots.txt"
] | Some servers have a robots.txt file in order to stop web crawlers from crawling through their websites. Is there a way to make a web crawler ignore the robots.txt file? I am using Mechanize for python. | [**This**](http://dinomite.net/2007/web-browsing-with-python/) looks like what you need:
```
from mechanize import Browser
br = Browser()
# Ignore robots.txt
br.set_handle_robots( False )
```
but you know what you're doing⦠|
Web Crawler - Ignore Robots.txt file? | 8,386,481 | 8 | 2011-12-05T14:05:02Z | 8,386,555 | 21 | 2011-12-05T14:10:33Z | [
"python",
"web-crawler",
"mechanize",
"robots.txt"
] | Some servers have a robots.txt file in order to stop web crawlers from crawling through their websites. Is there a way to make a web crawler ignore the robots.txt file? I am using Mechanize for python. | The [documentation](http://wwwsearch.sourceforge.net/mechanize/) for mechanize has this sample code:
```
br = mechanize.Browser()
....
# Ignore robots.txt. Do not do this without thought and consideration.
br.set_handle_robots(False)
```
That does exactly what you want. |
Extracting specific columns in numpy array | 8,386,675 | 30 | 2011-12-05T14:20:47Z | 8,386,737 | 60 | 2011-12-05T14:24:54Z | [
"python",
"syntax",
"numpy"
] | This is an easy question but say I have an MxN matrix. All I want to do is extract specific columns and store them in another numpy array but I get invalid syntax errors.
Here is the code:
```
extractedData = data[[:,1],[:,9]].
```
It seems like the above line should suffice but I guess not. I looked around but could... | I assume you wanted columns `1` and `9`? That's
```
data[:, [1, 9]]
``` |
Extracting specific columns in numpy array | 8,386,675 | 30 | 2011-12-05T14:20:47Z | 8,386,754 | 12 | 2011-12-05T14:26:02Z | [
"python",
"syntax",
"numpy"
] | This is an easy question but say I have an MxN matrix. All I want to do is extract specific columns and store them in another numpy array but I get invalid syntax errors.
Here is the code:
```
extractedData = data[[:,1],[:,9]].
```
It seems like the above line should suffice but I guess not. I looked around but could... | Assuming you want to get columns 1 and 9 with that code snippet, it should be:
```
extractedData = data[:,[1,9]]
``` |
How to find more than one substring from a string in Python | 8,386,697 | 2 | 2011-12-05T14:22:12Z | 8,386,829 | 7 | 2011-12-05T14:31:20Z | [
"python",
"biopython"
] | For example if i have a string 'ATGAGGGATAGAGGGTTGGGAGAGATGGATAGGGGATAGATTG'
i have to get substring between ATG and TTG , as we can see there are two of these kinds in a string.
I am not able to figure out anyway to do it , plz help me thru it! | Using regular expression can easily get you there.
For example:
```
import re
a = 'ATGAGGGATAGAGGGTTGGGAGAGATGGATAGGGGATAGATTG'
print re.findall("ATG(.*?)TTG", a)
```
Output:
```
['AGGGATAGAGGG', 'GATAGGGGATAGA']
``` |
Python argparse and bash completion | 8,387,924 | 44 | 2011-12-05T15:48:21Z | 9,419,042 | 13 | 2012-02-23T18:32:43Z | [
"python",
"argparse",
"bash-completion"
] | I would like to get auto-completion on my python scripts also in the arguments.
I had never really understood how the bash\_completion worked (for arguments), but after I digged in I understood that:
1. it uses "complete" to bind a completing function to a command
2. every completing function basically is a copy of t... | [Bash "completion"](http://www.caliban.org/bash/#completion) really is great. And easy for programs written in Python....
I think this is just what you want: [optcomplete: Shell Completion Self-Generator for Python](http://furius.ca/optcomplete/). It is available, e.g., as the "python-optcomplete" package in Ubuntu.
... |
Python argparse and bash completion | 8,387,924 | 44 | 2011-12-05T15:48:21Z | 13,554,814 | 47 | 2012-11-25T19:50:46Z | [
"python",
"argparse",
"bash-completion"
] | I would like to get auto-completion on my python scripts also in the arguments.
I had never really understood how the bash\_completion worked (for arguments), but after I digged in I understood that:
1. it uses "complete" to bind a completing function to a command
2. every completing function basically is a copy of t... | Shameless self-promotion: <https://github.com/kislyuk/argcomplete>
argcomplete provides bash completion for argparse. |
How to use urllib to download image from web | 8,389,090 | 3 | 2011-12-05T17:12:48Z | 8,389,368 | 12 | 2011-12-05T17:32:15Z | [
"python",
"urllib"
] | I'm trying to download an image using this code:
```
from urllib import urlretrieve
urlretrieve('http://gdimitriou.eu/wp-content/uploads/2008/04/google-image-search.jpg',
'google-image-search.jpg')
```
It worked. The image was downloaded and can be open by any image viewer software.
---
However, the co... | If you used the following, you can download the image:
```
wget http://upload.wikimedia.org/wikipedia/en/4/44/Zindagi1976.jpg
```
But if you did the following:
```
from urllib import urlretrieve
urlretrieve('http://upload.wikimedia.org/wikipedia/en/4/44/Zindagi1976.jpg',
'Zindagi1976.jpg')
```
You may ... |
Django Test Client and Subdomains | 8,389,109 | 9 | 2011-12-05T17:14:00Z | 8,751,766 | 8 | 2012-01-06T00:08:13Z | [
"python",
"django",
"testing"
] | I'm trying to figure out how to make the Django test client play nice with my app that puts each user on it's own subdomain. i.e. each account has account1.myapp.com, account2.myapp.com.
A user could be members of multiple subdomains (similar basecamp's model) so i handle which subdomain the request is being issued ag... | in your tests, when using the client, add the HTTP\_HOST parameter:
```
response = c.post(reverse('my-url'), data={}, HTTP_HOST='account1.myapp.com')
```
on your middleware now you should see the host changed! |
Unittest setUp/tearDown for several tests | 8,389,639 | 60 | 2011-12-05T17:54:11Z | 8,391,043 | 81 | 2011-12-05T19:56:23Z | [
"python",
"unit-testing"
] | Is there a function that is fired at the beginning/end of a scenario of tests? The functions setUp and tearDown are fired before/after every single test.
I typically would like to have this:
```
class TestSequenceFunctions(unittest.TestCase):
def setUpScenario(self):
start() #launched at the beginning, o... | As of 2.7 (per [the documentation](http://docs.python.org/library/unittest.html#setupclass-and-teardownclass)) you get `setUpClass` and `tearDownClass` which execute before and after the tests in a given class are run, respectively. Alternatively, if you have a group of them in one file, you can use `setUpModule` and `... |
How are generators and coroutines implemented in CPython? | 8,389,812 | 22 | 2011-12-05T18:10:16Z | 8,390,077 | 11 | 2011-12-05T18:32:39Z | [
"python",
"coroutine"
] | I've read that in CPython, the interpreter stack (the list of Python functions called to reach this point) is mixed with the C stack (the list of C functions that were called in the interpreter's own code). If so, then how are generators and coroutines implemented? How do they remember their execution state? Does CPyth... | The `yield` instruction takes the current executing context as a closure, and transforms it into an own living object. This object has a `__iter__` method which will continue after this yield statement.
So the call stack gets transformed into a heap object. |
How are generators and coroutines implemented in CPython? | 8,389,812 | 22 | 2011-12-05T18:10:16Z | 8,391,403 | 25 | 2011-12-05T20:26:02Z | [
"python",
"coroutine"
] | I've read that in CPython, the interpreter stack (the list of Python functions called to reach this point) is mixed with the C stack (the list of C functions that were called in the interpreter's own code). If so, then how are generators and coroutines implemented? How do they remember their execution state? Does CPyth... | The notion that Python's stack and C stack in a running Python program are intermixed can be misleading.
The Python stack is something completely separated than the actual C stack used by the interpreter. The data structures on Python stack are actually full Python "frame" objects (that can even be introspected and ha... |
In python how can I set multiple values of a list to zero simultaneously? | 8,390,517 | 7 | 2011-12-05T19:10:12Z | 8,390,541 | 17 | 2011-12-05T19:12:32Z | [
"python"
] | Conceptually, I want to do:
```
arr[20:] = 0
```
where `arr` is a `list`.
How can I do this? | You can do it directly using slice assignment.
```
arr[20:] = [0] * (len(arr) - 20)
```
But the natural way is just to iterate.
```
for i in xrange(20, len(arr)):
arr[i] = 0
``` |
Python: Why doesn't this work? (iteration over non-sequence) | 8,391,935 | 2 | 2011-12-05T21:11:48Z | 8,391,954 | 7 | 2011-12-05T21:13:44Z | [
"python",
"dictionary",
"iteration",
"sequence"
] | I have a dictionary with each key containing a list as a value. And I'm trying to go over all the items in the lists, and let's say I'm trying to print all the items as I go through, I wrote:
```
for item in aDict:
for item2 in aDict[item]:
print item2
```
This prints out the items in the list for the f... | One of your dictionary values is not a list! |
Dynamic arrays and structures in structures in python | 8,392,203 | 4 | 2011-12-05T21:35:15Z | 8,461,982 | 8 | 2011-12-11T04:35:33Z | [
"python",
"ctypes"
] | I am trying to implement this C structures in python using ctypes:
```
struct _rows {
int cols_count;
char *cols[];
}
struct _unit {
int rows_count;
struct _rows *rows;
}
int my_func(struct _unit *param);
```
Problem is that \_rows.cols is a dynamically sized array of char pointer and \_unit.rows is... | I'm making some assumptions about what the OP wants, and I'd love suggestions if there is an easier way to do this, but this is what I came up with:
### demo.py
```
import string
from ctypes import Structure,c_int,c_char_p,POINTER,cast,pointer,byref,CDLL
class Row(Structure):
_fields_ = [('cols_count', c_int),
... |
How to implement a Lock with a timeout in Python 2.7 | 8,392,640 | 16 | 2011-12-05T22:12:50Z | 8,393,033 | 14 | 2011-12-05T22:50:54Z | [
"python",
"multithreading",
"synchronization"
] | Is there a way to implement a lock in Python for multithreading purposes whose `acquire` method can have an arbitrary timeout? The only working solutions I found so far use polling, which
* I find inelegant and inefficient
* Doesn't preserve the bounded waiting / progress guarantee of the lock as a solution to the cri... | to elaborate on Steven's comment suggestion:
```
import threading
import time
lock = threading.Lock()
cond = threading.Condition(threading.Lock())
def waitLock(timeout):
with cond:
current_time = start_time = time.time()
while current_time < start_time + timeout:
if lock.acquire(False... |
django admin - group permissions to edit or view models | 8,392,780 | 7 | 2011-12-05T22:27:30Z | 8,393,130 | 8 | 2011-12-05T22:59:38Z | [
"python",
"django"
] | I'm searching for a way to customize the Django Administration to support permissions based on the user group.
For example, I've just created the Developers group, now I've also created the Tickets model, with AdminModel to specify how to list data.
I'd like to have this model visible only by Developers, and hidden t... | `ModelAdmin` has three methods dealing with user permission: `has_add_permission`, `has_change_permission` and `has_delete_permission`. All three should return boolean (`True`/`False`).
So you could do something like:
```
class TicketAdmin(admin.ModelAdmin):
...
def has_add_permission(self, request):
... |
itertools does not work in GAE? | 8,393,719 | 2 | 2011-12-06T00:10:00Z | 8,393,760 | 8 | 2011-12-06T00:16:42Z | [
"python",
"google-app-engine"
] | error log:
```
2011-12-05 14:56:01.211
<type 'exceptions.AttributeError'>: 'module' object has no attribute 'product'
Traceback (most recent call last):
File "/base/data/home/apps/s~ellipt-test/1.355173855249110456/helloworld.py", line 494, in <module>
F16 = field_elements(2, 4)
File "/base/data/home/apps/s~e... | The [app engine docs](http://code.google.com/appengine/docs/whatisgoogleappengine.html#The_Application_Environment) say:
> Your application can run in one of three runtime environments: [â¦] a choice of Python 2.5 or the experimental Python 2.7.
I'm assuming this implies the default Python is version 2.5.
The [`ite... |
ZMQ pub/sub reliable/scalable design | 8,394,076 | 3 | 2011-12-06T01:06:11Z | 8,400,389 | 7 | 2011-12-06T13:07:09Z | [
"python",
"publish-subscribe",
"zeromq",
"messagebroker"
] | I'm designin a pub/sub architecture using ZMQ. I need maximum reliability and scalability and am kind of lost in the hell of possibilities provided.
At the moment, I got a set a publishers and subscribers, linked by a broker. The broker is a simple forwarder device exposing a frontend for publishers, and a backend for... | It's not possible to answer your question directly because it's predicated on so many assumptions, many of which are probably wrong.
You're getting lost because you're using the wrong approach. Consider 0MQ as a language, one that you don't know very well yet. If you start by trying to write "maximum reliability and s... |
Complex foreign key constraint in SQLAlchemy | 8,394,177 | 7 | 2011-12-06T01:20:08Z | 8,395,021 | 9 | 2011-12-06T03:32:10Z | [
"python",
"sql",
"postgresql",
"database-design",
"sqlalchemy"
] | I have two tables, `SystemVariables` and `VariableOptions`. `SystemVariables` should be self-explanatory, and `VariableOptions` contains all of the possible choices for all of the variables.
`VariableOptions` has a foreign key, `variable_id`, which states which variable it is an option for. `SystemVariables` has a for... | You can implement that **without dirty tricks**. Just **extend the foreign key** referencing the chosen option to include `variable_id` in addition to `choice_id`.
Here is a working demo. Temporary tables, so you can easily play with it:
```
CREATE TEMP TABLE systemvariables (
variable_id integer PRIMARY KEY
, vari... |
pyschools: wrong answer being given by site? (Topic 2, Q 7) | 8,394,602 | 2 | 2011-12-06T02:22:43Z | 8,394,647 | 9 | 2011-12-06T02:28:28Z | [
"python"
] | I am new to python! Done my studying, gone through several books and now attempting pyschools challenges. Done Variables and data types successfully but Question 7 of Topic 2 (Functions) is giving me hell.
I am using Eclipse with Python (ver 3.2). in my eclipse, I get the answers 100, 51 and 525. Those are the same an... | You're using Python 3.x and they're using Python 2.x. In Python 2.x, the `/` operation is always an integer division when the arguments are integers. `1/2` is `0`. So, use `float()` to change one of your arguments to a floating-point number, such as `int((float(a) / b) * 100)`. Then `a/b` will have a fractional part.
... |
How to reverse geocode serverside with python, json and google maps? | 8,395,252 | 6 | 2011-12-06T04:11:57Z | 8,395,513 | 12 | 2011-12-06T04:55:43Z | [
"python",
"google-maps-api-3",
"reverse-geocoding"
] | I'm trying serverside reverse geocoding that can get me a json response and now I want to get 2 or 3 variables from the json response:
I'd like to parse for instance this data and end with eg.
`administrative_area_level_1 = 'Stockholm'`
`jsondata = json.load(urllib2.urlopen('http://maps.googleapis.com/maps/api/geocod... | ## Processing the response
There is **no need to parse the JSON** - it is already parsed by `json.load()` and returned as Python's data structure. **Use it like simple dictionary** with lists or different dictionaries in it.
## Accessing the needed part of the response
To access data you should be working with you c... |
how to sort alphanumerically in Unix with sort? More complex than seems | 8,395,395 | 4 | 2011-12-06T04:34:12Z | 8,395,493 | 11 | 2011-12-06T04:52:46Z | [
"python",
"bash",
"shell",
"unix",
"sorting"
] | I'm trying to sort a string of letters and numbers alphanumerically in an "intuitive"/natural way using the unix `sort` command, but cannot get it to sort properly. I have this file:
```
$ cat ~/headers
@42EBKAAXX090828:6:100:1699:328/2
@42EBKAAXX090828:6:10:1077:1883/2
@42EBKAAXX090828:6:102:785:808/2
```
I'd like ... | the `-V` option appears to do what you want - natural sorting. Intended for version numbers apparently (hence the letter chosen)
```
sort -V ~/headers
```
outputs
```
@42EBKAAXX090828:6:10:1077:1883/2
@42EBKAAXX090828:6:100:1699:328/2
@42EBKAAXX090828:6:102:785:808/2
``` |
String formatting options: pros and cons | 8,395,925 | 22 | 2011-12-06T05:53:36Z | 8,395,950 | 20 | 2011-12-06T05:58:35Z | [
"python",
"string-formatting"
] | These are two very popular ways of formatting a string in Python. One is using a `dict`:
```
>>> 'I will be %(years)i on %(month)s %(day)i' % {'years': 21, 'month': 'January', 'day': 23}
'I will be 21 on January 23'
```
And the other one using a simple `tuple`:
```
>>> 'I will be %i on %s %i' % (21, 'January', 23)
'... | I'm not exactly answering your question, but just thought it'd be nice to throw `format` into your mix.
I personally prefer the syntax of `format` to both:
```
'I will be {years} on {month} {day}'.format(years=19, month='January', day=23)
```
If I want something compact, I just write:
```
'I will be {} on {} {}'.fo... |
String formatting options: pros and cons | 8,395,925 | 22 | 2011-12-06T05:53:36Z | 8,396,057 | 20 | 2011-12-06T06:14:21Z | [
"python",
"string-formatting"
] | These are two very popular ways of formatting a string in Python. One is using a `dict`:
```
>>> 'I will be %(years)i on %(month)s %(day)i' % {'years': 21, 'month': 'January', 'day': 23}
'I will be 21 on January 23'
```
And the other one using a simple `tuple`:
```
>>> 'I will be %i on %s %i' % (21, 'January', 23)
'... | ## Why `format()` is more flexible than `%` string operations
I think you should really stick to `format()` method of `str`, because it is the preferred way to format strings and will probably replace string formatting operation in the future.
Furthermore, it has some really good features, that can also **combine pos... |
Invert image displayed by imshow in matplotlib | 8,396,101 | 30 | 2011-12-06T06:20:14Z | 8,396,124 | 47 | 2011-12-06T06:24:06Z | [
"python",
"image",
"matplotlib"
] | I wanted the `imshow()` function in `matplotlib.pyplot` to display images the opposite way, i.e upside down. Is there a simple way to do this? | Specify the keyword argument `origin='lower'` or `origin='upper'` in your call to `imshow`. |
Putting command in the background with Fabric does not work on some hosts | 8,396,987 | 15 | 2011-12-06T08:19:49Z | 8,397,584 | 23 | 2011-12-06T09:20:15Z | [
"python",
"ssh",
"fabric"
] | For testing purposes, I am running the following command, with plain ssh command line tool:
```
ssh user@host "nohup sleep 100 >> /tmp/xxx 2>&1 < /dev/null &"
```
This is working as expected, in all my hosts: a sleep process is created in the background, and the ssh finishes immediately.
I am trying to implement thi... | You are probably bumping into the infamous [**Fabric issue #395**](https://github.com/fabric/fabric/issues/395). The easiet workaround for these problems is to run your task with `pty=False`. |
/usr/bin/ld: cannot find -lpython2.7 | 8,400,272 | 12 | 2011-12-06T12:58:30Z | 8,400,446 | 17 | 2011-12-06T13:10:58Z | [
"python",
"linux",
"mysql-python"
] | I'm trying to install MySQLdb with Python 2.7. The error I'm getting looks like this:
```
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3 -I/usr/include/mysql -I/opt/python2.7/include/python2.7 -c _mysql.c -o build/te... | It can't find the Python library, not the executable. Run `locate libpython2.7.a` to see where your Python library is located, and add it to the library path (e.g. if it is in `/opt/python2.7/lib`, you want to call `LDFLAGS="-L/opt/python2.7/lib" make`).
The `@` symbol means the file is a symbolic link; `*` means it's... |
/usr/bin/ld: cannot find -lpython2.7 | 8,400,272 | 12 | 2011-12-06T12:58:30Z | 11,831,037 | 9 | 2012-08-06T15:14:57Z | [
"python",
"linux",
"mysql-python"
] | I'm trying to install MySQLdb with Python 2.7. The error I'm getting looks like this:
```
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3 -I/usr/include/mysql -I/opt/python2.7/include/python2.7 -c _mysql.c -o build/te... | The above solution didn't quite do it for me as I was using pip to install mysql-python, but was definitely a big push in the right direction. For the benefit of anyone who lands here from Google in the same situation as me, my solution was to symlink libpython2.7.a from the python installation directory to the lib dir... |
python pip silent install | 8,400,382 | 5 | 2011-12-06T13:06:15Z | 8,400,396 | 12 | 2011-12-06T13:07:57Z | [
"python",
"pip"
] | Is there a way to do a silent install with pip?
For some more background I'm using fabric to do server deployments and I want to be able to setup a new server or update an existing one without any interaction and some of the packages require a y/n response. | If the answer is always `y`:
```
yes | pip install <package>
``` |
Error in PIL installed with PIP - Django,Python | 8,401,085 | 3 | 2011-12-06T13:59:53Z | 8,401,970 | 11 | 2011-12-06T15:01:31Z | [
"python",
"django",
"osx",
"python-imaging-library",
"pip"
] | I installed PIL using PIP. However, using PIL on Django, when trying to upload a .jpg file, I get the error:
> Upload a valid image. The file you uploaded was either not an image or a corrupted image.
I read on the Internet about this error and a solution was to delete the compiled files for the current OS, then use ... | PIL need to find some libraries like libjpeg and libz during installation.
We encountered the same problems on our server and we installed PIL system-wide using
```
aptitude install python-imaging
```
This is a quick fix and it works for us.
Also googling about this show two ways how to fix this problem using PIL.
... |
Dictionary access speed comparison with integer key against string key | 8,403,681 | 16 | 2011-12-06T16:53:58Z | 8,403,754 | 15 | 2011-12-06T17:00:52Z | [
"python",
"dictionary"
] | I've got a large dictionary from which I have to look up for values a lot of times. My keys are integers but represent labels so do not need to be added, substracted, etc... I ended up trying to assess access time between string key and integer key dictionary and here is the result.
```
from timeit import Timer
Dint ... | CPython's `dict` implementation is in fact optimized for string key lookups. There are two different functions, `lookdict` and `lookdict_string` (`lookdict_unicode` in Python 3), which can be used to perform lookups. Python will use the string-optimized version until a search for non-string data, after which the more g... |
Parallelism in python isn't working right | 8,403,768 | 7 | 2011-12-06T17:01:36Z | 8,404,061 | 9 | 2011-12-06T17:22:48Z | [
"python",
"multithreading",
"google-app-engine",
"python-2.7",
"python-multithreading"
] | I was developing an app on gae using python 2.7, an ajax call requests some data from an API, a single request could take ~200 ms, however when I open two browsers and make two requests at a very close time they take more than the double of that, I've tried putting everything in threads but it didn't work.. (this happe... | [David Beazley gave a talk](http://python.mirocommunity.org/video/1479/pycon-2010-understanding-the-p) about this issue at PyCon 2010.
As others have already stated, for some tasks, using threading especially with multiple cores can lead to slower performance than the same task performed by a single thread. The problem... |
What's the pythonic way of conditional variable initialization? | 8,404,856 | 10 | 2011-12-06T18:26:01Z | 8,405,005 | 9 | 2011-12-06T18:38:23Z | [
"python"
] | Due to the scoping rules of Python, all variables once initialized within a scope are available thereafter. Since conditionals do not introduce new scope, constructs in other languages (such as initializing a variable before that condition) aren't necessarily needed. For example, we might have:
```
def foo(optionalvar... | Python also has a very useful if syntax pattern which you can use here
```
message = get_other_message() if optional_var else get_message()
```
Or if you want to compare strictly with None
```
message = get_other_message() if optional_var is not None else get_message()
```
Unlike with example 1) you posted this... |
Installing PIL with JPEG support on Mac OS X | 8,404,956 | 36 | 2011-12-06T18:34:48Z | 8,408,212 | 17 | 2011-12-06T23:08:17Z | [
"python",
"django",
"python-imaging-library",
"libjpeg"
] | I posted a question before regarding this subject, and read other ones posted before, but none has successfully solved my problem.
I am trying to install PIL on Mac OS X Lion, as I need it for a Django application. I also need JPEG support, so I need a JPEG decoder as well.
I have tried to download the libjpeg source... | I installed libjpeg and PIL on Snow and it was migrated without problems to Lion.
I think however that you have the same problem I faced with installing libjpeg 7 on Snow. The solution for me was :
> * Make sure that you are NOT using GCC 4.0. That means those export lines in your .bash\_profile file that you needed ... |
Installing PIL with JPEG support on Mac OS X | 8,404,956 | 36 | 2011-12-06T18:34:48Z | 10,524,708 | 16 | 2012-05-09T22:00:25Z | [
"python",
"django",
"python-imaging-library",
"libjpeg"
] | I posted a question before regarding this subject, and read other ones posted before, but none has successfully solved my problem.
I am trying to install PIL on Mac OS X Lion, as I need it for a Django application. I also need JPEG support, so I need a JPEG decoder as well.
I have tried to download the libjpeg source... | Make sure you have homebrew and pip, and then run:
```
brew install libjpeg
pip install pil
``` |
Installing PIL with JPEG support on Mac OS X | 8,404,956 | 36 | 2011-12-06T18:34:48Z | 12,194,881 | 89 | 2012-08-30T10:32:11Z | [
"python",
"django",
"python-imaging-library",
"libjpeg"
] | I posted a question before regarding this subject, and read other ones posted before, but none has successfully solved my problem.
I am trying to install PIL on Mac OS X Lion, as I need it for a Django application. I also need JPEG support, so I need a JPEG decoder as well.
I have tried to download the libjpeg source... | In our virtualenv we found all we needed to do was:
```
pip uninstall PIL
brew install libjpeg
pip install PIL
```
which is simpler than some of the above and may be enough for others with this problem too.
Although there was an xcode warning on the brew and a setup.py package warning on the reinstall of PIL, all the... |
Installing PIL with JPEG support on Mac OS X | 8,404,956 | 36 | 2011-12-06T18:34:48Z | 13,143,595 | 10 | 2012-10-30T16:33:58Z | [
"python",
"django",
"python-imaging-library",
"libjpeg"
] | I posted a question before regarding this subject, and read other ones posted before, but none has successfully solved my problem.
I am trying to install PIL on Mac OS X Lion, as I need it for a Django application. I also need JPEG support, so I need a JPEG decoder as well.
I have tried to download the libjpeg source... | I used the following binary to get libpng and libjpeg installed systemwide on OSX:
[libpng & libjpeg for OSX](http://ethan.tira-thompson.com/Mac_OS_X_Ports.html)
Because I already had PIL installed (via pip on a virtualenv), I ran:
```
pip uninstall PIL
pip install PIL --upgrade
```
This resolved the `decoder JPEG ... |
Python 3.2 - cookielib | 8,405,096 | 7 | 2011-12-06T18:46:24Z | 8,405,294 | 16 | 2011-12-06T19:02:11Z | [
"python",
"python-3.x"
] | I have working 2.7 code, however there are no such thing as cookielib and urllib2 in 3.2? How can I make this code work on 3.2? In case someone is wondering - I'm on Windows.
*Example 2.7*
```
import urllib, urllib2, cookielib
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
... | From [Python docs](http://docs.python.org/library/cookielib.html):
> Note The cookielib module has been renamed to http.cookiejar in Python
> 3.0. **The 2to3 tool will automatically adapt imports when converting your sources to 3.0**.
Is that not an acceptable solution? If not, why? |
Why does Pycharm's inspector complain about "d = {}"? | 8,406,242 | 64 | 2011-12-06T20:16:50Z | 8,406,391 | 86 | 2011-12-06T20:29:00Z | [
"python",
"pycharm"
] | When initializing a dictionary with `d = {}` Pycharm's code inspector generates a warning, saying
> This dictionary creation could be rewritten as a dictionary literal.
If I rewrite it `d = dict()` the warning goes away. Since `{}` already *is* a dictionary literal, I'm pretty sure the message is erroneous. Furthermo... | **What is the following code to your dictionary declaration?**
I think pycharm will trigger the error if you have something like:
```
dic = {}
dic['aaa'] = 5
```
as you could have written
```
dic = {'aaa': 5}
```
BTW: The fact that the error goes away if you use the function doesn't necessarily mean that pycharm b... |
finding element of numpy array that satisfies condition | 8,407,090 | 8 | 2011-12-06T21:27:42Z | 8,407,219 | 9 | 2011-12-06T21:38:02Z | [
"python",
"search",
"numpy"
] | One can use `numpy`'s `extract` function to match an element in an array. The following code matches an element `'a.'` exactly in an array. Suppose I want
to match all elements containing `'.'`, how would I do that? Note that in this case, there would be two matches. I'd also like to get the row and column number of th... | You can use the [string operations](http://docs.scipy.org/doc/numpy/reference/routines.char.html#string-information):
```
>>> import numpy as np
>>> x = np.array([['a.','cd'],['ef','g.']])
>>> x[np.char.find(x, '.') > -1]
array(['a.', 'g.'],
dtype='|S2')
```
**EDIT:** As per request in the comments... If you w... |
Python: how to make a recursive generator function | 8,407,760 | 3 | 2011-12-06T22:24:41Z | 8,407,800 | 15 | 2011-12-06T22:27:22Z | [
"python",
"recursion",
"generator"
] | I have been working on generating all possible submodels for a biological problem. I have a working recursion for generating a big list of all the submodels I want. However, the lists get unmanageably large pretty fast (N=12 is just possible in the example below, N>12 uses too much memory). So I wanted to convert it to... | You should change this:
```
submodel_generator(newpat, current+1, maxn)
```
to this:
```
for b in submodel_generator(newpat, current+1, maxn):
yield b
```
This will recursively yield the value from successive calls to the function.
**[Update]:** Note that as of Python 3.3, you can use the new [yield from](http... |
How to change the name of a Django app? | 8,408,046 | 48 | 2011-12-06T22:51:04Z | 8,408,131 | 94 | 2011-12-06T22:59:12Z | [
"python",
"django"
] | I have changed the name of an app in Django by renaming its folder, imports and all its references (templates/indexes). But now I get this error when I try to run `python manage.py runserver`
```
Error: Could not import settings 'nameofmynewapp.settings' (Is it on sys.path?): No module named settings
```
How can I de... | follow these steps to change django app name -
1. Rename the folder which is in your project root
2. Change any references to your app in their dependencies, i.e. the app's `views.py`, `urls.py` , 'manage.py' , and `settings.py` files.
3. Edit the database table `django_content_type` with the following command: `UPDAT... |
How to change the name of a Django app? | 8,408,046 | 48 | 2011-12-06T22:51:04Z | 27,225,328 | 13 | 2014-12-01T09:31:44Z | [
"python",
"django"
] | I have changed the name of an app in Django by renaming its folder, imports and all its references (templates/indexes). But now I get this error when I try to run `python manage.py runserver`
```
Error: Could not import settings 'nameofmynewapp.settings' (Is it on sys.path?): No module named settings
```
How can I de... | New in Django 1.7 is a app registry that stores configuration and provides introspection. This machinery let's you change several app attributes.
The main point I want to make is that renaming an app isn't always necessary: With app configuration it is possible to resolve conflicting apps. But also the way to go if yo... |
Python timedelta issue with negative values | 8,408,397 | 13 | 2011-12-06T23:28:16Z | 8,408,546 | 24 | 2011-12-06T23:45:52Z | [
"python",
"timedelta"
] | Hi I need some help to understand why this is happening.
I have a method to track 'time remaining' in an event program:
```
def get_program_time_budget(self):
return self.estimated_duration-self.get_program_duration()
```
All fine when the estimated\_duration > self.get\_program\_duration() but when this goes the... | If you are using Python 2.7 or higher you can use [`timedelta.total_seconds()`](http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds) to get an integer representation of the timedelta as a positive or negative number of seconds.
```
>>> datetime.timedelta(-1, 86100).total_seconds()
-300.0
```
... |
Django : CSRF verification failed even after adding {% csrf_token %} | 8,408,545 | 3 | 2011-12-06T23:45:42Z | 8,410,247 | 8 | 2011-12-07T04:04:30Z | [
"python",
"django"
] | **views.py:**
```
def index(request):
return render_to_response('index.html', {})
def photos(request, artist):
if not artist:
return render_to_response('photos.html', {'error' : 'no artist supplied'})
photos = get_photos_for_artist(artist)
if not photos:
logging.error('Issue while gett... | add `context_instance=RequestContext(request)` to every view that you will use a form inside it:
```
return render_to_response('index.html', {}, context_instance=RequestContext(request) )
return render_to_response('photos.html', {'photos': photos}, context_instance=RequestContext(request) )
``` |
matplotlib: Set markers for individual points on a line | 8,409,095 | 58 | 2011-12-07T00:56:02Z | 8,409,110 | 109 | 2011-12-07T00:57:45Z | [
"python",
"numpy",
"matplotlib"
] | I have used matplotlib to plot lines on a figure. Now I would now like to set the style, specifically the marker, for individual points on the line. How do I do this?
Edit:
to clarify my question, which was answered, I want to be able to set the style for individual markers on a line, not every marker on said line. | Specify the keyword args `linestyle` and/or `marker` in your call to `plot`.
For example, using a dashed line and blue circle markers:
```
plt.plot(range(10), linestyle='--', marker='o', color='b')
```
A shortcut call for the same thing:
```
plt.plot(range(10), '--bo')
```
` also has a `set_markevery()` method which allows you to only set markers on certain points - see <http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.lines.Line2D.set_marker> |
Unable to deserialize PyMongo ObjectId from JSON | 8,409,194 | 6 | 2011-12-07T01:07:20Z | 8,409,539 | 11 | 2011-12-07T02:04:23Z | [
"python",
"json",
"mongodb",
"pymongo",
"bson"
] | I'm seemingly unable to deserialize my MongoDB JSON document with the BSON [json\_util](http://api.mongodb.org/python/current/api/bson/json_util.html).
The json.loads function is choking on the `ObjectId()` string. I had understood json\_util capable of handling MongoDB's ObjectId format and transforming into usable J... | I think your string form actually looks like the python representation...
```
s = '{"_id": {"$oid": "4edebd262ae5e93b41000000"}}'
u = json.loads(s, object_hook=json_util.object_hook)
print u # Result: {u'_id': ObjectId('4edebd262ae5e93b41000000')}
s = json.dumps(u, default=json_util.default)
print s # Result: {... |
How to install Python 2.7 bindings for OpenCV using MacPorts | 8,410,443 | 9 | 2011-12-07T04:36:55Z | 8,547,012 | 14 | 2011-12-17T18:36:13Z | [
"python",
"opencv",
"osx-lion",
"macports"
] | When trying to "import cv" in python I get: "ImportError: No module named cv". This question has appeared in many forms, but I haven't found the answer that helps.
On my Mac OS X Lion, among many other ports, I have run:
```
sudo port install python27
```
and
```
sudo port install opencv +python27
```
Running:
``... | I had this same problem. It looks like a (maybe?) bug with the OpenCV install script for 2.3.1a. It will not create the Python bindings unless NumPy is already installed.
To fix it:
```
sudo port uninstall opencv
sudo port install py27-numpy
sudo port install opencv +python27
```
That worked for me! I found this by ... |
Can argparse in python 2.7 be told to require a minimum of TWO arguments? | 8,411,218 | 4 | 2011-12-07T06:22:31Z | 8,411,421 | 14 | 2011-12-07T06:46:21Z | [
"python",
"argparse"
] | My application is a specialized file comparison utility and obviously it does not make sense to compare only one file, so `nargs='+'` is not quite appropriate.
`nargs=N` only excepts a maximum of `N` arguments, but I need to accept an infinite number of arguments as long as there are at least two of them. | Short answer is you can't do that because nargs doesn't support something like '2+'.
Long answer is you can workaround that using something like this:
```
parser = argparse.ArgumentParser(usage='%(prog)s [-h] file file [file ...]')
parser.add_argument('file1', nargs=1, metavar='file')
parser.add_argument('file2', nar... |
Twisted MySQL adbapi return dictionary | 8,411,613 | 5 | 2011-12-07T07:07:57Z | 8,730,096 | 9 | 2012-01-04T16:18:14Z | [
"python",
"twisted"
] | Is there any way to return dictionary result from adbapi query to MySQL?
```
[name: 'Bob', phone_number: '9123 4567']
```
Default returns tuple.
```
['Bob', '9123 4567']
```
For simple Python & MySQL we can use **MySQLdb.cursors.DictCursor**. But how to use it with twisted adbapi
---
**UPD:** I solved it but I th... | You can direct MySQLdb to use `DictCursor` by passing it as the value for the `cursorclass` argument to the `connect` function. `ConnectionPool` allows you to pass arbitrary arguments through to the connect method:
```
import MySQLdb
pool = ConnectionPool("MySQLdb", ..., cursorclass=MySQLdb.cursors.DictCursor)
...
```... |
Why this error from urllib? | 8,411,622 | 10 | 2011-12-07T07:09:00Z | 8,419,306 | 14 | 2011-12-07T17:00:57Z | [
"python",
"google-app-engine",
"urllib2"
] | I get a strange error when using urllib:
```
INFO 2011-12-07 07:02:45,101 main.py:884] urlhttp://maps.googleapis.com/maps/api/geocode/json?latlng=59.3333,18.05&sensor=false
WARNING 2011-12-07 07:02:45,103 urlfetch_stub.py:428] Stripped prohibited headers from URLFetch request: ['Host']
ERROR 2011-12-07 07:02:4... | This seems to be a bug with the SDK. I was able to replicate the exact same behavior. Is there any reason you are using `urllib2` instead of `urllib`?
Using Python2.7 and SDK 1.6.1, I tested the following:
```
import urllib
url = 'http://maps.googleapis.com/maps/api/geocode/json' + \
'?latlng={},{}&sensor=f... |
How do I check in python if an element of a list is empty? | 8,411,889 | 3 | 2011-12-07T07:39:43Z | 8,411,922 | 7 | 2011-12-07T07:43:26Z | [
"python",
"list",
"element"
] | I have a list like
```
l = []
```
How do I check if l[i] is empty?
```
l[i] = ''
```
and
```
l[i] = ""
```
dont't work. | Try:
```
if l[i]:
print 'Found element!'
else:
print 'Empty element.'
``` |
Syntax sugar for querying a Python list which element occurs first | 8,412,223 | 12 | 2011-12-07T08:18:41Z | 8,412,229 | 7 | 2011-12-07T08:19:33Z | [
"python",
"list",
"syntactic-sugar"
] | I have a list of many elements.
I care about two of its elements, `a` and `b`.
I don't know the order of the list, nor do I want to sort it.
Is there a nice one-liner that will return `True` if `a` occurs before `b` and false otherwise? | You can use `list.index`:
```
l.index(a) < l.index(b)
```
This of course assumes that both items are present in the list. |
Syntax sugar for querying a Python list which element occurs first | 8,412,223 | 12 | 2011-12-07T08:18:41Z | 8,412,252 | 9 | 2011-12-07T08:21:55Z | [
"python",
"list",
"syntactic-sugar"
] | I have a list of many elements.
I care about two of its elements, `a` and `b`.
I don't know the order of the list, nor do I want to sort it.
Is there a nice one-liner that will return `True` if `a` occurs before `b` and false otherwise? | In the interests of diversity, you could also:
```
b in l[l.index(a):]
```
This will be `True` if `a == b`. If you know that `a != b`,
```
b in l[l.index(a) + 1:]
``` |
Syntax sugar for querying a Python list which element occurs first | 8,412,223 | 12 | 2011-12-07T08:18:41Z | 8,412,352 | 8 | 2011-12-07T08:33:43Z | [
"python",
"list",
"syntactic-sugar"
] | I have a list of many elements.
I care about two of its elements, `a` and `b`.
I don't know the order of the list, nor do I want to sort it.
Is there a nice one-liner that will return `True` if `a` occurs before `b` and false otherwise? | ## Edit: Rewritten to check more cases
OK, so this problem needs a bit more work. Mark Byers is completely right in that my first test only covered cases where the result would be `True`. This is especially relevant because we need exception handlers for the other solutions. So I've gone into a bit more detail:
```
s... |
User authentication in tornado websocket application | 8,412,665 | 7 | 2011-12-07T09:02:26Z | 8,412,743 | 9 | 2011-12-07T09:09:02Z | [
"python",
"authentication",
"tornado"
] | Now, i improve my tornado skills and have a question about user auth.
And my solution is create secure token on first page and next send it with other data, from javascript to tornado server where do checking and auth user.
i think about cookie but i don't know how i can read cookies in `WebSocketHandler.on_message`
... | I suggest you read the [overview section](http://www.tornadoweb.org/en/branch2.4/overview.html) in the documentation.
There should be some relevant content there:
* [Cookies and secure cookies](http://www.tornadoweb.org/en/branch2.4/overview.html#cookies-and-secure-cookies)
* [User Authentication](http://www.tornadow... |
Printing a word Document within Python | 8,413,207 | 3 | 2011-12-07T09:42:56Z | 8,413,374 | 8 | 2011-12-07T09:54:11Z | [
"python"
] | I have a simple batch file here which will print a word document from the command line.
```
"C:\Program Files\Microsoft Office\Office12\winword.exe" "p:\docs\daily checks.doc" /mFilePrintDefault /mFileExit
```
I am trying to place this into a python script, I have managed to get the document to open by using
```
sub... | This should work:
```
subprocess.Popen(["C:\\Program Files\Microsoft Office\Office12\winword.exe", "P:\\docs\\daily checks.doc", "/mFilePrintDefault", "/mFileExit"]).communicate()
```
Or, altenatively,
```
subprocess.Popen("'C:\\Program Files\Microsoft Office\Office12\winword.exe' 'P:\\docs\\daily checks.doc' /mFile... |
Comparing instances of a dict subclass | 8,415,555 | 3 | 2011-12-07T12:49:17Z | 8,415,985 | 8 | 2011-12-07T13:22:17Z | [
"python"
] | I have subclassed dict to add an extra method (so no overriding).
Now, I try to compare two of those subclasses, and I get something weird :
```
>>> d1.items() == d2.items()
True
>>> d1.values() == d2.values()
True
>>> d1.keys() == d2.keys()
True
>>> d1 == d2
False
```
**EDIT**
That's damn weird ... I don't underst... | the problem you're seing has nothing at all to do with subclassing `dict`. in fact this behavior can be seen using a regular dict. The problem is how you have defined the *keys* you're using. A simple class like:
```
>>> class Foo(object):
... def __init__(self, value):
... self.value = value
...
... ... |
In python, is there a good idiom for using context managers in setup/teardown | 8,416,208 | 26 | 2011-12-07T13:39:26Z | 11,180,583 | 19 | 2012-06-24T19:33:49Z | [
"python",
"unit-testing",
"contextmanager"
] | I am finding that I am using plenty of context managers in Python. However, I have been testing a number of things using them, and I am often needing the following:
```
class MyTestCase(unittest.TestCase):
def testFirstThing(self):
with GetResource() as resource:
u = UnderTest(resource)
u.doStuff()
... | How about overriding `unittest.TestCase.run()` as illustrated below? This approach doesn't require calling any private methods or doing something to every method, which is what the questioner wanted.
```
from contextlib import contextmanager
import unittest
@contextmanager
def resource_manager():
yield 'foo'
cla... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.