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 |
|---|---|---|---|---|---|---|---|---|---|
Scraping websites with Javascript enabled? | 3,362,859 | 13 | 2010-07-29T13:18:43Z | 13,661,202 | 7 | 2012-12-01T16:17:18Z | [
"javascript",
"python",
"screen-scraping"
] | I'm trying to scrape and submit information to websites that heavily rely on Javascript to do most of its actions. The website won't even work when i disable Javascript in my browser.
I've searched for some solutions on Google and SO and there was someone who suggested i should reverse engineer the Javascript, but i h... | I wrote a small tutorial on this subject, this might help:
<http://koaning.io/dynamic-scraping-with-python.html>
Basically what you do is you have the selenium library pretend that it is a firefox browser, the browser will wait until all javascript has loaded before it continues passing you the html string. Once you ... |
AttributeError: 'module' object has no attribute (when using cPickle) | 3,363,281 | 11 | 2010-07-29T14:03:06Z | 12,295,393 | 7 | 2012-09-06T07:54:38Z | [
"python"
] | I am trying to load the function in a remote environment using cPickle. But I got the
error "the 'module' object has no attribute ..." . Where I really stuck is the namespace has
already contain that attributes , even though it fails to load
Please Help
```
import inspect
import cPickle as pickle
from run import run
... | I found this link helpful:
<http://stefaanlippens.net/pickleproblem>
It gives two solutions. The better solution is to add to the head of the loading module (or `__main__`):
```
from myclassmodule import MyClass
```
But I think a better solution should exist. |
python: if row[1].upper().find(brand)!=-1: | 3,364,106 | 3 | 2010-07-29T15:18:03Z | 3,364,134 | 8 | 2010-07-29T15:21:20Z | [
"python"
] | are these two statements equivalent?
```
if row[1].upper().find(brand)!=-1:
```
and
```
if row[1].upper().find(brand):
``` | No, they aren't equal. In Python, any nonzero number is treated as being True, so the second statement will be considered true if the expression evaluates to -1, and false if the expression evaluates to 0 (when it should be true).
Use the first statement. |
Has anyone parsed Wiktionary? | 3,364,279 | 26 | 2010-07-29T15:36:05Z | 3,364,332 | 18 | 2010-07-29T15:40:21Z | [
"python",
"web-services",
"dictionary",
"wiktionary"
] | [Wiktionary](http://en.wiktionary.org) is a wiki dictionary that covers many languages. It even has translations. I would be interested in parsing it and playing with the data, has anyone does anything like this before? Is there any library I can use? (Preferably Python.) | Wiktionary runs on MediaWiki, which [has an API](http://www.mediawiki.org/wiki/API).
One of the subpages for the API documentation is [Client code, which lists some Python libraries](http://www.mediawiki.org/wiki/API%3aClient_code#Python). |
Has anyone parsed Wiktionary? | 3,364,279 | 26 | 2010-07-29T15:36:05Z | 3,366,887 | 17 | 2010-07-29T20:59:08Z | [
"python",
"web-services",
"dictionary",
"wiktionary"
] | [Wiktionary](http://en.wiktionary.org) is a wiki dictionary that covers many languages. It even has translations. I would be interested in parsing it and playing with the data, has anyone does anything like this before? Is there any library I can use? (Preferably Python.) | I had at one time downloaded a wiktionary dump, trying to gather together words and definitions for slavic languages. I approached it using elementtree to go thru the xml file that is the dump. I would avoid trying to scrape or crawl the site, and just download the xml dump that wikimedia provides for wiktionary. Go to... |
Has anyone parsed Wiktionary? | 3,364,279 | 26 | 2010-07-29T15:36:05Z | 5,906,919 | 7 | 2011-05-06T04:52:31Z | [
"python",
"web-services",
"dictionary",
"wiktionary"
] | [Wiktionary](http://en.wiktionary.org) is a wiki dictionary that covers many languages. It even has translations. I would be interested in parsing it and playing with the data, has anyone does anything like this before? Is there any library I can use? (Preferably Python.) | I had a crack at parsing the german wiktionary. I ended up writing it off as too difficult, but I put my (not at all tidied up) code up at <https://github.com/benreynwar/wiktionary-parser> before I gave up. Although there are conventions used by the editors they are not enforced by anything other than peer oversight. T... |
Has anyone parsed Wiktionary? | 3,364,279 | 26 | 2010-07-29T15:36:05Z | 9,735,019 | 11 | 2012-03-16T09:51:06Z | [
"python",
"web-services",
"dictionary",
"wiktionary"
] | [Wiktionary](http://en.wiktionary.org) is a wiki dictionary that covers many languages. It even has translations. I would be interested in parsing it and playing with the data, has anyone does anything like this before? Is there any library I can use? (Preferably Python.) | [wordnik](http://wordnik.com) has done a good job parsing-out definitions, etc
and they have a [great api](http://api.wordnik.com)
like the others have mentioned, wiktionary is a formatting-disaster, and was not built to be computer-readable |
Best practices for doing accounting in Python | 3,364,699 | 4 | 2010-07-29T16:16:29Z | 3,365,105 | 7 | 2010-07-29T16:57:46Z | [
"python",
"decimal",
"money",
"accounting",
"freetds"
] | I am writing a web2py application that requires summing dollar amounts without losing precision. I realize I need to use Decimals for this, but I've found myself having to wrap every single number I get from the database with:
`Decimal(str(myval))`
Before I go crazy adding that to all of my code, is there a better wa... | First, keep all numbers in decimal form in the database -- you don't mention what DB engine you're using, but every engine supports such functionality, e.g., [here](http://dev.mysql.com/doc/refman/5.5/en/precision-math-decimal-changes.html) is MySQL's `DECIMAL` type documentation. I hope you're already doing that, but,... |
How to import all submodules? | 3,365,740 | 23 | 2010-07-29T18:18:44Z | 3,365,846 | 20 | 2010-07-29T18:33:28Z | [
"python",
"import",
"module"
] | I have a directory structure as follows:
```
| main.py
| scripts
|--| __init__.py
| script1.py
| script2.py
| script3.py
```
From `main.py`, the module `scripts` is imported. I tried using `pkgutils.walk_packages` in combination with `__all__`, but using that, I can only import all the submodules directly un... | **Edit:** Here's one way to recursively import everything at runtime...
It uses exec, so there's almost certainly a better way, but it does work (even for arbitrarily nested sub-packages, I think).
(Contents of `__init__.py` in top package directory)
```
import pkgutil
__all__ = []
for loader, module_name, is_pkg i... |
How to import all submodules? | 3,365,740 | 23 | 2010-07-29T18:18:44Z | 25,083,161 | 8 | 2014-08-01T15:03:59Z | [
"python",
"import",
"module"
] | I have a directory structure as follows:
```
| main.py
| scripts
|--| __init__.py
| script1.py
| script2.py
| script3.py
```
From `main.py`, the module `scripts` is imported. I tried using `pkgutils.walk_packages` in combination with `__all__`, but using that, I can only import all the submodules directly un... | Simply works, and allows relative import inside packages:
```
def import_submodules(package_name):
""" Import all submodules of a module, recursively
:param package_name: Package name
:type package_name: str
:rtype: dict[types.ModuleType]
"""
package = sys.modules[package_name]
return {
... |
Add elements in a list of dictionaries | 3,366,170 | 6 | 2010-07-29T19:20:04Z | 3,366,366 | 9 | 2010-07-29T19:47:36Z | [
"python",
"dictionary",
"nested"
] | I have a very long list of dictionaries with string indices and integer values. Many of the keys are the same across the dictionaries, though not all. I want to generate one dictionary in which the keys are the union of the keys in the separate dictionaries and the values are the sum of all the values corresponding to ... | Here are some microbenchmarks which suggest `f2` (see below) might be an improvement. `f2` uses `iteritems` which allows you avoid an extra dict lookup in the inner loop:
```
import collections
import string
import random
def random_dict():
n=random.randint(1,26)
keys=list(string.letters)
random.shuffle(k... |
Notepad++ indentation messes up | 3,366,499 | 22 | 2010-07-29T20:05:58Z | 3,366,526 | 18 | 2010-07-29T20:08:48Z | [
"python",
"notepad++",
"indentation"
] | I'm coding in Python and I really like Notepad++. However, off late when I use tab to indent, it seems fine in Notepad++, but when I run the program I get an indentation error, and when I check my code in Emacs or something, I find that Notepad++ actually adds more tab spaces than it shows on screen. What is happening? | I would suggest going to View > Show Symbol > Show Whitespace and Tab to get an better idea of how your indentations look. |
Notepad++ indentation messes up | 3,366,499 | 22 | 2010-07-29T20:05:58Z | 3,366,550 | 56 | 2010-07-29T20:12:22Z | [
"python",
"notepad++",
"indentation"
] | I'm coding in Python and I really like Notepad++. However, off late when I use tab to indent, it seems fine in Notepad++, but when I run the program I get an indentation error, and when I check my code in Emacs or something, I find that Notepad++ actually adds more tab spaces than it shows on screen. What is happening? | There is no universal tab size, so I always make sure to replace tabs by spaces (so you know what you see is what you get everywhere else as well)
Go to Settings -> "Preferences..." -> Language Menu/Tab Settings and check 'Replace by space' |
insert variable values into a string in python | 3,367,288 | 3 | 2010-07-29T21:57:37Z | 3,367,295 | 7 | 2010-07-29T21:59:02Z | [
"python",
"gis"
] | As introduces a variable [i] into a string in python.
For example look at the following script, I just want to be able to give a name to the image, for example geo [0]. Tiff ... to geo [i]. tiff, or if you use an accountant as I can replace a portion of the value chain to generate a counter.
```
data = self.cmd("... | You can use the operator `%` to inject strings into strings:
```
"first string is: %s, second one is: %s" % (str1, "geo.tif")
```
This will give:
```
"first string is: STR1CONTENTS, second one is geo.tif"
```
You could also do integers with `%d`:
```
"geo%d.tif" % 3 # geo3.tif
``` |
Basic python arithmetic - division | 3,367,315 | 4 | 2010-07-29T22:02:03Z | 3,367,341 | 14 | 2010-07-29T22:06:07Z | [
"python",
"math",
"python-2.x"
] | I have two variables : count, which is a number of my filtered objects, and constant value per\_page. I want to divide count by per\_page and get integer value but I no matter what I try - I'm getting 0 or 0.0 :
```
>>> count = friends.count()
>>> print count
1
>>> per_page = 2
>>> print per_page
2
>>> pages = math.ce... | Python does integer division when both operands are integers, meaning that `1 / 2` is basically "how many times does 2 go into 1", which is of course 0 times. To do what you want, convert one operand to a float: `1 / float(2) == 0.5`, as you're expecting. And, of course, `math.ceil(1 / float(2))` will yield `1`, as you... |
howto extract simple string from tuple in python (newbie question) | 3,367,450 | 4 | 2010-07-29T22:23:01Z | 3,367,458 | 11 | 2010-07-29T22:24:19Z | [
"python",
"string",
"parsing",
"tuples"
] | I have a rather large tuple which contains:
```
[('and', 44023), ('cx', 37711), ('is', 36777) .... ]
```
I just want to extract the first string delimited by the single quotes, so the output for the above tuple would be:
```
and
cx
is
```
How do I code this (with extensibilty built in to some degree)? | ```
[tup[0] for tup in mylist]
```
This uses a list comprehension. You could also use parentheses instead of the outer brackets to make it a generator comprehension, so evaluation would be lazy. |
Efficiently carry out multiple string replacements in Python | 3,367,809 | 6 | 2010-07-29T23:42:01Z | 3,367,868 | 9 | 2010-07-29T23:58:15Z | [
"python",
"string",
"immutability"
] | If I would like to carry out multiple string replacements, what is the most efficient way to carry this out?
An example of the kind of situation I have encountered in my travels is as follows:
```
>>> strings = ['a', 'list', 'of', 'strings']
>>> [s.replace('a', '')...replace('u', '') for s in strings if len(s) > 2]
... | The specific example you give (deleting single characters) is perfect for the `translate` method of strings, as is substitution of single characters with single characters. If the input string is a Unicode one, then, as well as the two above kinds of "substitution", substitution of single characters with multiple chara... |
Is there a JavaScript or jQuery equivalent to Python's "sum" built-in function? | 3,368,224 | 7 | 2010-07-30T01:48:51Z | 3,368,235 | 7 | 2010-07-30T01:51:29Z | [
"javascript",
"jquery",
"python"
] | Say I have an array-ish container of decimal numbers. I want the sum. In Python I would do this:
```
x = [1.2, 3.4, 5.6]
sum(x)
```
Is there a similarly concise way to do this in JavaScript? | I guess there's none... but you can make one on javascript
```
Array.prototype.sum = function() {
return (! this.length) ? 0 : this.slice(1).sum() +
((typeof this[0] == 'number') ? this[0] : 0);
};
```
use it as,
```
[1,2,3,4,5].sum() //--> returns 15
[1,2,'',3,''].sum() //--> returns 6
[].sum() //--> return... |
Is there a JavaScript or jQuery equivalent to Python's "sum" built-in function? | 3,368,224 | 7 | 2010-07-30T01:48:51Z | 3,368,280 | 12 | 2010-07-30T02:04:04Z | [
"javascript",
"jquery",
"python"
] | Say I have an array-ish container of decimal numbers. I want the sum. In Python I would do this:
```
x = [1.2, 3.4, 5.6]
sum(x)
```
Is there a similarly concise way to do this in JavaScript? | Another approach, a simple iterative function:
```
function sum(arr) {
var result = 0, n = arr.length || 0; //may use >>> 0 to ensure length is Uint32
while(n--) {
result += +arr[n]; // unary operator to ensure ToNumber conversion
}
return result;
}
var x = [1.2, 3.4, 5.6];
sum(x); // 10.2
```
Yet anothe... |
BeautifulSoup(html) not working, saying can't call module? | 3,368,231 | 4 | 2010-07-30T01:50:50Z | 3,368,243 | 13 | 2010-07-30T01:54:36Z | [
"python",
"beautifulsoup"
] | ```
import urllib2
import urllib
from BeautifulSoup import BeautifulSoup # html
from BeautifulSoup import BeautifulStoneSoup # xml
import BeautifulSoup # everything
import re
f = o.open( 'http://www.google.com', p)
html = f.read()
f.close()
soup = BeautifulSoup(html)
```
**Getting an erro... | Your `import BeautifulSoup` makes `BeautifulSoup` refer to the module, not the class as it did after `from BeautifulSoup import BeautifulSoup`. If you're going to import the whole module, you might want to omit the `from ...` line or perhaps rename the class afterward:
```
from BeautifulSoup import BeautifulSoup
Soup... |
How do I access the properties of a many-to-many "through" table from a django template? | 3,368,442 | 31 | 2010-07-30T02:55:26Z | 3,368,833 | 21 | 2010-07-30T05:11:17Z | [
"python",
"django",
"django-templates",
"many-to-many",
"relationship"
] | From the Django documentation...
> When you're only dealing with simple many-to-many relationships such as mixing and matching pizzas and toppings, a standard ManyToManyField is all you need. However, sometimes you may need to associate data with the relationship between two models.
>
> For example, consider the case ... | The easiest way is just to pass the band to the template. Templates are capable of navigating the relationships between models and there is both members and membership\_set queryset managers on Group. So here is how I would do it:
view:
```
def group_details(request, group_id):
group = get_object_or_404(Group, pk... |
How to make float values in Python display .00 instead of .0? | 3,368,514 | 2 | 2010-07-30T03:21:53Z | 3,368,521 | 11 | 2010-07-30T03:23:51Z | [
"python",
"floating-point",
"integer",
"double"
] | Simple question, sorry I can;t figure this out. I have some numbers that are made by
float(STRING)
and they are displayed as xxx.0, but I want them to end in .00 if it is indeed a whole number. How would I do this?
Thanks!
EDIT:
Python saiys that float doesn't have a cal 'format()' | ```
>>> '%.2f' % 2.0
'2.00'
``` |
Find string between two substrings | 3,368,969 | 78 | 2010-07-30T05:50:28Z | 3,368,987 | 25 | 2010-07-30T05:56:47Z | [
"string",
"python",
"substring"
] | How do I find a string between two substrings (`'123STRINGabc' -> 'STRING'`)?
My current method is like this:
```
>>> start = 'asdf=5;'
>>> end = '123jasd'
>>> s = 'asdf=5;iwantthis123jasd'
>>> print((s.split(start))[1].split(end)[0])
iwantthis
```
However, this seems very inefficient and un-pythonic. What is a bett... | ```
s[len(start):-len(end)]
``` |
Find string between two substrings | 3,368,969 | 78 | 2010-07-30T05:50:28Z | 3,368,991 | 79 | 2010-07-30T05:58:16Z | [
"string",
"python",
"substring"
] | How do I find a string between two substrings (`'123STRINGabc' -> 'STRING'`)?
My current method is like this:
```
>>> start = 'asdf=5;'
>>> end = '123jasd'
>>> s = 'asdf=5;iwantthis123jasd'
>>> print((s.split(start))[1].split(end)[0])
iwantthis
```
However, this seems very inefficient and un-pythonic. What is a bett... | ```
s = "123123STRINGabcabc"
def find_between( s, first, last ):
try:
start = s.index( first ) + len( first )
end = s.index( last, start )
return s[start:end]
except ValueError:
return ""
def find_between_r( s, first, last ):
try:
start = s.rindex( first ) + len( fi... |
Find string between two substrings | 3,368,969 | 78 | 2010-07-30T05:50:28Z | 3,368,993 | 7 | 2010-07-30T05:58:26Z | [
"string",
"python",
"substring"
] | How do I find a string between two substrings (`'123STRINGabc' -> 'STRING'`)?
My current method is like this:
```
>>> start = 'asdf=5;'
>>> end = '123jasd'
>>> s = 'asdf=5;iwantthis123jasd'
>>> print((s.split(start))[1].split(end)[0])
iwantthis
```
However, this seems very inefficient and un-pythonic. What is a bett... | Here is one way to do it
```
_,_,rest = s.partition(start)
result,_,_ = rest.partition(end)
print result
```
Another way using regexp
```
import re
print re.findall(re.escape(start)+"(.*)"+re.escape(end),s)[0]
```
or
```
print re.search(re.escape(start)+"(.*)"+re.escape(end),s).group(1)
``` |
Find string between two substrings | 3,368,969 | 78 | 2010-07-30T05:50:28Z | 3,369,000 | 85 | 2010-07-30T05:59:57Z | [
"string",
"python",
"substring"
] | How do I find a string between two substrings (`'123STRINGabc' -> 'STRING'`)?
My current method is like this:
```
>>> start = 'asdf=5;'
>>> end = '123jasd'
>>> s = 'asdf=5;iwantthis123jasd'
>>> print((s.split(start))[1].split(end)[0])
iwantthis
```
However, this seems very inefficient and un-pythonic. What is a bett... | ```
import re
s = 'asdf=5;iwantthis123jasd'
result = re.search('asdf=5;(.*)123jasd', s)
print result.group(1)
``` |
Find string between two substrings | 3,368,969 | 78 | 2010-07-30T05:50:28Z | 3,369,567 | 23 | 2010-07-30T07:47:56Z | [
"string",
"python",
"substring"
] | How do I find a string between two substrings (`'123STRINGabc' -> 'STRING'`)?
My current method is like this:
```
>>> start = 'asdf=5;'
>>> end = '123jasd'
>>> s = 'asdf=5;iwantthis123jasd'
>>> print((s.split(start))[1].split(end)[0])
iwantthis
```
However, this seems very inefficient and un-pythonic. What is a bett... | String formatting adds some flexibility to what Nikolaus Gradwohl suggested. `start` and `end` can now be amended as desired.
```
import re
s = 'asdf=5;iwantthis123jasd'
start = 'asdf=5;'
end = '123jasd'
result = re.search('%s(.*)%s' % (start, end), s).group(1)
print(result)
``` |
Find string between two substrings | 3,368,969 | 78 | 2010-07-30T05:50:28Z | 18,790,509 | 12 | 2013-09-13T15:54:32Z | [
"string",
"python",
"substring"
] | How do I find a string between two substrings (`'123STRINGabc' -> 'STRING'`)?
My current method is like this:
```
>>> start = 'asdf=5;'
>>> end = '123jasd'
>>> s = 'asdf=5;iwantthis123jasd'
>>> print((s.split(start))[1].split(end)[0])
iwantthis
```
However, this seems very inefficient and un-pythonic. What is a bett... | ```
start = 'asdf=5;'
end = '123jasd'
s = 'asdf=5;iwantthis123jasd'
```
> print s[s.find(start)+len(start):s.rfind(end)]
```
iwantthis
``` |
Controlling Browser using Python? | 3,369,073 | 9 | 2010-07-30T06:16:21Z | 3,369,091 | 9 | 2010-07-30T06:20:38Z | [
"python",
"browser",
"webbrowser-control"
] | Is it possible to control a web browser like Firefox using Python?
I would want to do things like
* launch the browser
* force clicks on URLs
* take screenshots
etc. | [Selenium Remote Control](http://seleniumhq.org/projects/remote-control/index.html "Selenium RC") is a project that comes very close to what you are after. It is really easy to get working in Python with the `selenium.webdriver` subpackage that comes with it. Once upon a time, these were two projects. They've now been ... |
Controlling Browser using Python? | 3,369,073 | 9 | 2010-07-30T06:16:21Z | 3,370,724 | 8 | 2010-07-30T10:46:03Z | [
"python",
"browser",
"webbrowser-control"
] | Is it possible to control a web browser like Firefox using Python?
I would want to do things like
* launch the browser
* force clicks on URLs
* take screenshots
etc. | If you need to take screenshots, then you need to render the pages. I would recommend to use Selenium (as mentioned by Tim), or then [spynner](https://github.com/makinacorpus/spynner).
Here is a sample code of what you need using spynner:
```
import spynner
browser = spynner.Browser()
browser.load("http://stackoverf... |
Why < is slower than >= | 3,369,304 | 18 | 2010-07-30T07:04:50Z | 3,369,477 | 32 | 2010-07-30T07:33:02Z | [
"python",
"performance",
"optimization"
] | I am using the following code to do the test and it seems like < is slower that >=., does anyone know why?
```
import timeit
s = """
x=5
if x<0: pass
"""
t = timeit.Timer(stmt=s)
print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
#0.21 usec/pass
z = """
x=5
if x>=0: pass
"""
t2 = timeit.Ti... | In Python 3.1.2, sometime < is faster than >=. I try to read it in disassembler,
```
import dis
def f1():
x=5
if x < 0: pass
def f2():
x = 5
if x >=0: pass
>>> dis.dis(f1)
2 0 LOAD_CONST 1 (5)
3 STORE_FAST 0 (x)
3 6 LOAD_FAST ... |
When is using __call__ a good idea? | 3,369,640 | 9 | 2010-07-30T08:02:34Z | 3,369,912 | 15 | 2010-07-30T08:46:20Z | [
"python",
"oop"
] | What are peoples' opinions on using the `__call__`. I've only very rarely seen it used, but I think it's a very handy tool to use when you know that a class is going to be used for some default behaviour. | I think your intuition is about right.
Historically, callable objects (or what I've sometimes heard called "functors") have been used in the OO world to simulate closures. In C++ they're frequently indispensable.
However, `__call__` has quite a bit of competition in the Python world:
* A regular named method, whose ... |
Revert the `--no-site-packages` option with virtualenv | 3,371,136 | 84 | 2010-07-30T11:50:19Z | 3,374,514 | 114 | 2010-07-30T18:54:30Z | [
"python",
"virtualenv"
] | I have created a virtualenv using the `--no-site-packages` option and installed lots of libraries. Now I would like to revert the `--no-site-packages` option and use also the global packages.
Can I do that without recreating the virtualenv?
**More precisely:**
I wonder what *exactly* happens when creating a virtuale... | Try removing (or renaming) the file `no-global-site-packages.txt` in your `Lib` folder under your virtual environment.
Where **venv** is the name of your virtual environment, and **python3.4** corresponds to whichever version of python involved, for example:
```
$ rm venv/lib/python3.4/no-global-site-packages.txt
```... |
Revert the `--no-site-packages` option with virtualenv | 3,371,136 | 84 | 2010-07-30T11:50:19Z | 33,411,094 | 7 | 2015-10-29T10:00:28Z | [
"python",
"virtualenv"
] | I have created a virtualenv using the `--no-site-packages` option and installed lots of libraries. Now I would like to revert the `--no-site-packages` option and use also the global packages.
Can I do that without recreating the virtualenv?
**More precisely:**
I wonder what *exactly* happens when creating a virtuale... | When using [virtualenvwrapper](https://bitbucket.org/dhellmann/virtualenvwrapper) to manage virtualenvs, you can use the shell function `toggleglobalsitepackages` to switch between using and not using site packages. |
Call int() function on every list element in Python | 3,371,269 | 94 | 2010-07-30T12:12:58Z | 3,371,274 | 194 | 2010-07-30T12:13:33Z | [
"python",
"list"
] | I have a list with numeric strings, like so:
```
numbers = ['1', '5', '10', '8'];
```
I would like to convert every list element to integer, so it would look like this:
```
numbers = [1, 5, 10, 8];
```
I could do it using a loop, like so:
```
new_numbers = [];
for n in numbers:
new_numbers.append(int(n));
numb... | This is what list comprehensions are for:
```
numbers = [ int(x) for x in numbers ]
``` |
Call int() function on every list element in Python | 3,371,269 | 94 | 2010-07-30T12:12:58Z | 3,371,286 | 65 | 2010-07-30T12:15:10Z | [
"python",
"list"
] | I have a list with numeric strings, like so:
```
numbers = ['1', '5', '10', '8'];
```
I would like to convert every list element to integer, so it would look like this:
```
numbers = [1, 5, 10, 8];
```
I could do it using a loop, like so:
```
new_numbers = [];
for n in numbers:
new_numbers.append(int(n));
numb... | In Python 2.x another approach is to use `map`:
```
numbers = map(int, numbers)
```
Note: in Python 3.x `map` returns a map object which you can convert to a list if you want:
```
numbers = list(map(int, numbers))
``` |
Call int() function on every list element in Python | 3,371,269 | 94 | 2010-07-30T12:12:58Z | 3,371,427 | 8 | 2010-07-30T12:37:50Z | [
"python",
"list"
] | I have a list with numeric strings, like so:
```
numbers = ['1', '5', '10', '8'];
```
I would like to convert every list element to integer, so it would look like this:
```
numbers = [1, 5, 10, 8];
```
I could do it using a loop, like so:
```
new_numbers = [];
for n in numbers:
new_numbers.append(int(n));
numb... | If you are intending on passing those integers to a function or method, consider this example:
```
sum(int(x) for x in numbers)
```
This construction is intentionally remarkably similar to list comprehensions mentioned by adamk. Without the square brackets, it's called a `generator expression`, and is a very memory e... |
Call int() function on every list element in Python | 3,371,269 | 94 | 2010-07-30T12:12:58Z | 3,378,388 | 9 | 2010-07-31T13:57:40Z | [
"python",
"list"
] | I have a list with numeric strings, like so:
```
numbers = ['1', '5', '10', '8'];
```
I would like to convert every list element to integer, so it would look like this:
```
numbers = [1, 5, 10, 8];
```
I could do it using a loop, like so:
```
new_numbers = [];
for n in numbers:
new_numbers.append(int(n));
numb... | just a point,
```
numbers = [int(x) for x in numbers]
```
the list comprehension is more natural, while
```
numbers = map(int, x)
```
is faster.
*Probably this will not matter in most cases*
Useful read: [LP vs map](https://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map) |
String concatenation in Python | 3,371,745 | 3 | 2010-07-30T13:14:26Z | 3,371,851 | 7 | 2010-07-30T13:25:14Z | [
"python",
"compilation",
"internals",
"object-identity"
] | Can you describe difference between two ways of string concatenation: simple `__add__` operator and `%s` patterns?
I had some investigation in this question and found `%s` (in form without using parentheses) a little faster.
Also another question was appeared: why result of `'hell%s' % 'o'` refers to another memory re... | Here is a small exercise:
```
>>> def f1():
'hello'
>>> def f2():
'hel' 'lo'
>>> def f3():
'hel' + 'lo'
>>> def f4():
'hel%s' % 'lo'
>>> def f5():
'hel%s' % ('lo',)
>>> for f in (f1, f2, f3, f4, f5):
print(f.__name__)
dis.dis(f)
f1
1 0 LOAD_CONST 1 (Non... |
Algorithm to determine exchange rate | 3,372,375 | 8 | 2010-07-30T14:22:53Z | 3,372,418 | 11 | 2010-07-30T14:28:03Z | [
"python",
"currency",
"finance"
] | Given a data set of various currency pairs, how do I efficiently compute the implied fx rate for a pair not supplied in the data set?
For example, say my database/table looks like this (this data is fudged):
```
GBP x USD = 1.5
USD x GBP = 0.64
GBP x EUR = 1.19
AUD x USD = 1.1
```
Notice that (GBP,USD) != 1/(USD,GBP... | You're looking for the shortest path in a directed graph, where the currencies are the vertices and the given exchange rates are the edges.
If an exchange rate is given only for one direction, you can add one for the opposite direction with a higher cost. |
Profile Memory Allocation in Python (with support for Numpy arrays) | 3,372,444 | 24 | 2010-07-30T14:30:32Z | 19,258,939 | 9 | 2013-10-08T21:38:03Z | [
"python",
"numpy",
"memory-management",
"profile"
] | I have a program that contains a large number of objects, many of them Numpy arrays. My program is swapping miserably, and I'm trying to reduce the memory usage, because it actually can't finis on my system with the current memory requirements.
I am looking for a nice profiler that would allow me to check the amount o... | Have a look at [memory profiler](https://pypi.python.org/pypi/memory_profiler). It provides line by line profiling and `Ipython` integration, which makes it very easy to use it:
```
In [1]: import numpy as np
In [2]: %memit np.zeros(1e7)
maximum of 3: 70.847656 MB per loop
```
**Update**
As mentioned by @WickedGrey... |
Profile Memory Allocation in Python (with support for Numpy arrays) | 3,372,444 | 24 | 2010-07-30T14:30:32Z | 19,312,502 | 10 | 2013-10-11T07:25:27Z | [
"python",
"numpy",
"memory-management",
"profile"
] | I have a program that contains a large number of objects, many of them Numpy arrays. My program is swapping miserably, and I'm trying to reduce the memory usage, because it actually can't finis on my system with the current memory requirements.
I am looking for a nice profiler that would allow me to check the amount o... | One way to tackle the problem if you are calling lots of different functions and you are unsure where the swapping comes from would be to use the new plotting functionality from [memory\_profiler](https://pypi.python.org/pypi/memory_profiler). First you must decorate the different functions you are using with @profile.... |
How do I fix a "JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0)"? | 3,372,643 | 7 | 2010-07-30T14:54:09Z | 3,373,214 | 8 | 2010-07-30T15:56:28Z | [
"python",
"json",
"twitter",
"simplejson"
] | I'm trying to get Twitter API search results for a given hashtag using Python, but I'm having trouble with this "No JSON object could be decoded" error. I had to add the extra % towards the end of the URL to prevent a string formatting error. Could this JSON error be related to the extra %, or is it caused by something... | There were a couple problems with your initial code. First you never read in the content from twitter, just opened the url. Second in the url you set a callback (twitterSearch). What a call back does is wrap the returned json in a function call so in this case it would have been twitterSearch(). This is useful if you w... |
How to make a simple table in ReportLab | 3,372,885 | 5 | 2010-07-30T15:19:46Z | 3,396,870 | 8 | 2010-08-03T13:24:19Z | [
"python",
"table",
"pdf",
"pdf-generation"
] | How can I make simple table in ReportLab? I need to make a simple 2x20 table and put in some data. Can someone point me to an example? | The simplest table function:
```
table = Table(data, colWidths=270, rowHeights=79)
```
How many columns & end rows depend from tuple of data. All our table functions looks like:
```
from reportlab.platypus import SimpleDocTemplate
from reportlab.platypus.tables import Table
cm = 2.54
def print_pdf(modeladmin, reque... |
modifying a python callable so it calls before() , actual function then after() | 3,373,188 | 4 | 2010-07-30T15:53:50Z | 3,373,265 | 14 | 2010-07-30T16:05:50Z | [
"python",
"callable"
] | I am not sure if this is the best way to have `before` and `after` functions be called around a function `f1()`.
```
class ba(object):
def __init__(self, call, before, after):
self.call = call
self.before = before
self.after = after
def __call__(self, *args):
self.before()
... | I'd use a decorator, like so:
```
from functools import wraps
class withBeforeAfter(object):
def __init__(self, before, after):
self.before = before
self.after = after
def __call__(self, wrappedCall):
@wraps(wrappedCall)
def wrapCall(*args, **kwargs):
try:
... |
Set Colorbar Range in matplotlib | 3,373,256 | 60 | 2010-07-30T16:04:03Z | 3,376,734 | 79 | 2010-07-31T04:01:35Z | [
"python",
"graph",
"matplotlib"
] | I have the following code:
```
import matplotlib.pyplot as plt
cdict = {
'red' : ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)),
'green': ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)),
'blue' : ( (0.0, 1.0, 1.0), (0.02, .75, .75), (1., 0.45, 0.45))
}
cm = m.colors.LinearSegmentedColormap('my_co... | Using `vmin` and `vmax` forces the range for the colors. Here's an example:

```
import matplotlib as m
import matplotlib.pyplot as plt
import numpy as np
cdict = {
'red' : ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)),
'green': ( (0.0, 0.0, 0.0), (0.02, .4... |
Set Colorbar Range in matplotlib | 3,373,256 | 60 | 2010-07-30T16:04:03Z | 3,376,856 | 27 | 2010-07-31T04:51:53Z | [
"python",
"graph",
"matplotlib"
] | I have the following code:
```
import matplotlib.pyplot as plt
cdict = {
'red' : ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)),
'green': ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)),
'blue' : ( (0.0, 1.0, 1.0), (0.02, .75, .75), (1., 0.45, 0.45))
}
cm = m.colors.LinearSegmentedColormap('my_co... | Use the [CLIM](http://matplotlib.sourceforge.net/api/cm_api.html#matplotlib.cm.ScalarMappable.set_clim) function (equivalent to [CAXIS](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/caxis.html) function in MATLAB):
```
plt.pcolor(X, Y, v, cmap=cm)
plt.clim(-4,4)
plt.show()
``` |
compiling vim with python support | 3,373,914 | 47 | 2010-07-30T17:24:20Z | 3,374,130 | 8 | 2010-07-30T17:51:19Z | [
"python",
"vim"
] | I'm trying to compile Vim 7.2 with Python 2.5.1 support, but I'm having some trouble.
1. I run configure which seems like it is working as expected
```
./configure --with-features=huge --enable-pythoninterp --prefix=/home/username/vimpy
```
I can see that changes to `--with-features` works as I expect (t... | You could try adding the option `--with-python-config-dir=/your/python/config/dir`
The path should point to the location of the file config.c of your Python installation. |
compiling vim with python support | 3,373,914 | 47 | 2010-07-30T17:24:20Z | 5,293,524 | 71 | 2011-03-14T00:26:38Z | [
"python",
"vim"
] | I'm trying to compile Vim 7.2 with Python 2.5.1 support, but I'm having some trouble.
1. I run configure which seems like it is working as expected
```
./configure --with-features=huge --enable-pythoninterp --prefix=/home/username/vimpy
```
I can see that changes to `--with-features` works as I expect (t... | I've also had "... and link flags for Python are sane... no: PYTHON DISABLED"
On Ubuntu 10.04 you have to install '**python2.6-dev**'. The flags for ./configure are:
```
--enable-pythoninterp
--with-python-config-dir=/usr/lib/python2.6/config
```
Make sure you got a path to directory, which contains '**config.c**' ... |
Graphing in Python 3.x | 3,374,457 | 14 | 2010-07-30T18:43:19Z | 3,408,364 | 16 | 2010-08-04T18:01:28Z | [
"python",
"graph",
"python-3.x",
"matplotlib"
] | In Python 2.6, I used matplotlib to make some simple graphs. However, it is incompatible with Python 3.1.
What are some alternative modules that can accomplish the same thing without being very complex? | You say you want to create some simple graphs but haven't really said how simple or what sort of graphs you want. So long as they aren't too complex you might want to consider using the [Google Chart API](http://code.google.com/apis/chart/).
e.g. . |
How do I run a django TestCase manually / against other database? | 3,374,658 | 11 | 2010-07-30T19:17:12Z | 4,797,873 | 10 | 2011-01-25T19:23:04Z | [
"python",
"django",
"unit-testing"
] | I have some methods written into a `django.test.TestCase` object that I'd like to run from the
`manage.py shell` on my real database. But when I try to instantiate the TestCase object to run the test method, I get this error:
```
ValueError: no such test method in <class 'track.tests.MentionTests'>: runTest
```
Is th... | Here's a method that I found recently. I haven't found anything better yet.
```
from django.test.utils import setup_test_environment
from unittest import TestResult
from my_app.tests import TheTestWeWantToRun
setup_test_environment()
t = TheTestWeWantToRun('test_function_we_want_to_run')
r = TestResult()
t.run(r)
r.t... |
The "right" way to add python scripting to a non-python application | 3,374,801 | 20 | 2010-07-30T19:38:11Z | 3,392,895 | 8 | 2010-08-03T00:55:55Z | [
"c++",
"python",
"scripting",
"plugins",
"desktop-application"
] | I'm currently in the process of adding the ability for users to extend the functionality of my desktop application (C++) using plugins scripted in python.
The naive method is easy enough. Embed the python static library and follow any number of the dozens of tutorials scattered around the web describing how to initial... | One effective way to accomplish this is to use a message-passing/communicating processes architecture, allowing you to accomplish your goal with Python, but not limiting yourself to Python.
```
------------------------------------
| App <--> Ext. API <--> Protocol | <--> (Socket) <--> API.py <--> Script
-------------... |
How do I track motion using OpenCV in Python? | 3,374,828 | 10 | 2010-07-30T19:44:01Z | 3,383,915 | 26 | 2010-08-01T22:03:30Z | [
"python",
"opencv"
] | I can get frames from my webcam using [OpenCV](http://opencv.willowgarage.com/wiki/) in Python. The camshift example is close to what I want, but I don't want human intervention to define the object. I want to get the center point of the total pixels that have changed over the course of several frame, i.e. the center o... | I've got some working code translated from the [C](http://en.wikipedia.org/wiki/C_%28programming_language%29) version of code found in the blog post *[Motion Detection using OpenCV](http://sundararajana.blogspot.com/2007/05/motion-detection-using-opencv.html)*:
```
#!/usr/bin/env python
import cv
class Target:
... |
With the Python Imaging Library (PIL), how does one compose an image with an alpha channel over another image? | 3,374,878 | 9 | 2010-07-30T19:51:31Z | 3,375,291 | 10 | 2010-07-30T20:54:06Z | [
"python",
"image-processing",
"python-imaging-library"
] | I have two images, both with alpha channels. I want to put one image over the other, resulting in a new image with an alpha channel, just as would occur if they were rendered in layers. I would like to do this with the Python Imaging Library, but recommendations in other systems would be fantastic, even the raw math wo... | I couldn't find an [alpha composite](http://en.wikipedia.org/wiki/Alpha_compositing) function in PIL, so here is my attempt at implementing it with numpy:
```
import numpy as np
import Image
def alpha_composite(src, dst):
'''
Return the alpha composite of src and dst.
Parameters:
src -- PIL RGBA Imag... |
With the Python Imaging Library (PIL), how does one compose an image with an alpha channel over another image? | 3,374,878 | 9 | 2010-07-30T19:51:31Z | 3,376,602 | 25 | 2010-07-31T03:03:17Z | [
"python",
"image-processing",
"python-imaging-library"
] | I have two images, both with alpha channels. I want to put one image over the other, resulting in a new image with an alpha channel, just as would occur if they were rendered in layers. I would like to do this with the Python Imaging Library, but recommendations in other systems would be fantastic, even the raw math wo... | This appears to do the trick:
```
from PIL import Image
bottom = Image.open("a.png")
top = Image.open("b.png")
r, g, b, a = top.split()
top = Image.merge("RGB", (r, g, b))
mask = Image.merge("L", (a,))
bottom.paste(top, (0, 0), mask)
bottom.save("over.png")
``` |
With the Python Imaging Library (PIL), how does one compose an image with an alpha channel over another image? | 3,374,878 | 9 | 2010-07-30T19:51:31Z | 15,919,800 | 10 | 2013-04-10T07:40:37Z | [
"python",
"image-processing",
"python-imaging-library"
] | I have two images, both with alpha channels. I want to put one image over the other, resulting in a new image with an alpha channel, just as would occur if they were rendered in layers. I would like to do this with the Python Imaging Library, but recommendations in other systems would be fantastic, even the raw math wo... | Pillow 2.0 now contains an `alpha_composite` function that does this.
```
img3 = Image.alpha_composite(img1, img2)
``` |
How to give Tkinter file dialog focus | 3,375,227 | 7 | 2010-07-30T20:43:29Z | 7,090,747 | 7 | 2011-08-17T09:41:14Z | [
"python",
"tkinter"
] | I'm using OS X. I'm double clicking my script to run it from Finder. This script imports and runs the function below.
I'd like the script to present a Tkinter open file dialog and return a list of files selected.
Here's what I have so far:
```
def open_files(starting_dir):
"""Returns list of filenames+paths give... | For anybody that ends up here via Google (like I did), here is a hack I've devised that works in both Windows and Ubuntu. In my case, I actually still need the terminal, but just want the dialog to be on top when displayed.
```
# Make a top-level instance and hide since it is ugly and big.
root = Tkinter.Tk()
root.wit... |
What are the benefits (and drawbacks) of a weakly typed language? | 3,376,252 | 14 | 2010-07-31T00:24:10Z | 3,376,323 | 9 | 2010-07-31T00:53:21Z | [
"php",
"python",
"c",
"types"
] | I'm a big fan of PHP and it's obviously a very weakly-typed language. I realize some of the benefits include the general independence of changing variable types on the fly and such.
What I'm wondering about are the drawbacks. What can you get out of a strongly-typed language like C that you otherwise can't get from a ... | The cited advantage of *static* typing is that there are whole classes of errors caught at compile time, that cannot reach runtime. For example, if you have a statically-typed class or interface as a function parameter, then you are darn well not going to accidentally pass in an object of the wrong type (without an exp... |
Can someone please explain this bit of Python code? | 3,376,643 | 4 | 2010-07-31T03:22:35Z | 3,376,664 | 8 | 2010-07-31T03:31:49Z | [
"python",
"closures"
] | I started working in Python just recently and haven't fully learned all the nuts and bolts of it, but recently I came across [this post](http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/67666) that explains why python has closures, in there, there is a sample code that goes like this:
```
y = 0
def foo():
... | Before the `nonlocal` keyword was added in Python 3 (and still today, if you're stuck on `2.*` for whatever reason), a nested function just couldn't rebind a local barename of its outer function -- because, normally, an assignment statement to a barename, such as `x = 23`, means that `x` is a local name for the functio... |
beautifulsoup, Find th with text 'price', then get price from next th | 3,376,803 | 5 | 2010-07-31T04:30:34Z | 3,376,904 | 8 | 2010-07-31T05:08:07Z | [
"python",
"beautifulsoup"
] | My html looks like:
```
<td>
<table ..>
<tr>
<th ..>price</th>
<th>$99.99</th>
</tr>
</table>
</td>
```
So I am in the current table cell, how would I get the 99.99 value?
I have so far:
```
td[3].findChild('th')
```
But I need to do:
**Find th with text 'price', then get next ... | Think about it in "steps"... given that some `x` is the root of the subtree you're considering,
```
x.findAll(text='price')
```
is the list of all items in that subtree containing text `'price'`. The parents of those items then of course will be:
```
[t.parent for t in x.findAll(text='price')]
```
and if you only w... |
how to deepcopy a queue in python | 3,377,202 | 2 | 2010-07-31T07:08:11Z | 3,377,290 | 9 | 2010-07-31T07:49:23Z | [
"python",
"copy",
"queue"
] | Hi How to deepcopy a Queue in python?
Thanks | The [`queue` module](http://docs.python.org/library/queue.html) in Python is used for synchronizing shared data between threads. It is *not* intended as a data structure and it doesn't support copying (not even shallow copy).
(It is possible to construct many deepcopy's of a Queue by `.get` and `.put`, but the origina... |
Memoization Handler | 3,377,258 | 10 | 2010-07-31T07:31:35Z | 3,377,272 | 13 | 2010-07-31T07:37:50Z | [
"python",
"dynamic-programming",
"memoization"
] | **Is it "good practice" to create a class like the one below that can handle the memoization process for you?** The benefits of memoization are so great (in some cases, like this one, where it drops from 501003 to 1507 function calls and from 1.409 to 0.006 seconds of CPU time on my computer) that it seems a class like... | You can memoize without having to resort to `eval`.
A (very basic) memoizer:
```
def memoized(f):
cache={}
def ret(*args):
if args in cache:
return cache[args]
else:
answer=f(*args)
cache[args]=answer
return answer
return ret
@memoized
def f... |
How do I efficiently fill a file with null data from python? | 3,377,891 | 5 | 2010-07-31T11:33:14Z | 3,377,909 | 16 | 2010-07-31T11:39:28Z | [
"python",
"file"
] | I need to create files of arbitrary size that contain no data. The are potentially quite large. While I could just loop through and write a single null character until I've reached the file size, that seems ugly.
```
with open(filename,'wb') as f:
# what goes here?
```
What is the efficient, pythonic way to do thi... | You can seek to a specific position and write a byte, and the OS will magically make the rest of the file appear.
```
with open(filename, "wb") as f:
f.seek(999999)
f.write("\0")
```
You need to write at least one byte for this to work. |
How do I efficiently fill a file with null data from python? | 3,377,891 | 5 | 2010-07-31T11:33:14Z | 3,377,918 | 8 | 2010-07-31T11:41:39Z | [
"python",
"file"
] | I need to create files of arbitrary size that contain no data. The are potentially quite large. While I could just loop through and write a single null character until I've reached the file size, that seems ugly.
```
with open(filename,'wb') as f:
# what goes here?
```
What is the efficient, pythonic way to do thi... | ```
with open('zero', 'w') as f:
f.seek(999999999)
f.write('\0')
```
Will create a [sparse file](http://en.wikipedia.org/wiki/Sparse_file) if the OS supports it. The magic is that files created this way do not take any space (until you copy it elsewhere with a program that does not preserve holes) |
Is there a visual profiler for Python? | 3,378,953 | 72 | 2010-07-31T16:37:13Z | 3,379,134 | 38 | 2010-07-31T17:34:54Z | [
"python",
"user-interface",
"profiling",
"profiler"
] | I use [cProfile](http://docs.python.org/library/profile.html) now but I find it tedious to write pstats code just to query the statistics data.
I'm looking for a visual tool that shows me what my Python code is doing in terms of CPU time and memory allocation.
Some examples from the Java world are [visualvm](https://... | I'm only aware of [RunSnakeRun](http://www.vrplumber.com/programming/runsnakerun/).
There was also some talk some time ago about an integrated profiler in PyDev (Eclipse), but I don't know if that will ever see the light of day.
Update: Unfortunately it seems that RunSnakeRun is no longer maintained, and it does not ... |
Is there a visual profiler for Python? | 3,378,953 | 72 | 2010-07-31T16:37:13Z | 10,572,769 | 11 | 2012-05-13T15:03:33Z | [
"python",
"user-interface",
"profiling",
"profiler"
] | I use [cProfile](http://docs.python.org/library/profile.html) now but I find it tedious to write pstats code just to query the statistics data.
I'm looking for a visual tool that shows me what my Python code is doing in terms of CPU time and memory allocation.
Some examples from the Java world are [visualvm](https://... | I use gprof2dot.py. The result looks [like this](http://log2.ch/misc/profile_tiny_straight_line_preview.png). I use those commands:
```
python -m cProfile -o profile.dat my_program.py
gprof2dot.py -f pstats profile.dat | dot -Tpng -o profile.png
```
You need [graphviz](http://www.graphviz.org/) and [gprof2dot.py]... |
Is there a visual profiler for Python? | 3,378,953 | 72 | 2010-07-31T16:37:13Z | 12,557,366 | 54 | 2012-09-24T00:07:17Z | [
"python",
"user-interface",
"profiling",
"profiler"
] | I use [cProfile](http://docs.python.org/library/profile.html) now but I find it tedious to write pstats code just to query the statistics data.
I'm looking for a visual tool that shows me what my Python code is doing in terms of CPU time and memory allocation.
Some examples from the Java world are [visualvm](https://... | A friend and I have written a Python profile viewer called [SnakeViz](http://jiffyclub.github.io/snakeviz/) that runs in a web browser. If you are already successfully using [RunSnakeRun](http://www.vrplumber.com/programming/runsnakerun/) SnakeViz may not add that much value, but SnakeViz is much easier to install.
Ed... |
Is there a visual profiler for Python? | 3,378,953 | 72 | 2010-07-31T16:37:13Z | 19,877,128 | 7 | 2013-11-09T14:31:00Z | [
"python",
"user-interface",
"profiling",
"profiler"
] | I use [cProfile](http://docs.python.org/library/profile.html) now but I find it tedious to write pstats code just to query the statistics data.
I'm looking for a visual tool that shows me what my Python code is doing in terms of CPU time and memory allocation.
Some examples from the Java world are [visualvm](https://... | [Spyder](https://github.com/spyder-ide/spyder) also provides a pretty nice gui for cProfile:
 |
Writing blob from SQLite to file using Python | 3,379,166 | 11 | 2010-07-31T17:42:02Z | 3,387,596 | 23 | 2010-08-02T12:14:33Z | [
"python",
"sql",
"sqlite",
"binary",
"blob"
] | A clueless Python newbie needs help. I muddled through creating a simple script that inserts a binary file into a blog field in a SQLite database:
```
import sqlite3
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
input_note = raw_input(_(u'Note: '))
input_type = 'A'
input_file = raw_input(_(u'Ent... | Here's a script that does read a file, put it in the database, read it from database and then write it to another file:
```
import sqlite3
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
with open("...", "rb") as input_file:
ablob = input_file.read()
cursor.execute("INSERT INTO notes (id, file) V... |
Using Numpy Vectorize on Functions that Return Vectors | 3,379,301 | 14 | 2010-07-31T18:20:10Z | 3,379,505 | 21 | 2010-07-31T19:25:37Z | [
"python",
"arrays",
"numpy",
"vectorization"
] | `numpy.vectorize` takes a function f:a->b and turns it into g:a[]->b[].
This works fine when `a` and `b` are scalars, but I can't think of a reason why it wouldn't work with b as an `ndarray` or list, i.e. f:a->b[] and g:a[]->b[][]
For example:
```
import numpy as np
def f(x):
return x * np.array([1,1,1,1,1], dt... | `np.vectorize` is just a convenience function. It doesn't actually [make code run any faster](http://www.mail-archive.com/numpy-discussion@scipy.org/msg00587.html). If it isn't convenient to use `np.vectorize`, simply write your own function that works as you wish.
The purpose of `np.vectorize` is to transform functio... |
Python Window Resize | 3,380,003 | 4 | 2010-07-31T22:24:20Z | 3,380,153 | 7 | 2010-07-31T23:14:16Z | [
"python",
"gtk",
"pygtk"
] | Using Python + PyGTK.
Is there a signal/event way of checking for a window resize? If so then what is the easiest way of implementing and using this signal. | a [`gtk.Window`](http://library.gnome.org/devel/pygtk/stable/class-gtkwindow.html) is also a [`gtk.Container`](http://library.gnome.org/devel/pygtk/stable/class-gtkcontainer.html), so it answers to the [`check-resize`](http://library.gnome.org/devel/pygtk/stable/class-gtkcontainer.html#signal-gtkcontainer--check-resize... |
How do I use gluLookAt properly? | 3,380,100 | 12 | 2010-07-31T22:57:20Z | 3,380,207 | 36 | 2010-07-31T23:40:25Z | [
"python",
"opengl",
"graphics",
"pyopengl"
] | I don't want to get into complex trigonometry to calculate rotations and things like that for my 3D world so gluLookAt seems like a nice alternative. According to the documentation all I need to do is place 3 coordinates for the cameras position, three for what I should be looking at and an "up" position. The last made... | (The intuition behind the "up" vector in gluLookAt is simple: Look at anything. Now tilt your head 90 degrees. Where you are hasn't changed, the direction you're looking at hasn't changed, but the image in your retina clearly has. What's the difference? Where the top of your head is pointing to. That's the up vector.)
... |
using backslash in python (not to escape) | 3,380,484 | 12 | 2010-08-01T02:19:50Z | 3,380,487 | 20 | 2010-08-01T02:22:03Z | [
"python",
"string",
"backslash"
] | ```
import os
path= os.getcwd()
final= path +'\xulrunner.exe ' + path + '\application.ini'
print final
```
I want the out put:
> c:\python25\xulrunner.exe
> c:\python25\application.ini
I don't want backslash to work as string, i mean don't want it to escape or do anything special. But i get an error
> Invalid \x es... | To answer your question directly, put `r` in front of the string.
```
final= path + r'\xulrunner.exe ' + path + r'\application.ini'
```
But a better solution would be `os.path.join`:
```
final = os.path.join(path, 'xulrunner.exe') + ' ' + \
os.path.join(path, 'application.ini')
```
(the backslash there is ... |
using backslash in python (not to escape) | 3,380,484 | 12 | 2010-08-01T02:19:50Z | 3,380,867 | 11 | 2010-08-01T05:22:32Z | [
"python",
"string",
"backslash"
] | ```
import os
path= os.getcwd()
final= path +'\xulrunner.exe ' + path + '\application.ini'
print final
```
I want the out put:
> c:\python25\xulrunner.exe
> c:\python25\application.ini
I don't want backslash to work as string, i mean don't want it to escape or do anything special. But i get an error
> Invalid \x es... | You can escape the slash. Use `\\` and you get just one slash. |
Dump data from django Feincms | 3,380,586 | 5 | 2010-08-01T03:09:27Z | 3,777,477 | 8 | 2010-09-23T10:35:40Z | [
"python",
"django",
"django-manage.py",
"feincms"
] | I'm using feincms in a django project and I want to use manage.py dumpdata but I get nothing:
```
python manage.py dumpdata feincms
[]
``` | If you want to dump the page data you need to run dumpdata on the page app. The page models live there, not in feincms:
```
python manage.py dumpdata page
``` |
Python index more than once | 3,380,654 | 3 | 2010-08-01T03:42:35Z | 3,380,891 | 7 | 2010-08-01T05:32:31Z | [
"python",
"string",
"indexing",
"substring"
] | I know that `.index()` will return where a substring is located in python.
However, what I want is to find where a substring is located for the nth time, which would work like this:
```
>> s = 'abcdefacbdea'
>> s.index('a')
0
>> s.nindex('a', 1)
6
>>s.nindex('a', 2)
11
```
Is there a way to do this in python? | How about...
```
def nindex(mystr, substr, n=0, index=0):
for _ in xrange(n+1):
index = mystr.index(substr, index) + 1
return index - 1
```
Obs: as [`str.index()`](http://docs.python.org/library/stdtypes.html#str.index) does, `nindex()` raises `ValueError` when the substr is not found. |
Converting a RGB color tuple to a six digit code, in Python | 3,380,726 | 21 | 2010-08-01T04:22:01Z | 3,380,739 | 45 | 2010-08-01T04:26:47Z | [
"python",
"colors",
"rgb"
] | I need to convert (0, 128, 64) to something like this #008040. I'm not sure what to call the latter, making searching difficult. | Use the format operator `%`:
```
>>> '#%02x%02x%02x' % (0, 128, 64)
'#008040'
```
Note that it won't check bounds...
```
>>> '#%02x%02x%02x' % (0, -1, 9999)
'#00-1270f'
``` |
Converting a RGB color tuple to a six digit code, in Python | 3,380,726 | 21 | 2010-08-01T04:22:01Z | 3,380,754 | 18 | 2010-08-01T04:35:34Z | [
"python",
"colors",
"rgb"
] | I need to convert (0, 128, 64) to something like this #008040. I'm not sure what to call the latter, making searching difficult. | ```
def clamp(x):
return max(0, min(x, 255))
"#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b))
```
This uses the preferred method of string formatting, as [described in PEP 3101](http://www.python.org/dev/peps/pep-3101/). It also uses `min()` and `max` to ensure that `0 <= {r,g,b} <= 255`.
**Update** ... |
python adds "E" to string | 3,382,234 | 15 | 2010-08-01T13:40:15Z | 3,382,259 | 8 | 2010-08-01T13:48:29Z | [
"python",
"postgresql",
"psycopg"
] | This string:
```
"CREATE USER %s PASSWORD %s", (user, pw)
```
always gets expanded to:
```
CREATE USER E'someuser' PASSWORD E'somepassword'
```
Can anyone tell me why?
Edit:
The expanded string above is the string my database gives me back in the error message. I'm using psycopg2 to access my postgres database. Th... | Not only the E but the quotes appear to come from whatever type user and pw have. %s simply does what str() does, which may fall back to repr(), both of which have corresponding methods `__str__` and `__repr__`. Also, that isn't the code that generates your result (I'd assumed there was a %, but now see only a comma). ... |
python adds "E" to string | 3,382,234 | 15 | 2010-08-01T13:40:15Z | 3,382,594 | 10 | 2010-08-01T15:39:11Z | [
"python",
"postgresql",
"psycopg"
] | This string:
```
"CREATE USER %s PASSWORD %s", (user, pw)
```
always gets expanded to:
```
CREATE USER E'someuser' PASSWORD E'somepassword'
```
Can anyone tell me why?
Edit:
The expanded string above is the string my database gives me back in the error message. I'm using psycopg2 to access my postgres database. Th... | As the OP's edit reveals he's using PostgreSQL, [the docs](http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html) for it are relevant, and they say:
> PostgreSQL also accepts "escape"
> string constants, which are an
> extension to the SQL standard. An
> escape string constant is specified by
> writing the... |
python adds "E" to string | 3,382,234 | 15 | 2010-08-01T13:40:15Z | 13,891,511 | 15 | 2012-12-15T10:47:28Z | [
"python",
"postgresql",
"psycopg"
] | This string:
```
"CREATE USER %s PASSWORD %s", (user, pw)
```
always gets expanded to:
```
CREATE USER E'someuser' PASSWORD E'somepassword'
```
Can anyone tell me why?
Edit:
The expanded string above is the string my database gives me back in the error message. I'm using psycopg2 to access my postgres database. Th... | To pass identifiers to postgresql through psycopg use `AsIs` from the `extensions` module
```
from psycopg2.extensions import AsIs
import psycopg2
connection = psycopg2.connect(database='db', user='user')
cur = connection.cursor()
cur.mogrify(
'CREATE USER %s PASSWORD %s', (AsIs('someuser'), AsIs('somepassword'))
... |
Downloading an image, want to save to folder, check if file exists | 3,382,812 | 4 | 2010-08-01T16:39:45Z | 3,382,869 | 8 | 2010-08-01T16:53:21Z | [
"python",
"file-io",
"download"
] | So I have a recordset (sqlalchemy) of products that I am looping, and I want to download an image and save it to a folder.
If the folder doesn't exist, I want to create it.
Also, I want to first check if the image file exists in the folder. **If it does, don't download just skip that row.**
```
/myscript.py
/images/... | I think you can just use `urllib.urlretrieve` here:
```
import errno
import os
import urllib
def require_dir(path):
try:
os.makedirs(path)
except OSError, exc:
if exc.errno != errno.EEXIST:
raise
directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "images")
requir... |
Python daemonize | 3,383,741 | 6 | 2010-08-01T20:59:49Z | 3,383,762 | 8 | 2010-08-01T21:06:22Z | [
"python",
"daemon"
] | I would like to daemonize a python process, and now want to ask if it is good practice to have a daemon running, like a parent process and call another class which opens 10-30 threads.
I'm planning on writing a monitoring script for group of servers and would like to check every server every 5 mins, that each server i... | Maybe you should use <http://pypi.python.org/pypi/python-daemon> |
Learning Python; How can I make this more Pythonic? | 3,384,010 | 4 | 2010-08-01T22:36:48Z | 3,384,160 | 20 | 2010-08-01T23:33:24Z | [
"python"
] | I am a PHP developer exploring the outside world. I have decided to start learning Python.
The below script is my first attempt at porting a PHP script to Python. Its job is to take tweets from a Redis store. The tweets are coming from Twitter's Streaming API and stored as JSON objects. Then the information needed is ... | Instead of:
```
i=0
end=20
last_id=0
data=[]
while(i<=end):
i = i + 1
...
```
code:
```
last_id=0
data=[]
for i in xrange(1, 22):
...
```
Same semantics, more compact and Pythonic.
Instead of
```
if not last or last == None:
```
do just
```
if not last:
```
since `None` is false-ish... |
Why is Python 3.0 (or later) better? | 3,384,361 | 8 | 2010-08-02T00:56:08Z | 3,384,416 | 10 | 2010-08-02T01:10:41Z | [
"python"
] | I learned Python as my first serious (non BASIC) language about 10 years ago. Since then, I have learned lots of others, but I tend to 'think' in Python. When I look at the list of changes I do not see one *I need this* feature. I usually say to myself, hmm that would been a good way of doing it, but why change it now?... | As a key feature, a lot of people seem to be pretty exited about ([supposedly](http://en.wikipedia.org/wiki/Leaky_abstraction)) transparent unicode support. They changed it from `str` (8-bit char array/default string type) and `unicode` (unicode string), to `str` (default (unicode compatable) string) and `bytes` (binar... |
Deriving class from `object` in python | 3,384,374 | 21 | 2010-08-02T01:00:05Z | 3,386,914 | 19 | 2010-08-02T10:35:16Z | [
"python",
"class",
"inheritance"
] | So I'm just learning python (I know plenty of other languages) and I'm confused about something. I think this is due to lack of documentation (at least that I could find). On a few websites, I've read that you should derive your classes from `object`:
```
class Base(object):
pass
```
But I don't see what that doe... | Mostly it isn't going to matter whether or not you inherit from object, but if you don't there are bugs waiting to catch you out when you've forgotten that you decided not to bother.
Some subtle things just won't work properly if you don't ultimately inherit from object:
1. Using properties in classic classes only pa... |
Python 3.2 - GIL - good/bad? | 3,384,385 | 16 | 2010-08-02T01:03:54Z | 3,384,453 | 18 | 2010-08-02T01:21:17Z | [
"python",
"multithreading",
"locking",
"interpreter"
] | Python 3.2 ALPHA [**is out**](http://python.org/download/releases/3.2/).
From the Change Log, it appears the GIL has been entirely rewritten.
A few questions:
1. Is having a GIL good or bad? (and
why).
2. Is the new GIL better? If so, how?
**UPDATE**:
I'm fairly new to Python. So all of this is new to my but I ... | The best explanation I've seen as to why the GIL sucks is here:
<http://www.dabeaz.com/python/GIL.pdf>
And the same guy has a presentation on the new GIL here:
<http://www.dabeaz.com/python/NewGIL.pdf>
If that's all that's been done it still sucks - just not as bad. Multiple threads will behave better. Multi-core w... |
How to wrap a python dict? | 3,385,269 | 7 | 2010-08-02T05:35:49Z | 3,385,299 | 11 | 2010-08-02T05:42:16Z | [
"python",
"dictionary"
] | I want to implement a class that will *wrap* -- not subclass -- the python `dict` object, so that when a change is detected in a backing store I can re-create the delegated dict object. I intend to check for changes in the backing store each time the dict is accessed for a read.
Supposing I was to create an object to ... | You can subclass the [ABC](http://docs.python.org/library/collections.html?highlight=collections#abcs-abstract-base-classes) (abstract base class) `collections.Mapping` (or `collections.MutableMapping` if you also want to allow code using your instances to alter the simulated/wrapped dictionary, e.g. by indexed assignm... |
IDLE processes numerical input in a weird way (python 2.6) | 3,385,646 | 2 | 2010-08-02T07:00:23Z | 3,385,660 | 12 | 2010-08-02T07:03:22Z | [
"python",
"syntax"
] | If you simply type an integer after the `>>>` prompt they give you in the IDLE interpreter, most of the time it'll simply bounce the number back at you.
```
>>> 3
3
>>> 8
8
>>> 10
10
```
Start the nubmer off with a 0 however, and some interesting errors happen.
```
>>> 010
8
>>> 020
16
``` | In Python 2, an integer literal starting with 0 is considered octal, i.e. in base 8. And obviously, 10 oct == 8 dec (or generally, 10 in base b == b base 10). Likewise, 12 oct == 10 dec, and so on. |
List of lists and "Too many values to unpack" | 3,386,107 | 7 | 2010-08-02T08:22:07Z | 3,386,139 | 8 | 2010-08-02T08:27:39Z | [
"python"
] | I'm trying to use the following code on a list of lists to create a new list of lists, whose new elements are a certain combination of elements from the lists inside the old list...if that makes any sense! Here is the code:
```
for index, item in outputList1:
outputList2 = outputList2.append(item[6:].extend(outpu... | You've forgotten to use enumerate, you mean to do this:
```
for index,item in enumerate(outputList1) :
pass
``` |
List of lists and "Too many values to unpack" | 3,386,107 | 7 | 2010-08-02T08:22:07Z | 3,386,141 | 12 | 2010-08-02T08:28:18Z | [
"python"
] | I'm trying to use the following code on a list of lists to create a new list of lists, whose new elements are a certain combination of elements from the lists inside the old list...if that makes any sense! Here is the code:
```
for index, item in outputList1:
outputList2 = outputList2.append(item[6:].extend(outpu... | the `for` statement iterates over an iterable -- in the case of a list, it iterates over the contents, one by one, so in each iteration, one value is available.
When using `for index, item in list:` you are trying to unpack one value into two variables. This would work with `for key, value in dict.items():` which iter... |
Python - How can I fetch emails via POP or IMAP through a proxy? | 3,386,724 | 4 | 2010-08-02T10:06:45Z | 3,387,230 | 7 | 2010-08-02T11:24:10Z | [
"python",
"proxy",
"imap",
"pop"
] | Neither poplib or imaplib seem to offer proxy support and I couldn't find much info about it despite my google-fu attempts.
I'm using python to fetch emails from various imap/pop enabled servers and need to be able to do it through proxies.
Ideally, I'd like to be able to do it in python directly but using a wrapper ... | You don't need to dirtily hack imaplib. You could try using the SocksiPy package, which supports socks4, socks5 and http proxy (connect):
Something like this, obviously you'd want to handle the setproxy options better, via extra arguments to a custom `__init__` method, etc.
```
from imaplib import IMAP4, IMAP4_SSL, I... |
Python csv without header | 3,387,191 | 4 | 2010-08-02T11:16:50Z | 3,387,212 | 13 | 2010-08-02T11:20:50Z | [
"python",
"csv"
] | With header information in csv file, city can be grabbed as:
```
city = row['city']
```
Now how to assume that csv file does not have headers, there is only 1 column, and column is city. | You can still use your line, if you declare the headers yourself, since you know it:
```
with open('data.csv') as f:
cf = csv.DictReader(f, fieldnames=['city'])
for row in cf:
print row['city']
```
For more information check [`csv.DictReader`](http://docs.python.org/library/csv#csv.DictReader) info in... |
Safest way to convert float to integer in python? | 3,387,655 | 119 | 2010-08-02T12:20:20Z | 3,387,715 | 108 | 2010-08-02T12:25:50Z | [
"python",
"math",
"integer",
"python-2.x"
] | Python's math module contain handy functions like `floor` & `ceil`. These functions take a floating point number and return the nearest integer below or above it. However these functions return the answer as a floating point number. For example:
```
import math
f=math.floor(2.3)
```
Now `f` returns:
```
2.0
```
Wha... | All integers that can be represented by floating point numbers have an exact representation. So you can safely use `int` on the result. Inexact representations occur only if you are trying to represent a rational number with a denominator that is not a power of two.
That this works is not trivial at all! It's a proper... |
Safest way to convert float to integer in python? | 3,387,655 | 119 | 2010-08-02T12:20:20Z | 3,387,769 | 34 | 2010-08-02T12:31:09Z | [
"python",
"math",
"integer",
"python-2.x"
] | Python's math module contain handy functions like `floor` & `ceil`. These functions take a floating point number and return the nearest integer below or above it. However these functions return the answer as a floating point number. For example:
```
import math
f=math.floor(2.3)
```
Now `f` returns:
```
2.0
```
Wha... | You could use the round function. If you use no second parameter (# of significant digits) then I think you will get the behavior you want.
IDLE output.
```
>>> round(2.99999999999)
3
>>> round(2.6)
3
>>> round(2.5)
3
>>> round(2.4)
2
``` |
Safest way to convert float to integer in python? | 3,387,655 | 119 | 2010-08-02T12:20:20Z | 14,536,398 | 56 | 2013-01-26T11:16:54Z | [
"python",
"math",
"integer",
"python-2.x"
] | Python's math module contain handy functions like `floor` & `ceil`. These functions take a floating point number and return the nearest integer below or above it. However these functions return the answer as a floating point number. For example:
```
import math
f=math.floor(2.3)
```
Now `f` returns:
```
2.0
```
Wha... | Use `int(your non integer number)` will nail it.
```
print int(2.3) # "2"
print int(math.sqrt(5)) # "2"
``` |
Safest way to convert float to integer in python? | 3,387,655 | 119 | 2010-08-02T12:20:20Z | 14,538,905 | 13 | 2013-01-26T16:24:58Z | [
"python",
"math",
"integer",
"python-2.x"
] | Python's math module contain handy functions like `floor` & `ceil`. These functions take a floating point number and return the nearest integer below or above it. However these functions return the answer as a floating point number. For example:
```
import math
f=math.floor(2.3)
```
Now `f` returns:
```
2.0
```
Wha... | > That this works is not trivial at all! It's a property of the IEEE floating point representation that intâfloor = ââ
â if the magnitude of the numbers in question is small enough, but different representations are possible where int(floor(2.3)) might be 1.
*This post explains why it works in that range*.
In ... |
Safest way to convert float to integer in python? | 3,387,655 | 119 | 2010-08-02T12:20:20Z | 24,342,897 | 23 | 2014-06-21T15:06:18Z | [
"python",
"math",
"integer",
"python-2.x"
] | Python's math module contain handy functions like `floor` & `ceil`. These functions take a floating point number and return the nearest integer below or above it. However these functions return the answer as a floating point number. For example:
```
import math
f=math.floor(2.3)
```
Now `f` returns:
```
2.0
```
Wha... | Combining two of the previous results, we have:
```
int(round(some_float))
```
This converts a float to an integer fairly dependably. |
Python: How to "perfectly" override a dict | 3,387,691 | 110 | 2010-08-02T12:23:28Z | 3,387,975 | 125 | 2010-08-02T13:00:25Z | [
"python",
"inheritance",
"dictionary",
"get",
"set"
] | How can I make as "perfect" a subclass of *dict* as possible? The end goal is
to have a simple *dict* in which the keys are lowercase.
It would seem that should be some tiny set of primitives I can override to make
this work, but all my research and attempts have made it seem like this isn't
the case:
* If I [overrid... | You can write an object that behaves like a dict quite easily with [ABC](http://docs.python.org/library/abc.html)s
(Abstract Base Classes) from the [collections](http://docs.python.org/2/library/collections.html) module. It even tells you
if you missed a method, so below is the minimal version that shuts the ABC up.
`... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.