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 |
|---|---|---|---|---|---|---|---|---|---|
how to make sortable datatype in Python? | 4,630,341 | 6 | 2011-01-07T21:12:44Z | 4,630,368 | 8 | 2011-01-07T21:16:40Z | [
"python",
"sorting",
"data-structures"
] | I have a class representing something with a few fields. When a list of instances of this class is sorted, I want them to be sorted in a particular order (get a particular key from each one). I can just do `list.sort(key=Classname.sortKey)` and define a `sortKey` method, but I'd rather just do `list.sort()` and have it... | Check out <http://wiki.python.org/moin/HowTo/Sorting/>
You want to override `__lt__` in your class for the built in `sort` function to work the way you described. |
How to include a quote in a raw Python string? | 4,630,465 | 39 | 2011-01-07T21:27:30Z | 4,630,497 | 60 | 2011-01-07T21:31:15Z | [
"python",
"syntax"
] | ```
>>> r"what"ever"
SyntaxError: invalid syntax
>>> r"what\"ever"
'what\\"ever'
```
So how do we get the quote but not the slash?
And please don't suggest `r'what"ever'` because then the question just becomes how do we include both types of quotes?
[related](http://stackoverflow.com/questions/647769/why-cant-python... | If you want to use double quotes in strings but not single quotes, you can just use single quotes as the delimiter instead:
```
r'what"ever'
```
If you need both kinds of quotes in your string, use a triple-quoted string:
```
r"""what"ev'er"""
```
If you want to include both kinds of triple-quoted strings in your s... |
Defining lists as global variables in Python | 4,630,543 | 8 | 2011-01-07T21:37:14Z | 4,630,641 | 13 | 2011-01-07T21:54:17Z | [
"python",
"list",
"global-variables"
] | I am using a list on which some functions works in my program. This is a shared list actually and all of my functions can edit it. Is it really necessary to define it as "global" in all the functions?
I mean putting the global keyword behind it in each function that uses it, or defining it outside of all the functions... | When you assign a variable (`x = ...`), you are creating a variable in the current scope (e.g. local to the current function). If it happens to shadow a variable fron an outer (e.g. global) scope, well too bad - Python doesn't care (and that's a good thing). So you can't do this:
```
x = 0
def f():
x = 1
f()
print... |
Unresolved Import Issues with PyDev and Eclipse | 4,631,377 | 79 | 2011-01-07T23:55:27Z | 4,632,022 | 106 | 2011-01-08T02:26:19Z | [
"python",
"pydev",
"python-import"
] | I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04.
I want to be able to use the file odbchelper.py, wh... | In the properties for your pydev project, there's a pane called "PyDev - PYTHONPATH", with a sub-pane called "External Libraries". You can add source folders (any folder that has an `__init__.py`) to the path using that pane. Your project code will then be able to import modules from those source folders. |
Unresolved Import Issues with PyDev and Eclipse | 4,631,377 | 79 | 2011-01-07T23:55:27Z | 6,200,696 | 34 | 2011-06-01T11:54:34Z | [
"python",
"pydev",
"python-import"
] | I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04.
I want to be able to use the file odbchelper.py, wh... | I just upgraded a WXWindows project to Python 2.7 and had no end of trouble getting Pydev to recognize the new interpreter. Did the same thing as above configuring the interpreter, made a fresh install of Eclipse and Pydev. Thought some part of python must have been corrupt, so I re-installed everything again. Arghh! C... |
Unresolved Import Issues with PyDev and Eclipse | 4,631,377 | 79 | 2011-01-07T23:55:27Z | 13,709,672 | 11 | 2012-12-04T18:38:59Z | [
"python",
"pydev",
"python-import"
] | I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04.
I want to be able to use the file odbchelper.py, wh... | I fixed my pythonpath and everything was dandy when I imported stuff through the console, but all these previously unresolved imports were still marked as errors in my code, no matter how many times I restarted eclipse or refreshed/cleaned the project.
I right clicked the project->Pydev->Remove error markers and it go... |
Unresolved Import Issues with PyDev and Eclipse | 4,631,377 | 79 | 2011-01-07T23:55:27Z | 29,351,006 | 11 | 2015-03-30T16:07:52Z | [
"python",
"pydev",
"python-import"
] | I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04.
I want to be able to use the file odbchelper.py, wh... | I am using eclipse kepler 4.3, PyDev 3.9.2 and on my ubuntu 14.04 I encountered with the same problem. I tried and spent hours, with all the above most of the options but in vain. Then I tried the following which was great:
* Select **Project**-> RightClick-> **PyDev**-> **Remove PyDev Project Config**
* file-> **rest... |
Is there some lispy language that seamlessly integrates with Python? | 4,632,030 | 10 | 2011-01-08T02:29:26Z | 4,632,036 | 8 | 2011-01-08T02:33:12Z | [
"python",
"clojure",
"lisp",
"scheme"
] | Is there a language based on S-expressions with powerful macros that allows as seamless integration with Python as Clojure with JVM?
I want to try using such syntax and features while having access to all usual python libraries (including PyQt). | I've been working a project to do this: [psil](http://github.com/ghewgill/psil). I have a series of [blog posts](http://hewgill.com/journal/tags/psil) talking about what I've done. Here's the short [manifesto](http://hewgill.com/journal/entries/514-psil-manifesto):
> Psil is a new general-purpose programming language ... |
PIL /JPEG Library / Help! | 4,632,261 | 49 | 2011-01-08T04:00:19Z | 4,632,835 | 52 | 2011-01-08T07:05:35Z | [
"python",
"django",
"python-imaging-library",
"redhat",
"libjpeg"
] | I tried to use PIL to do some JPEG work in my django app with PIL but I'm getting this IOError.. not sure what to do.
```
""decoder jpeg not available""
```
Am I missing the JPEG decoder from my server? If so, how do I fix it? | You need to install jpeg library first and reinstall your PIL. For example, I'm using CentOS, to install libjpeg, I run
```
sudo yum install -y libjpeg-devel
```
It depends on what kind of linux you are using. And here you have to remove the old PIL
```
rm -rf /usr/lib/python2.6/site-packages/PIL-1.1.7-py2.6-linux-x... |
PIL /JPEG Library / Help! | 4,632,261 | 49 | 2011-01-08T04:00:19Z | 8,933,619 | 20 | 2012-01-19T21:34:24Z | [
"python",
"django",
"python-imaging-library",
"redhat",
"libjpeg"
] | I tried to use PIL to do some JPEG work in my django app with PIL but I'm getting this IOError.. not sure what to do.
```
""decoder jpeg not available""
```
Am I missing the JPEG decoder from my server? If so, how do I fix it? | A stronger answer can be found at [install pil on virtualenv with libjpeg](http://stackoverflow.com/questions/4435016/install-pil-on-virtualenv-with-libjpeg)
For me what finally worked on Ubutu was:
```
pip uninstall PIL
sudo apt-get install libjpeg8-dev
pip install PIL
```
The Python Imaging Library (PIL) seems rea... |
PIL /JPEG Library / Help! | 4,632,261 | 49 | 2011-01-08T04:00:19Z | 12,301,138 | 71 | 2012-09-06T13:24:13Z | [
"python",
"django",
"python-imaging-library",
"redhat",
"libjpeg"
] | I tried to use PIL to do some JPEG work in my django app with PIL but I'm getting this IOError.. not sure what to do.
```
""decoder jpeg not available""
```
Am I missing the JPEG decoder from my server? If so, how do I fix it? | *I have found this answer from author "edward"*
On Ubuntu precise, PIL doesn't find the jpeg library files, even once they are installed. The easiest way to fix this is to make a symlink after you have installed the jpeg dev package. So, I needed an extra step:
**for x64 OS**
```
pip uninstall PIL
sudo apt-get insta... |
Is there a better way to switch between HTML and JSON output in Pyramid? | 4,633,320 | 20 | 2011-01-08T09:54:11Z | 4,634,070 | 50 | 2011-01-08T13:26:19Z | [
"python",
"api",
"pylons",
"pyramid"
] | ```
# /test{.format} no longer seems to work...
config.add_route('test', '/test.{ext}', view='ms.views.test')
```
views.py:
```
from pyramid.response import Response
from pyramid.renderers import render
import json
def test(request):
extension = request.matchdict['ext']
variables = {'name' : 'blah', 'asd' :... | I think, the better way is to add the same view twice with difference renderers. Suppose we have the following view:
```
def my_view(request):
return {"message": "Hello, world!"}
```
Now in our configuration we can add the same view twice:
```
from pyramid.config import Configurator
config = Configurator()
confi... |
Python: Convert JSON (returned by URL) into List | 4,634,209 | 8 | 2011-01-08T14:04:07Z | 4,634,301 | 13 | 2011-01-08T14:24:22Z | [
"python",
"json"
] | I am requesting youtube search terms for use with jquery autocomplete, but am having a hard time converting the URL response into a proper format.
In my (Django/Python) view I do:
```
data2 = urllib2.urlopen('http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&jsonp=window.yt.www.sugge... | remove the `&jsonp=window.yt.www.suggest.handleResponse` part
```
import json
import urllib2
data = urllib2.urlopen('http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&q=jum&cp=3')
j = json.load(data)
k = [i for i, j, k in j[1]]
l = json.dumps(k)
``` |
Excel Solver in Python | 4,634,317 | 5 | 2011-01-08T14:28:17Z | 4,637,012 | 13 | 2011-01-09T00:33:38Z | [
"python"
] | I'm trying to implement something like this
<http://office.microsoft.com/en-us/excel-help/using-solver-to-rate-sports-teams-HA001124601.aspx>
in python with python libraries only (not calling Excel solver).
Can someone point me to the right libraries to be using + some dive-in tutorials to get started ? | You are looking for NumPy (matrix manipulation and number-crunching) and SciPy (optimization).
To get started, see [numpy: learning resources](http://stackoverflow.com/questions/4375094/numpy-learning-resources)
I worked out the given example as follows:
* I opened the sample Excel files in OpenOffice
* I copied the ... |
Python regex parse stream | 4,634,376 | 21 | 2011-01-08T14:41:13Z | 8,713,311 | 13 | 2012-01-03T13:54:31Z | [
"python",
"regex",
"stream"
] | Is there any way to use regex match on a stream in python?
like
```
reg = re.compile(r'\w+')
reg.match(StringIO.StringIO('aa aaa aa'))
```
And I don't want to do this by getting the value of the whole string. I want to know if there's any way to match regex on a srtream(on-the-fly).
Thanks! -vitiv | I had the same problem. The first thought was to implement a `LazyString` class, which acts like a string but only reading as much data from the stream as currently needed (I did this by reimplementing `__getitem__` and `__iter__` to fetch and buffer characters up to the highest position accessed...).
This didn't work... |
Python: can unittest display expected and actual values? | 4,634,625 | 7 | 2011-01-08T15:38:40Z | 4,634,640 | 7 | 2011-01-08T15:41:14Z | [
"python",
"unit-testing"
] | If I have an assert in a unittest.TestCase as shown below:
```
self.assertTrue( person.age == 42, "age incorrect")
```
When it fails, it gives the "age incorrect" message. What I would also like to see is the expected and actual values. What's the best way to go about doing this? Is it something unittest can do?
**E... | see: [assertEqual](http://docs.python.org/library/unittest.html#unittest.TestCase.assertEqual)
```
self.assertEqual(person.age, 42, 'age incorrect')
```
or with the default message (to answer the comment):
```
self.assertEqual(person.age, 42)
``` |
FreqDist with NLTK | 4,634,787 | 13 | 2011-01-08T16:12:46Z | 4,634,924 | 27 | 2011-01-08T16:44:40Z | [
"python",
"nlp",
"nltk"
] | NLTK in python has a function which gives you the frequency of words within a text. I am trying to pass my text as an argument but the result is of the form: [' ', 'e', 'a', 'o', 'n', 'i', 't', 'r', 's', 'l', 'd', 'h', 'c', 'y', 'b', 'u', 'g', '\n', 'm', 'p', 'w', 'f', ',', 'v', '.', "'", 'k', 'B', '"', 'M', 'H', '9', ... | `FreqDist` expects an iterable of tokens. A string is iterable --- the iterator yields every character.
Pass your text to a tokenizer first, and pass the tokens to `FreqDist`. |
FreqDist with NLTK | 4,634,787 | 13 | 2011-01-08T16:12:46Z | 6,500,258 | 13 | 2011-06-27T23:58:28Z | [
"python",
"nlp",
"nltk"
] | NLTK in python has a function which gives you the frequency of words within a text. I am trying to pass my text as an argument but the result is of the form: [' ', 'e', 'a', 'o', 'n', 'i', 't', 'r', 's', 'l', 'd', 'h', 'c', 'y', 'b', 'u', 'g', '\n', 'm', 'p', 'w', 'f', ',', 'v', '.', "'", 'k', 'B', '"', 'M', 'H', '9', ... | FreqDist runs on an array of tokens. You're sending it a an array of characters (a string) where you should have tokenized the input first:
```
words = nltk.tokenize.word_tokenize(p)
fdist = FreqDist(words)
``` |
`from x import y` vs. `from x.y import *` | 4,635,017 | 5 | 2011-01-08T17:04:43Z | 4,635,074 | 10 | 2011-01-08T17:14:54Z | [
"python"
] | What is the difference between these two lines?
```
from PyQt4 import QtGui
from PyQt4.QtGui import *
```
The first line is "import QtGui class from module PyQt4".
But what does second line means? "Import everything from QtGui of module PyQt4".
Is not it the same? | First statement imports the specified module into the current namespace.
Second statement imports everything from the specified module into the current namespace.
So 1) means you still need to explicitly reference any classes/functions etc through the module namespace
2) Means you don't
Here's a compare and contr... |
Django: Non-ASCII character | 4,635,188 | 17 | 2011-01-08T17:34:43Z | 4,635,222 | 32 | 2011-01-08T17:41:28Z | [
"python",
"django",
"unicode",
"utf-8"
] | My Django View/Template is not able to handle special characters. The simple view below fails because of the ñ. I get below error:
> Non-ASCII character '\xf1' in file"
```
def test(request):
return HttpResponse('español')
```
Is there some general setting that I need to set? It would be weird if I had to hand... | Do you have this at the beginning of your script:
```
# -*- coding: utf-8 -*-
```
...?
See this: <http://www.python.org/dev/peps/pep-0263/>
**EDIT**: For the second problem, it's about the html encoding. Put this in the head of your html page (you should send the request as an html page, otherwise I don't think you... |
Django: Non-ASCII character | 4,635,188 | 17 | 2011-01-08T17:34:43Z | 4,635,237 | 8 | 2011-01-08T17:44:34Z | [
"python",
"django",
"unicode",
"utf-8"
] | My Django View/Template is not able to handle special characters. The simple view below fails because of the ñ. I get below error:
> Non-ASCII character '\xf1' in file"
```
def test(request):
return HttpResponse('español')
```
Is there some general setting that I need to set? It would be weird if I had to hand... | You need the coding comment Gabi mentioned and also use the unicode "u" sign before your string :
```
return HttpResponse(u'español')
```
The best page I found on the web explaining all the ASCII/Unicode mess is this one :
<http://www.stereoplex.com/blog/python-unicode-and-unicodedecodeerror>
Enjoy! |
Django: Non-ASCII character | 4,635,188 | 17 | 2011-01-08T17:34:43Z | 12,567,569 | 11 | 2012-09-24T14:54:43Z | [
"python",
"django",
"unicode",
"utf-8"
] | My Django View/Template is not able to handle special characters. The simple view below fails because of the ñ. I get below error:
> Non-ASCII character '\xf1' in file"
```
def test(request):
return HttpResponse('español')
```
Is there some general setting that I need to set? It would be weird if I had to hand... | Insert at the top of views.py
```
# -*- coding: utf-8 -*-
```
And add "u" before your string
```
my_str = u"plus de détails"
```
Solved! |
Create list of square powers of numbers in range using generator | 4,636,656 | 3 | 2011-01-08T23:00:53Z | 4,636,665 | 13 | 2011-01-08T23:02:57Z | [
"python",
"range",
"generator"
] | I'd like to rewrite this part of code using generator :
```
basic = []
for x in range(0,11):
basic.append(x**2)
```
How can I do this ? Tried :
```
basic.append(x**2 for x in range(0,11))
```
but it raises syntax error in `x**2` part. | You'd be better off using list comprehension:
```
basic = [x*x for x in range(11)]
``` |
Create list of square powers of numbers in range using generator | 4,636,656 | 3 | 2011-01-08T23:00:53Z | 4,636,702 | 8 | 2011-01-08T23:09:58Z | [
"python",
"range",
"generator"
] | I'd like to rewrite this part of code using generator :
```
basic = []
for x in range(0,11):
basic.append(x**2)
```
How can I do this ? Tried :
```
basic.append(x**2 for x in range(0,11))
```
but it raises syntax error in `x**2` part. | You are mistaken; your code doesn't produce a syntax error, it just does the wrong thing:
```
>>> basic = []
>>> basic.append(x**2 for x in range(0,11))
>>> basic
[<generator object <genexpr> at 0x01E9AD78>]
>>>
```
If you must use a generator:
```
>>> basic = list(x**2 for x in range(0,11))
>>> basic
[0, 1, 4, 9, 1... |
Python equivalent of Sinatra | 4,636,942 | 19 | 2011-01-09T00:16:20Z | 4,637,034 | 16 | 2011-01-09T00:36:05Z | [
"python",
"model-view-controller",
"sinatra",
"web.py"
] | I know that many people use Sinatra when programming webapps in Ruby because they don't want their framework to get in the way by forcing them to use MVC.
Is there something similar in Python? I'm looking for a framework which provides the glue between Python and the web, and not much more. I've looked at Web.py, but ... | Take a look at the [Flask microframework](http://flask.pocoo.org/) |
Python equivalent of Sinatra | 4,636,942 | 19 | 2011-01-09T00:16:20Z | 4,637,035 | 11 | 2011-01-09T00:36:06Z | [
"python",
"model-view-controller",
"sinatra",
"web.py"
] | I know that many people use Sinatra when programming webapps in Ruby because they don't want their framework to get in the way by forcing them to use MVC.
Is there something similar in Python? I'm looking for a framework which provides the glue between Python and the web, and not much more. I've looked at Web.py, but ... | There are several micro web frameworks. I personally like [Bottle](http://bottle.paws.de/docs/dev/index.html)
A good [overview list of options exist here](http://wiki.python.org/moin/WebFrameworks). |
Sqlite3, OperationalError: unable to open database file | 4,636,970 | 28 | 2011-01-09T00:23:31Z | 4,637,055 | 34 | 2011-01-09T00:41:20Z | [
"python",
"sqlite3"
] | Question: Why can I not open the database?
---
Info: I'm working on a project whose purpose is not important but uses a sqlite3 database. I made a test program that runs and passes to it the location to make a database:
`/tmp/cer/could.db`
and the unit test program can make the db no problem. I then go actually use... | Primary diagnosis: SQLite is unable to open that file for some reason.
Checking the obvious reasons why, and in approximate order that I recommend checking:
* Is the program running on the same machine as you're testing it?
* Is it running as you (or at least the same user as you're testing it as)?
* Is the disk cont... |
Sqlite3, OperationalError: unable to open database file | 4,636,970 | 28 | 2011-01-09T00:23:31Z | 8,638,260 | 14 | 2011-12-26T18:38:46Z | [
"python",
"sqlite3"
] | Question: Why can I not open the database?
---
Info: I'm working on a project whose purpose is not important but uses a sqlite3 database. I made a test program that runs and passes to it the location to make a database:
`/tmp/cer/could.db`
and the unit test program can make the db no problem. I then go actually use... | This worked for me:
```
conn = sqlite3.connect("C:\\users\\guest\\desktop\\example.db")
```
Note: Double slashes in the full path
Using *python v2.7* on Win 7 enterprise and Win Xp Pro
Hope this helps someone. |
Python: Importing a file from a parent folder | 4,636,976 | 9 | 2011-01-09T00:24:49Z | 4,637,045 | 8 | 2011-01-09T00:39:14Z | [
"python"
] | ...Now I know this question has been asked many times & I have looked at these other threads. Nothing so far has worked, from using sys.path.append('.') to just import foo
I have a python file that wishes to import a file (that is in its parent directory). Can you help me figure out how my child file can successfully ... | ```
from .. import a
```
Should do it. This will only work on recent versions of Python--from 2.6, I believe [Edit: since 2.5].
Each level (Comp and Subcomp) must also be have an `__init__.py` file for this to work. You've said that they do. |
Is there a way to control how pytest-xdist runs tests in parallel? | 4,637,036 | 13 | 2011-01-09T00:36:16Z | 4,639,466 | 7 | 2011-01-09T13:46:31Z | [
"python",
"py.test"
] | I have the following directory layout:
```
runner.py
lib/
tests/
testsuite1/
testsuite1.py
testsuite2/
testsuite2.py
testsuite3/
testsuite3.py
testsuite4/
testsuite4.py
```
The format of testsuite\*.py modules is as follows:
... | With pytest-xdist there currently no kind of "per-file" or "per-test-suite" distribution. Actually, if a per-file distribution (e.g. tests in a file will be only executed by at most one worker at a time) would already help your use case i encourage you to file a feature issue with the pytest issue tracker at <https://b... |
Python equivalent for C++ STL vector/list containers | 4,637,095 | 10 | 2011-01-09T00:58:51Z | 4,637,106 | 10 | 2011-01-09T01:00:52Z | [
"c++",
"python",
"list",
"vector",
"containers"
] | Is there something similar in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) that I would use for a container that's like a vector and a list?
Any links would be helpful too. | You can use the inbuilt list - underlying implementation is similar to C++ vector. Although some things differ - for example, you can put objects of different type in one and the same list.
<http://effbot.org/zone/python-list.htm> |
Efficient Python Daemon | 4,637,420 | 24 | 2011-01-09T02:58:21Z | 4,637,530 | 7 | 2011-01-09T03:31:42Z | [
"python",
"daemon"
] | I was curious how you can run a python script in the background, repeating a task every 60 seconds. I know you can put something in the background using &, is that effeictive for this case?
I was thinking of doing a loop, having it wait 60s and loading it again, but something feels off about that. | I think your idea is pretty much exactly what you want. For example:
```
import time
def do_something():
with open("/tmp/current_time.txt", "w") as f:
f.write("The time is now " + time.ctime())
def run():
while True:
time.sleep(60)
do_something()
if __name__ == "__main__":
run()
... |
Efficient Python Daemon | 4,637,420 | 24 | 2011-01-09T02:58:21Z | 8,375,012 | 69 | 2011-12-04T11:37:37Z | [
"python",
"daemon"
] | I was curious how you can run a python script in the background, repeating a task every 60 seconds. I know you can put something in the background using &, is that effeictive for this case?
I was thinking of doing a loop, having it wait 60s and loading it again, but something feels off about that. | Rather than writing your own daemon, use [python-daemon](http://pypi.python.org/pypi/python-daemon) instead! [python-daemon](http://pypi.python.org/pypi/python-daemon) implements the well-behaved daemon specification of [PEP 3143](http://python.org/dev/peps/pep-3143), "Standard daemon process library".
I have included... |
Python "dir" equivalent in Clojure | 4,637,615 | 15 | 2011-01-09T04:01:30Z | 4,637,712 | 15 | 2011-01-09T04:38:18Z | [
"python",
"clojure",
"dir"
] | Does anybody know if there is a Clojure equivalent for Pythons "dir". Basically I need to know the functions I can call on something or more specifically for java objects I want to know the methods and properties available (I am not sure if in java they are called methods and properties, this is C# lingo). | `clojure.contrib.repl-utils/show` for use at the REPL:
```
user=> (use '[clojure.contrib.repl-utils :only (show)])
nil
user=> (show String)
=== public final java.lang.String ===
[ 0] static CASE_INSENSITIVE_ORDER : Comparator
[ 1] static copyValueOf : String (char[])
[ 2] static copyValueOf : String (char[],int,int)... |
Python "dir" equivalent in Clojure | 4,637,615 | 15 | 2011-01-09T04:01:30Z | 4,638,158 | 8 | 2011-01-09T07:29:02Z | [
"python",
"clojure",
"dir"
] | Does anybody know if there is a Clojure equivalent for Pythons "dir". Basically I need to know the functions I can call on something or more specifically for java objects I want to know the methods and properties available (I am not sure if in java they are called methods and properties, this is C# lingo). | The [`clojure.repl`](http://clojure.github.com/clojure/clojure.repl-api.html) namespace (which is available since Clojure 1.2) contains the macro [`dir`](http://clojure.github.com/clojure/clojure.repl-api.html#clojure.repl/dir) and the function [`dir-fn`](http://clojure.github.com/clojure/clojure.repl-api.html#clojure.... |
Using class variable as non-default argument in python | 4,638,008 | 8 | 2011-01-09T06:39:21Z | 4,638,019 | 14 | 2011-01-09T06:43:37Z | [
"python",
"class",
"variables",
"default-value"
] | is there a way to keep a private class variable within the class and still use it as the default value to a non-default variable (without defining that value before, outside of the class)?
example:
```
class a:
def __init__(self):
self.__variable = 6
def b(self, value = self.__variable):
print... | You're overthinking the problem:
```
class a:
def __init__(self):
self.__variable = 6
def b(self, value=None):
if value is None:
value = self.__variable
print value
``` |
Python nested dict comprehension | 4,638,889 | 3 | 2011-01-09T11:30:03Z | 4,638,902 | 8 | 2011-01-09T11:33:24Z | [
"python",
"dictionary",
"list-comprehension"
] | Can someone explain how to do nested dict comprehensions?
```
>> j = dict(((x+y,0) for x in 'cd') for y in 'ab')
>> {('ca', 0): ('da', 0), ('cb', 0): ('db', 0)}
```
I would have liked:
```
>> j
>> {'ca':0, 'cb':0, 'da':0, 'db':0}
```
Thanks! | ```
dict((x+y,0) for x in 'cd' for y in 'ab')
``` |
Parsing JSON file with Python -> google map api | 4,639,311 | 2 | 2011-01-09T13:22:56Z | 4,639,373 | 15 | 2011-01-09T13:31:42Z | [
"python",
"json",
"api",
"parsing",
"google-maps"
] | I am trying to get started with JSON in Python, but it seems that I misunderstand something in the JSON concept. I followed the [google api example](http://code.google.com/apis/maps/documentation/webservices/index.html#ParsingJSON), which works fine. But when I change the code to a lower level in the JSON response (as ... | The key to understanding `jsonResponse`'s format is to print it out:
```
import urllib, json
import pprint
URL2 = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false"
googleResponse = urllib.urlopen(URL2)
jsonResponse = json.loads(googleResponse.read())... |
Error "mismatched input" expecting DEDENT | 4,639,556 | 5 | 2011-01-09T14:03:14Z | 4,639,581 | 12 | 2011-01-09T14:08:52Z | [
"python"
] | Following this [tutorial](http://netbeans.org/kb/docs/python/temperature-converter.html#02) I got the following error where y = 1;
I'm using Netbeans 6.5 for Python. thanks
```
y=1
^
```
SyntaxError: line 8:3 mismatched input '' expecting DEDENT (temperatureconverter.py, line 8)
the following is the pyth... | In the `print` statement you used 2 spaces to indent the line, while in the next one you put 3 spaces.
Whitespace is significant in Python. Specifically, if you have a certain level of indentation in one line you can't just use another one for the next line. |
Why is a method not identical to itself? | 4,639,908 | 12 | 2011-01-09T15:12:13Z | 4,639,982 | 17 | 2011-01-09T15:29:48Z | [
"python",
"comparison",
"identity"
] | The [Python documentation about the `is` operator](http://docs.python.org/reference/expressions.html#is) says:
> The operators `is` and `is not` test for
> object identity: `x is y` is true if and
> only if `x` and `y` are the same object. `x
> is not y` yields the inverse truth
> value.
Let's try that:
```
>>> def ... | When you ask for an attribute of an instance which is a function, you get a *bound method*: a callable object which wraps the function defined in the class and passes the instance as the first argument. In Python 2.x, when you ask for an attribute of a class which is a function you get a similar proxy object called an ... |
What is a VM and why do dynamic languages need one? | 4,640,809 | 16 | 2011-01-09T18:05:58Z | 4,640,820 | 26 | 2011-01-09T18:08:07Z | [
"java",
"python",
"c",
"haskell",
"vm-implementation"
] | So, for example, Python and Java have a VM, C and Haskell do not. (Correct me if I'm wrong)
Thinking about what languages on both sides of the line have, I can't find the reason. Java is static in a lot of ways, while Haskell provides a lot of dynamic features. | It's nothing to do with static vs. dynamic.
Rather, it's about becoming independent from the underlying hardware platform ("build once, run everywhere" - in theory...)
Actually, it's nothing to do with the language, either. One could write a C compiler that generates bytecode for the JVM. One could write a Java compi... |
What is a VM and why do dynamic languages need one? | 4,640,809 | 16 | 2011-01-09T18:05:58Z | 4,652,718 | 12 | 2011-01-10T23:28:55Z | [
"java",
"python",
"c",
"haskell",
"vm-implementation"
] | So, for example, Python and Java have a VM, C and Haskell do not. (Correct me if I'm wrong)
Thinking about what languages on both sides of the line have, I can't find the reason. Java is static in a lot of ways, while Haskell provides a lot of dynamic features. | Let's forget about VMs for a sec (we'll get back to those below, I promise), and start with this important fact:
## C doesn't have garbage collection.
For a language to provide garbage collection, there has to be some sort of **"runtime"**/runtime-environment/thing that will perform it.
That's why Python, Java, and ... |
Error installing a python module | 4,641,131 | 12 | 2011-01-09T19:09:22Z | 4,641,166 | 23 | 2011-01-09T19:16:00Z | [
"python",
"windows-7",
"installation",
"setuptools"
] | I am trying to install a python module with the standard `python setup.py install` but I get the following error. I am fairly new to python but I have been able to install other modules in this way in the past. I am under the impression this module `setuptools` is not something I am supposed to have gotten separate fro... | Apparently, that package requires you to have setuptools to install it. Setuptools is a module that provides easy installation of Python packages. You can get it on pypi, [here](https://pypi.python.org/pypi/setuptools). |
Cython inline function with numpy array as parameter | 4,641,200 | 13 | 2011-01-09T19:23:02Z | 24,591,012 | 8 | 2014-07-05T22:17:25Z | [
"python",
"performance",
"numpy",
"inline",
"cython"
] | Consider code like this:
```
import numpy as np
cimport numpy as np
cdef inline inc(np.ndarray[np.int32_t] arr, int i):
arr[i]+= 1
def test1(np.ndarray[np.int32_t] arr):
cdef int i
for i in xrange(len(arr)):
inc(arr, i)
def test2(np.ndarray[np.int32_t] arr):
cdef int i
for i in xrange(le... | More than 3 years have passed since the question was posted and there have been great progress in the meantime. On this code (Update 2 of the question):
```
# cython: infer_types=True
# cython: boundscheck=False
# cython: wraparound=False
import numpy as np
cimport numpy as np
cdef inline inc(np.ndarray[np.int32_t, n... |
in string, capitalize allcaps words and leave the rest alone | 4,641,465 | 2 | 2011-01-09T20:08:21Z | 4,641,491 | 10 | 2011-01-09T20:12:07Z | [
"python"
] | For example, having gone through this procedure the string:
```
Hello, WORLD, McGisty, you are my HERO THAT I am.
```
should return/be:
```
Hello, World, McGisty, you are my Hero That I am.
``` | ```
>>> x = 'Hello, WORLD, McGisty, you are my HERO THAT I am.'
>>> m = ' '.join(e.capitalize() if e.isupper() else e for e in x.split())
>>> m
'Hello, World, McGisty, you are my Hero That I am.'
``` |
Add to integers in a list | 4,641,765 | 5 | 2011-01-09T21:02:44Z | 4,641,797 | 10 | 2011-01-09T21:07:47Z | [
"python",
"list",
"integer",
"add"
] | I have a list of integers and I was wondering if it would be possible to add to individual integers in this list. | You can append to the end of a list:
```
foo = [1,2,3,4,5]
foo.append( 4 )
foo.append( [8,7] )
print(foo) #[1, 2, 3, 4, 5, 4, [8, 7]]
```
You can edit items in the list like this:
```
foo = [1,2,3,4,5]
foo[3] = foo[3] + 4
print(foo) #[1,2,3,8,5]
```
Insert integers into the middle of ... |
Python data types | 4,642,032 | 2 | 2011-01-09T21:44:21Z | 4,642,068 | 9 | 2011-01-09T21:49:09Z | [
"python",
"types"
] | Is this statement true?
> Python does not enforce a strict type
> on containers or variables. With this
> concept, developers can design a
> container to hold different types of
> data
I'm doing an essay on Python and found this statement on a [random site](http://ugweb.cs.ualberta.ca/~c410/F07/410/presentations/Repo... | Yep its true.
Besides designing a container, regular lists can hold several types
```
>>> myList = [1, 3.14, 'string', {'key1':'value1'}, frozenset([5,2,2,3]), [1,2,3],(5+2j),(4.0,5.0), True, type(5)]
>>> myList
[1, 3.1400000000000001, 'string', {'key1': 'value1'}, frozenset([2, 3, 5]), [1, 2, 3], (5+2j), (4.0, 5.0),... |
Iterating on a dictionary, adding keys and values | 4,642,258 | 3 | 2011-01-09T22:29:39Z | 4,642,280 | 13 | 2011-01-09T22:34:14Z | [
"python",
"dictionary",
"iteration",
"amend"
] | I would like to iterate on a dictionary, amending the dictionary each time rather than what is currently happening which is resetting the old value with the new one.
My current code is:
```
while True:
grades = { raw_input('Please enter the module ID: '):raw_input('Please enter the grade for the module: ') }
```
... | In your example, grades (dictionary) is getting refreshed each time with a new key,value pair.
```
>>> grades = { 'k':'x'}
>>> grades
{'k': 'x'}
>>> grades = { 'newinput':'newval'}
>>> grades
{'newinput': 'newval'}
>>>
```
What you should have been doing is update the key,value pair for the same dict:
```
>>> grades... |
How to sort dictionaries by keys in Python | 4,642,501 | 9 | 2011-01-09T23:18:34Z | 4,642,509 | 29 | 2011-01-09T23:20:48Z | [
"python",
"sorting",
"dictionary"
] | can anyone tell me how i can sort this:
```
{'a': [1, 2, 3], 'c': ['one', 'two'], 'b': ['blah', 'bhasdf', 'asdf'], 'd': ['asdf', 'wer', 'asdf', 'zxcv']}
```
into
```
{'a': [1, 2, 3], 'b': ['blah', 'bhasdf', 'asdf'], 'c': ['one', 'two'],'d': ['asdf', 'wer', 'asdf', 'zxcv']}
```
?
thanx
UPDATE 1, code sample:
So I ... | Dicts don't have an order.
You can call sorted but this just gives you a sorted list of the keys:
```
>>> sorted(d)
['a', 'b', 'c', 'd']
```
You can treat it as an iterable and sort the key-value tuples, but then you've just got a list of tuples. That's not the same as a dict.
```
>>> sorted(d.items())
[
('a', [1,... |
How to sort dictionaries by keys in Python | 4,642,501 | 9 | 2011-01-09T23:18:34Z | 4,642,615 | 18 | 2011-01-09T23:46:17Z | [
"python",
"sorting",
"dictionary"
] | can anyone tell me how i can sort this:
```
{'a': [1, 2, 3], 'c': ['one', 'two'], 'b': ['blah', 'bhasdf', 'asdf'], 'd': ['asdf', 'wer', 'asdf', 'zxcv']}
```
into
```
{'a': [1, 2, 3], 'b': ['blah', 'bhasdf', 'asdf'], 'c': ['one', 'two'],'d': ['asdf', 'wer', 'asdf', 'zxcv']}
```
?
thanx
UPDATE 1, code sample:
So I ... | The **correct** answer is that if you want the items of a dictionary in a sorted order, you should use the sorted() function *when you loop over the dictionary*:
```
for k, v in sorted(d.items()):
print k, ':', v
```
or
```
for k in sorted(d):
print d[k]
```
Or similar.
The OrderedDict mentioned is for dict... |
How do I check whether this user is anonymous or actually a user on my system? | 4,642,596 | 21 | 2011-01-09T23:40:36Z | 4,642,607 | 45 | 2011-01-09T23:42:51Z | [
"python",
"django",
"http",
"authentication"
] | ```
def index(request):
the_user = request.user
```
In Django, how do I know if it's a real user or not? I tried:
`if the_user:` but "AnonymousUser" is there even if no one logs in. So, it always returns true and this doesn't work. | Use [`is_anonymous`](http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.is_anonymous) |
Setup.py: install lxml with Python2.6 on CentOS | 4,642,942 | 31 | 2011-01-10T01:12:45Z | 4,643,058 | 49 | 2011-01-10T01:38:24Z | [
"python",
"lxml",
"python-2.6",
"python-import",
"centos5"
] | I have installed Python 2.6.6 on CentOS 5.4,
```
[siyuan.tong@SC-055 lxml-2.3beta1]$ python
Python 2.6.6 (r266:84292, Jan 4 2011, 09:49:55)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
```
I want to use the lxml module, but build from s... | I had the same issue, I managed to install it after installing the package `libxslt-devel` and `python-devel` which seems to be your problem:
`yum install libxslt-devel python-devel`
`python setup.py install`
```
Installed /usr/lib/python2.6/site-packages/lxml-2.2.8-py2.6-linux-i686.egg
Processing dependencies for l... |
Intercept Tkinter "Exit" command? | 4,643,007 | 6 | 2011-01-10T01:27:19Z | 4,643,082 | 11 | 2011-01-10T01:45:56Z | [
"python",
"client-server",
"tkinter",
"exit"
] | I'm writing a client-server program in Python with Tkinter. I need the server to keep track of the connected clients. For this, I would like to have the client send an automated message to the server after the exit button(the standard "X" in the corner) is clicked. How can I know when the user is exiting the program? | You want to use the [wm\_protocol](http://effbot.org/tkinterbook/wm.htm#Tkinter.Wm.protocol-method) method of the toplevel window. Specifically, you are interested in the `WM_DELETE_WINDOW` protocol. If you use that method, it allows you to register a callback which is called when the window is being destroyed.
Usage:... |
Why does Celery work in Python shell, but not in my Django views? (import problem) | 4,643,065 | 14 | 2011-01-10T01:39:21Z | 4,643,087 | 10 | 2011-01-10T01:46:56Z | [
"python",
"django",
"unix",
"import",
"celery"
] | I installed Celery (latest stable version.)
I have a directory called `/home/myuser/fable/jobs`. Inside this directory, I have a file called tasks.py:
```
from celery.decorators import task
from celery.task import Task
class Submitter(Task):
def run(self, post, **kwargs):
return "Yes, it works!!!!!!"
```
... | I believe your tasks.py file needs to be in a django app (that's registered in settings.py) in order to be imported. Alternatively, you might try importing the tasks from an `__init__.py` file in your main project or one of the apps.
Also try starting celeryd from manage.py:
```
$ python manage.py celeryd -E -B -lDEB... |
Why does Celery work in Python shell, but not in my Django views? (import problem) | 4,643,065 | 14 | 2011-01-10T01:39:21Z | 6,899,753 | 11 | 2011-08-01T14:16:59Z | [
"python",
"django",
"unix",
"import",
"celery"
] | I installed Celery (latest stable version.)
I have a directory called `/home/myuser/fable/jobs`. Inside this directory, I have a file called tasks.py:
```
from celery.decorators import task
from celery.task import Task
class Submitter(Task):
def run(self, post, **kwargs):
return "Yes, it works!!!!!!"
```
... | This is what I did which finally worked
in Settings.py I added
```
CELERY_IMPORTS = ("myapp.jobs", )
```
under myapp folder I created a file called jobs.py
```
from celery.decorators import task
@task(name="jobs.add")
def add(x, y):
return x * y
```
Then ran from commandline: python manage.py celeryd -l info
... |
Fast prime factorization module | 4,643,647 | 48 | 2011-01-10T04:19:07Z | 4,643,685 | 11 | 2011-01-10T04:27:10Z | [
"python",
"algorithm",
"prime-factoring"
] | I am looking for an **implementation** or **clear algorithm** for getting the prime factorization of *N* in either python, pseudocode or anything else well-readable. There are a few demands/facts:
* *N* is between 1 and ~20 digits
* No pre-calculated lookup table, memoization is fine though.
* Need not to be mathemati... | Pollard-Brent in implemented in Python:
<https://comeoncodeon.wordpress.com/2010/09/18/pollard-rho-brent-integer-factorization/> |
Fast prime factorization module | 4,643,647 | 48 | 2011-01-10T04:19:07Z | 4,739,751 | 8 | 2011-01-19T19:33:10Z | [
"python",
"algorithm",
"prime-factoring"
] | I am looking for an **implementation** or **clear algorithm** for getting the prime factorization of *N* in either python, pseudocode or anything else well-readable. There are a few demands/facts:
* *N* is between 1 and ~20 digits
* No pre-calculated lookup table, memoization is fine though.
* Need not to be mathemati... | There is no need to calculate `smallprimes` using `primesbelow`, use `smallprimeset` for that.
`smallprimes = (2,) + tuple(n for n in xrange(3,1000,2) if n in smallprimeset)`
Divide your `primefactors` into two functions for handling `smallprimes` and other for `pollard_brent`, this can save a couple of iterations as... |
Fast prime factorization module | 4,643,647 | 48 | 2011-01-10T04:19:07Z | 31,986,424 | 12 | 2015-08-13T11:03:18Z | [
"python",
"algorithm",
"prime-factoring"
] | I am looking for an **implementation** or **clear algorithm** for getting the prime factorization of *N* in either python, pseudocode or anything else well-readable. There are a few demands/facts:
* *N* is between 1 and ~20 digits
* No pre-calculated lookup table, memoization is fine though.
* Need not to be mathemati... | If you don't want to reinvent the wheel, use the library [sympy](http://www.sympy.org/)
```
pip install sympy
```
Use the function [`sympy.ntheory.factorint`](http://docs.sympy.org/latest/modules/ntheory.html?highlight=factorint#sympy.ntheory.factor_.factorint)
```
>>> from sympy.ntheory import factorint
>>> factori... |
Python how to get a list of color that used in one image | 4,643,847 | 3 | 2011-01-10T05:08:27Z | 4,643,905 | 16 | 2011-01-10T05:19:58Z | [
"python",
"python-imaging-library"
] | Python how to get a list of color that used in one image
I use PIL, and I want to have a dictionary of colors that are used in this image, including color(key) and number of pixel points it used.
How to do that? | The getcolors method should do the trick. See [the docs](http://www.pythonware.com/library/pil/handbook/image.htm#Image.getcolors).
```
Image.open('file.jpg').getcolors() => a list of (count, color) tuples or None
``` |
How do I extend the Django "login" form? | 4,643,884 | 9 | 2011-01-10T05:15:29Z | 4,643,972 | 19 | 2011-01-10T05:37:33Z | [
"python",
"django",
"oop",
"class",
"authentication"
] | So, right now I'm doing the basic login. In urls.py, I go to django contrib login:
```
(r'^login/?$','django.contrib.auth.views.login',{'template_name':'login.html'}),
```
That shoots it to here:
```
@csrf_protect
@never_cache
def login(request, template_name='registration/login.html',
redirect_field_name=... | You need to subclass the `AuthenticationForm` class, and then you need to change your `urls.py`,
```
class MyAuthenticationForm(AuthenticationForm):
# add your form widget here
widget = .....
```
Then import this class into your `urls.py` file and update the call,
```
(r'^login/?$','django.contrib.auth.views... |
Python: Converting string into decimal number | 4,643,991 | 11 | 2011-01-10T05:41:08Z | 4,644,000 | 27 | 2011-01-10T05:42:51Z | [
"python",
"string",
"floating-point",
"decimal"
] | I have a python list with strings in this format:
```
A1 = [' "29.0" ',' "65.2" ',' "75.2" ']
```
How do I convert those strings into decimal numbers to perform arithmetic operations on the list elements? | If you want the result as the nearest binary floating point number use `float`:
```
result = [float(x.strip(' "')) for x in A1]
```
If you want the result stored exactly use [`Decimal`](http://docs.python.org/library/decimal.html) instead of `float`:
```
from decimal import Decimal
result = [Decimal(x.strip(' "')) f... |
Python how to sort this list? | 4,644,025 | 6 | 2011-01-10T05:47:17Z | 4,644,059 | 12 | 2011-01-10T05:53:42Z | [
"python",
"list"
] | ```
lst = [(1,(1,3,5)), (5,(2,3,4)),(3,(2,3,4))]
```
I want to sort by the first value, descending order. | just like this:
```
sorted(lst, reverse=True)
``` |
The @login_required decorator of Django redirects people to /accounts/login when they aren't registered. How to change this URL? | 4,644,049 | 7 | 2011-01-10T05:51:53Z | 4,644,077 | 12 | 2011-01-10T05:57:15Z | [
"python",
"django",
"authentication",
"configuration",
"login"
] | I want it to redirect to "/login" instead of "/accounts/login"
Is there a setting I can change? | Add `LOGIN_URL = '/login'` to your settings.py
See [the docs](http://docs.djangoproject.com/en/1.2/ref/settings/#login-url) for more. |
Django: Where to put global models? | 4,644,559 | 4 | 2011-01-10T07:25:13Z | 4,644,573 | 7 | 2011-01-10T07:28:47Z | [
"python",
"django",
"django-models"
] | I'm building a fairly large website in Django, and it's my first time doing anything of this scale with the framework. (I have, however, used it in the past, so I know my way around and am not a total newbie.) I have a number of model classes which will be used throughout the application, so my question is where would ... | I think the easiest way is to make a "main" application and then import the models from that application into your other peripheral apps when you need the main models.
```
manage.py startapp main
``` |
Python Tkinter padding issue | 4,646,289 | 5 | 2011-01-10T11:24:36Z | 4,646,794 | 8 | 2011-01-10T12:26:43Z | [
"python",
"tkinter"
] | I am learning Tkinter and building a simple 8 puzzle game.
(Example: <http://www.permadi.com/java/puzzle8/>)
Each number is a Canvas object placed into a Frame using a grid layout. One of the objects is adding extra padding between the Canvas objects. I set the border width to the Canvas objects to -2 which solved s... | Most likely the cause of your problem is that you're neglecting to set the `highlightthickness` attribute of each canvas to zero. This value controls a colored ring around the widget used to denote that it has focus.
Here's a trick when trying to solve these types of layout issues: Give each widget a different backgro... |
What can be used instead of parse_qs function | 4,646,560 | 4 | 2011-01-10T11:59:52Z | 4,646,611 | 11 | 2011-01-10T12:05:48Z | [
"python",
"deprecated",
"feedparser",
"python-2.4"
] | I have the following code for parsing youtube feed and returning youtube movie id. How can I rewrite this to be python 2.4 compatible which I suppose doesn't support `parse_qs` function ?
```
YTSearchFeed = feedparser.parse("http://gdata.youtube.com" + path)
videos = []
for yt in YTSearchFeed.entries:
url_data = u... | I assume your existing code runs in 2.6 or something newer, and you're trying to go back to 2.4? `parse_qs` used to be in the `cgi` module before it was moved to `urlparse`. Try `import cgi`, `cgi.parse_qs`.
Inspired by [TryPyPy's](http://stackoverflow.com/users/555569/trypypy) comment, I think you could make your sou... |
Parsing parameters in Python Cmd module | 4,646,622 | 2 | 2011-01-10T12:07:17Z | 4,646,654 | 7 | 2011-01-10T12:10:38Z | [
"python",
"cmd"
] | I am writing a command line tool in Python using the Cmd module.
I want to be able to issue commands such as:
```
resize -file all -height 100 -width 200 -type jpeg
```
or
```
resize -file 'a file.jpg' -type png -height 50 -width 50
```
[edit] To be clear the above command is to be enter into my command line appli... | you are looking for [optparse](http://docs.python.org/library/optparse.html) ([argparse](http://docs.python.org/library/argparse.html) for python 2.7+)
**edit:** In fact according to [this](http://docs.python.org/library/optparse.html#parsing-arguments) section of docs, you can call function `parse_args` passing a lis... |
How do I reverse a part (slice) of a list in Python? | 4,647,368 | 15 | 2011-01-10T13:33:38Z | 4,647,379 | 15 | 2011-01-10T13:36:02Z | [
"python"
] | Why doesn't this work?
```
# to reverse a part of the string in place
a = [1,2,3,4,5]
a[2:4] = reversed(a[2:4]) # This works!
a[2:4] = [0,0] # This works too.
a[2:4].reverse() # But this doesn't work
``` | `a[2:4]` creates a copy of the selected sublist, and this copy is reversed by `a[2:4].reverse()`. This does not change the original list. Slicing Python lists always creates copies -- you can use
```
b = a[:]
```
to copy the whole list. |
What is the Pythonic way of reordering a list consisting of dicts? | 4,647,524 | 4 | 2011-01-10T13:56:48Z | 4,647,551 | 12 | 2011-01-10T13:59:36Z | [
"sorting",
"python",
"lambda"
] | I have the the following list:
```
list = [{'nr' : 2, 'name': 'streamname'}, {'nr' : 3,'name': 'streamname'}, {'nr' : 1, 'name': 'streamname'}]
```
So how would I reorder it to become like this in an efficient way in python?
```
list = [{'nr' : 1, 'name': 'streamname'}, {'nr' : 2,'name': 'streamname'}, {'nr' : 3, 'n... | No, using `cmp=` is not efficient. Use `key=` instead. Like so:
```
sorted(list, key=lambda x: x['nr'])
```
The reason is simple: `cmp` compares two objects. If your list is long, there are many combinations of two objects you can have to compare, so a list that is twice as long takes much more than twice as long to ... |
WSGI Middleware for OAuth authentication | 4,648,838 | 7 | 2011-01-10T16:14:27Z | 4,648,917 | 7 | 2011-01-10T16:21:27Z | [
"python",
"oauth",
"wsgi",
"middleware",
"flask"
] | I have build a very small web application using [Flask](http://flask.pocoo.org/). Now I would like to add very basic authentication to the site (I don't need authorization). As Flask does not support auth&auth out of the box, I'd like to plug in a WSGI middleware doing this job. The web-app is only used by roughly 10 p... | Flask has an [OpenAuth](http://packages.python.org/Flask-OAuth/) [extension](http://flask.pocoo.org/extensions/) that's written by the [Armin Ronacher](https://github.com/mitsuhiko/flask-oauth) (Flask's author). It provides Flask with support for Open Auth 1.0. |
Convert Python program to C/C++ code? | 4,650,243 | 67 | 2011-01-10T18:46:12Z | 4,650,280 | 57 | 2011-01-10T18:49:28Z | [
"c++",
"python",
"c",
"code-generation"
] | is it possible to convert a Python program to C/C++?
I need to implement a couple of algorithms, and I'm not sure if the performance gap is big enough to justify all the pain I'd go through when doing it in C/C++ (which I'm not good at). I thought about writing one simple algorithm and benchmark it against such a conv... | Yes. Look at [Cython](http://cython.org/). It does just that: Converts Python to C for speedups. |
Convert Python program to C/C++ code? | 4,650,243 | 67 | 2011-01-10T18:46:12Z | 4,650,472 | 21 | 2011-01-10T19:08:16Z | [
"c++",
"python",
"c",
"code-generation"
] | is it possible to convert a Python program to C/C++?
I need to implement a couple of algorithms, and I'm not sure if the performance gap is big enough to justify all the pain I'd go through when doing it in C/C++ (which I'm not good at). I thought about writing one simple algorithm and benchmark it against such a conv... | [Shed Skin](http://shed-skin.blogspot.com/) is "a (restricted) Python-to-C++ compiler". |
Convert Python program to C/C++ code? | 4,650,243 | 67 | 2011-01-10T18:46:12Z | 4,650,953 | 81 | 2011-01-10T20:04:19Z | [
"c++",
"python",
"c",
"code-generation"
] | is it possible to convert a Python program to C/C++?
I need to implement a couple of algorithms, and I'm not sure if the performance gap is big enough to justify all the pain I'd go through when doing it in C/C++ (which I'm not good at). I thought about writing one simple algorithm and benchmark it against such a conv... | > If the C variant needs x hours less, then I'd invest that time in letting the algorithms run longer/again
"invest" isn't the right word here.
1. Build a working implementation in Python. You'll finish this long before you'd finish a C version.
2. Measure performance with the Python profiler. Fix any problems you fi... |
Difference between decorator classes and decorator functions | 4,650,333 | 7 | 2011-01-10T18:55:10Z | 4,650,418 | 7 | 2011-01-10T19:03:03Z | [
"python",
"syntax",
"decorator"
] | I guess that's how they are called, but I will give examples just in case.
Decorator class:
```
class decorator(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print 'something'
self.func(*args, **kwargs)
```
Decorator function:
```
def decor... | If you can write a function to implement your decorator you should prefer it. But not all decorators can easily be written as a function - for example when you want to store some internal state.
```
class counted(object):
""" counts how often a function is called """
def __init__(self, func):
self.func... |
Python: Convert Unicode to ASCII without errors for CSV file | 4,650,639 | 4 | 2011-01-10T19:28:31Z | 4,650,737 | 10 | 2011-01-10T19:38:08Z | [
"python",
"unicode",
"csv",
"ascii",
"diacritics"
] | I've been reading all questions regarding conversion from Unicode to CSV in Python here in StackOverflow and I'm still lost. Everytime I receive a "UnicodeEncodeError: 'ascii' codec can't encode character u'\xd1' in position 12: ordinal not in range(128)"
```
buffer=cStringIO.StringIO()
writer=csv.writer(buffer, csv.e... | Correct, ñ is not a valid ASCII character, so you can't encode it to ASCII. So you can, as your code does above, ignore them. Another way, namely to remove the accents, you can find here:
[What is the best way to remove accents in a python unicode string?](http://stackoverflow.com/questions/517923/what-is-the-best-way... |
Accessing model field attributes in Django | 4,651,098 | 6 | 2011-01-10T20:19:53Z | 4,651,152 | 7 | 2011-01-10T20:25:57Z | [
"python",
"django",
"models"
] | I have a model in Django 1.2.4:
```
class MyModel():
foo = IntegerField(verbose_name="bar")
def printFoo(self):
print("Value of %s is %d" % (foo.verbose_name, foo))
```
I'm trying to get both the value and verbose name of a field. How can I do this?
I've looked at `myModel._meta.fields`, but I'm not... | Probably like this:
```
MyModel._meta.get_field('foo').verbose_name
```
See [How can I programmatically obtain the max\_length of a Django model field?](http://stackoverflow.com/questions/1829216/how-can-i-programmatically-obtain-the-max-length-of-a-django-model-field/1829286#1829286) for a very similar question. |
Reference list item by index within Django template? | 4,651,172 | 49 | 2011-01-10T20:27:43Z | 4,651,208 | 82 | 2011-01-10T20:29:57Z | [
"python",
"django",
"django-templates"
] | This may be simple, but I looked around and couldn't find an answer. What's the best way to reference a single item in a list from a Django template?
In other words how do I do the equivalent of `{{ data[0] }}` within the template language?
Thanks. | It looks like `{{ data.0 }}`. See [Variables and lookups](https://docs.djangoproject.com/en/1.5/ref/templates/api/#variables-and-lookups). |
Reference list item by index within Django template? | 4,651,172 | 49 | 2011-01-10T20:27:43Z | 4,651,237 | 19 | 2011-01-10T20:33:09Z | [
"python",
"django",
"django-templates"
] | This may be simple, but I looked around and couldn't find an answer. What's the best way to reference a single item in a list from a Django template?
In other words how do I do the equivalent of `{{ data[0] }}` within the template language?
Thanks. | `{{ data.0 }}` should work.
Let's say you wrote `data.obj` django tries `data.obj` and `data.obj()`. If they don't work it tries `data["obj"]`. In your case `data[0]` can be written as `{{ data.0 }}`. But I recommend you to pull `data[0]` in the view and send it as separate variable. |
Reference list item by index within Django template? | 4,651,172 | 49 | 2011-01-10T20:27:43Z | 29,664,945 | 9 | 2015-04-16T03:41:49Z | [
"python",
"django",
"django-templates"
] | This may be simple, but I looked around and couldn't find an answer. What's the best way to reference a single item in a list from a Django template?
In other words how do I do the equivalent of `{{ data[0] }}` within the template language?
Thanks. | A better way: custom template tag: <https://docs.djangoproject.com/en/dev/howto/custom-template-tags/>
such as get List[x] in templates:
in template
```
{% load index %}
{{ List|index:x }}
```
templatetags/index.py
```
from django import template
register = template.Library()
@register.filter
def index(List, i):
... |
Why is MutableString deprecated in Python? | 4,651,344 | 19 | 2011-01-10T20:45:03Z | 4,651,422 | 26 | 2011-01-10T20:55:44Z | [
"python",
"string",
"python-3.x",
"deprecated",
"mutable"
] | Why was the [MutableString](http://docs.python.org/library/userdict.html#UserString.MutableString) class deprecated in Python 2.6;
and why was it removed in Python 3? | The `MutableString` class was meant to be educational, and not to be used in real programs. If you look at the implementation, you'd see that you can't really use this in a serious application requiring mutable strings.
If you need mutable bytestrings, you might consider using `bytearray` that's available in Python 2.... |
Numpy grouping using itertools.groupby performance | 4,651,683 | 21 | 2011-01-10T21:27:44Z | 4,652,265 | 23 | 2011-01-10T22:31:53Z | [
"python",
"algorithm",
"numpy"
] | I have many large (>35,000,000) lists of integers that will contain duplicates. I need to get a count for each integer in a list. The following code works, but seems slow. Can anyone else better the benchmark using Python and preferably Numpy?
```
def group():
import numpy as np
from itertools import groupby
... | i get a 3x improvement doing something like this:
```
def group():
import numpy as np
values = np.array(np.random.randint(0,3298,size=35000000),dtype='u4')
values.sort()
dif = np.ones(values.shape,values.dtype)
dif[1:] = np.diff(values)
idx = np.where(dif>0)
vals = values[idx]
count = n... |
Metaclass Mixin or Chaining? | 4,651,729 | 15 | 2011-01-10T21:32:34Z | 4,652,310 | 7 | 2011-01-10T22:38:33Z | [
"python",
"metaclass"
] | Is it possible to chain metaclasses?
I have class `Model` which uses `__metaclass__=ModelBase` to process its namespace dict. I'm going to inherit from it and "bind" another metaclass so it won't shade the original one.
First approach is to subclass `class MyModelBase(ModelBase)`:
```
MyModel(Model):
__metaclass... | A type can have only one metaclass, because a metaclass simply states what the class statement does - having more than one would make no sense. For the same reason "chaining" makes no sense: the first metaclass creates the type, so what is the 2nd supposed to do?
You will have to merge the two metaclasses (just like w... |
Is there a matplotlib equivalent of MATLAB's datacursormode? | 4,652,439 | 34 | 2011-01-10T22:54:04Z | 4,674,445 | 48 | 2011-01-12T21:52:31Z | [
"python",
"matplotlib"
] | In MATLAB, one can use `datacursormode` to add annotation to a graph when user mouses over. Is there such thing in matplotlib? Or I need to write my own event using `matplotlib.text.Annotation`? | *Late Edit / Shameless Plug:* This is now available (with much more functionality) as [`mpldatacursor`](https://github.com/joferkington/mpldatacursor). Calling `mpldatacursor.datacursor()` will enable it for all matplotlib artists (including basic support for z-values in images, etc).
---
As far as I know, there isn'... |
How to install python syntax support for Vim on Mac OSX? | 4,652,472 | 11 | 2011-01-10T22:56:41Z | 4,652,812 | 8 | 2011-01-10T23:43:17Z | [
"python",
"vim"
] | I recently started programming in python and have fallen in love with Vim over the past few weeks. I know want to use Vim as my primary editor for python files. I know there are python plugins for Vim, but I am very confused as to where/how I can install these. I don't really understand where Vim is installed. I'm runn... | You will find that you have a folder by name `.vim` in your home directory `cd ~` and it will contain the following directories
```
ftdetect/ ftplugin/ plugin/ syntax/
```
You need to download the [plugins](http://www.vim.org/scripts/script.php?script_id=790) and install them (copy them) to those directories.
Apa... |
How to install python syntax support for Vim on Mac OSX? | 4,652,472 | 11 | 2011-01-10T22:56:41Z | 4,661,417 | 22 | 2011-01-11T18:49:33Z | [
"python",
"vim"
] | I recently started programming in python and have fallen in love with Vim over the past few weeks. I know want to use Vim as my primary editor for python files. I know there are python plugins for Vim, but I am very confused as to where/how I can install these. I don't really understand where Vim is installed. I'm runn... | To best answer your initial question: "How to install python syntax support in Vim":
There is no need to install anything! If you have not made any modifications (e.g. no configuration changes for vim in `~/.vimrc`) try the following:
* Open a Python file with vim
* type the following command `:syntax on`
You should... |
Python dictionary: Remove all the keys that begins with s | 4,653,626 | 5 | 2011-01-11T02:35:30Z | 4,653,641 | 15 | 2011-01-11T02:38:07Z | [
"python",
"dictionary"
] | I've got a dictionary like
```
dic = {'s_good': 23, 's_bad': 39, 'good_s': 34}
```
I want to remove all the keys that begins with 's\_'
So in this case first two will be removed.
Is there any efficient way to do so? | This should do it:
```
for k in dic.keys():
if k.startswith('s_'):
dic.pop(k)
``` |
Python dictionary: Remove all the keys that begins with s | 4,653,626 | 5 | 2011-01-11T02:35:30Z | 4,653,660 | 15 | 2011-01-11T02:41:38Z | [
"python",
"dictionary"
] | I've got a dictionary like
```
dic = {'s_good': 23, 's_bad': 39, 'good_s': 34}
```
I want to remove all the keys that begins with 's\_'
So in this case first two will be removed.
Is there any efficient way to do so? | ```
for k in dic.keys():
if k.startswith('s_'):
del dic[k]
``` |
overwriting file in ziparchive | 4,653,768 | 14 | 2011-01-11T03:00:23Z | 4,653,863 | 21 | 2011-01-11T03:16:39Z | [
"python",
"ziparchive"
] | I have `archive.zip` with two files: `hello.txt` and `world.txt`
I want to overwrite `hello.txt` file with new one with that code:
```
import zipfile
z = zipfile.ZipFile('archive.zip','a')
z.write('hello.txt')
z.close()
```
but it won't overwrite file, somehow it creates another instance of `hello.txt` â take a l... | There's no way to do that with python zipfile module. You have to create a new zip file and recompress everything again from the first file, plus the new modified file.
Below is some code to do just that. But note that it isn't efficient, since it decompresses and then recompresses all data.
```
import tempfile
impor... |
Python: Append item to list N times | 4,654,414 | 23 | 2011-01-11T05:11:23Z | 4,654,441 | 38 | 2011-01-11T05:15:02Z | [
"python",
"list"
] | This seems like something Python would have a shortcut for. I want to append an item to a list N times, effectively doing this:
```
l = []
x = 0
for i in range(100):
l.append(x)
```
It would seem to me that there should be an "optimized" method for that, something like:
```
l.append_multiple(x, 100)
```
Is ther... | For immutable data types:
```
l = [0] * 100
# [0, 0, 0, 0, 0, ...]
l = ['foo'] * 100
# ['foo', 'foo', 'foo', 'foo', ...]
```
For values that are stored by reference and you may wish to modify later (like sub-lists, or dicts):
```
l = [{} for x in range(100)]
```
(The reason why the first method is only a good idea... |
Python: Append item to list N times | 4,654,414 | 23 | 2011-01-11T05:11:23Z | 4,654,446 | 11 | 2011-01-11T05:15:35Z | [
"python",
"list"
] | This seems like something Python would have a shortcut for. I want to append an item to a list N times, effectively doing this:
```
l = []
x = 0
for i in range(100):
l.append(x)
```
It would seem to me that there should be an "optimized" method for that, something like:
```
l.append_multiple(x, 100)
```
Is ther... | Use extend to add a list comprehension to the end.
```
l.extend([x for i in range(100)])
```
See the [Python docs](http://docs.python.org/tutorial/datastructures.html) for more information. |
Rotate logfiles each time the application is started (Python) | 4,654,915 | 9 | 2011-01-11T06:44:06Z | 4,654,956 | 22 | 2011-01-11T06:52:03Z | [
"python",
"logging",
"rotation"
] | I'm using the logging module in Python and I would like it to create a new logfile each time my application is started. The older logfiles shoud be rotated (eg: logfile.txt -> logfile1.txt, etc).
I already found this:
<http://docs.python.org/library/logging.html>
> BaseRotatingHandler is the base class
> for handler... | I might be enough to use `RotatingFileHandler` without `maxBytes`, then call `doRollover()` on application start.
Yup, seems to work fine. The code below will create a new log file on each application run, with added timestamps for log start and close times. Running it will print the list of available log files. You c... |
How to accomplish relative import in python | 4,655,526 | 19 | 2011-01-11T08:19:17Z | 4,656,228 | 24 | 2011-01-11T09:46:41Z | [
"python",
"import",
"python-2.x",
"relative"
] | ```
stuff/
__init__.py
mylib.py
Foo/
__init__.py
main.py
foo/
__init__.py
script.py
```
`script.py` wants to import `mylib.py`
This is just an example, but really I just want to do a relative import of a module in a parent directory. I've tried various thing... | After fiddling with it a bit more, I realized how to set it up, and for the sake of specificity I won't use foo bar names. My project directory is set up as...
```
tools/
core/
object_editor/
# files that need to use ntlib.py
editor.py # see example at bottom
__init__.py... |
Why can I not access this class member in python? | 4,655,745 | 3 | 2011-01-11T08:49:20Z | 4,655,770 | 11 | 2011-01-11T08:52:24Z | [
"python",
"class-members"
] | I have the following code
```
class Transcription(object):
WORD = 0
PHONE = 1
STATE = 2
def __init__(self):
self.transcriptions = []
def align_transcription(self,model,target=Transcription.PHONE):
pass
```
The important part here is that I would like to have a class member as def... | You can't access it because `Transcription` isn't defined at the time that the `def` statement is running.
```
def align_transcription(self,model,target=PHONE):
pass
```
will do the trick. The `PHONE` name is available in the namespace which will become the `Transcription` class *after* the `class` statement... |
Python: How to know if two dictionary have the same keys | 4,656,329 | 7 | 2011-01-11T09:56:51Z | 4,656,353 | 10 | 2011-01-11T09:59:15Z | [
"python",
"dictionary"
] | ```
dic1 = {'a':'a','b':'c','c':'d'}
dic2 = {'b':'a','a':'c','c':'d'}
dic1.keys() =>['a', 'b', 'c']
dic2.keys() =>['b', 'a', 'c']
```
dic1 and dic2 have the same keys, but in different order.
How to tell they have same keys(do not consider the order)? | ```
set(dic1.keys()) == set(dic2.keys())
``` |
Python: How to know if two dictionary have the same keys | 4,656,329 | 7 | 2011-01-11T09:56:51Z | 4,656,478 | 21 | 2011-01-11T10:13:52Z | [
"python",
"dictionary"
] | ```
dic1 = {'a':'a','b':'c','c':'d'}
dic2 = {'b':'a','a':'c','c':'d'}
dic1.keys() =>['a', 'b', 'c']
dic2.keys() =>['b', 'a', 'c']
```
dic1 and dic2 have the same keys, but in different order.
How to tell they have same keys(do not consider the order)? | python 2.7
**[dict views](http://docs.python.org/library/stdtypes.html#dictionary-view-objects):**
Supports direct set operations, etc.
```
>>> dic1 = {'a':'a','b':'c','c':'d'}
>>> dic2 = {'b':'a','a':'c','c':'d'}
>>> dic1.viewkeys() == dic2.viewkeys()
True
>>> dic1.viewkeys() - dic2.viewkeys()
set([])
>>> dic1.viewk... |
Socket error "IP address not valid in its context" - Python | 4,657,347 | 7 | 2011-01-11T11:57:14Z | 4,657,548 | 13 | 2011-01-11T12:21:22Z | [
"python",
"windows",
"django",
"networking",
"windows-server-2008"
] | I'm using **Python 2.6** and **Windows Server 2008**.
The server has **two IP addresses 1 internal, 1 external**.
---
**I need Python to use the external IP address, but while doing so I get this:**
> socket.error: [Error 10049] The requested address is not valid in its context
---
To be more precise I'm using Dj... | That's an error Windows gives when you're trying to bind to an address on the local machine that's not assigned to any of the adapters on the machine. If `ipconfig` doesn't show it, you can't bind to it.
If the external address is on a router that is NAT'ing requests from it to the server's internal address, you can't... |
Python, geometry and visualisation | 4,657,541 | 4 | 2011-01-11T12:20:39Z | 4,657,586 | 7 | 2011-01-11T12:27:02Z | [
"python",
"geometry",
"visualization"
] | I'm looking for a Python library that would allow me to visualise geometrical data. Nothing extremely complicated, just a bunch of points in the plane or space and a few basic shapes that I would generate.
I had a look at [this question and the answers to it](http://stackoverflow.com/questions/1076778/good-geometry-li... | How about [Matplotlib/mplot3D](http://www.scipy.org/Cookbook/Matplotlib/mplot3D)? |
Py_INCREF/DECREF: When | 4,657,764 | 23 | 2011-01-11T12:47:52Z | 4,659,190 | 29 | 2011-01-11T15:22:45Z | [
"python",
"python-c-api"
] | Is one correct in stating the following:
* If a Python object is created in a C function, but the function doesn't return it, no `INCREF` is needed, but a `DECREF` is.
* [false]If the function does return it, you do need to `INCREF`, in the function that receives the return value.[/false]
* When assigning C typed vari... | First, read this more carefully, specifically the last paragraph, <http://docs.python.org/extending/extending.html#ownership-rules>
Easy way to think about it is thinking about the reference counts.
1. Your first statement is correct. If you create a new Python object (say `PyLong`) then it already has a reference co... |
How to evaluate simple math expressions in config files | 4,658,033 | 3 | 2011-01-11T13:19:32Z | 4,658,125 | 9 | 2011-01-11T13:29:40Z | [
"python",
"configuration-files",
"configparser"
] | I would like to use a configuration file with some simple math expressions like adding or substracting.
For example:
```
[section]
a = 10
b = 15
c = a-5
d = b+c
```
Is there any way to do this using a ConfigParser module? I found some examples of using strings as a kind of variables in config files, but if i'm usin... | Why use ConfigParser? Why not just
config.py:
```
a = 10
b = 15
c = a-5
d = b+c
```
script.py:
```
import config
print(config.c)
# 5
print(config.d)
# 20
``` |
how to sort by length of string followed by alphabetical order? | 4,659,524 | 24 | 2011-01-11T15:52:00Z | 4,659,539 | 54 | 2011-01-11T15:53:19Z | [
"python",
"sorting"
] | I'm currently new to python and got stuck at this question, can't seem to find the proper answer.
question:Given a list of words, return a list with the same words in order of length (longest to shortest), the second sort criteria should be alphabetical. Hint: you need think of two functions.
This is what I have so f... | You can do it in two steps like this:
```
the_list.sort() # sorts normally by alphabetical order
the_list.sort(key=len, reverse=True) # sorts by descending length
```
Python's sort is stable, which means that sorting the list by length leaves the elements in alphabetical order when the length is equal.
You can also ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.