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
Raspberry pi flashing LED issue - Python vs Java
19,821,461
14
2013-11-06T19:52:17Z
19,875,931
10
2013-11-09T12:27:22Z
[ "java", "python", "raspberry-pi" ]
i am trying to make an LED light flash on the raspberry pi using some code i found online ( i know - not the best but it was a tutorial site) When i run the following python code the led light flashes; ``` import RPi.GPIO as GPIO import time pinNum = 4 GPIO.setmode(GPIO.BCM) #numbering scheme that corresponds to brea...
I believe that your pin numbers might be off. Since the java code does not throw exceptions, I'd consider it likely that one of the pins is activated, but which has a different index than the one your LED is connected to. The documentation of Pi4J lists this table for pin number reference: <https://projects.drogon.net...
Raspberry pi flashing LED issue - Python vs Java
19,821,461
14
2013-11-06T19:52:17Z
19,926,300
11
2013-11-12T10:10:27Z
[ "java", "python", "raspberry-pi" ]
i am trying to make an LED light flash on the raspberry pi using some code i found online ( i know - not the best but it was a tutorial site) When i run the following python code the led light flashes; ``` import RPi.GPIO as GPIO import time pinNum = 4 GPIO.setmode(GPIO.BCM) #numbering scheme that corresponds to brea...
The GPIO\_4 in the Python GPIO code corresponds to this diagram ![enter image description here](http://i.stack.imgur.com/PGR48.png) The pi4j corresponds to the diagram below ![enter image description here](http://i.stack.imgur.com/9WyFZ.png) So GPIO\_04 is in a completely different location! You should change the j...
Python regex match OR operator
19,821,487
3
2013-11-06T19:54:00Z
19,821,774
7
2013-11-06T20:09:10Z
[ "python", "regex", "string", "time" ]
I'm trying to match time formats in AM or PM. ``` i.e. 02:40PM 12:29AM ``` I'm using the following regex ``` timePattern = re.compile('\d{2}:\d{2}(AM|PM)') ``` but it keeps returning only `AM` `PM` string without the numbers. What's going wrong?
Use a non capturing group `(?:` and reference to the match group. Use `re.I` for case insensitive matching. ``` import re def find_t(text): return re.search(r'\d{2}:\d{2}(?:am|pm)', text, re.I).group() ``` You can also use `re.findall()` for recursive matching. ``` def find_t(text): return re.findall(r'\d{...
Python properties as instance attributes
19,822,932
4
2013-11-06T21:13:09Z
19,823,001
8
2013-11-06T21:16:59Z
[ "python", "properties" ]
I am trying to write a class with dynamic properties. Consider the following class with two read-only properties: ``` class Monster(object): def __init__(self,color,has_fur): self._color = color self._has_fur = has_fur @property def color(self): return self._color @property def ha...
No, there is no such thing as per-instance properties; like all descriptors, properties are *always* looked up on the class. See the [descriptor HOWTO](http://docs.python.org/2/howto/descriptor.html) for exactly how that works. You *can* implement dynamic attributes using a `__getattr__` hook instead, which can check ...
I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"
19,824,721
3
2013-11-06T23:05:06Z
19,824,763
7
2013-11-06T23:07:25Z
[ "python" ]
I don't understand why I can't use my variable `c`. code: ``` from turtle import * speed(0) hideturtle() c = 450 def grid(x,y,a): seth(0) pu() goto(x,y) pd() for i in range(4): forward(a) rt(90) for i in range(c/10): seth(0) forward(10) rt(90) ...
In: ``` for i in range(c/10): ``` You're creating a float as a result - to fix this use the int division operator: ``` for i in range(c // 10): ```
Django test client does not log in
19,827,342
15
2013-11-07T03:14:09Z
19,827,423
18
2013-11-07T03:21:57Z
[ "python", "django", "unit-testing", "django-testing" ]
I am attempting to log in the test client using its built in login function. I am trying to unit test views and need to log in to test some of them. I have been trying to do this for too long and need help. A few notes: create\_user() does create a valid user, It has been used in other locations. From what I have see...
You cannot access the password directly. The `password` attribute is encrypted. (See [Password management in Django](https://docs.djangoproject.com/en/1.6/topics/auth/passwords/).) For example, here sample output of password. ``` >>> user = User.objects.create_user(username='asdf', email='[email protected]', password=...
Why do single quote( ' ) and double quote( " ) get different results in python's json module?
19,827,383
4
2013-11-07T03:17:29Z
19,827,394
12
2013-11-07T03:18:11Z
[ "python", "json" ]
I have such piece of python code: ``` import json single_quote = '{"key": "value"}' double_quote = "{'key': 'value'}" data = json.loads(single_quote) # get a dict: {'key': 'value'} data = json.loads(double_quote) # get a ValueError: Expecting property name: line 1 column 2 (char 1) ``` In python, `single_quote` and `...
That's because only the first example is valid JSON. JSON data have keys and values surrounded by `"..."` and not `'...'`. There are other "rules" that you may not be expecting. There's a great list on this wikipedia page [here](http://en.wikipedia.org/wiki/JSON#Data_types.2C_syntax_and_example). For example, booleans...
Pydev Not Recognized in Eclipse
19,827,404
21
2013-11-07T03:19:19Z
19,827,715
15
2013-11-07T03:54:46Z
[ "python", "eclipse", "ide", "pydev" ]
I've been using PyDev within Eclipse on my Mac for about two years now. Updated Eclipse today, and suddenly PyDev is completely missing. Tried everything, included a complete uninstall and fresh install, but although PyDev shows up as installed in the menu, it appears nowhere else. PyDev version: 3.0.0.201311051910 Ec...
To see what the problem is, I upgraded from PyDev 2.8.2 to 3.0.0 just for this. It caused me a world of hurt. That version is *filled* with bugs. Nothing is working for me, including the perspectives or the debugger. I just went back to 2.8.2 and all is well again. I am also on Kepler and Mac. Go to 2.8.2. YOu can unin...
Pydev Not Recognized in Eclipse
19,827,404
21
2013-11-07T03:19:19Z
19,856,964
10
2013-11-08T10:38:19Z
[ "python", "eclipse", "ide", "pydev" ]
I've been using PyDev within Eclipse on my Mac for about two years now. Updated Eclipse today, and suddenly PyDev is completely missing. Tried everything, included a complete uninstall and fresh install, but although PyDev shows up as installed in the menu, it appears nowhere else. PyDev version: 3.0.0.201311051910 Ec...
Check if you are using Java 7, it is needed now for PyDev 3. Source: <http://pydev.org/download.html> and PyDev bugtracker. After upgrading my java-version it worked for me again.
Pydev Not Recognized in Eclipse
19,827,404
21
2013-11-07T03:19:19Z
20,977,072
11
2014-01-07T16:41:32Z
[ "python", "eclipse", "ide", "pydev" ]
I've been using PyDev within Eclipse on my Mac for about two years now. Updated Eclipse today, and suddenly PyDev is completely missing. Tried everything, included a complete uninstall and fresh install, but although PyDev shows up as installed in the menu, it appears nowhere else. PyDev version: 3.0.0.201311051910 Ec...
If you can't / will not upgrade to Java 7: Uninstall latest PyDev version 1. Help >> About Eclipse 2. Press button "Installation Details" 3. Select "PyDev for Eclipse" 4. Press button "Uninstall..." 5. Close, OK Install version 2.8.2 1. Help >> Install New Software... 2. select in drop-down list "Work w...
startswith TypeError in function
19,827,615
12
2013-11-07T03:42:29Z
19,827,633
16
2013-11-07T03:45:07Z
[ "python", "python-3.x" ]
Here is the code: ``` def readFasta(filename): """ Reads a sequence in Fasta format """ fp = open(filename, 'rb') header = "" seq = "" while True: line = fp.readline() if (line == ""): break if (line.startswith('>')): ...
It's because you're opening the file in bytes mode, and so you're calling `bytes.startswith()` and not `str.startswith()`. You need to do `line.startswith(b'>')`, which will make `'>'` a [bytes literal](http://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals).
Matplotlib - Drawing a smooth circle in a polar plot
19,827,792
4
2013-11-07T04:03:26Z
19,828,753
9
2013-11-07T05:40:13Z
[ "python", "matplotlib", "circle", "polar-coordinates" ]
I really like the polar plot of matplotlib and would love to keep working with it (since my data points are given in polar coordinates anyway and my environment is circular). However, in the plot, I would like to add circles of given radii at specific points. Usually, I would do: ``` ax = plt.subplot(111) ax.scatt...
You can set `transform` argument of the `Circle`: ``` %matplotlib inline import pylab as pl import numpy as np N = 100 theta = np.random.rand(N)*np.pi*2 r = np.cos(theta*2) + np.random.randn(N)*0.1 ax = pl.subplot(111, polar=True) ax.scatter(theta, r) circle = pl.Circle((0.5, 0.3), 0.2, transform=ax.transData._b, co...
TypeError: 'numpy.float64' object is not callable
19,828,212
2
2013-11-07T04:49:02Z
19,828,259
8
2013-11-07T04:53:38Z
[ "python", "numpy" ]
So, what im trying to do is get certain numbers from certain positions in a array of a given > range and put them into an equation ``` yy = arange(4) xx = arange(5) Area = ((xx[2] - xx[1])(yy[2] + yy[1])) / 2 ``` I try to run it and I get this.. ``` ----> ((xx[2] - xx[1])(yy[2] + yy[1])) / 2 TypeError: 'numpy.int64'...
Python does not follow the same rules as written math. You must explicitly indicate multiplication. ### Bad: ``` (a)(b) ``` *(unless `a` is a function)* ### Good: ``` (a) * (b) ```
How to convert datetime string to UTC to plot points on Highcharts
19,828,299
3
2013-11-07T04:58:38Z
19,828,352
7
2013-11-07T05:03:22Z
[ "python", "highcharts" ]
I'm working on HighCharts Spline Irregular Data. Here the data is passed as ``` data: [ [Date.UTC(1970, 9, 27), 0 ], [Date.UTC(1970, 10, 10), 0.6 ], [Date.UTC(1970, 10, 18), 0.7 ], [Date.UTC(1970, 11, 2), 0.8 ], [Date.UTC(1970, 11, 9), 0.6 ], [Date.UTC(1970, 11, 16), 0.6 ], ...
The problem is that HighCharts expects time series data to be given in milliseconds, not seconds so you will need to put in a multiplier of 1000. You can convert from your strings to milliseconds since epoch like so: ``` >>> int(datetime.datetime.strptime("2013-11-07 00:10:27", "%Y-%m-%d %H:%M:%S").strftime('%s')) * ...
How to check whether a pandas DataFrame is empty?
19,828,822
68
2013-11-07T05:45:35Z
19,828,967
107
2013-11-07T05:55:48Z
[ "python", "pandas" ]
How to check whether a pandas `DataFrame` is empty? In my case I want to print some message in terminal if the `DataFrame` is empty.
You can use the attribute `df.empty` to check whether it's empty or not: ``` if df.empty: print('DataFrame is empty!') ``` Source: [Pandas Documentation](http://pandas.pydata.org/pandas-docs/dev/basics.html#boolean-reductions)
How to check whether a pandas DataFrame is empty?
19,828,822
68
2013-11-07T05:45:35Z
24,933,234
13
2014-07-24T12:06:18Z
[ "python", "pandas" ]
How to check whether a pandas `DataFrame` is empty? In my case I want to print some message in terminal if the `DataFrame` is empty.
I use len function. It's much faster than empty(). len(df.index) is even faster. ``` import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(10000, 4), columns=list('ABCD')) def empty(df): return df.empty def lenz(df): return len(df) == 0 def lenzi(df): return len(df.index) == 0 ''' %...
pip install gives error: Unable to find vcvarsall.bat
19,830,942
43
2013-11-07T08:19:40Z
19,831,360
23
2013-11-07T08:46:03Z
[ "python", "python-2.7", "pip", "zipline" ]
Using `pip install zipline` on Windows 8 with Python 2.7 gives me the error: ``` Downloading/unpacking six (from python-dateutil==2.1->delorean->zipline[all]) Running setup.py egg_info for package six Installing collected packages: blist, pytz, requests, python-dateutil, six Running setup.py install for blist ...
You could use ol' good `easy_install zipline` instead. `easy_install` isn't pip but one good aspect of it is the ability to download and install binary packages too, which would free you for the need having VC++ ready. This of course relies of the assumption that the binaries were prepared for your Python version. UP...
pip install gives error: Unable to find vcvarsall.bat
19,830,942
43
2013-11-07T08:19:40Z
23,397,327
55
2014-04-30T20:20:30Z
[ "python", "python-2.7", "pip", "zipline" ]
Using `pip install zipline` on Windows 8 with Python 2.7 gives me the error: ``` Downloading/unpacking six (from python-dateutil==2.1->delorean->zipline[all]) Running setup.py egg_info for package six Installing collected packages: blist, pytz, requests, python-dateutil, six Running setup.py install for blist ...
The problem here is the line 292 (Using Python 3.4.3 here) in `$python_install_prefix/Lib/distutils/msvc9compiler.py` which says: ``` VERSION = get_build_version() ``` This only checks for the MSVC version that your python was built with. Just replacing this line with your actual Visual Studio version, eg. `12.0` for...
pip install gives error: Unable to find vcvarsall.bat
19,830,942
43
2013-11-07T08:19:40Z
28,911,105
8
2015-03-07T03:39:06Z
[ "python", "python-2.7", "pip", "zipline" ]
Using `pip install zipline` on Windows 8 with Python 2.7 gives me the error: ``` Downloading/unpacking six (from python-dateutil==2.1->delorean->zipline[all]) Running setup.py egg_info for package six Installing collected packages: blist, pytz, requests, python-dateutil, six Running setup.py install for blist ...
If you are getting this error on Python 2.7 you can now get the [Microsoft Visual C++ Compiler for Python 2.7](http://www.microsoft.com/en-us/download/details.aspx?id=44266) as a stand alone download. If you are on 3.3 or later you need to install Visual Studio 2010 express which is available for free here: <https://w...
wtforms raise a validation error after the form is validated
19,831,351
5
2013-11-07T08:45:40Z
19,834,740
13
2013-11-07T11:27:29Z
[ "python", "flask", "wtforms", "flask-wtforms" ]
I have a registration form that collects credit card info. The workflow is as follows: * User enters registration data and card data through stripe. * The form is validated for registration data. * If the form is valid, payment is processed. * If payment goes through, it's all good, the user is registered and moves on...
I solved it by manually appending errors to the field i wanted. It looks like that ``` try: [...] except StripeError as e: form.payment.errors.append('the error message') else: db.session.commit() return redirect(url_for('home')) ```
How to use a file in a hadoop streaming job using python?
19,833,722
6
2013-11-07T10:38:35Z
19,834,873
8
2013-11-07T11:35:01Z
[ "python", "hadoop", "hadoop-streaming" ]
I want to read a list from a file in my hadoop streaming job. Here is my simple mapper.py: ``` #!/usr/bin/env python import sys import json def read_file(): id_list = [] #read ids from a file f = open('../user_ids','r') for line in f: line = line.strip() id_list.append(line) retur...
``` hadoop jar contrib/streaming/hadoop-streaming-1.1.1.jar -file ./mapper.py \ -mapper ./mapper.py -file ./reducer.py -reducer ./reducer.py \ -input test/input.txt -output test/output -file '../user_ids' ``` Does ../user\_ids exist on your local file path when you execute the job? If it does then you need to ame...
pandas much slower than numpy?
19,834,075
6
2013-11-07T10:54:38Z
19,836,221
9
2013-11-07T12:39:58Z
[ "python", "numpy", "pandas" ]
The code below suggests that pandas may be much slower than numpy, at least in the specifi case of the function clip(). What is surprising is that making a roundtrip from pandas to numpy and back to pandas, while performing the calculations in numpy, is still much faster than doing it in pandas. Shouldn't the pandas f...
In master/0.13 (release very shortly), this is much faster (still slightly slower that native numpy because of handling of alignment/dtype/nans). In 0.12 it was applying per column, so this was a relatively expensive operation. ``` In [4]: arr = np.random.randn(1000, 1000) In [5]: df=pd.DataFrame(arr) In [6]: %time...
Add rate of change to Pandas DataFrame
19,837,352
5
2013-11-07T13:34:42Z
19,837,905
7
2013-11-07T14:02:16Z
[ "python", "numpy", "pandas" ]
I have the following Pandas DataFrame: ``` lastrun value 0 2013-10-24 13:10:05+00:00 55376 1 2013-10-24 14:10:32+00:00 56738 2 2013-10-24 15:52:31+00:00 58239 3 2013-10-24 23:52:09+00:00 59981 4 2013-10-25 00:52:04+00:00 ...
You can use the `diff` method: ``` df['new_column'] = df['source_column'].diff() ```
Python Lambda in a loop
19,837,486
17
2013-11-07T13:42:43Z
19,837,590
7
2013-11-07T13:47:35Z
[ "python", "loops", "anonymous-function" ]
Considering the following code snippet : ``` # directorys == {'login': <object at ...>, 'home': <object at ...>} for d in directorys: self.command["cd " + d] = (lambda : self.root.change_directory(d)) ``` I expect to create a dictionary of two function as following : ``` # Expected : self.command == { "cd lo...
This is due to the point at which d is being bound. The lambda functions all point at the *variable* `d` rather than the current *value* of it, so when you update `d` in the next iteration, this update is seen across all your functions. For a simpler example: ``` funcs = [] for x in [1,2,3]: funcs.append(lambda: x)...
Python Lambda in a loop
19,837,486
17
2013-11-07T13:42:43Z
19,837,683
22
2013-11-07T13:52:05Z
[ "python", "loops", "anonymous-function" ]
Considering the following code snippet : ``` # directorys == {'login': <object at ...>, 'home': <object at ...>} for d in directorys: self.command["cd " + d] = (lambda : self.root.change_directory(d)) ``` I expect to create a dictionary of two function as following : ``` # Expected : self.command == { "cd lo...
You need to bind d for each function created. One way to do that is to pass it as a parameter with a default value: ``` lambda d=d: self.root.change_directory(d) ``` Now the d inside the function uses the parameter, even though it has the same name, and the default value for that is evaluated when the function is cre...
Python Tkinter: Update Image in Canvas
19,838,972
2
2013-11-07T14:52:11Z
19,842,646
8
2013-11-07T17:29:36Z
[ "python", "tkinter" ]
This is the essence of the code I'm having trouble with: ``` camelot = Canvas(main, width = 400, height = 300) camelot.grid(row = 0, column = 0, rowspan = 11, columnspan = 3) MyImage = PhotoImage(file = "sample1.gif") camelot.create_image(0, 0, anchor = NW, image = MyImage) ``` This is run at the beginning. What I wa...
Add image to canvas: `self.image_on_canvas = self.canvas.create_image(0, 0, image = ...)` Change image: `self.canvas.itemconfig(self.image_on_canvas, image = ...)` --- Full example: ``` from Tkinter import * #---------------------------------------------------------------------- class MainWindow(): #------...
Grammatical List Join in Python
19,838,976
23
2013-11-07T14:52:21Z
19,839,257
13
2013-11-07T15:04:02Z
[ "python", "list", "python-2.7" ]
What's the most pythonic way of joining a list so that there are commas between each item, except for the last which uses "and"? ``` ["foo"] --> "foo" ["foo","bar"] --> "foo and bar" ["foo","bar","baz"] --> "foo, bar and baz" ["foo","bar","baz","bah"] --> "foo, bar, baz and bah" ```
Try this, it takes into consideration the edge cases and uses `format()`, to show another possible solution: ``` def my_join(lst): if not lst: return "" elif len(lst) == 1: return str(lst[0]) return "{} and {}".format(", ".join(lst[:-1]), lst[-1]) ``` Works as expected: ``` my_join([]) =...
Grammatical List Join in Python
19,838,976
23
2013-11-07T14:52:21Z
19,839,338
24
2013-11-07T15:06:45Z
[ "python", "list", "python-2.7" ]
What's the most pythonic way of joining a list so that there are commas between each item, except for the last which uses "and"? ``` ["foo"] --> "foo" ["foo","bar"] --> "foo and bar" ["foo","bar","baz"] --> "foo, bar and baz" ["foo","bar","baz","bah"] --> "foo, bar, baz and bah" ```
This expression does it: ``` print ", ".join(data[:-2] + [" and ".join(data[-2:])]) ``` As seen here: ``` >>> data ['foo', 'bar', 'baaz', 'bah'] >>> while data: ... print ", ".join(data[:-2] + [" and ".join(data[-2:])]) ... data.pop() ... foo, bar, baaz and bah foo, bar and baaz foo and bar foo ```
Upgrade to numpy 1.8.0 on Ubuntu 12.04
19,839,488
16
2013-11-07T15:12:35Z
19,840,524
8
2013-11-07T15:55:52Z
[ "python", "ubuntu", "numpy", "installation", "upgrade" ]
I'm running Ubuntu 12.04 which comes by default with `NumPy 1.6.0` (I have, actually *had*, `Python 2.7.3` installed). As a result of the answer to this question [polyfit() got an unexpected keyword argument 'w'](http://stackoverflow.com/questions/19838579/polyfit-got-an-unexpected-keyword-argument-w), I need to upgrad...
Ok, so I tried: ``` pip uninstall numpy ``` which returned: ``` Successfully uninstalled numpy ``` So then I did: ``` pip install numpy ``` but it said: ``` Requirement already satisfied (use --upgrade to upgrade): numpy in /home/gabriel/.local/lib/python2.7/site-packages Cleaning up... ``` so apparently it was...
Upgrade to numpy 1.8.0 on Ubuntu 12.04
19,839,488
16
2013-11-07T15:12:35Z
21,959,856
43
2014-02-22T20:07:49Z
[ "python", "ubuntu", "numpy", "installation", "upgrade" ]
I'm running Ubuntu 12.04 which comes by default with `NumPy 1.6.0` (I have, actually *had*, `Python 2.7.3` installed). As a result of the answer to this question [polyfit() got an unexpected keyword argument 'w'](http://stackoverflow.com/questions/19838579/polyfit-got-an-unexpected-keyword-argument-w), I need to upgrad...
``` sudo pip install numpy --upgrade ``` will do the same thing with slightly less effort.
faster code then numpy.dot for matrix multiplication?
19,839,539
9
2013-11-07T15:14:51Z
19,839,985
25
2013-11-07T15:36:02Z
[ "python", "numpy", "matrix-multiplication", "hdf5", "pytables" ]
Here [Matrix multiplication using hdf5](http://stackoverflow.com/questions/19684575/matrix-multiplication-using-hdf5) I use hdf5 (pytables) for big matrix multiplication, but I was suprised because using hdf5 it works even faster then using plain numpy.dot and store matrices in RAM, what is the reason of this behavior?...
`np.dot` dispatches to [BLAS](https://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms) when * NumPy has been compiled to use BLAS, * a BLAS implementation is available at run-time, * your data has one of the dtypes `float32`, `float64`, `complex32` or `complex64`, and * the data is suitably aligned in memory. ...
Python Matplotlib Venn diagram
19,841,535
17
2013-11-07T16:38:21Z
19,841,728
29
2013-11-07T16:46:27Z
[ "python", "matplotlib", "venn-diagram" ]
I want to plot variables that belongs to certain groups. Say that I have 6 variables that I want to sort into these 3 groups and plot like a venn diagram. I would like to annotate the variable names into the three bubbles. In this simple example we could say that 1 variable is in group 1, 3 variables in group 2 and ...
There is a beautiful Venn diagram add-on for matplotlib called [matplotlib-venn](https://pypi.python.org/pypi/matplotlib-venn). It looks like it can be completely customized to do what you are looking for, from the size of the circles (proportional to the set size), to inner and outer labels. Using the example code on...
How to disable a widget in Kivy?
19,842,429
2
2013-11-07T17:19:32Z
19,843,015
7
2013-11-07T17:48:12Z
[ "python", "user-interface", "widget", "kivy" ]
I read the Kivy tutorial and couldn't find how to disable a widget (for example, a Button). ``` def foo(self, instance, *args): #... main business logic, and then instance.disable = False # type(instance) = kivy.uix.Button ``` I bind `foo` with `functools.partial`. What is the correct parameter?
1. It's `disabled`, not `disable` 2. Set it to True Example: ``` from kivy.uix.button import Button from kivy.app import App from functools import partial class ButtonTestApp(App): def foo(self, instance, *args): instance.disabled = True def build(self): btn = Button() btn.bind(on_pr...
How to disable a widget in Kivy?
19,842,429
2
2013-11-07T17:19:32Z
19,843,217
9
2013-11-07T17:57:19Z
[ "python", "user-interface", "widget", "kivy" ]
I read the Kivy tutorial and couldn't find how to disable a widget (for example, a Button). ``` def foo(self, instance, *args): #... main business logic, and then instance.disable = False # type(instance) = kivy.uix.Button ``` I bind `foo` with `functools.partial`. What is the correct parameter?
If you are using kivy version >= 1.8 then you can just do widget.disabled = True. If on previous versions you can simply manage the disabling yourself, just make sure it doesn't react to touch and displays a alternative look when disabled.
Migrating data when changing an NDB field's property type
19,842,671
5
2013-11-07T17:30:36Z
19,848,970
7
2013-11-07T23:40:47Z
[ "python", "google-app-engine", "app-engine-ndb" ]
Suppose I initially create an ndb.Model and wanted to change a field's ndb property type (e.g. IntegerProperty to StringProperty), but wanted to cast the current data stored in that field so that I don't lose that data. One method would be to simply create a new field name and then migrate the data over with a script, ...
How you approach this will depend on how many entities you have. If you a relatively small number of entities say in the 10000's I would just use the remote\_api and retrieve the raw underlying data from the datastore and manipulate the data directly then write it back, not using the models. For instance this will fetc...
Structure of inputs to scipy minimize function
19,843,752
12
2013-11-07T18:26:13Z
19,845,135
19
2013-11-07T19:42:11Z
[ "python", "numpy", "scipy", "minimize" ]
I have inherited some code that is trying to minimize a function using `scipy.optimize.minimize`. I am having trouble understanding some of the inputs to the `fun` and `jac` arguments The call to minimize looks something like this: ``` result = minimize(func, jac=jac_func, args=(D_neg, D, C), method = 'TNC' ...other ...
The short answer is that `G` is maintained by the optimizer as part of the minimization process, while the `(D_neg, D, and C)` arguments are passed in as-is from the `args` tuple. By default, `scipy.optimize.minimize` takes a function `fun(x)` that accepts one argument `x` (which might be an array or the like) and ret...
psycopg: Python.h: No such file or directory
19,843,945
17
2013-11-07T18:36:04Z
19,843,961
33
2013-11-07T18:36:47Z
[ "python", "psycopg2" ]
I'm compiling psycopg2 and get the following error: **Python.h: No such file or directory** How to compile it, Ubuntu12 x64.
Python 2: ``` sudo apt-get install python-dev ``` Python 3: ``` sudo apt-get install python3-dev ```
psycopg: Python.h: No such file or directory
19,843,945
17
2013-11-07T18:36:04Z
19,844,013
7
2013-11-07T18:39:17Z
[ "python", "psycopg2" ]
I'm compiling psycopg2 and get the following error: **Python.h: No such file or directory** How to compile it, Ubuntu12 x64.
if you take a look at PostgreSQL's faq page ( <http://initd.org/psycopg/docs/faq.html> ) you'll see that they recommend installing pythons development package, which is usually called `python-dev`. You can install via > sudo apt-get install python-dev
List as value in dictionary, get key of longest list
19,845,258
3
2013-11-07T19:48:37Z
19,845,287
9
2013-11-07T19:50:10Z
[ "python", "list", "dictionary" ]
Give a dictionary like this ``` testDict = {76: [4], 32: [2, 4, 7, 3], 56: [2, 58, 59]} ``` How do I get the key of the longest list? In this case it would be `32`.
Use `max`: ``` >>> max(testDict, key=lambda x:len(testDict[x])) 32 ``` If multiple keys contain the longest list: > I want to get multiple keys then. ``` >>> testDict = {76: [4], 32: [2, 4, 7, 3], 56: [2, 58, 59], 10: [1, 2, 3, 4]} >>> mx = max(len(x) for x in testDict.itervalues()) >>> [k for k, v in testDict.iter...
Python Threading inside a class
19,846,332
12
2013-11-07T20:45:25Z
19,846,691
27
2013-11-07T21:05:32Z
[ "python", "multithreading" ]
I recently started with python's threading module. After some trial and error I managed to get basic threading working using the following sample code given in most tutorials. ``` class SomeThread(threading.Thread): def __init__(self, count): threading.Thread.__init__(self) def run(self): prin...
If I understand correctly you want to run a function in a separate thread? There are several ways to do that. But basically you wrap your function like this: ``` class MyClass: somevar = 'someval' def _func_to_be_threaded(self): # main body def func_to_be_threaded(self): threading.Thread(...
Why do list comprehensions write to the loop variable, but generators don't?
19,848,082
71
2013-11-07T22:32:57Z
19,848,117
9
2013-11-07T22:35:11Z
[ "python", "python-2.7", "generator", "list-comprehension" ]
If I do something with list comprehensions, it writes to a local variable: ``` i = 0 test = any([i == 2 for i in xrange(10)]) print i ``` This prints "9". However, if I use a generator, it doesn't write to a local variable: ``` i = 0 test = any(i == 2 for i in xrange(10)) print i ``` This prints "0". Is there any ...
> Personally, it would seem better to me if list comprehensions didn't write to local variables. You are correct. This is fixed in Python 3.x. The behavior is unchanged in 2.x so that it doesn't impact existing code that (ab)uses this hole.
Why do list comprehensions write to the loop variable, but generators don't?
19,848,082
71
2013-11-07T22:32:57Z
19,848,124
15
2013-11-07T22:35:28Z
[ "python", "python-2.7", "generator", "list-comprehension" ]
If I do something with list comprehensions, it writes to a local variable: ``` i = 0 test = any([i == 2 for i in xrange(10)]) print i ``` This prints "9". However, if I use a generator, it doesn't write to a local variable: ``` i = 0 test = any(i == 2 for i in xrange(10)) print i ``` This prints "0". Is there any ...
As [PEP 289](http://www.python.org/dev/peps/pep-0289/) (Generator Expressions) explains: > The loop variable (if it is a simple variable or a tuple of simple variables) is not exposed to the surrounding function. This facilitates the implementation and makes typical use cases more reliable. It appears to have been do...
Why do list comprehensions write to the loop variable, but generators don't?
19,848,082
71
2013-11-07T22:32:57Z
19,848,168
70
2013-11-07T22:38:45Z
[ "python", "python-2.7", "generator", "list-comprehension" ]
If I do something with list comprehensions, it writes to a local variable: ``` i = 0 test = any([i == 2 for i in xrange(10)]) print i ``` This prints "9". However, if I use a generator, it doesn't write to a local variable: ``` i = 0 test = any(i == 2 for i in xrange(10)) print i ``` This prints "0". Is there any ...
Python’s creator, Guido van Rossum, mentions this when he wrote about [generator expressions](http://python-history.blogspot.de/2010/06/from-list-comprehensions-to-generator.html) that were uniformly built into Python 3: (emphasis mine) > We also made another change in Python 3, to improve equivalence between list c...
Error loading DLL in python, not a valid win32 application
19,849,077
17
2013-11-07T23:49:03Z
27,910,041
12
2015-01-12T20:16:01Z
[ "python", "dll", "ctypes" ]
I am trying to load a DLL in python to call functions. ``` import ctypes from ctypes import * dsusb = ctypes.WinDLL('c:\python27\dsusb.dll') ``` I get the following error in my stack. ``` C:\Python27>python test.py Traceback (most recent call last): File "test.py", line 4, in <module> dsusb = ctypes.WinDLL('c...
As the comments suggest, it could be an architecture problem. If you're using a 32bit DLL with 64bit Python, or vice-versa, then you'll probably get errors. Since I've had your error before, I recommend trying to load your DLL with 32bit Python.
How would I make a random hexdigit code generator using .join and for loops?
19,849,789
5
2013-11-08T01:03:03Z
19,849,950
8
2013-11-08T01:22:03Z
[ "python", "string", "join", "for-loop", "random" ]
I am new to programming and one assignment I have to do is create a random hexdigit colour code generator using for loops and .join. Is my program below even close to how you do it, or is it completely off? And, is there a way to make a random amount of numbers and letters appear within 6? ``` import random str = ("A"...
Strings can be iterated over, so my code would look like this. ``` import random def gen_hex_colour_code(): return ''.join([random.choice('0123456789ABCDEF') for x in range(6)]) if __name__ == '__main__': print gen_hex_colour_code() ``` results in ``` In [8]: 9F04A4 In [9]: C9B520 In [10]: DAF3E3 In [11]...
How to compile a string of Python code into a module whose functions can be called?
19,850,143
7
2013-11-08T01:44:50Z
19,850,183
11
2013-11-08T01:49:03Z
[ "python" ]
In Python, I have a string of some Python source code containing functions like: ``` mySrc = ''' def foo(): print("foo") def bar(): print("bar") ''' ``` I'd like to compile this string into some kind of **module-like object** so I can call the functions contained in the code. Here's pseudo-code for what I'd...
You have to both compile and execute it: ``` myMod = compile(mySrc, '', 'exec') exec(myMod) foo() ``` You can pass dicts to `exec` to stop `foo` from “leaking” out. Combine it with a module object created using `types.ModuleType`: ``` from types import ModuleType … compiled = compile(mySrc, '', 'exec') module ...
Rename Pandas DataFrame Index
19,851,005
24
2013-11-08T03:19:20Z
19,851,521
57
2013-11-08T04:19:28Z
[ "python", "pandas", "dataframe" ]
I've a csv file without header, with a DateTime index. I want to rename the index and column name, but with df.rename() only the column name is renamed. Bug? I'm on version 0.12.0 ``` In [2]: df = pd.read_csv(r'D:\Data\DataTimeSeries_csv//seriesSM.csv', header=None, parse_dates=[[0]], index_col=[0] ) In [3]: df.head(...
The `rename` method takes a dictionary for the index which applies to index *values*. You want to rename to index level's name: ``` df.index.names = ['Date'] ``` *A good way to think about this is that columns and index are the same type of object (`Index` or `MultiIndex`), and you can interchange the two via trans...
How to pull X amounts of previous data into row in CSV
19,851,304
4
2013-11-08T03:53:02Z
19,986,246
11
2013-11-14T19:09:20Z
[ "python", "date", "datetime", "python-2.7", "csv" ]
I have a very large CSV of data, and I need to append previous data to each row for each name in the column 2 for dates previous to the current one stipultated in column2. I think the easiest way to represent this problem is to provide a detailed example similar to my real data, but scaled down significantly: ``` Data...
It appears your file is in date order. If we take the last entry per name per date, and add that to a sized deque for each name while writing out each row, that should do the trick: ``` import csv from collections import deque, defaultdict from itertools import chain, islice, groupby from operator import itemgetter #...
Django Project: django-admin.py: command not found
19,851,666
3
2013-11-08T04:35:04Z
19,851,733
8
2013-11-08T04:42:08Z
[ "python", "django", "python-2.7", "web" ]
I'm trying to create a Django project. I've looked up solutions everywhere and it is still not working. I am running Python 2.7 and Django 1.3.1. I have tried to create a symbolic link but it doesn't work because django-admin.py already exists. Here is the bash: ``` user@user:~$ django-admin.py startproject mysite ...
``` user@user:~$ django-admin startproject mysite ```
run nosetests in all subdirectories
19,852,548
3
2013-11-08T05:57:34Z
19,872,576
7
2013-11-09T05:08:16Z
[ "python", "python-3.x", "nose" ]
I can run tests in `workflow` folder with `nosetests`: ``` workflow maks$ nosetests .......... ---------------------------------------------------------------------- Ran 10 tests in 0.093s OK ``` my tests live in `test` folder: ``` workflow maks$ ls __pycache__ iterations.py test data iteration...
If you make your `workflow` folder a module by placing `__init__.py` in it, nose should be able to find your tests.
How to keep multiple independent celery queues?
19,853,378
15
2013-11-08T07:07:08Z
21,328,806
26
2014-01-24T09:21:15Z
[ "python", "celery" ]
I'm trying to keep multiple celery queues with different tasks and workers in the same redis database. Really just a convenience issue of only wanting one redis server rather than two on my machine. I followed the celery tutorial docs verbatim, as it as the only way to get it to work for me. Now when I try to duplicat...
By default everything goes into a default queue named `celery` (and this is what `celery worker` will process if no queue is specified) So say you have your `do_work` task function in `django_project_root/myapp/tasks.py`. You could configure the `do_work` task to live in it's own queue like so: ``` CELERY_ROUTES = {...
In-place row-wise operation on pandas DataFrame
19,853,554
6
2013-11-08T07:18:24Z
19,853,804
9
2013-11-08T07:36:28Z
[ "python", "pandas" ]
Suppose I have this: ``` >>> x = pandas.DataFrame([[1.0, 2.0, 3.0], [3, 4, 5]], columns=["A", "B", "C"]) >>> print x A B C 0 1 2 3 1 3 4 5 ``` Now I want to normalize `x` by row --- that is, divide each row by its sum. As described in [this question](http://stackoverflow.com/questions/18594469/normalizing-...
You can do this directly in numpy (without creating a copy): ``` In [11]: x1 = x.values.T In [12]: x1 Out[12]: array([[ 1., 3.], [ 2., 4.], [ 3., 5.]]) In [13]: x1 /= x1.sum(0) In [14]: x Out[14]: A B C 0 0.166667 0.333333 0.500000 1 0.250000 0.333333 0.416667 ``` ...
How to install SIP and PyQt on a virtual environment?
19,856,927
11
2013-11-08T10:36:17Z
21,974,281
11
2014-02-23T20:45:33Z
[ "python", "pyqt", "virtualenv" ]
I am new to `virtualenv`. I want to install spyder, which require `PyQt4`, which requires `SIP`. `pip` doesn't work, so I downloaded `SIP`, and I did the following commands: ``` python configure.py make make install ``` But I received this error: ``` make[1]: entrant dans le répertoire « /stck2/stck2.2/ptoniato/p...
Here are the steps I used to install sip in my virtualenv. The trick is to make sure that you use the (undocumented?) `--always-copy` flag, so that it doesn't just *symlink* the `/usr/include/python2.7` directory into your `virtualenv`. ``` virtualenv --always-copy ve . ve/bin/activate wget http://sourceforge.net/proj...
OSX Mavericks broken pip and virtualenv
19,857,672
11
2013-11-08T11:12:16Z
20,292,078
22
2013-11-29T19:11:19Z
[ "python", "pip", "osx-mavericks" ]
Upgraded to OSX Mavericks and everything broke. I have tried the "sudo easy\_install pip" trick and it seems to pup pip somewhere else: ``` Best match: pip 1.4.1 Processing pip-1.4.1-py2.7.egg pip 1.4.1 is already the active version in easy-install.pth Installing pip script to /Library/Frameworks/Python.framework/Vers...
Probably you have used `easy_install` to install `pip` and the mixture of both py package manage tools lead to the `pkg_resources.DistributionNotFound` problem. To fix it, run: ``` easy_install --upgrade pip ```
What is the reliable method to find most time consuming part of the code?
19,857,749
22
2013-11-08T11:16:11Z
19,857,889
34
2013-11-08T11:22:17Z
[ "python", "profiling", "performance" ]
Along my source code I try to capture and measure the time release of a segment in Python. How can I measure that segment pass time in a convenient way with good precision?
Use a **profiler**. Python's [`cProfile`](http://docs.python.org/2/library/profile.html#module-cProfile) is included in the standard libary. For an even more convenient way, use the package [`profilestats`](https://pypi.python.org/pypi/profilestats/). Then you can use a decorator to just decorate the functions you wa...
check if a string contains a number
19,859,282
44
2013-11-08T12:37:06Z
19,859,308
55
2013-11-08T12:38:23Z
[ "python", "string" ]
Most of the questions I've found are biased on the fact they're looking for letters in their numbers, whereas I'm looking for numbers in what I'd like to be a numberless string. I need to enter a string and check to see if it contains any numbers and if it does reject it. the function isdigit() only returns true if AL...
You can use [`any`](https://docs.python.org/3/library/functions.html#any) function, with the [`str.isdigit`](https://docs.python.org/3/library/stdtypes.html#str.isdigit) function, like this ``` >>> def hasNumbers(inputString): ... return any(char.isdigit() for char in inputString) ... >>> hasNumbers("I own 1 dog"...
check if a string contains a number
19,859,282
44
2013-11-08T12:37:06Z
19,859,340
12
2013-11-08T12:39:57Z
[ "python", "string" ]
Most of the questions I've found are biased on the fact they're looking for letters in their numbers, whereas I'm looking for numbers in what I'd like to be a numberless string. I need to enter a string and check to see if it contains any numbers and if it does reject it. the function isdigit() only returns true if AL...
You can use a combination of [`any`](http://docs.python.org/2/library/functions.html#any), [`str.isdigit`](https://docs.python.org/3/library/stdtypes.html#str.isdigit) and [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions): ``` def num_there(s): return any(i.isdigit() f...
check if a string contains a number
19,859,282
44
2013-11-08T12:37:06Z
31,861,306
7
2015-08-06T16:40:54Z
[ "python", "string" ]
Most of the questions I've found are biased on the fact they're looking for letters in their numbers, whereas I'm looking for numbers in what I'd like to be a numberless string. I need to enter a string and check to see if it contains any numbers and if it does reject it. the function isdigit() only returns true if AL...
<https://docs.python.org/2/library/re.html> You should better use regular expression. It's much faster. ``` import re def f1(string): return any(i.isdigit() for i in string) def f2(string): return re.search('\d', string) # if you compile the regex string first, it's even faster RE_D = re.compile('\d') de...
Excluding directories in os.walk
19,859,840
47
2013-11-08T13:06:31Z
19,859,907
90
2013-11-08T13:10:41Z
[ "python" ]
I'm writing a script that descends into a directory tree (using os.walk()) and then visits each file matching a certain file extension. However, since some of the directory trees that my tool will be used on also contain sub directories that in turn contain a **LOT** of useless (for the purpose of this script) stuff, I...
Modifying `dirs` *in-place* will prune the (subsequent) files and directories visited by `os.walk`: ``` # exclude = set([...]) for root, dirs, files in os.walk(top, topdown=True): dirs[:] = [d for d in dirs if d not in exclude] ``` --- From help(os.walk): > When topdown is true, the caller can modify the dirnam...
Using a Python list comprehension a bit like a zip
19,860,098
4
2013-11-08T13:21:08Z
19,860,135
7
2013-11-08T13:22:57Z
[ "python", "list", "list-comprehension" ]
Ok, so I'm really bad at writing Python list comprehensions with more than one "for," but I want to get better at it. I want to know for sure whether or not the line ``` >>> [S[j]+str(i) for i in range(1,11) for j in range(3) for S in "ABCD"] ``` can be amended to return something like `["A1","B1","C1","D1","A2","B2"...
You have too many loops there. You don't need `j` at all. This does the trick: ``` [S+str(i) for i in range(1,11) for S in "ABCD"] ```
python: remove all rows in pandas dataframe that contain a string
19,860,389
14
2013-11-08T13:36:55Z
19,861,545
12
2013-11-08T14:34:17Z
[ "python", "pandas", "dataframe" ]
I've got a pandas dataframe called data and I want to remove all rows that contain a string in any column. For example, below we see the 'gdp' column has a string at index 3, and 'cap' at index 1. ``` data = y gdp cap 0 1 2 5 1 2 3 ab 2 8 7 2 3 3 bc 7 4 6 7 7 5 4 8 ...
You can apply a function that tests row-wise your `DataFrame` for the presence of strings, e.g., say that `df` is your `DataFrame` ``` rows_with_strings = df.apply( lambda row : any([ isinstance(e, basestring) for e in row ]) , axis=1) ``` This will produce a mask for your DataFrame indicat...
Convert images to webP using Pillow
19,860,639
5
2013-11-08T13:49:49Z
19,861,234
7
2013-11-08T14:19:37Z
[ "python", "python-imaging-library", "webp", "pillow" ]
I'm trying to convert .jpg images to webp format using [PIL](https://pypi.python.org/pypi/Pillow/). I'm using the this code: ``` from PIL import Image import glob, os for infile in glob.glob("*.jpg"): file, ext = os.path.splitext(infile) im = Image.open(infile).convert("RGB") im.save(file + ".webp", "WEB...
Make sure to install `WEBP` dev library for your OS. For Debian/Ubuntu it's `libwebp-dev`. You may need reinstall Pillow as well. In the output of Pillow install log you should see: ``` --- WEBP support available ```
composition and aggregation in python
19,861,785
2
2013-11-08T14:45:13Z
19,863,217
11
2013-11-08T15:53:38Z
[ "python" ]
I want to know how to implement composition and aggregation in **UML terms** in python. If I understood: 1. Aggregation: ``` class B: pass class A(object): def __init__(self): self.B = B ``` 2. Composition: In other languages I saw this implemented as a pointer to B. I guess here `self.B` is a poi...
[If I understand correctly](http://aviadezra.blogspot.ca/2009/05/uml-association-aggregation-composition.html), aggregation vs composition is about the responsibilities of an object to its members (e.g. if you delete an instance, do you also delete its members?). Mainly, it will depend a lot on the implementation. For...
matplotlib change linewidth on line segments, using list
19,862,011
3
2013-11-08T14:57:29Z
19,863,106
7
2013-11-08T15:49:02Z
[ "python", "matplotlib" ]
I would like to be able to change width of a line according to a list of values. For example if I have the following list to plot: a = [0.0, 1.0, 2.0, 3.0, 4.0] could I use the following list to set the linewidth? b = [1.0, 1.5, 3.0, 2.0, 1.0] It doesn't seem to be supported, but they say "anything is possible" so ...
Basically, you have two options. 1. Use a `LineCollection`. In this case, your line widths will be in points, and the line width will be constant for each segment. 2. Use a polygon (easiest with `fill_between`, but for complex curves you may need to create it directly). In this case, your line widths will be in data u...
matplotlib legend background color
19,863,368
18
2013-11-08T16:00:32Z
19,863,736
16
2013-11-08T16:17:50Z
[ "python", "matplotlib" ]
Is there while `rcParams['legend.frameon'] = 'False'` a simple way to fill the legend area background with a given colour. More specifically I would like the grid not to be seen on the legend area because it disturbs the text reading. The keyword `framealpha` sounds like what I need but it doesn't change anything. ``...
You can set the edge color and the face color separately like this: ``` frame.set_facecolor('green') frame.set_edgecolor('red') ``` There's more information under FancyBboxPatch [here](http://matplotlib.org/api/artist_api.html).
python: convert numerical data in pandas dataframe to floats in the presence of strings
19,864,028
7
2013-11-08T16:31:58Z
19,866,269
15
2013-11-08T18:40:05Z
[ "python", "pandas", "dataframe" ]
I've got a pandas dataframe with a column 'cap'. This column mostly consists of floats but has a few strings in it, for instance at index 2. ``` df = cap 0 5.2 1 na 2 2.2 3 7.6 4 7.5 5 3.0 ... ``` I import my data from a csv file like so: ``` df = DataFrame(pd.read_csv(myfile.file)) ``` Unfort...
*Calculations with columns of float64 dtype (rather than object) are much more efficient, so this is usually preferred... it will also allow you to do other calculations. Because of this is [recommended to use NaN for missing data](http://stackoverflow.com/questions/17534106/what-is-the-difference-between-nan-and-none/...
Python: Reverse DNS Lookup in a shared hosting
19,867,548
2
2013-11-08T19:59:01Z
19,867,936
8
2013-11-08T20:27:08Z
[ "python", "shared-hosting", "reverse-lookup" ]
Is there any way to do a reverse lookup using python, to check the list of websites sharing the same IP address in a shared hosting. [Some web sites](http://www.yougetsignal.com/tools/web-sites-on-web-server/) offer a tool for this purpose .
# DNSPython Technically, you can use [DNSPython](http://www.dnspython.org/) to do a reverse lookup. Pip install it ``` $ pip install dnspython ``` Then do your reverse query: ``` >>> from dns import resolver >>> from dns import reversename >>> addr = reversename.from_address("74.125.227.114") >>> resolver.query(ad...
Changing certain values in multiple columns of a pandas DataFrame at once
19,867,734
14
2013-11-08T20:11:35Z
19,867,768
24
2013-11-08T20:14:12Z
[ "python", "pandas" ]
Suppose I have the following DataFrame: ``` In [1]: df Out[1]: apple banana cherry 0 0 3 good 1 1 4 bad 2 2 5 good ``` This works as expected: ``` In [2]: df['apple'][df.cherry == 'bad'] = np.nan In [3]: df Out[3]: apple banana cherry 0 0 3 good 1 NaN 4 bad ...
You should use loc and do this **without chaining**: ``` In [11]: df.loc[df.cherry == 'bad', ['apple', 'banana']] = np.nan In [12]: df Out[12]: apple banana cherry 0 0 3 good 1 NaN NaN bad 2 2 5 good ``` *See the docs on [returning a view vs a copy](http://pandas.pydata.org/p...
Group a list by word length
19,868,075
2
2013-11-08T20:37:25Z
19,868,092
9
2013-11-08T20:38:15Z
[ "python", "list" ]
For example, I have a list, say ``` list = ['sight', 'first', 'love', 'was', 'at', 'It'] ``` I want to group this list by word length, say ``` newlist = [['sight', 'first'],['love'], ['was'], ['at', 'It']] ``` Please help me on it. Appreciation!
Use `itertools.groupby`: ``` >>> from itertools import groupby >>> lis = ['sight', 'first', 'love', 'was', 'at', 'It'] >>> [list(g) for k, g in groupby(lis, key=len)] [['sight', 'first'], ['love'], ['was'], ['at', 'It']] ``` Note that for `itertools.groupby` to work properly all the items must be sorted by length, ot...
Find (bash command) doesn't work with subprocess?
19,868,457
2
2013-11-08T21:03:21Z
19,868,520
8
2013-11-08T21:08:25Z
[ "python", "sed", "find", "subprocess", "xargs" ]
I have renamed a css class name in a number of (python-django) templates. The css files however are wide-spread across multiple files in multiple directories. I have a python snippet to start renaming from the root dir and then recursively rename all the css files. ``` from os import walk, curdir import subprocess CO...
You're not trying to run a single command, but a shell pipeline of multiple commands, and you're trying to do it without invoking the shell. That can't possibly work. The way you're doing this, `|` is just one of the arguments to `find`, which is why `find` is telling you that it doesn't understand that argument with t...
Set line colors according to colormap
19,868,548
2
2013-11-08T21:10:22Z
19,868,688
9
2013-11-08T21:20:20Z
[ "python", "matplotlib" ]
I have a series of lines stored in a list like so: ``` line_list = [line_1, line_2, line_3, ..., line_M] ``` where each `line_i` is a sub-list composed of two sub-sub-lists, one for the x coordinates and the other for the y coordinates: ``` line_i = [[x_1i, x2_i, .., x_Ni], [y_1i, y_2i, .., y_Ni]] ``` I also have a...
It's easiest to use a `LineCollection` for this. In fact, it expects the lines to be in a similar format to what you already have. To color the lines by a third variable, just specify the `array=floats_list`. As an example: ``` import numpy import matplotlib.pyplot as plt from matplotlib.collections import LineCollect...
How do I sort a list with "Nones last"
19,868,767
5
2013-11-08T21:25:38Z
19,868,837
14
2013-11-08T21:29:46Z
[ "python", "list", "sorting" ]
I'm sorting a list of dicts by a key: ``` groups = sorted(groups, key=lambda a: a['name']) ``` some of the dicts have name set to `None`, and Python 2 places `None` values before any other, so they're placed at the front of the sorted list. A naive fix would be ``` groups = sorted(groups, key=lambda a: a['name'] or ...
You can do this by keying it on a tuple: ``` groups = sorted(groups, key=lambda a: (a['name'] is None, a['name'])) ``` --- This works because Python compares tuples lexicographically (on the first element, then on the second to break ties), and because False gets sorted earlier than True. A list of groups like ``` ...
Why I am suddenly seeing `Usage: source deactivate` whenever I run virtualenvwrapper commands?
19,869,059
15
2013-11-08T21:45:37Z
24,071,615
12
2014-06-05T23:03:32Z
[ "python", "virtualenvwrapper", "anaconda" ]
I never used to see this message before when using virtualenvwrapper, but now I'm suddenly seeing this message whenever I run, say, `mkvirtualenv <environment>` or `workon <environment>`: ``` Usage: source deactivate removes the 'bin' directory of the environment activated with 'source activate' from PATH. ``` I hav...
`workon`, which is defined in `/usr/local/bin/virtualenvwrapper.sh`, calls `deactivate`. A script of the same name is present in Anaconda's bin, so it gets called by workon. The best solution I've found so far is to rename activate and deactivate in Anaconda's bin. If there's a better solution, please comment and I'll...
Equivalent of transform in R/ddply in Python/pandas?
19,870,745
9
2013-11-09T00:14:25Z
19,870,814
14
2013-11-09T00:21:44Z
[ "python", "pandas", "plyr" ]
In R's ddply function, you can compute any new columns group-wise, and append the result to the original dataframe, such as: ``` ddply(mtcars, .(cyl), transform, n=length(cyl)) # n is appended to the df ``` In Python/pandas, I have computed it first, and then merge, such as: ``` df1 = mtcars.groupby("cyl").apply(lam...
You can add a column to a DataFrame by assigning the result of a groupby/transform operation to it: ``` mtcars['n'] = mtcars.groupby("cyl")['cyl'].transform('count') ``` --- ``` import pandas as pd import pandas.rpy.common as com mtcars = com.load_data('mtcars') mtcars['n'] = mtcars.groupby("cyl")['cyl'].transform(...
Why is some code Deterministic in Python2 and Non-Deterministic in Python 3?
19,872,253
16
2013-11-09T04:08:45Z
19,872,287
28
2013-11-09T04:16:46Z
[ "python", "string", "python-3.x", "bioinformatics", "non-deterministic" ]
I'm trying to write a script to calculate all of the possible fuzzy string match matches to for a short string, or 'kmer', and the same code that works in Python 2.7.X gives me a non-deterministic answer with Python 3.3.X, and I can't figure out why. I iterate over a dictionary, itertools.product, and itertools.combin...
**If** by "non-deterministic" you mean the order in which dictionary keys appear (when you iterate over a dictionary) changes from run to run, and the dictionary keys are strings, please say so. Then I can help. But so far you haven't said any of that ;-) Assuming that's the problem, here's a little program: ``` d = ...
Python - sort lists based on their sum
19,872,530
3
2013-11-09T05:00:51Z
19,872,546
8
2013-11-09T05:02:56Z
[ "python", "list", "sorting" ]
I want to sort a list that contains lists based on the sum of each inner list. here's the current snippet I've got ``` vectors = [] for i in range(0, 10): vectors.append(generate_vector()) # generate_vector() works, creates a list for vector in vectors: coin_list = findbest(vector) # findbest(vector) outputs...
You can use the `key` param in sorted function ``` data = [[1,2,3], [14, 7], [5, 6, 1]] print sorted(data, key=sum) ``` **Output** ``` [[1, 2, 3], [5, 6, 1], [14, 7]] ``` If you want to sort inplace ``` data = [[1,2,3], [14, 7], [5, 6, 1]] data.sort(key=sum) print data ``` **Output** ``` [[1, 2, 3], [5, 6, 1], [...
UnicodeDecodeError while using json.dumps()
19,872,773
6
2013-11-09T05:40:23Z
19,872,879
13
2013-11-09T05:54:18Z
[ "python", "json", "python-2.7", "unicode" ]
I have strings as follows in my python list (taken from command prompt): ``` >>> o['records'][5790] (5790, 'Vlv-Gate-Assy-Mdl-\xe1M1-2-\xe19/16-10K-BB Credit Memo ', 60, True, '40141613') >>> ``` I have tried suggestions as mentioned here: [Changing default encoding of Python?](http://stackoverflow.com/qu...
`\xe1` is not decodable using utf-8, utf-16 encoding. ``` >>> '\xe1'.decode('utf-8') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode...
error when compiling cx_Freeze on Ubuntu
19,873,673
13
2013-11-09T07:48:11Z
26,356,331
8
2014-10-14T08:44:04Z
[ "python", "ubuntu", "python-3.x", "cx-freeze", "linuxmint" ]
I'm using Python 3.3.2 on Ubuntu , when I compiled cx\_Freeze from source ,the following error occurred ,any ideas? ``` philip@linuxmint ~/cx_Freeze-4.3.2 $ sudo python3 setup.py install [sudo] password for philip: adding base module named _dummy_thread adding base module named _frozen_importlib adding base module na...
Change file setup.py from ``` if not vars.get("Py_ENABLE_SHARED", 0): vars = distutils.sysconfig.get_config_vars() if not vars.get("Py_ENABLE_SHARED", 0): ``` to ``` if True: vars = distutils.sysconfig.get_config_vars() if True: ``` Remember to install python(3)-dev a...
Removing empty elements from an array in Python
19,875,595
4
2013-11-09T11:52:29Z
19,875,634
13
2013-11-09T11:55:12Z
[ "python", "arrays", "file", "elements" ]
``` with open("text.txt", 'r') as file: for line in file: line = line.rstrip('\n' + '').split(':') print(line) ``` I am having trouble trying to remove empty lists in the series of arrays that are being generated. I want to make every line an array in `text.txt`, so I would have the ability to accu...
Since I can't see your exact line, its hard to give you a solution that matches your requirements perfectly, but if you want to get all the elements in a list that are not empty strings, then you can do this: ``` >>> l = ["ch", '', '', 'e', '', 'e', 'se'] >>> [var for var in l if var] Out[4]: ['ch', 'e', 'e', 'se'] ``...
Django gives Bad Request (400) when DEBUG = False
19,875,789
164
2013-11-09T12:11:41Z
19,875,816
273
2013-11-09T12:14:22Z
[ "python", "django" ]
I am new to django-1.6. When I run the django server with `DEBUG = True`, it's running perfectly. But when I change `DEBUG` to `False` in the settings file, then the server stopped and it gives the following error on the command prompt: ``` CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. ``` Afte...
The [`ALLOWED_HOSTS` list](https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts) should contain fully qualified *host names*, **not** urls. Leave out the port and the protocol. If you are using `127.0.0.1`, I would add `localhost` to the list too: ``` ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] ``` You co...
OpenCV - cannot find module cv2
19,876,079
21
2013-11-09T12:44:32Z
21,131,649
11
2014-01-15T07:42:03Z
[ "python", "opencv", "raspberry-pi" ]
I have installed OpenCV on the Occidentalis operating system (a variant of Raspbian) on a Raspberry Pi, using jayrambhia's script found here: <https://github.com/jayrambhia/Install-OpenCV/blob/master/Ubuntu/opencv_latest.sh>. It installed version 2.4.5. When I try to import the module cv2 in a python program, I get th...
Try to add the following line in `~/.bashrc` ``` export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH ```
OpenCV - cannot find module cv2
19,876,079
21
2013-11-09T12:44:32Z
21,511,572
26
2014-02-02T14:14:38Z
[ "python", "opencv", "raspberry-pi" ]
I have installed OpenCV on the Occidentalis operating system (a variant of Raspbian) on a Raspberry Pi, using jayrambhia's script found here: <https://github.com/jayrambhia/Install-OpenCV/blob/master/Ubuntu/opencv_latest.sh>. It installed version 2.4.5. When I try to import the module cv2 in a python program, I get th...
This happens when python cannot refer to your default site-packages folder where you have kept the required python files or libraries Add these lines in the code: ``` import sys sys.path.append('/usr/local/lib/python2.7/site-packages') ``` or before running the python command in bash move to */usr/local/lib/python2...
OpenCV - cannot find module cv2
19,876,079
21
2013-11-09T12:44:32Z
35,546,806
7
2016-02-22T06:07:26Z
[ "python", "opencv", "raspberry-pi" ]
I have installed OpenCV on the Occidentalis operating system (a variant of Raspbian) on a Raspberry Pi, using jayrambhia's script found here: <https://github.com/jayrambhia/Install-OpenCV/blob/master/Ubuntu/opencv_latest.sh>. It installed version 2.4.5. When I try to import the module cv2 in a python program, I get th...
I solved my issue using the following command : ``` conda install opencv ```
Print string over plotted line (mimic contour plot labels)
19,876,882
13
2013-11-09T14:06:07Z
19,883,433
16
2013-11-09T21:39:30Z
[ "python", "matplotlib" ]
The [contour plot demo](http://matplotlib.org/examples/pylab_examples/contour_demo.html) shows how you can plot the curves with the level value plotted over them, see below. ![enter image description here](http://i.stack.imgur.com/nRnFP.png) Is there a way to do this same thing for a simple line plot like the one obt...
You could simply add some text ([MPL Gallery](http://matplotlib.org/examples/pylab_examples/fancytextbox_demo.html)) like ``` import matplotlib.pyplot as plt import numpy as np x = [1.81,1.715,1.78,1.613,1.629,1.714,1.62,1.738,1.495,1.669,1.57,1.877,1.385] y = [0.924,0.915,0.914,0.91,0.909,0.905,0.905,0.893,0.886,0.8...
python module import - relative paths issue
19,876,993
9
2013-11-09T14:17:21Z
19,877,478
18
2013-11-09T15:12:19Z
[ "python", "module" ]
I'm developing my own module in python 2.7. It resides in `~/Development/.../myModule` instead of `/usr/lib/python2.7/dist-packages` or `/usr/lib/python2.7/site-packages`. The internal structure is: ``` /project-root-dir /server __init__.py service.py http.py /client __init__.py client.py ``` ...
# My Python development workflow This is a basic process to develop Python packages that incorporates what I believe to be the best practices in the community. It's basic - if you're really serious about developing Python packages, there still a bit more to it, and everyone has their own preferences, but it should ser...
NameError: global name 'unicode' is not defined - in Python 3
19,877,306
24
2013-11-09T14:51:49Z
19,877,309
38
2013-11-09T14:52:17Z
[ "python", "unicode", "python-3.x", "nameerror", "bidi" ]
I am trying to use a Python package called bidi. In a module in this package (algorithm.py) there are some lines that give me error, although it is part of the package. Here are the lines: ``` # utf-8 ? we need unicode if isinstance(unicode_or_str, unicode): text = unicode_or_str decoded = False else: tex...
Python 3 renamed the `unicode` type to `str`, the old `str` type has been replaced by `bytes`. ``` if isinstance(unicode_or_str, str): text = unicode_or_str decoded = False else: text = unicode_or_str.decode(encoding) decoded = True ``` You may want to read the [Python 3 porting HOWTO](http://docs.pyt...
dev_appserver.py: command not found
19,877,869
6
2013-11-09T15:52:00Z
19,878,020
8
2013-11-09T16:04:38Z
[ "python", "google-app-engine", "ubuntu" ]
Trying to run a python app on Google app engine in Ubuntu like so ``` $ dev_appserver.py helloworld ``` where helloworld contains the file app.yaml but I am getting this error > dev\_appserver.py: command not found
After downloading the App Engine source files you will have to add the directory in the path in order to be able to execute that script file. Open your `.bashrc` file that is located in the home directory and this line with the correct path ([read more](http://askubuntu.com/q/60218/1173)): ``` export PATH=/path/to/go...
sum value of two different dictionaries which is having same key
19,882,641
3
2013-11-09T20:24:16Z
19,882,686
7
2013-11-09T20:28:16Z
[ "python" ]
i am having two dictionaries ``` first = {'id': 1, 'age': 23} second = {'id': 4, 'out': 100} ``` I want output dictionary as ``` {'id': 5, 'age': 23, 'out':100} ``` I tried ``` >>> dict(first.items() + second.items()) {'age': 23, 'id': 4, 'out': 100} ``` but i am getting id as 4 but i want to it to be 5 .
You want to use [collections.Counter](http://docs.python.org/2/library/collections.html#collections.Counter): ``` from collections import Counter first = Counter({'id': 1, 'age': 23}) second = Counter({'id': 4, 'out': 100}) first_plus_second = first + second print first_plus_second ``` Output: ``` Counter({'out': ...
what is difference between (**) and (<<) in python?
19,882,922
3
2013-11-09T20:50:08Z
19,882,996
8
2013-11-09T20:56:17Z
[ "python", "bit-shift", "exponent" ]
``` a = 100000000 c = (2**(a-1))-1 b = (2<<(a-1))-1 m = 1000000007 print b%m print c%m ``` Output : ``` 494499947 247249973 ``` I am using \*\* and << operator in python to find powers of 2 raised to a very large number . However similar operations give different result. Just curious why?
The results are different because the equivalent of `2 ** n` is `1 << n`, not `2 << n`.
Python: Collections.Counter vs defaultdict(int)
19,883,015
8
2013-11-09T20:57:46Z
19,883,180
15
2013-11-09T21:14:03Z
[ "python" ]
Suppose I have some data that looks like the following. ``` Lucy = 1 Bob = 5 Jim = 40 Susan = 6 Lucy = 2 Bob = 30 Harold = 6 ``` I want to combine 1) remove duplicate keys, and 2) add the values for these duplicate keys. That means I'd get the key/values: ``` Lucy = 3 Bob = 35 Jim = 40 Susan = 6 Harold = 6 ``` Woul...
Both `Counter` and `defaultdict(int)` can work fine here, but there are few differences between them: * `Counter` supports most of the operations you can do on a [multiset](http://en.wikipedia.org/wiki/Multiset). So, if you want to use those operation then go for Counter. * `Counter` won't add new keys to the dict whe...
Binary as list of 1s and 0s to int
19,883,285
4
2013-11-09T21:24:34Z
19,883,308
14
2013-11-09T21:26:25Z
[ "python" ]
I would like to convert a list of integer 1s and 0s which represent a binary number to an int. something along the lines of: ``` >>> [1,1,0,1].toint() ``` would give an output of `13`
Strings are unnecessary here: ``` >>> l = [1,1,0,1] >>> >>> sum(j<<i for i,j in enumerate(reversed(l))) 13 ``` --- **Relevant documentation:** * [`sum()`](http://docs.python.org/3/library/functions.html#sum) * [`enumerate()`](http://docs.python.org/3/library/functions.html#enumerate) * [`reversed()`](http://docs.p...
Python: `from x import *` not importing everything
19,883,870
3
2013-11-09T22:27:13Z
19,883,892
8
2013-11-09T22:29:31Z
[ "python", "python-import" ]
I know that `import *` is bad, but I sometimes use it for quick prototyping when I feel too lazy to type or remember the imports I am trying the following code: ``` from OpenGL.GL import * shaders.doSomething() ``` It results in an error: `NameError: global name 'shaders' is not defined' If I change the imports: ...
If `shaders` is a submodule and [it’s not included in `__all__`](http://docs.python.org/3/tutorial/modules.html#importing-from-a-package), `from … import *` won’t import it. [And yes, it is a submodule.](http://pyopengl.sourceforge.net/documentation/pydoc/OpenGL.GL.shaders.html)
Python Variable "resetting"
19,884,327
9
2013-11-09T23:15:41Z
19,884,337
13
2013-11-09T23:17:11Z
[ "python", "python-2.7" ]
I am setting a string to something in a function, then trying to print it in another to find that the string never changed. Am I doing something wrong? Defining the variable at the top of my script ``` CHARNAME = "Unnamed" ``` Function setting the variable ``` def setName(name): CHARNAME = name prin...
When you do `CHARNAME = name` in the `setName` function, you are defining it *only* for that scope. i.e, it can not be accessed outside of the function. Hence, the *global* vriable `CHARNAME` (the one with the value `"Unnamed"`), is untouched, and you proceed to print its contents after calling the function You aren't...
How do I import modules in pycharm?
19,885,821
45
2013-11-10T03:07:18Z
19,885,882
60
2013-11-10T03:17:31Z
[ "python", "python-2.7", "pycharm", "gnuradio" ]
In *PyCharm*, I've added the Python environment `/usr/bin/python`. However, ``` from gnuradio import gr ``` fails as an *undefined reference*. However, it works fine in the Python interpreter from the command line. GNURadio works fine with python outside of Pycharm. Everything is installed and configured how I want ...
## Adding a Path Go into Settings -> Project Settings -> Project Interpreter. Then press configure interpreter, and navigate to the "Paths" tab. ![pycharm path tab](https://i.imgur.com/Q5pcWDX.jpg) Press the + button in the Paths area. You can put the path to the module you'd like it to recognize. ### But I don't ...
How do I import modules in pycharm?
19,885,821
45
2013-11-10T03:07:18Z
27,007,843
24
2014-11-19T02:22:20Z
[ "python", "python-2.7", "pycharm", "gnuradio" ]
In *PyCharm*, I've added the Python environment `/usr/bin/python`. However, ``` from gnuradio import gr ``` fails as an *undefined reference*. However, it works fine in the Python interpreter from the command line. GNURadio works fine with python outside of Pycharm. Everything is installed and configured how I want ...
My version is PyCharm Professional edition 3.4, and the **Adding a Path** part is different. You can go to "Preferences" --> "Project Interpreter". Choose the tool button at the right top corner. Then choose "More..." --> "Show path for the selected interpreter" --> "Add". Then you can add a path.
How do I import modules in pycharm?
19,885,821
45
2013-11-10T03:07:18Z
32,319,926
12
2015-08-31T21:02:32Z
[ "python", "python-2.7", "pycharm", "gnuradio" ]
In *PyCharm*, I've added the Python environment `/usr/bin/python`. However, ``` from gnuradio import gr ``` fails as an *undefined reference*. However, it works fine in the Python interpreter from the command line. GNURadio works fine with python outside of Pycharm. Everything is installed and configured how I want ...
For me, it was just a matter of marking the directory as a source root.
How do I import modules in pycharm?
19,885,821
45
2013-11-10T03:07:18Z
32,911,111
24
2015-10-02T15:52:52Z
[ "python", "python-2.7", "pycharm", "gnuradio" ]
In *PyCharm*, I've added the Python environment `/usr/bin/python`. However, ``` from gnuradio import gr ``` fails as an *undefined reference*. However, it works fine in the Python interpreter from the command line. GNURadio works fine with python outside of Pycharm. Everything is installed and configured how I want ...
You should never need to modify the path directly, either through environment variables or `sys.path`. Whether you use the os (ex. `apt-get`), or `pip` in a virtualenv, packages will be installed to a location already on the path. In your example, GNU Radio is installed to the system Python 2's standard `site-packages...
Global name 'X' not defined
19,889,493
5
2013-11-10T12:04:57Z
19,889,507
8
2013-11-10T12:06:30Z
[ "python", "global", "nameerror" ]
I looked in all kind of similar questions, but just couldn't find one that fitted my situation (or maybe there is one, but I'm new to programming). The version of Python that I use is 2.7.4, and I get in my program the error on line 11: `NameError: global name 'opp' is not defined` I wanted to make a calculator for d...
You should call your function, otherwise `opp` will not get defined. ``` oppervlakte() print opp ``` But a better way would to return `opp` from the function and assign to a variable in global namespace. ``` def oppervlakte(): lengte = int(raw_input("Voer de lengte in: ")) #call int() here br = int(raw_input...
Save facebook profile picture in model using python-social-auth
19,890,824
6
2013-11-10T14:26:00Z
19,902,090
13
2013-11-11T08:43:31Z
[ "python", "django", "facebook", "django-socialauth" ]
How to store the get Facebook profile picture of a user while logging in through Facebook and saving it in my userprofile model. I found this link which says how to do so using django-social-auth, <https://gist.github.com/kalamhavij/1662930>. but signals is now deprecated and I have to use pipeline. Any idea how can ...
This is how it worked with me. (from <https://github.com/omab/python-social-auth/issues/80>) Add the following code to pipeline.py: ``` from requests import request, HTTPError from django.core.files.base import ContentFile def save_profile_picture(strategy, user, response, details, is_new=...
Updating csv with data from a csv with different formatting
19,892,107
5
2013-11-10T16:28:50Z
20,057,249
9
2013-11-18T20:31:19Z
[ "python", "python-2.7", "csv", "pandas" ]
I'm trying to update a csv file with some student figures provided by other sources however they've formatted their csv data slightly differently to ours. It needs to match students based on three criteras their name, their class and finally the first few letters of the location so for the first few students from Clas...
Here are two solutions: a pandas solution and a plain python solution. First a pandas solution which unsurprisingly looks a whole lot like the other pandas solutions... First load in the data ``` import pandas import numpy as np cdf1 = pandas.read_csv('csv1',dtype=object) #dtype = object allows us to preserve the n...