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 |
|---|---|---|---|---|---|---|---|---|---|
Passing image object as a button background in Kivy | 17,392,202 | 5 | 2013-06-30T15:59:10Z | 17,396,927 | 9 | 2013-07-01T03:07:14Z | [
"python",
"kivy"
] | In Kivy, is there a way to pass image object as a button background, instead of image file name?
`button.background_normal` property accepts only strings. I would like to customize image properties, such as `allow_stretch = False`.
If that succeeds, how can I specify image alignment inside a button, eg. to make it to... | The source is just a property of Button and it is a string as you pointed out. You want a Widget inside a Widget, and that is the basic way Kivy works. So just add the Image as it is. A little bit of positioning would do the rest.
You have to be careful with the positioning. Make sure it is in a visible part and nothi... |
Arrays used as indices must be of integer (or boolean) type | 17,393,989 | 4 | 2013-06-30T19:18:40Z | 24,261,734 | 9 | 2014-06-17T10:42:57Z | [
"python",
"scikit-learn"
] | Errors are like this:
```
Traceback (most recent call last):
File "NearestCentroid.py", line 53, in <module>
clf.fit(X_train.todense(),y_train)
File "/usr/local/lib/python2.7/dist-packages/scikit_learn-0.13.1-py2.7-linux-i686.egg/sklearn/neighbors/nearest_centroid.py", line 115, in fit
variance = np.array(... | I had a similar problem using the Pystruct `pystruct.learners.OneSlackSSVM`.
It occured because my training labels were floats, in stead of integers. In my case, it was because I initialized the labels with np.ones, without specifying dtype=np.int8. Hope it helps. |
How to use raw_input() with while-loop | 17,394,495 | 4 | 2013-06-30T20:20:55Z | 17,394,510 | 7 | 2013-06-30T20:23:17Z | [
"python",
"while-loop",
"raw-input"
] | Just trying to write a program that will take the users input and add it to the list 'numbers':
```
print "Going to test my knowledge here"
print "Enter a number between 1 and 20:"
i = raw_input('>> ')
numbers = []
while 1 <= i <= 20 :
print "Ok adding %d to numbers set: " % i
numbers.append(i)
print "... | `raw_input` returns a string not an integer:
So,
```
>>> 1 <= "4" <= 20
False
```
Use `int()`:
```
i = int(raw_input('>> '))
```
Use just `if`, if you're only taking a single input from user:
```
if 1 <= i <= 20 :
print "Ok adding %d to numbers set: " % i
numbers.append(i)
print "Okay the numbers se... |
Add dimensions to a Numpy Array | 17,394,882 | 10 | 2013-06-30T21:10:55Z | 25,755,697 | 10 | 2014-09-10T00:47:26Z | [
"python",
"arrays",
"opencv",
"numpy"
] | I'm starting off with a numpy array of an image.
```
In[1]:img = cv2.imread('test.jpg')
```
The shape is what you might expect for a 640x480 RGB image.
```
In[2]:img.shape
Out[2]: (480, 640, 3)
```
However, this image that I have is a frame of a video, which is 100 frames long. Ideally, I would like to have a singl... | You're asking how to add a dimension to a NumPy array, so that that dimension can then be grown to accommodate new data. A dimension can be added as follows:
`image = image[..., np.newaxis]`. |
How to access a function inside a function? | 17,395,338 | 7 | 2013-06-30T22:12:29Z | 17,395,350 | 14 | 2013-06-30T22:14:21Z | [
"python",
"function"
] | I am wondering how I can access a function inside another function.
I saw code like this:
```
>>> def make_adder(x):
def adder(y):
return x+y
return adder
>>> a = make_adder(5)
>>> a(10)
15
```
So, is there another way to call the `adder` function? And my second question is why in the last line I ... | You really don't want to go down this rabbit hole, but if you insist, it is possible. With some work.
The nested function is created *anew* for each call to `make_adder()`:
```
>>> import dis
>>> dis.dis(make_adder)
2 0 LOAD_CLOSURE 0 (x)
3 BUILD_TUPLE 1
... |
Python â How can I find the square matrix of a lower triangular numpy matrix? (with a symmetrical upper triangle) | 17,395,367 | 6 | 2013-06-30T22:17:03Z | 17,395,389 | 7 | 2013-06-30T22:20:36Z | [
"python",
"arrays",
"numpy"
] | I generated a lower triangular matrix, and I want to complete the matrix using the values in the lower triangular matrix to form a square matrix, symmetrical around the diagonal zeros.
```
lower_triangle = numpy.array([
[0,0,0,0],
[1,0,0,0],
[2,3,0,0],
[4,5,6,0]])
```
I want to generate the following complete matrix,... | You can simply add it to its transpose:
```
>>> m
array([[0, 0, 0, 0],
[1, 0, 0, 0],
[2, 3, 0, 0],
[4, 5, 6, 0]])
>>> m + m.T
array([[0, 1, 2, 4],
[1, 0, 3, 5],
[2, 3, 0, 6],
[4, 5, 6, 0]])
``` |
How do I change the current line highlight background in Pycharm? | 17,396,314 | 10 | 2013-07-01T01:15:11Z | 17,396,334 | 18 | 2013-07-01T01:19:13Z | [
"python",
"ide",
"pycharm"
] | The question says it all. I need the place to style the current line highlight. | Under settings:
```
IDE Settings
|
Editor
|
Colors & Fonts
|
General
|
Caret Row
``` |
Brew Install Python Fails Due to Link gdbm link issue | 17,396,538 | 4 | 2013-07-01T01:57:30Z | 18,584,847 | 11 | 2013-09-03T05:39:45Z | [
"python",
"homebrew"
] | I am used to macport and recently got a new mac book pro 10.8.4, and I switched `brew` and tried to install python but I am getting following error:
```
brew install python --universal --framework
Error: You must `brew link gdbm' before python can be installed
```
I tried to follow following links to install python u... | I had the same issue., Try to change the ownership of the directory (recursively)
```
sudo chown -R username:admin /usr/local/include
```
In the above command., replace the username with your username.
This should resolve the issue |
index a Python Pandas dataframe with multiple conditions SQL like where statement | 17,396,898 | 7 | 2013-07-01T03:02:26Z | 17,396,984 | 12 | 2013-07-01T03:15:37Z | [
"python",
"sql",
"indexing",
"pandas"
] | I am experienced in R and new to Python Pandas. I am trying to index a DataFrame to retrieve rows that meet a set of several logical conditions - much like the "where" statement of SQL.
I know how to do this in R with dataframes (and with R's data.table package, which is more like a Pandas DataFrame than R's native da... | ```
# subset1: All rows and columns where:
# (fruit in fruitsInclude) AND (Vegetable not in vegetablesExlude)
df.ix[df['Fruit'].isin(fruitsInclude) & ~df['Vegetable'].isin(vegetablesExclude)]
# subset2: All rows and columns where:
# (fruit in fruitsInclude) AND [(Vegetable not in vegetablesExlude) OR (Animal == ... |
Getting the mean of multiple axis of a numpy array | 17,397,231 | 5 | 2013-07-01T03:56:54Z | 17,403,375 | 15 | 2013-07-01T11:27:22Z | [
"python",
"numpy"
] | In numpy is there a fast way of calculating the mean across multiple axis? I am calculating the mean on all but the 0 axis of an n-dimensional array.
I am currently doing this;
```
for i in range(d.ndim - 1):
d = d.mean(axis=1)
```
I'm wondering if there is a solution that doesn't use a python loop. | In numpy 1.7 you can give multiple axis to `np.mean`:
```
d.mean(axis=tuple(range(1, d.ndim)))
```
I am guessing this will perform similarly to the other proposed solutions, unless reshaping the array to flatten all dimensions triggers a copy of the data, in which case this should be much faster. So this is probably ... |
What does it mean when people say CPython is written in C? | 17,400,805 | 2 | 2013-07-01T09:08:20Z | 17,400,825 | 17 | 2013-07-01T09:09:34Z | [
"python",
"c"
] | From what I know, CPython programs are compiled into intermediate bytecode, which is executed by the virtual machine. Then how does one identify without knowing beforehand that CPython is written in C. Isn't there some common DNA for both which can be matched to identify this? | The **interpreter** is written in C.
It compiles Python code into bytecode, and then an evaluation loop interprets that bytecode to run your code.
You identify what Python is written in by looking at it's source code. See the [source for the evaluation loop](http://hg.python.org/cpython/file/5bc3d8d22a93/Python/ceval... |
What does it mean when people say CPython is written in C? | 17,400,805 | 2 | 2013-07-01T09:08:20Z | 17,401,698 | 12 | 2013-07-01T09:58:36Z | [
"python",
"c"
] | From what I know, CPython programs are compiled into intermediate bytecode, which is executed by the virtual machine. Then how does one identify without knowing beforehand that CPython is written in C. Isn't there some common DNA for both which can be matched to identify this? | Python isn't written in C. Arguably, Python is written in an esoteric English dialect using BNF.
However, all the following statements are true:
1. *Python is a language, consisting of a language specification and a bunch of standard modules*
2. Python source code is compiled to a bytecode representation
3. this byte... |
debianzing a python program to get a .deb | 17,401,381 | 7 | 2013-07-01T09:41:34Z | 17,402,676 | 12 | 2013-07-01T10:48:36Z | [
"python",
"apt",
"linuxmint"
] | **aim**
To create an installable `.deb` file(or package). Which when clicked would install the software on a Linux machine and an icon would be put on the GNOME panel. So as to launch this application from there.
**What I have referred to**
I referred to two debianizing guides.
[Guide 1](http://showmedo.com/videotu... | I just tested `stdeb` (see <https://pypi.python.org/pypi/stdeb> ) a Python package for turning any other Python package into a Debian package.
First I installed stdeb:
```
apt-get install python-stdeb
```
Then I made a simple script called `myscript.py` with the following contents:
```
def main():
print "Hello ... |
How to unpack a function-returned tuple? | 17,401,489 | 2 | 2013-07-01T09:47:08Z | 17,401,509 | 7 | 2013-07-01T09:48:15Z | [
"python",
"python-2.7",
"iterable-unpacking"
] | I want to append a table with a list of function-returned values, some of them are tuples:
```
def get_foo_bar():
# do stuff
return 'foo', 'bar'
def get_apple():
# do stuff
return 'apple'
table = list()
table.append([get_foo_bar(), get_apple()])
```
This yields:
```
>>> table
[[('foo', 'bar'), 'app... | Use [`.extend()`](http://docs.python.org/2/tutorial/datastructures.html#more-on-lists):
```
>>> table.extend(get_foo_bar())
>>> table.append(get_apple())
>>> [table]
[['foo', 'bar', 'apple']]
```
Or, you can concatenate tuples:
```
>>> table = []
>>> table.append(get_foo_bar() + (get_apple(),))
>>> table
[('foo', 'b... |
Is it possible in Python to declare that method must be overriden? | 17,402,622 | 2 | 2013-07-01T10:45:27Z | 17,402,642 | 8 | 2013-07-01T10:47:08Z | [
"python",
"oop",
"inheritance",
"methods",
"override"
] | I have an "abstract" class, such as:
```
class A:
def do_some_cool_stuff():
''' To override '''
pass
def do_some_boring_stuff():
return 2 + 2
```
And class B, subclassing A:
```
class B(A):
def do_stuff()
return 4
```
Is there any way to declare, that a method `A.do_some... | Yes, by defining `A` as an [ABC (Abstract Base Class)](http://docs.python.org/2/library/abc.html):
```
from abc import ABCMeta, abstractmethod
class A(object):
__metaclass__ = ABCMeta
@abstractmethod
def do_some_cool_stuff():
''' To override '''
pass
def do_some_boring_stuff():
... |
How can I fix ValueError: Too many values to unpack" in Python? | 17,403,371 | 9 | 2013-07-01T11:27:06Z | 17,403,499 | 8 | 2013-07-01T11:33:16Z | [
"python",
"python-3.x"
] | I am trying to populate a dictionary with the contents of my text file ("out3.txt").
My text file is of the form:
```
vs,14100
mln,11491
the,7973
cts,7757
```
...and so on...
I want my dictionary `answer` to be of the form:
```
answer[vs]=14100
answer[mln]=11491
```
...and so on...
My code is:
```
import os... | You have empty `line`s in your input file and I suspect one of the `line`s that you have not shared with us has too many commas in it (hence "too many values to unpack").
You can protect against this, like so:
```
import collections
answer = collections.defaultdict(list)
with open('out3.txt', 'r+') as istream:
f... |
PYTHON SCRAPY Can't POST information to FORMS, | 17,403,596 | 7 | 2013-07-01T11:38:18Z | 17,412,128 | 10 | 2013-07-01T19:25:09Z | [
"python",
"forms",
"post",
"web-scraping",
"scrapy"
] | I think that I will ask very big favor as i struggling with this problem several days. I tried all possible (in my best knowledge) ways and still no result. I am doing something wrong, but still can't figure out what it is. So thank you every one who are willing enough to go to this adventure.
First things first:
I am ... | Here's a working example of using `Request.from_response` for `delta.com`:
```
from scrapy.item import Item, Field
from scrapy.http import FormRequest
from scrapy.spider import BaseSpider
class DeltaItem(Item):
title = Field()
link = Field()
desc = Field()
class DmozSpider(BaseSpider):
name = "delt... |
Python lists with scandinavic letters | 17,403,826 | 4 | 2013-07-01T11:50:09Z | 17,403,843 | 10 | 2013-07-01T11:51:15Z | [
"python",
"list"
] | Can anyone explain what causes this for better understanding of the environment?
emacs, unix
input:
```
with open("example.txt", "r") as f:
for files in f:
print files
split = files.split()
print split
```
output:
```
Hello world
['Hello', 'world']
Hello wörld
['Hello', 'w\xf6rld']
``` | Python is printing the string representation, which includes a non-printable byte. Non-printable bytes (anything outside the ASCII range or a control character) is displayed as an escape sequence.
The point is that you can copy that representation and paste it into Python code or into the interpreter, producing the ex... |
Jinja has a "center" formatting option, but how about "right align"? | 17,404,527 | 5 | 2013-07-01T12:28:50Z | 17,404,620 | 10 | 2013-07-01T12:35:09Z | [
"python",
"jinja2"
] | Say I have
```
{% for key,value in adict %}
{{key}}:{{value}}
{% endfor %}
```
How do I ensure that all of the keys are padded such that the output is
```
something: 1
someotherthing: 3
thelastthing: 2
```
edit: This is **not** a webpage I am working on, I am just getting string output for printing. | `{{ key.rjust(20) }}:{{value}}` did the trick
I did not know you could just call python string commands from the box. If someone has a more "jinja" solution, using pipes, I will give the answer to that. |
(Python) How to XOR two hex strings so that each byte is XORed separately? | 17,404,690 | 7 | 2013-07-01T12:38:59Z | 17,404,827 | 9 | 2013-07-01T12:46:20Z | [
"python",
"string",
"hex",
"encode",
"xor"
] | I have been posting similar questions here for a couple of days now, but it seems like I was not asking the right thing, so excuse me if I have exhausted you with my XOR questions :D.
To the point - I have two hex strings and I want to XOR these strings such that each byte is XORed separately (i.e. each pair of number... | Use [`binascii.unhexlify()`](http://docs.python.org/2/library/binascii.html#binascii.unhexlify) to turn your hex strings to binary data, then XOR that, going back to hex with [`binascii.hexlify()`](http://docs.python.org/2/library/binascii.html#binascii.hexlify):
```
>>> from binascii import unhexlify, hexlify
>>> s1 ... |
How can I use relative path to read local files in Django app? | 17,406,126 | 4 | 2013-07-01T13:51:45Z | 17,407,140 | 9 | 2013-07-01T14:39:40Z | [
"python",
"django",
"relative-path"
] | My django app has to read some text files from the file system. So I make a directory in my app directery, and use relative path to open and read from the file.
```
areas = parseXmlFile('xml_files/area.xml')
```
When I run server to debug using `manage.py runserver`, that's ok. But I run server using `manage.py runfc... | I'll suggest you to use `absolute path` but in a more clever way. Declare in your `settings.py` something like `XMLFILES_FOLDER` and have your `settings.py` like this:
```
import os
settings_dir = os.path.dirname(__file__)
PROJECT_ROOT = os.path.abspath(os.path.dirname(settings_dir))
XMLFILES_FOLDER = os.path.join(PRO... |
Is there a more efficient way to convert this phone number to plain text? | 17,407,303 | 2 | 2013-07-01T14:48:05Z | 17,407,333 | 10 | 2013-07-01T14:49:38Z | [
"python"
] | I want to convert a phone number with parentheses and a hyphen between the sixth and seventh digit to 10 numbers with no formatting. This code does the trick, but it's unwieldy and I was wondering whether there's a more efficient method?
Thanks!
```
phone_number = "(251) 342-7344"
phone_number=phone_number.replace("... | You can use `str.translate`:
```
>>> from string import punctuation,whitespace
>>> strs = "(251) 342-7344"
>>> strs.translate(None, punctuation+whitespace)
'2513427344'
```
Using `str.isdigit` and `str.join`:
```
>>> "".join([x for x in strs if x.isdigit()])
'2513427344'
```
**Timing comparisons**:
```
>>> strs = ... |
Recursive function (factorial) breaks Clojure with IntOverflow but not Python | 17,408,537 | 2 | 2013-07-01T15:47:04Z | 17,408,925 | 7 | 2013-07-01T16:06:22Z | [
"python",
"clojure"
] | I define a recursive function in the same way in both Clojure and Python:
```
;;;Clojure:
(defn factorial [n]
(if (< n 1)
1
(* n (factorial (- n 1)))))
#Python:
def factorial(n):
if n<1:
return 1
else:
return n*factorial(n-1)
```
In Python if I run factorial(200) I get:
```
78865786736... | By default, Clojure uses JVM Longs to represent integers, so the range is from -2^63 to 2^(63-1).
In order to use arbitrary precision in Clojure, you can use the `+'`, `*'`, `-'`, `inc'`, and `dec'` versions of the given operators. |
Obtaining data from PubMed using python | 17,409,107 | 5 | 2013-07-01T16:17:27Z | 20,149,984 | 13 | 2013-11-22T16:39:54Z | [
"python",
"text-mining"
] | I have a list of PubMed entries along with the PubMed ID's. I would like to create a python script or use python which accepts a PubMed id number as an input and then fetches the abstract from the PubMed website.
So far I have come across NCBI Eutilities and the importurl library in Python but I don't know how I shoul... | Using [Biopython](http://biopython.org)'s module called [Entrez](http://biopython.org/DIST/docs/api/Bio.Entrez-module.html), you can get the abstract along with all other metadata quite easily. This will print the abstract:
```
from Bio.Entrez import efetch
def print_abstract(pmid):
handle = efetch(db='pubmed', i... |
Error no module named curses | 17,410,116 | 5 | 2013-07-01T17:20:34Z | 18,163,513 | 7 | 2013-08-10T15:44:23Z | [
"python",
"windows",
"python-2.7",
"telnet",
"curses"
] | When I try to run the following code...
```
from telnetsrvlib import *
if __name__ == '__main__':
"Testing - Accept a single connection"
class TNS(SocketServer.TCPServer):
allow_reuse_address = True
class TNH(TelnetHandler):
def cmdECHO(self, params):
""" [<arg> ...]
Echo parameters
E... | You could also look into installing the curses module from here:
<http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses>.
It allows python's native curses to be used on Windows, so all your standard python curses code can be used. |
Matplotlib scatter plot legend | 17,411,940 | 20 | 2013-07-01T19:12:15Z | 17,412,294 | 55 | 2013-07-01T19:35:25Z | [
"python",
"matplotlib",
"legend",
"scatter-plot"
] | I created a 4D scatter plot graph to represent different temperatures in a specific area. When I create the legend, the legend shows the correct symbol and color but adds a line through it. The code I'm using is:
```
colors=['b', 'c', 'y', 'm', 'r']
lo = plt.Line2D(range(10), range(10), marker='x', color=colors[0])
ll... | # 2D scatter plot
Using the `scatter` method of the `matplotlib.pyplot` module should work (at least with matplotlib 1.2.1 with Python 2.7.5), as in the example code below. Also, if you are using scatter plots, use `scatterpoints=1` rather than `numpoints=1` in the legend call to have only one point for each legend en... |
printing stdout in realtime from a subprocess that requires stdin | 17,411,966 | 11 | 2013-07-01T19:14:03Z | 17,413,045 | 17 | 2013-07-01T20:25:42Z | [
"python",
"subprocess"
] | This is a follow up to [this question](http://stackoverflow.com/questions/17395243/printing-stdout-in-realtime-from-subprocess), but if I want to pass an argument to `stdin` to `subprocess`, how can I get the output in real time? This is what I currently have; I also tried replacing `Popen` with `call` from the `subpro... | In order to grab stdout from the subprocess in real time you need to decide exactly what behavior you want; specifically, you need to decide whether you want to deal with the output line-by-line or character-by-character, and whether you want to block while waiting for output or be able to do something else while waiti... |
How to split data into trainset and testset randomly? | 17,412,439 | 10 | 2013-07-01T19:44:33Z | 17,413,351 | 27 | 2013-07-01T20:44:15Z | [
"python",
"file-io"
] | I have a large dataset and want to split it into training(50%) and testing set(50%).
Say I have 100 examples stored the input file, each line contains one example. I need to choose 50 lines as training set and 50 lines testing set.
My idea is first generate a random list with length 100 (values range from 1 to 100), ... | This can be done similarly in Python using lists, (note that the whole list is shuffled in place).
```
import random
with open("datafile.txt", "rb") as f:
data = f.read().split('\n')
random.shuffle(data)
train_data = data[:50]
test_data = data[50:]
``` |
Learn Python the Hard Way Exercise 43 | 17,414,219 | 2 | 2013-07-01T21:44:24Z | 17,414,418 | 7 | 2013-07-01T22:02:53Z | [
"python"
] | I do not understand how the script gets the next room, and generally how the "Engine" and "Map" classes work. Here's an excerpt:
```
Class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge': TheBridge(),
'escape_p... | The `Map` object is a Class which maps your scenes. It has some scenes saved in an array.
```
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge': TheBridge(),
'escape_pod': EscapePod(),
'death': Death()
}
```
When an object of Map is made you... |
multipart data POST using python requests: no multipart boundary was found | 17,415,084 | 16 | 2013-07-01T23:10:49Z | 17,438,575 | 28 | 2013-07-03T02:02:12Z | [
"python",
"multipartform-data",
"python-requests"
] | I have a form-data as well as file to be sent in the same POST. For ex, {duration: 2000, file: test.wav}. I saw the many threads here on multipart/form-data posting using python requests. They were useful, especially [this one](http://stackoverflow.com/questions/12592553/python-requests-multipart-http-post?rq=1).
My s... | You should NEVER set that header yourself. We set the header properly with the boundary. If you set that header, we won't and your server won't know what boundary to expect (since it is added to the header). Remove your custom Content-Type header and you'll be fine. |
What is Python's equivalent of Java's standard for-loop? | 17,415,198 | 7 | 2013-07-01T23:24:11Z | 17,415,221 | 15 | 2013-07-01T23:26:34Z | [
"java",
"python",
"loops",
"for-loop",
"translate"
] | I'm writing a simple algorithm to check the primality of an integer and I'm having a problem translating this Java code into Python:
```
for (int i = 3; i < Math.sqrt(n); i += 2) {
if (n % i == 0)
return false;
}
```
So, I've been trying to use this, but I'm obviously skipping the division by 3:
```
i = ... | The only `for`-loop in Python is technically a "for-each", so you can use something like
```
for i in xrange(3, int(math.sqrt(n)), 2): # use 'range' in Python 3
if n % i == 0:
return False
```
Of course, Python can do better than that:
```
all(n % i for i in xrange(3, int(math.sqrt(n)), 2))
```
would b... |
Hardware interrupt for synchronous data acquisition | 17,415,354 | 6 | 2013-07-01T23:43:45Z | 17,416,449 | 7 | 2013-07-02T02:21:47Z | [
"python",
"linux",
"hardware-interface"
] | I am looking for a simple means of triggering my data acquisition software using an external TTL pulse. I need to sample data from multiple sources synchronously with a 5 Hz reference clock. The acquisition does not need real-time priority but I want to ensure that my software is triggered as soon as possible and exact... | Rather than use the parallel port, have you considered using a serial device? Since you have a TTL signal, you'll possibly need a level converter to convert TTL to RS232 +/- 12V levels. Once you're using a serial device, you can use the standard serial `ioctl()` calls to detect a change in control signal status.
Speci... |
My primality test ignores a condition. What am I doing wrong? | 17,415,495 | 3 | 2013-07-02T00:04:22Z | 17,415,511 | 11 | 2013-07-02T00:07:02Z | [
"python",
"loops"
] | As a newbie python enthusiast, I find this very annoying:
```
def isPrime(x):
if x < 0: raise Exception("The number is negative.")
if x == 0 or x == 1: return False
if x == 2: return True
else:
if x % 2 == 0: return False
for i in xrange (3, int(math.sqrt(x)), 2): #-------> This doesn't... | You want `xrange (3, int(math.sqrt(x)) + 1, 2)` - remember that `xrange` iterates through all values from its start point, inclusive, to its stop point, exclusive.
More concretely, when `x` is 9, you have `xrange (3, 3, 2)` which does not iterate over anything. |
pip cannot install anything | 17,416,938 | 24 | 2013-07-02T03:27:48Z | 22,828,906 | 14 | 2014-04-03T05:52:06Z | [
"python",
"pip"
] | ```
> pip install yolk
Downloading/unpacking yolk
Cannot fetch index base URL https://pypi.python.org/simple/
Could not find any downloads that satisfy the requirement yolk
No distributions at all found for yolk
Storing complete log in /Users/harith/.pip/pip.log
```
when I read the file I see
```
> cat /Users/har... | This is the full text of the blog post linked below:
If you've tried installing a package with pip recently, you may have encountered this error:
```
Could not fetch URL https://pypi.python.org/simple/Django/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1... |
pip cannot install anything | 17,416,938 | 24 | 2013-07-02T03:27:48Z | 25,711,340 | 12 | 2014-09-07T14:37:46Z | [
"python",
"pip"
] | ```
> pip install yolk
Downloading/unpacking yolk
Cannot fetch index base URL https://pypi.python.org/simple/
Could not find any downloads that satisfy the requirement yolk
No distributions at all found for yolk
Storing complete log in /Users/harith/.pip/pip.log
```
when I read the file I see
```
> cat /Users/har... | I used to use the `easy_install pip==1.2.1` workaround but I randomly [found](https://stackoverflow.com/questions/25662073/python-django-cannot-use-imagefield-because-pillow-is-not-installed) that if you're having this bug, you probably installed a 32bit version of python.
In short : If you install a 64bit version of ... |
Python Requests encoding POST data | 17,417,620 | 10 | 2013-07-02T04:50:51Z | 17,419,188 | 9 | 2013-07-02T06:50:49Z | [
"python",
"python-2.7",
"python-requests"
] | Version: Python 2.7.3
Other libraries: Python-Requests 1.2.3, jinja2 (2.6)
I have a script that submits data to a forum and the problem is that non-ascii characters appear as garbage. For instance a name like André Téchiné comes out as André Téchiné.
Here's how the data is submitted:
1) Data is initiall... | Your client behaves as it should e.g. running `nc -l 8888` as a server and making a request:
```
import requests
requests.post('http://localhost:8888', data={u'post': u'Andr\xe9 T\xe9chin\xe9'})
```
shows:
```
POST / HTTP/1.1
Host: localhost:8888
Content-Length: 33
Content-Type: application/x-www-form-urlencoded
Ac... |
Elegant way to perform tuple arithmetic | 17,418,108 | 20 | 2013-07-02T05:39:08Z | 17,418,125 | 13 | 2013-07-02T05:41:05Z | [
"python",
"python-2.7",
"numpy",
"tuples"
] | What is the most elegant and concise way (without creating my own class with operator overloading) to perform tuple arithmetic in Python 2.7?
Lets say I have two tuples:
```
a = (10, 10)
b = (4, 4)
```
My intended result is
```
c = a - b = (6, 6)
```
I currently use:
```
c = (a[0] - b[0], a[1] - b[1])
```
I also... | Use `zip` and a generator expression:
```
c = tuple(x-y for x, y in zip(a, b))
```
**Demo:**
```
>>> a = (10, 10)
>>> b = (4, 4)
>>> c = tuple(x-y for x, y in zip(a, b))
>>> c
(6, 6)
```
Use [`itertools.izip`](http://docs.python.org/2/library/itertools.html#itertools.izip) for a memory efficient solution.
help on ... |
Elegant way to perform tuple arithmetic | 17,418,108 | 20 | 2013-07-02T05:39:08Z | 17,418,173 | 21 | 2013-07-02T05:44:18Z | [
"python",
"python-2.7",
"numpy",
"tuples"
] | What is the most elegant and concise way (without creating my own class with operator overloading) to perform tuple arithmetic in Python 2.7?
Lets say I have two tuples:
```
a = (10, 10)
b = (4, 4)
```
My intended result is
```
c = a - b = (6, 6)
```
I currently use:
```
c = (a[0] - b[0], a[1] - b[1])
```
I also... | One option would be,
```
>>> from operator import sub
>>> c = tuple(map(sub, a, b))
>>> c
(6, 6)
```
And [`itertools.imap`](http://docs.python.org/2/library/itertools.html#itertools.imap) can serve as a replacement for `map`.
Of course you can also use other functions from [`operator`](http://docs.python.org/2/libra... |
Elegant way to perform tuple arithmetic | 17,418,108 | 20 | 2013-07-02T05:39:08Z | 17,418,273 | 18 | 2013-07-02T05:52:43Z | [
"python",
"python-2.7",
"numpy",
"tuples"
] | What is the most elegant and concise way (without creating my own class with operator overloading) to perform tuple arithmetic in Python 2.7?
Lets say I have two tuples:
```
a = (10, 10)
b = (4, 4)
```
My intended result is
```
c = a - b = (6, 6)
```
I currently use:
```
c = (a[0] - b[0], a[1] - b[1])
```
I also... | If you're looking for fast, you can use numpy:
```
>>> import numpy
>>> numpy.subtract((10, 10), (4, 4))
array([6, 6])
```
and if you want to keep it in a tuple:
```
>>> tuple(numpy.subtract((10, 10), (4, 4)))
(6, 6)
``` |
Understanding Python Unicode and Linux terminal | 17,419,126 | 6 | 2013-07-02T06:47:42Z | 17,419,466 | 13 | 2013-07-02T07:06:58Z | [
"python",
"linux",
"unicode",
"cjk"
] | I have a Python script that writes some strings with UTF-8 encoding. In my script I am using mainly the `str()` function to cast to string. It looks like that:
```
mystring="this is unicode string:"+japanesevalues[1]
#japanesevalues is a list of unicode values, I am sure it is unicode
print mystring
```
I don't use ... | The terminal has a character set, and Python knows what that character set is, so it will automatically decode your Unicode strings to the byte-encoding that the terminal uses, in your case UTF-8.
But when you redirect, you are no longer using the terminal. You are now just using a Unix pipe. That Unix pipe doesn't ha... |
OpenCV: solvePnP tvec units and axes directions | 17,423,302 | 4 | 2013-07-02T10:32:50Z | 17,428,649 | 7 | 2013-07-02T14:45:56Z | [
"python",
"opencv",
"coordinate-systems",
"camera-calibration"
] | I'm trying to find the relative position of the camera to the chessboard (or the other way around) - I feel OK with converting between different coordinate systems, e.g. as suggested [here](http://stackoverflow.com/questions/14444433/calculate-camera-world-position-with-opencv-python?rq=1). I decided to use chessboard ... | The camera coordinates are the same as image coordinates. So You have x axe pointing in the right side from the camera, y axe is pointing down, and z is pointing in the direction caera is faced. This is a clockwise axe system, and the same would apply to the chessboard, so if You specified the origin in, lets say, uppe... |
Implementing pyqtgraph multiprocessing into a pyqt widget | 17,424,009 | 2 | 2013-07-02T11:09:56Z | 17,426,223 | 8 | 2013-07-02T12:55:40Z | [
"python",
"multithreading",
"matplotlib",
"multiprocessing",
"pyqtgraph"
] | I am trying to plot images on a GUI that I am designing in Python. The full program will be collecting image data from a camera and then displaying the images on the GUI. I have explored using matplotlib, but it was too slow for my application. I need the plot to update rather quickly (preferably as fast as I can acqui... | There are three general approaches to keeping your GUI responsive while doing work in the background:
1. **Timers** -- Everything operates within the GUI thread and your work is done by having a timer
call some function in between GUI updates. This is the simplest and most common approach and is
very likely to b... |
Extracting all rows from pandas Dataframe that have certain value in a specific column | 17,424,182 | 4 | 2013-07-02T11:17:57Z | 17,424,855 | 9 | 2013-07-02T11:50:22Z | [
"python",
"pandas",
"dataframe"
] | I am relatively new to Python/Pandas and am struggling with extracting the correct data from a pd.Dataframe. What I actually have is a Dataframe with 3 columns:
```
data =
Position Letter Value
1 a TRUE
2 f FALSE
3 c TRUE
4 d TRUE
5 k FALSE
```
What I want ... | You can test which Values are True:
```
In [11]: data['Value'] == True
Out[11]:
0 True
1 False
2 True
3 True
4 False
Name: Value, dtype: bool
```
and then use fancy indexing to pull out those rows:
```
In [12]: data[data['Value'] == True]
Out[12]:
Position Letter Value
0 1 a True
2... |
ImportError: No module named ' ' while Import class in the __init__.py file Python | 17,424,348 | 3 | 2013-07-02T11:26:18Z | 17,424,443 | 10 | 2013-07-02T11:30:19Z | [
"python",
"import"
] | I am new to python programming . I have create package called kitchen. i want import a class file through `__init__.py` file.
I am python version : 3.3.2
OS platform : windows
Fridge.py
```
class Fridge:
def __init__(self, items={}):
"""Optionally pass in an initial dictionary of items"""
if ... | You are using Python 3. Do
```
from .Courses import Courses
from .Fridge import Fridge
```
Python 2 would look for `Courses` module in the same dir, but Python 3 looks for `Courses` module in site packages - and, obviously, it's not there.
P.S. "Phython" - sounds interesting ;) |
How to inherit from Python None | 17,424,516 | 6 | 2013-07-02T11:34:29Z | 17,424,702 | 13 | 2013-07-02T11:42:58Z | [
"python"
] | I would like to create a class that inherites from `None`.
Tried this:
```
class InvalidKeyNone(None):
pass
```
but that gives me:
```
TypeError: Error when calling the metaclass bases
cannot create 'NoneType' instances
```
What would be the correct solution that gives me a type that behaves exactly like `... | `None` is a [constant](http://docs.python.org/2/library/constants.html), the sole value of [`types.NoneType`](http://docs.python.org/2/library/types.html#types.NoneType)
Anyway, when you try to inherit from `types.NoneType`
```
from types import NoneType
class InvalidKeyNone(NoneType):
pass
foo = InvalidKeyNone... |
How to inherit from Python None | 17,424,516 | 6 | 2013-07-02T11:34:29Z | 17,424,777 | 9 | 2013-07-02T11:46:51Z | [
"python"
] | I would like to create a class that inherites from `None`.
Tried this:
```
class InvalidKeyNone(None):
pass
```
but that gives me:
```
TypeError: Error when calling the metaclass bases
cannot create 'NoneType' instances
```
What would be the correct solution that gives me a type that behaves exactly like `... | Subclassing None does not make sense, since it is a singleton and There Can Be Only One. You say you want a class with the same behaviour, but None does not have any behaviour!
If what you really want is a unique placeholder that you can return from a function to indicate a special case then simplest way to do this is... |
What is the most efficient way to create a dictionary of two pandas Dataframe columns? | 17,426,292 | 10 | 2013-07-02T12:58:45Z | 17,426,500 | 18 | 2013-07-02T13:08:23Z | [
"python",
"dictionary",
"pandas",
"dataframe"
] | What is the most efficient way to organise the following pandas Dataframe:
data =
```
Position Letter
1 a
2 b
3 c
4 d
5 e
```
into a dictionary like `alphabet[1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e']`? | ```
In [9]: Series(df.Letter.values,index=df.Position).to_dict()
Out[9]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
```
Speed comparion (using Wouter's method)
```
In [6]: df = DataFrame(randint(0,10,10000).reshape(5000,2),columns=list('AB'))
In [7]: %timeit dict(zip(df.A,df.B))
1000 loops, best of 3: 1.27 ms per loop... |
How to transform a tuple to a string of values without comma and parentheses | 17,426,386 | 11 | 2013-07-02T13:02:52Z | 17,426,417 | 28 | 2013-07-02T13:04:20Z | [
"python"
] | I retrieved data from a sql query by using
```
bounds = cursor.fetchone()
```
And I get a tuple like:
```
(34.2424, -64.2344, 76.3534, 45.2344)
```
And I would like to have a string like `34.2424 -64.2344 76.3534 45.2344`
Does a function exist that can do that? | Use [`str.join()`](http://docs.python.org/2/library/stdtypes.html#str.join):
```
>>> mystring = ' '.join(map(str, (34.2424, -64.2344, 76.3534, 45.2344)))
>>> print mystring
34.2424 -64.2344 76.3534 45.2344
```
You'll have to use map here (which converts all the items in the tuple to strings) because otherwise you wil... |
word frequency in python not working | 17,426,634 | 4 | 2013-07-02T13:14:47Z | 17,426,673 | 8 | 2013-07-02T13:17:03Z | [
"python",
"dictionary"
] | I am trying to count frequencies of words in a text file using python.
I am using the following code:
```
openfile=open("total data", "r")
linecount=0
for line in openfile:
if line.strip():
linecount+=1
count={}
while linecount>0:
line=openfile.readline().split()
for word in line:
if wo... | This loop `for line in openfile:` moves the file pointer at the end of the file.
So, if you want to read the data again then either move the pointer(`openfile.seek(0)`) to the start of the file or re-open the file.
To get the word frequency better use `Collections.Counter`:
```
from collections import Counter
with op... |
Getting a "too many values to unpack" value error | 17,427,548 | 4 | 2013-07-02T13:56:56Z | 17,427,589 | 14 | 2013-07-02T13:58:58Z | [
"python"
] | **I've looked at other answers but it looks like they use 2 different values.**
The code:
```
user = ['X', 'Y', 'Z']
info = [['a','b','c',], ['d','e','f'], ['g','h','i']]
for u, g in user, range(len(user)):
print '|',u,'|',info[g][0],'|',info[g][1],'|',info[g][2],'| \n'
```
So basically, it needs to output:
``... | ```
for u,g in user, range(len(user)):
```
is actually equivalent to:
```
for u,g in (user, range(len(user))):
```
i.e a tuple. It first returns the `user` list and then `range`. As the number of items present in `user` are `3` and on LHS you've just two variable (`u`,`b`), so you're going to get that error.
```
... |
Python: Differentiating between row and column vectors | 17,428,621 | 12 | 2013-07-02T14:44:29Z | 17,428,859 | 22 | 2013-07-02T14:55:28Z | [
"python",
"arrays",
"numpy",
"vector",
"scipy"
] | Is there a good way of differentiating between row and column vectors in python? So far I'm using numpy and scipy and what I see so far is that If I was to give one a vector, say
```
from numpy import *
Vector = array([1,2,3])
```
they wouldn't be able to say weather I mean a row or a column vector. Moreover:
```
ar... | You can make the distinction explicit by adding another dimension to the array.
```
>>> a = np.array([1, 2, 3])
>>> a
array([1, 2, 3])
>>> a.transpose()
array([1, 2, 3])
>>> a.dot(a.transpose())
14
```
Now force it to be a column vector:
```
>>> a.shape = (3,1)
>>> a
array([[1],
[2],
[3]])
>>> a.transp... |
constructing absolute path with os.path.join() | 17,429,044 | 11 | 2013-07-02T15:02:25Z | 28,080,468 | 15 | 2015-01-22T02:41:14Z | [
"python",
"path",
"absolute-path"
] | I'd like to construct an absolute path in python, while at the same time staying fairly oblivious of things like path-separator.
**edit0:** for instance there is a directory on the root of my filesystem `/etc/init.d` (or `C:\etc\init.d` on w32), and I want to construct this only from the elements `etc` and `init.d` (o... | Using `os.sep` as root worked for me:
```
path.join(os.sep, 'python', 'bin')
```
Linux: `/python/bin`
Windows: `\python\bin`
Adding `path.abspath()` to the mix will give you drive letters on Windows as well and is still compatible with Linux:
```
path.abspath(path.join(os.sep, 'python', 'bin'))
```
Linux: `/pytho... |
Django url pattern regex to pass a email as a parameter in the url | 17,429,088 | 3 | 2013-07-02T15:04:24Z | 17,429,576 | 8 | 2013-07-02T15:27:20Z | [
"python",
"regex",
"django"
] | I am writing a view which is accepting a email as parameter passed by url like
```
url(r'^admin/detail_consultant_service/((?P<consultant_id>\[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}))/$',
'admin_tool.views.consultant_service_detail', name="consultant_service_detail"),
```
And here is the content of my temp... | You are passing a positional argument instead of a keyword argument. The following should work:
```
{% url consultant_service_detail consultant_id=consultant.id %}
```
Also if you are using Django>=1.5 you should use the `url` as follows:
```
{% url 'consultant_service_detail' consultant_id=consultant.id %}
```
And... |
How to join two sets in one line without using "|" | 17,429,123 | 40 | 2013-07-02T15:05:51Z | 17,429,279 | 8 | 2013-07-02T15:12:46Z | [
"python",
"set"
] | Assume that `S` and `T` are assigned sets. Without using the join operator `|`, how can I find the union of the two sets? This, for example, finds the intersection:
```
S = {1, 2, 3, 4}
T = {3, 4, 5, 6}
S_intersect_T = { i for i in S if i in T }
```
So how can I find the union of two sets in one line without using `|... | Assuming you also can't use `s.union(t)`, which is equivalent to `s | t`, you could try
```
>>> from itertools import chain
>>> set(chain(s,t))
set([1, 2, 3, 4, 5, 6])
```
Or, if you want a comprehension,
```
>>> {i for j in (s,t) for i in j}
set([1, 2, 3, 4, 5, 6])
``` |
How to join two sets in one line without using "|" | 17,429,123 | 40 | 2013-07-02T15:05:51Z | 17,429,304 | 7 | 2013-07-02T15:13:38Z | [
"python",
"set"
] | Assume that `S` and `T` are assigned sets. Without using the join operator `|`, how can I find the union of the two sets? This, for example, finds the intersection:
```
S = {1, 2, 3, 4}
T = {3, 4, 5, 6}
S_intersect_T = { i for i in S if i in T }
```
So how can I find the union of two sets in one line without using `|... | If by join you mean union, try this:
```
set(list(s) + list(t))
```
It's a bit of a hack, but I can't think of a better one liner to do it. |
How to join two sets in one line without using "|" | 17,429,123 | 40 | 2013-07-02T15:05:51Z | 17,430,228 | 82 | 2013-07-02T15:57:03Z | [
"python",
"set"
] | Assume that `S` and `T` are assigned sets. Without using the join operator `|`, how can I find the union of the two sets? This, for example, finds the intersection:
```
S = {1, 2, 3, 4}
T = {3, 4, 5, 6}
S_intersect_T = { i for i in S if i in T }
```
So how can I find the union of two sets in one line without using `|... | You can use a method for sets: `set.union(other_set)`
Note that it returns a new set i.e it do not modify itself. |
How to join two sets in one line without using "|" | 17,429,123 | 40 | 2013-07-02T15:05:51Z | 19,027,490 | 13 | 2013-09-26T11:51:35Z | [
"python",
"set"
] | Assume that `S` and `T` are assigned sets. Without using the join operator `|`, how can I find the union of the two sets? This, for example, finds the intersection:
```
S = {1, 2, 3, 4}
T = {3, 4, 5, 6}
S_intersect_T = { i for i in S if i in T }
```
So how can I find the union of two sets in one line without using `|... | You could use `or_` alias:
```
>>> from operator import or_
>>> reduce(or_, [{1, 2, 3, 4}, {3, 4, 5, 6}])
set([1, 2, 3, 4, 5, 6])
``` |
How to join two sets in one line without using "|" | 17,429,123 | 40 | 2013-07-02T15:05:51Z | 28,200,936 | 47 | 2015-01-28T19:39:47Z | [
"python",
"set"
] | Assume that `S` and `T` are assigned sets. Without using the join operator `|`, how can I find the union of the two sets? This, for example, finds the intersection:
```
S = {1, 2, 3, 4}
T = {3, 4, 5, 6}
S_intersect_T = { i for i in S if i in T }
```
So how can I find the union of two sets in one line without using `|... | Sorry, why can't we use the join operator again?
```
>>> set([1,2,3]) | set([4,5,6])
set([1, 2, 3, 4, 5, 6])
``` |
Idiomatic python - property or method? | 17,429,159 | 14 | 2013-07-02T15:07:42Z | 17,429,395 | 9 | 2013-07-02T15:17:15Z | [
"python",
"django"
] | I have a django model class that maintains state as a simple property. I have added a couple of helper properties to the class to access aggregate states - e.g. `is_live` returns false if the state is any one of `['closed', 'expired', 'deleted']` etc.
As a result of this my model has a collection of is\_ properties, t... | It is okay to do that, especially if you will use the following pattern:
```
class SomeClass(models.Model):
@property
def is_complete(self):
if not hasattr(self, '_is_complete'):
related_objects = self.do_complicated_database_lookup()
self._is_complete = len(related_objects) == ... |
In praw, I'm trying to print the comment body, but what if I encounter an empty comment? | 17,430,409 | 6 | 2013-07-02T16:06:15Z | 17,431,054 | 12 | 2013-07-02T16:37:47Z | [
"python",
"reddit"
] | I am trying to print all the comments from the top posts of a subreddit so that my bot can analyse them. I had it running earlier in the day, but I tried running it now and I have come across an error.
Here is my code:
```
r = praw.Reddit('Comment crawler v1.0 by /u/...')
r.login('username', 'password')
subreddit=r.g... | It usually helps to add the stacktrace so people can see the actual error. However, as the PRAW maintainer, I know the error is something like `MoreComments type has no attribute body`.
There are three simple ways to handle your problem. The first is to simply wrap the `if "Cricketbot"` statement in a try/except and i... |
Matplotlib: Scatter Plot to Foreground on top of a Contour Plot | 17,431,441 | 9 | 2013-07-02T16:56:33Z | 17,432,641 | 10 | 2013-07-02T18:01:59Z | [
"python",
"matplotlib",
"scatter-plot",
"scatter"
] | Does anyone know a way to bring a scatter plot to the foreground in matplotlib? I have to display the scatter plotting on top of the contour, but by default it is plotted underneath...
Thanks in advance! | You can manually choose in which order the different plots are to be displayed with the [`zorder`](http://matplotlib.org/api/artist_api.html#matplotlib.artist.Artist.set_zorder) parameter of e.g. the `scatter` method.
To demonstrate, see the code below, where the scatter plot in the left subplot has `zorder=1` and in ... |
Get All Follower IDs in Twitter by Tweepy | 17,431,807 | 14 | 2013-07-02T17:15:58Z | 17,490,816 | 22 | 2013-07-05T14:05:33Z | [
"python",
"twitter",
"tweepy"
] | Is it possible to get the full follower list of an account who has more than one million followers, like McDonald's?
I use Tweepy and follow the code:
```
c = tweepy.Cursor(api.followers_ids, id = 'McDonalds')
ids = []
for page in c.pages():
ids.append(page)
```
I also try this:
```
for id in c.items():
id... | In order to avoid rate limit, you can/should wait before the next follower page request. Looks hacky, but works:
```
import time
import tweepy
auth = tweepy.OAuthHandler(..., ...)
auth.set_access_token(..., ...)
api = tweepy.API(auth)
ids = []
for page in tweepy.Cursor(api.followers_ids, screen_name="McDonalds").pa... |
Elegantly Assign Variables of Unknown Length | 17,433,668 | 4 | 2013-07-02T18:59:57Z | 17,433,727 | 7 | 2013-07-02T19:03:22Z | [
"python"
] | (Sorry. The title's pretty unclear. I couldn't come up with a good one.)
Say I have a url like so (it's root-relative):
```
"/forums/support/windows/help_i_deleted_sys32/6/"
```
and I'm trying to split this into a class structure like this:
```
class Forum_Spot:
def __init__(self, url):
parts = url.stri... | Use sequence unpacking:
```
>>> strs = "/forums/support/"
>>> spl =strs.strip('/').split('/')
>>> a,b,c,d,e = spl + [None]*(5-len(spl))
>>> a,b,c,d,e
('forums', 'support', None, None, None)
>>> strs = "/forums/support/windows/"
>>> spl =strs.strip('/').split('/')
>>> a,b,c,d,e = spl + [None]*(5-len(spl))
>>> a,b,c,d... |
py.test parametrizing test classes | 17,434,031 | 3 | 2013-07-02T19:20:05Z | 22,417,893 | 7 | 2014-03-15T00:08:09Z | [
"python",
"py.test"
] | I have a class for testing some of my code. I would like to parametrize the setup and rerun the class with different parameters:
```
class TestNormalLTEPlasma:
def setup(self, t=10000):
self.plasma = plasma.LTEPlasma.from_abundance(t, {'Si':1.0}, 1e-13, atom_data, 10*86400)
def test_beta_rad(self):
... | Instead of your setup function, create a parametrized test fixture:
```
ts = range(2000, 20001, 1000) # This creates a list of numbers from 2000 to 20000 in increments of 1000.
@pytest.fixture(params=ts)
def plasma(request):
return plasma.LTEPlasma.from_abundance(request.param, {'Si':1.0}, 1e-13, atom_data, 10*8... |
Generating all combinations of a list in python | 17,434,070 | 13 | 2013-07-02T19:22:10Z | 17,434,095 | 14 | 2013-07-02T19:23:35Z | [
"python",
"list",
"combinations"
] | Here's the question:
Given a list of items in Python, how would I go by to get all the possible combinations of the items?
There are several similar questions on this site, that suggest using itertools.combine, but that returns only a subset of what I need:
```
stuff = [1, 2, 3]
for L in range(0, len(stuff)+1):
... | Use [`itertools.permutations`:](http://docs.python.org/2/library/itertools.html#itertools.permutations)
```
>>> stuff = [1, 2, 3]
>>> for L in range(0, len(stuff)+1):
for subset in itertools.permutations(stuff, L):
print(subset)
...
()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
... |
Generating all combinations of a list in python | 17,434,070 | 13 | 2013-07-02T19:22:10Z | 29,092,091 | 7 | 2015-03-17T05:45:57Z | [
"python",
"list",
"combinations"
] | Here's the question:
Given a list of items in Python, how would I go by to get all the possible combinations of the items?
There are several similar questions on this site, that suggest using itertools.combine, but that returns only a subset of what I need:
```
stuff = [1, 2, 3]
for L in range(0, len(stuff)+1):
... | **You can generate all the combinations of a list in python using this simple code**
```
import itertools
a = [1,2,3,4]
for i in xrange(1,len(a)+1):
print list(itertools.combinations(a,i))
```
**Result:**
```
[(1,), (2,), (3,), (4,)]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
[(1, 2, 3), (1, 2, 4), (1, 3, ... |
Scrape data from a table with scrapy | 17,434,196 | 3 | 2013-07-02T19:28:56Z | 17,434,445 | 7 | 2013-07-02T19:43:26Z | [
"python",
"web-scraping",
"scrapy"
] | Scrape data from a table with scrapy. The table html is like:
```
<table class="tablehd">
<tr class="colhead">
<td width="170">MON, NOV 11</td>
<td width="80">Item</td>
<td width="60" align="center"></td>
<td width="210">Item</td>
<td width="220">Item</td>
</tr>
<tr class="oddrow">
<td> Item </a></td>
<td> Item </td... | Not sure what exactly do you want to see in your items, but here's an example and I hope this is it:
```
class MyItem(Item):
value = Field()
class MySpider(BaseSpider):
...
def parse(self, response):
hxs = HtmlXPathSelector(response)
items = hxs.select('//table[@class="tablehd"]/td')
... |
Read Bash Variables into a Python Script | 17,435,056 | 12 | 2013-07-02T20:15:06Z | 17,435,116 | 18 | 2013-07-02T20:18:32Z | [
"python",
"bash",
"scripting",
"environment-variables"
] | I am running a bash script (test.sh) and it loads in environment variables (from env.sh). That works fine, but I am trying to see python can just load in the variables already in the bash script.
Yes I know it would probably be easier to just pass in the specific variables I need as arguments, but I was curious if it ... | You need to export the variables in bash, or they will be local to bash:
```
export test1
```
Then, in python
```
import os
print os.environ["test1"]
``` |
Django functional LiveServerTestCase - After submitting form with selenium, objects save to non-test database | 17,435,155 | 5 | 2013-07-02T20:20:21Z | 17,437,982 | 11 | 2013-07-03T00:37:08Z | [
"python",
"django"
] | Absolutely losing my brain over this. I can't figure out why this is happening. Each time I run this test, the object gets saved to the normal, non-test database. However, both assertions at the end of the test fail anyway, saying they can't find ANY users in the database, even though each time the test runs I have to ... | According to [the `LiveServerTestCase` docs](https://docs.djangoproject.com/en/1.4/topics/testing/#django.test.LiveServerTestCase), the live server is on port 8081 by default. However you are fetching the page from port 8000 instead.
I expect you are running the dev server on port 8000 and your tests are connecting to... |
Selenium versus BeautifulSoup for web scraping | 17,436,014 | 11 | 2013-07-02T21:19:17Z | 17,436,663 | 22 | 2013-07-02T22:09:03Z | [
"javascript",
"python",
"selenium",
"beautifulsoup"
] | I'm scraping content from a website using Python. First I used `BeautifulSoup` and `Mechanize` on Python but I saw that the website had a button that created content via JavaScript so I decided to use `Selenium`.
Given that I can find elements and get their content using Selenium with methods like `driver.find_element... | Before answering your question directly, it's worth saying as a starting point: if all you need to do is pull content from static HTML pages, you should probably use [`urllib2`](http://docs.python.org/2/library/urllib2.html) with [`lxml`](http://lxml.de/) or [`BeautifulSoup`](http://www.crummy.com/software/BeautifulSou... |
Complex query (subqueries, window functions) with sqlalchemy | 17,437,317 | 4 | 2013-07-02T23:14:39Z | 17,457,858 | 11 | 2013-07-03T20:48:27Z | [
"python",
"sql",
"sqlalchemy"
] | I'm trying to write the following sql query with sqlalchemy ORM:
```
SELECT * FROM
(SELECT *, row_number() OVER(w)
FROM (select distinct on (grandma_id, author_id) * from contents) as c
WINDOW w AS (PARTITION BY grandma_id ORDER BY RANDOM())) AS v1
WHERE row_number <= 4;
```
This is what I've done so far:
... | `windowed_contents.c.row_number` against a `label()` is how you'd do it, works for me (note the `select_entity_from()` method is new in SQLA 0.8.2 and will be needed here in 0.9 vs. `select_from()`):
```
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
Base... |
(Python) How to get diagonal(A*B) without having to perform A*B? | 17,437,817 | 6 | 2013-07-03T00:19:07Z | 17,437,885 | 13 | 2013-07-03T00:27:16Z | [
"python",
"numpy",
"matrix"
] | Let's say we have two matrices `A` and `B` and let matrix `C` be `A*B` (matrix multiplication not element-wise). We wish to get only the diagonal entries of `C`, which can be done via `np.diagonal(C)`. However, this causes unnecessary time overhead, because we are multiplying A with B even though we only need the the m... | I might use `einsum` here:
```
>>> a = np.random.randint(0, 10, (3,3))
>>> b = np.random.randint(0, 10, (3,3))
>>> a
array([[9, 2, 8],
[5, 4, 0],
[8, 0, 6]])
>>> b
array([[5, 5, 0],
[3, 5, 5],
[9, 4, 3]])
>>> a.dot(b)
array([[123, 87, 34],
[ 37, 45, 20],
[ 94, 64, 18]])
... |
FTP upload files Python | 17,438,096 | 11 | 2013-07-03T00:54:21Z | 17,438,193 | 10 | 2013-07-03T01:06:02Z | [
"python",
"ftp"
] | I am trying to upload file from windows server to a unix server (basically trying to do FTP). I have used the code below
```
#!/usr/bin/python
import ftplib
import os
filename = "MyFile.py"
ftp = ftplib.FTP("xx.xx.xx.xx")
ftp.login("UID", "PSW")
ftp.cwd("/Unix/Folder/where/I/want/to/put/file")
os.chdir(r"\\windows\fol... | If you are trying to store a file try setting it to read mode instead of write mode.
```
ftp.storlines("STOR " + filename, open(filename, 'r'))
```
also if you plan on using the ftp lib you should probably go through a tutorial, I'd recommend this [article](http://effbot.org/librarybook/ftplib.htm) from effbot. |
How to define metaclass for a class that extends from sqlalchemy declarative base | 17,438,879 | 8 | 2013-07-03T02:48:09Z | 17,457,899 | 7 | 2013-07-03T20:51:39Z | [
"python",
"dynamic",
"attributes",
"sqlalchemy",
"metaclass"
] | I use: Python 2.6 and sqlalchemy 0.6.1
This is what I am trying to do:
```
from sqlalchemy.types import (
Integer,
String,
Boolean
)
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class SampleMeta(type):
def __new__(cls, name, bases, attrs):
attrs.update({ ... | to use the metaclass, it would have to derive from Declaratives `DeclaredMeta` in this case. But no metaclass is needed for this use case. Use [mixins](http://docs.sqlalchemy.org/en/rel_0_8/orm/extensions/declarative.html#mixing-in-columns):
```
from sqlalchemy.types import (
Integer,
String,
Boolean
)
fro... |
Flask-SQLALchemy: No such table | 17,440,605 | 5 | 2013-07-03T05:49:45Z | 17,452,969 | 9 | 2013-07-03T16:10:05Z | [
"python",
"flask",
"flask-sqlalchemy"
] | I am trying to get Flask-SQLAlchemy working and running in to some hiccups. Take a look at the two files I'm using. When I run `gwg.py` and goto `/util/db/create-all` it spits out an error `no such table: stories`. I thought I did everything correct; can someone point out what I'm missing or whats wrong? It does create... | The issue here is one a gotcha in the Python import system. It can be simplified to the following explanation...
Assume you have two files in a directory...
a.py:
```
print 'a.py is currently running as module {0}'.format(__name__)
import b
print 'a.py as module {0} is done'.format(__name__)
```
b.py:
```
print 'b... |
Python/Django MySQL Datetime handling and timezone | 17,441,812 | 3 | 2013-07-03T07:11:17Z | 17,442,224 | 8 | 2013-07-03T07:34:40Z | [
"python",
"mysql",
"django",
"datetime",
"timezone"
] | I've got a model called `Vote` with a field `date` :
```
date = models.DateTimeField(auto_now_add=True)
```
When I add an element, the date in MySQL is an UTC date but I live in UTC+2 timezone
I think I correctly set the timezone in `settings.py` :
```
TIME_ZONE = 'Europe/Paris'
```
Python use the right timezone :... | It's a complex binding to explain. From [Django 1.4](https://docs.djangoproject.com/en/dev/ref/settings/#time-zone),
> When USE\_TZ is False, **this** is the time zone in which Django will store
> all datetimes. When USE\_TZ is True, **this** is the default time zone that
> Django will use to display datetimes in temp... |
pycharm no module named redis | 17,442,184 | 3 | 2013-07-03T07:32:31Z | 17,442,657 | 7 | 2013-07-03T07:58:54Z | [
"python",
"redis",
"pycharm"
] | I installed pythonï¼Django and Redis. In Vim I use âimport redisâ is OKï¼ when I use pycharm IDE to codeï¼ I write âimport redisâ ï¼ the pycharm tip âno module named redisâï¼ whyï¼ what should I to do ï¼ | As per my understanding pycharm will say "No module named redis" if you haven't set up python interpreter in pycharm or in case there is no such module you are trying to use installed in the python interpreter you are currently using for pycharm.
To add python interpreter to pycharm go to
File -> Settings -> Python in... |
Using object as key in dictionary in Python - Hash function | 17,443,033 | 6 | 2013-07-03T08:19:51Z | 17,445,665 | 7 | 2013-07-03T10:31:15Z | [
"python",
"object",
"dictionary",
"key"
] | I am trying to use an object as the key value to a dictionary in Python. I follow the recommendations from some other posts that we need to implement 2 functions: **hash** and **eq**
And with that, I am expecting the following to work but it didn't.
```
class Test:
def __init__(self, name):
self.name = na... | You don't need to redefine `hash` and `eq` to use an object as dictionary key.
```
class Test:
def __init__(self, name):
self.name = name
test_Dict = {}
obj = Test('abc')
test_Dict[obj] = obj
print test_Dict[obj].name
```
This works fine and print `abc`.
As explained by Ignacio Vazquez-Abrams you don't... |
convert a 2D numpy array to a 2D numpy matrix | 17,443,620 | 5 | 2013-07-03T08:52:36Z | 17,443,705 | 12 | 2013-07-03T08:56:19Z | [
"python",
"arrays",
"numpy",
"matrix"
] | I have a python code in which I have to convert a 2D array to a 2D matrix so that I can use it to calculate inverse.For that I am using numpy.matrix(array) but it is not working. Can anyone tell how to convert a 2D array to a numpy matrix? The array consists of all float numbers | If `a` is your array, [`np.asmatrix(a)`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.asmatrix.html) is a matrix. |
python supervisord program dependency | 17,443,692 | 13 | 2013-07-03T08:55:36Z | 17,444,236 | 16 | 2013-07-03T09:21:29Z | [
"python",
"supervisord"
] | I have `[program:A]`, `[program:B]` in my supervisord.conf
`B` depend `A`, means:
`A` should start before `B`.
How to ensure this by supervisor? | `supervisord` does not directly support dependencies. Your options instead are:
* Use priorities. Set `priority` for `A` to a low value and it'll be started before `B`, and shut down after `B`. The default value for `priority` is `999`.
If you put the two programs into one group as well, that'd let you start and st... |
Reading a huge .csv in python | 17,444,679 | 21 | 2013-07-03T09:44:48Z | 17,444,799 | 47 | 2013-07-03T09:50:41Z | [
"python",
"csv",
"python-2.7"
] | I'm currently trying to read data from .csv files in Python 2.7 with up to 1 million rows, and 200 columns (files range from 100mb to 1.6gb). I can do this (very slowly) for the files with under 300,000 rows, but once I go above that I get memory errors. My code looks like this:
```
def getdata(filename, criteria)... | You are reading all rows into a list, then processing that list. **Don't do that**.
Process your rows as you produce them. If you need to filter the data first, use a generator function:
```
import csv
def getstuff(filename, criterion):
with open(filename, "rb") as csvfile:
datareader = csv.reader(csvfil... |
theano - print value of TensorVariable | 17,445,280 | 28 | 2013-07-03T10:13:41Z | 17,453,598 | 28 | 2013-07-03T16:40:18Z | [
"python",
"debugging",
"theano"
] | **How can I print the numerical value of a theano TensorVariable?**
I'm new to theano, so please be patient :)
I have a function where I get `y` as a parameter.
Now I want to debug-print the shape of this `y` to the console.
Using
```
print y.shape
```
results in the console output (i was expecting numbers, i.e. `(2... | If y is a theano variable, y.shape will be a theano variable. so it is normal that
```
print y.shape
```
return:
```
Shape.0
```
If you want to evaluate the expression y.shape, you can do:
```
y.shape.eval()
```
if `y.shape` do not input to compute itself(it depend only on shared variable and constant). Otherwise... |
theano - print value of TensorVariable | 17,445,280 | 28 | 2013-07-03T10:13:41Z | 29,963,238 | 11 | 2015-04-30T08:54:07Z | [
"python",
"debugging",
"theano"
] | **How can I print the numerical value of a theano TensorVariable?**
I'm new to theano, so please be patient :)
I have a function where I get `y` as a parameter.
Now I want to debug-print the shape of this `y` to the console.
Using
```
print y.shape
```
results in the console output (i was expecting numbers, i.e. `(2... | For future readers: the previous answer is quite good.
But, I found the 'tag.test\_value' mechanism more beneficial for debugging purposes (see [theano-debug-faq](http://deeplearning.net/software/theano/tutorial/debug_faq.html#using-test-values)):
```
from theano import config
from theano import tensor as T
config.com... |
Connecting a slot to a button in QDialogButtonBox | 17,451,688 | 3 | 2013-07-03T15:10:19Z | 17,494,441 | 8 | 2013-07-05T17:50:06Z | [
"python",
"qt",
"pyqt",
"pyside"
] | I created a standard buttonBox from QtDesigner with Ok, Cancel, Reset.
I successfully connected the Ok and Cancel buttons using,
```
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
```
even defining my own accept function.
So how would I connect the reset button to say func... | In python .-
```
self.buttonBox.button(QtGui.QDialogButtonBox.Reset).clicked.connect(foo)
``` |
Multi Threaded TCP server in Python | 17,453,212 | 14 | 2013-07-03T16:21:05Z | 17,453,901 | 11 | 2013-07-03T16:55:57Z | [
"python",
"sockets",
"tcpserver"
] | I have created a simple multi threaded tcp server using python's threding module. This server creates a new thread each time a new client is connected.
```
#!/usr/bin/env python
import socket, threading
class ClientThread(threading.Thread):
def __init__(self,ip,port):
threading.Thread.__init__(self)
... | You should pass the client sock to the thread like you do with the ip address and the port:
```
class ClientThread(threading.Thread):
def __init__(self, ip, port, socket):
threading.Thread.__init__(self)
self.ip = ip
self.port = port
self.socket = socket
print "[+] New thre... |
python if user input contains string | 17,453,626 | 3 | 2013-07-03T16:41:56Z | 17,453,678 | 11 | 2013-07-03T16:44:10Z | [
"python",
"string",
"if-statement",
"input",
"python-3.x"
] | Very basic question.
We have the code:
```
a = input("how old are you")
if a == string:
do this
if a == integer (a != string):
do that
```
Obviously it doesn't work that way. But what is the easiest way to do this.
Thanks for any answers in advance.
We could also say:
```
if string in a:
do this
``` | You can use `str.isdigit` and `str.isalpha`:
```
if a.isalpha():
#do something
elif a.isdigit():
#do something
```
help on `str.isdigit`:
```
>>> print str.isdigit.__doc__
S.isdigit() -> bool
Return True if all characters in S are digits
and there is at least one character in S, False otherwise.
```
help on ... |
GradientBoostingClassifier with a BaseEstimator in scikit-learn? | 17,454,139 | 6 | 2013-07-03T17:07:47Z | 19,679,862 | 7 | 2013-10-30T10:34:44Z | [
"python",
"numpy",
"machine-learning",
"scikit-learn",
"ensemble-learning"
] | I tried to use GradientBoostingClassifier in scikit-learn and it works fine with its default parameters. However, when I tried to replace the BaseEstimator with a different classifier, it did not work and gave me the following error,
```
return y - np.nan_to_num(np.exp(pred[:, k] -
IndexError: too many indices
```
Do... | An improved version of [iampat](http://stackoverflow.com/users/456984/iampat)'s answer and slight modification of [scikit-developers](http://comments.gmane.org/gmane.comp.python.scikit-learn/9011)'s answer should do the trick.
```
class init:
def __init__(self, est):
self.est = est
def predict(self, X)... |
A bit confused with blitting (Pygame) | 17,454,257 | 8 | 2013-07-03T17:13:27Z | 17,456,583 | 22 | 2013-07-03T19:30:15Z | [
"python",
"pygame",
"blit"
] | I've just started learning some pygame (quite new to programming overall), and I have some very basic questions about how it works.
I haven't found a place yet that explains when I need to blit or not to include a certain surface on the screen. For example, when drawing a circle:
```
circle = pygame.draw.circle(scree... | # The short answer
> I haven't found a place yet that explains when I need to blit or not to include a certain surface on the screen.
Each operation will behave differently, and you'll need to read the documentation for the function you're working with.
# The long answer
## What Is Blitting?
First, you need to rea... |
Can Lupa be used to run untrusted lua code in python? | 17,454,263 | 4 | 2013-07-03T17:13:47Z | 17,455,485 | 9 | 2013-07-03T18:22:10Z | [
"python",
"lua",
"lupa"
] | Let's say I create `LuaRuntime` with `register_eval=False` and an `attribute_filter` that prevents access to anything except a few python functions. Is it safe to assume that lua code won't be able to do `os.system("rm -rf *")` or something like that? | From looking at the [Lupa doc](https://pypi.python.org/pypi/lupa/#restricting-lua-access-to-python-objects):
> **Restricting Lua access to Python objects**
>
> Lupa provides a simple mechanism to control access to Python objects. Each attribute access can be passed through a filter function as follows...
It doesn't s... |
The best way to get a list of followers in Python with Tweepy | 17,455,107 | 10 | 2013-07-03T18:00:24Z | 17,490,319 | 13 | 2013-07-05T13:41:48Z | [
"python",
"twitter",
"tweepy"
] | Is there a better way to get a list of followers screen names with Tweepy than this:
```
for follower in api.followers_ids('twitter'):
print api.get_user(follower).screen_name
``` | I think this is more efficient:
```
for user in tweepy.Cursor(api.followers, screen_name="twitter").items():
print user.screen_name
```
FYI, it uses [followers/list](https://dev.twitter.com/docs/api/1.1/get/followers/list) twitter API call. |
Python securely remove file | 17,455,300 | 4 | 2013-07-03T18:10:57Z | 17,455,341 | 7 | 2013-07-03T18:13:42Z | [
"python",
"file",
"erase"
] | How can i securely remove a file using python, the function `os.remove(path)` only removes the directory entry, but i want to securely remove the file, similar to the apple feature called "Secure Empty Trash" that randomly overwrites the file. What function securely removes a file using this method? | You can use [srm](http://en.wikipedia.org/wiki/Srm_%28Unix%29) to securely remove files. You can use Python's [os.system()](http://docs.python.org/2/library/os.html#os.system) function to call srm. |
Best way to install OpenCV on Windows with Enthought Canopy Python? | 17,457,515 | 3 | 2013-07-03T20:27:11Z | 17,457,833 | 10 | 2013-07-03T20:46:53Z | [
"python",
"windows",
"opencv",
"enthought"
] | I've got the Enthought Canopy Python distribution on Windows, and I'd
like to add the OpenCV python bindings.
I have downloaded the latest OpenCV from
<http://sourceforge.net/projects/opencvlibrary/>
but I don't see any setup.py file.
So I'm wondering:
What is the best way to install OpenCV on windows to have it work... | I stumbled on this same issue. Here's what I did:
1. Unpack the OpenCV distribution into a folder, for example: `C:\RPS\python\epd32`
2. Open a text editor and create a one line file that contains the full path where you installed OpenCV + the subdirectory where the python binding lives, for example: `C:\RPS\python\ep... |
How to structure python packages without repeating top level name for import | 17,457,782 | 9 | 2013-07-03T20:43:33Z | 17,530,651 | 15 | 2013-07-08T15:39:20Z | [
"python",
"module",
"package"
] | I'm brand new at python package management, and surely have done something wrong. I was encouraged to create a directory structure as follows:
```
bagoftricks
âââ bagoftricks
â  âââ bagoftricks
â  â  âââ __init__.py
â  â  âââ bagoftricks.py
â  âââ __init__.py... | The first level "bagoftricks" is fine. That's just the name of your "project" so to speak. In the you have a setup.py, and other files that tell the packaging systems what they need to know.
You can then have the code directly in this module, or in a src directory. You can even go as far as just having this structure:... |
Why does this snippet with a shebang #!/bin/sh and exec python inside 4 single quotes work? | 17,458,528 | 12 | 2013-07-03T21:37:29Z | 17,458,578 | 19 | 2013-07-03T21:41:03Z | [
"python",
"bash",
"arguments",
"sh",
"shebang"
] | I'm trying to understand one of the answers to this question:
[Cannot pass an argument to python with "#!/usr/bin/env python"](http://stackoverflow.com/questions/3306518/cannot-pass-an-argument-to-python-with-usr-bin-env-python)
```
#!/bin/sh
''''exec python -u -- "$0" ${1+"$@"} # '''
```
This works well, but I do n... | Python supports triple-quoted strings:
```
'''something'''
```
Shell supports only single-quoted strings:
```
'something'
```
By using *four* quotes, `sh` sees that as 2 empty strings, but Python sees the first three as the start of a triple-quoted string, and includes the fourth as part of the string value.
The r... |
Traversing objects in python | 17,459,355 | 3 | 2013-07-03T22:53:59Z | 17,459,370 | 10 | 2013-07-03T22:55:57Z | [
"python"
] | How can I write this code without repeating myself indefinitely?
```
fields = row.split('__')
if len(fields) == 1:
foo = getattr(bundle.obj, fields[0])
elif len(fields) == 2:
foo = getattr(getattr(bundle.obj, fields[0]), fields[1])
elif len(fields) == 3:
foo = getattr(getattr(getattr(bundle.obj,
... | Use [`reduce()`](http://docs.python.org/2/library/functions.html#reduce):
```
foo = reduce(getattr, fields, bundle.obj)
```
or a simple loop:
```
foo = bundle.obj
for field in fields:
foo = getattr(foo, field)
``` |
open() is not working for hidden files python | 17,460,719 | 4 | 2013-07-04T01:50:04Z | 17,460,761 | 8 | 2013-07-04T01:56:34Z | [
"python"
] | I want to create and write a .txt file in a hidden folder using python. I am using this code:
```
file_name="hi.txt"
temp_path = '~/.myfolder/docs/' + file_name
file = open(temp_path, 'w')
file.write('editing the file')
file.close()
print 'Execution completed.'
```
where ~/.myfolder/docs/ is a hidden folder. I ma get... | The problem isn't that it's hidden, it's that Python cannot resolve your use of `~` representing your home directory. Use [`os.path.expanduser`](http://docs.python.org/2/library/os.path.html#os.path.expanduser),
```
>>> with open('~/.FDSA', 'w') as f:
... f.write('hi')
...
Traceback (most recent call last):
Fil... |
Celery stop execution of a chain | 17,461,374 | 14 | 2013-07-04T03:27:15Z | 21,106,596 | 8 | 2014-01-14T05:23:50Z | [
"python",
"celery",
"django-celery",
"celery-task",
"celerybeat"
] | I have a check\_orders task that's executed periodically. It makes a group of tasks so that I can time how long executing the tasks took, and perform something when they're all done (this is the purpose of res.join [1] and grouped\_subs) The tasks that are grouped are pairs of chained tasks.
What I want is for when th... | In my opinion this is a common use-case that doesn't get enough love in the documentation.
Assuming you want to abort a chain mid-way while still reporting SUCCESS as status of the completed tasks, and not sending any error log or whatnot (else you can just raise an exception) then a way to accomplish this is:
```
@a... |
Python getting a string (key + value) from Python Dictionary | 17,462,994 | 4 | 2013-07-04T06:08:49Z | 17,463,020 | 12 | 2013-07-04T06:10:53Z | [
"python",
"string",
"dictionary"
] | I have dictionary structure. For example:
```
dict = {key1 : value1 ,key2 : value2}
```
What I want is the string which combines the key and the value
Needed string -->> key1\_value1 , key2\_value2
Any Pythonic way to get this will help.
Thanks
```
def checkCommonNodes( id , rs):
for r in rs:
for k... | A `list` of key-value `str`s,
```
>>> d = {'key1': 'value1', 'key2': 'value2'}
>>> ['{}_{}'.format(k,v) for k,v in d.iteritems()]
['key2_value2', 'key1_value1']
```
Or if you want a single string of all key-value pairs,
```
>>> ', '.join(['{}_{}'.format(k,v) for k,v in d.iteritems()])
'key2_value2, key1_value1'
```
... |
Python PrettyPrint output to variable | 17,463,483 | 6 | 2013-07-04T06:43:23Z | 17,463,566 | 13 | 2013-07-04T06:47:53Z | [
"python",
"pprint"
] | How to store a Python PrettyPrint output to some variable.
Any other way than eyeD3?
like this -
```
string_output = pp.pprint(dict)
``` | Use the [`pprint.pformat`](http://docs.python.org/2/library/pprint.html#pprint.pformat) function:
```
>>> my_dict = dict((i, i) for i in range(30))
>>> pp.pformat(my_dict)
'{0: 0,\n 1: 1,\n 2: 2,\n 3: 3,\n 4: 4,\n 5: 5,\n 6: 6,\n 7: 7,\n 8: 8,\n 9: 9,\n 10: 10,\n 11: 11,\n 12: 12,\n 13: 13,\n 14: 14,\n 15: 15,\n 16: 1... |
Can pandas automatically recognize dates? | 17,465,045 | 27 | 2013-07-04T08:08:39Z | 17,468,012 | 74 | 2013-07-04T10:32:01Z | [
"python",
"date",
"types",
"dataframe",
"pandas"
] | Today I was positively surprised by the fact that while reading data from a data file (for example) pandas is able to recognize types of values:
```
df = pandas.read_csv('test.dat', delimiter=r"\s+", names=['col1','col2','col3'])
```
For example it can be checked in this way:
```
for i, r in df.iterrows():
print... | You should add `parse_dates=True`, or `parse_dates=['column name']` when reading, thats usually enough to magically parse it. But there are always weird formats which need to be defined manually. In such a case you can also add a date parser function, which is the most flexible way possible.
Suppose you have a column ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.