title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Python Facebook SDK: 'module' object has no attribute 'GraphAPI' | 19,893,523 | 11 | 2013-11-10T18:39:48Z | 19,893,700 | 17 | 2013-11-10T18:54:29Z | [
"python",
"facebook",
"facebook-graph-api",
"module"
] | I am trying to run a basic example with the Facebook SDK for Python. I tried doing exactly what this [tutorial](http://www.slideshare.net/littleq0903/introduction-to-facebook-python-api) does from the command line (with "`pip install facebook`" and "`pip install facebook-sdk`" successfully done first...):
![enter imag... | If you are using Ubuntu or Debian, Just execute the following commands to get this working
```
sudo pip uninstall facebook
sudo pip uninstall facebook-sdk
sudo pip install facebook-sdk
```
For other operating systems, just remove `facebook` and `facebook-sdk` packages and install only `facebook-sdk`.
And then execut... |
Python Facebook SDK: 'module' object has no attribute 'GraphAPI' | 19,893,523 | 11 | 2013-11-10T18:39:48Z | 24,966,359 | 13 | 2014-07-26T00:32:56Z | [
"python",
"facebook",
"facebook-graph-api",
"module"
] | I am trying to run a basic example with the Facebook SDK for Python. I tried doing exactly what this [tutorial](http://www.slideshare.net/littleq0903/introduction-to-facebook-python-api) does from the command line (with "`pip install facebook`" and "`pip install facebook-sdk`" successfully done first...):
![enter imag... | I had the same problem when messing around with facebook-sdk for python the first time. It occured I named my python file "facebook.py", and made unconsiously a name clash. |
can't installing lxml on Ubuntu 12.04 | 19,894,197 | 7 | 2013-11-10T19:39:25Z | 19,897,119 | 26 | 2013-11-11T00:37:05Z | [
"python",
"ubuntu-12.04",
"lxml",
"python-import"
] | I've been trying to install lxml using `pip install lxml` and I get the error below. I've used `apt-get install python-dev libxml2 libxml2-dev libxslt-dev` before (suggested in other answers) but I still get the same error. I did not use control-c.
```
pip install lxml
Downloading/unpacking lxml
Downloading lxml-3.2... | Try this to get the deps:
```
apt-get build-dep python-lxml
``` |
can't installing lxml on Ubuntu 12.04 | 19,894,197 | 7 | 2013-11-10T19:39:25Z | 22,256,546 | 11 | 2014-03-07T17:18:44Z | [
"python",
"ubuntu-12.04",
"lxml",
"python-import"
] | I've been trying to install lxml using `pip install lxml` and I get the error below. I've used `apt-get install python-dev libxml2 libxml2-dev libxslt-dev` before (suggested in other answers) but I still get the same error. I did not use control-c.
```
pip install lxml
Downloading/unpacking lxml
Downloading lxml-3.2... | I had exactly this problem. Turned out to be a memory problem - I was installing reporter.py, which depends on lxml, on a server with only 500MB RAM, of which only 150MB was free. I killed off a few things to get up to ~300MB free, and just managed to squeeze out the installation of lxml. (Watching TOP showed available... |
Regex punctuation split [Python] | 19,894,478 | 10 | 2013-11-10T20:03:15Z | 19,894,514 | 9 | 2013-11-10T20:06:45Z | [
"python",
"regex",
"string",
"split",
"punctuation"
] | Can anyone help me a bit with regexs? I currently have this: `re.split(" +", line.rstrip())`, which separates by spaces.
How could I expand this to cover punctuation, too? | Using `string.punctuation` and character class:
```
>>> from string import punctuation
>>> r = re.compile(r'[\s{}]+'.format(re.escape(punctuation)))
>>> r.split('dss!dfs^ #$% jjj^')
['dss', 'dfs', 'jjj', '']
``` |
Regex punctuation split [Python] | 19,894,478 | 10 | 2013-11-10T20:03:15Z | 19,894,589 | 14 | 2013-11-10T20:12:27Z | [
"python",
"regex",
"string",
"split",
"punctuation"
] | Can anyone help me a bit with regexs? I currently have this: `re.split(" +", line.rstrip())`, which separates by spaces.
How could I expand this to cover punctuation, too? | The official Python documentation has a good example for this one. It will split on all non-alphanumeric characters (whitespace and punctuation). Literally \W is the character class for all Non-Word characters. Note: the underscore "\_" is considered a "word" character and will not be part of the split here.
```
re.sp... |
Can't Start Carbon - 12.04 - Python Error - ImportError: cannot import name daemonize | 19,894,708 | 23 | 2013-11-10T20:22:36Z | 19,916,809 | 21 | 2013-11-11T22:00:25Z | [
"python",
"bash",
"caching",
"carbon"
] | I am really hoping someone can help me as I have spent at-least 15 hours trying to fix this problem. I have been given a task by a potential employer and my solution is to use graphite/carbon/collectd. I am trying to run and install carbon / graphite 0.9.12 but I simply can't get carbon to start. Every time I try and s... | ```
pip install daemonize
```
then I opened /opt/graphite/lib/carbon/util.py and changed
```
from twisted.scripts._twistd_unix import daemonize
```
to
```
import daemonize
``` |
Can't Start Carbon - 12.04 - Python Error - ImportError: cannot import name daemonize | 19,894,708 | 23 | 2013-11-10T20:22:36Z | 19,929,348 | 47 | 2013-11-12T12:35:19Z | [
"python",
"bash",
"caching",
"carbon"
] | I am really hoping someone can help me as I have spent at-least 15 hours trying to fix this problem. I have been given a task by a potential employer and my solution is to use graphite/carbon/collectd. I am trying to run and install carbon / graphite 0.9.12 but I simply can't get carbon to start. Every time I try and s... | ```
pip install 'Twisted<12.0'
```
As you can see in the [requirements.txt](https://github.com/graphite-project/carbon/blob/master/requirements.txt), the newer version of Twisted does not seems to play well with it |
When to use the matplotlib.pyplot class and when to use the plot object (matplotlib.collections.PathCollection) | 19,895,262 | 10 | 2013-11-10T21:13:47Z | 21,004,357 | 7 | 2014-01-08T19:04:53Z | [
"python",
"matplotlib"
] | I wondered what the logic is behind the question when to use the plot instance (which is a `PathCollection`) and when to use the plot class itself.
```
import matplotlib.pyplot as plt
p = plt.scatter([1,2,3],[1,2,3])
```
brings up a scatter plot. To make it work, I have to say:
```
plt.annotate(...)
```
and to conf... | According to PEP20:
* "Explicit is better than implicit."
* "Simple is better than complex."
Oftentimes, the "make-it-just-work" code takes the pyplot route, as it hides away all of the figure and axes management that many wouldn't care about. This is often used for interactive mode coding, simple one-off scripts, or... |
Tkinter - Can't bind arrow key events | 19,895,877 | 6 | 2013-11-10T22:11:00Z | 19,895,973 | 10 | 2013-11-10T22:20:48Z | [
"python",
"tkinter"
] | I am trying to bind the left and right arrow keys to an event in Tkinter, but when I run the program it appears the events are not triggering. Here is the code:
```
from Tkinter import *
main = Tk()
def leftKey(event):
print "Left key pressed"
def rightKey(event):
print "Right key pressed"
frame = Frame(ma... | Try binding to your main variable:
```
from Tkinter import *
main = Tk()
def leftKey(event):
print "Left key pressed"
def rightKey(event):
print "Right key pressed"
frame = Frame(main, width=100, height=100)
main.bind('<Left>', leftKey)
main.bind('<Right>', rightKey)
frame.pack()
main.mainloop()
```
I sho... |
Tkinter - Can't bind arrow key events | 19,895,877 | 6 | 2013-11-10T22:11:00Z | 19,898,392 | 9 | 2013-11-11T03:32:06Z | [
"python",
"tkinter"
] | I am trying to bind the left and right arrow keys to an event in Tkinter, but when I run the program it appears the events are not triggering. Here is the code:
```
from Tkinter import *
main = Tk()
def leftKey(event):
print "Left key pressed"
def rightKey(event):
print "Right key pressed"
frame = Frame(ma... | The problem is simply that the frame you are binding to doesn't have the keyboard focus. When you press a key on the keyboard, the event is sent to the widget with the keyboard focus. By default, a frame does not have keyboard focus.
Add the following line to your code to move the keyboard focus to the frame:
```
fra... |
Could not parse the remainder: '[0]' from 'item[0]' Django | 19,895,894 | 6 | 2013-11-10T22:12:59Z | 19,895,904 | 21 | 2013-11-10T22:14:10Z | [
"python",
"html",
"arrays",
"django",
"list"
] | I am trying to make a table with values I get from a list but I keep getting the error "Could not parse the remainder: '[0]' from 'item[0]'" whenever I try to access an item in a list inside the main list.
The part of the code that is giving me problems is:
```
{% for item in lista_completa %}
<tr>
<td>
{... | You would write the following to get item `0`:
```
{{ item.0 }}
```
Similarly, to get the first item of the first item you'd write:
```
{{ item.0.0 }}
``` |
Locating the centroid (center of mass) of spherical polygons | 19,897,187 | 37 | 2013-11-11T00:44:50Z | 20,056,658 | 12 | 2013-11-18T19:58:42Z | [
"python",
"geometry",
"centroid"
] | I'm trying to work out how best to locate the centroid of an arbitrary shape draped over a unit sphere, with the input being ordered (clockwise or anti-cw) vertices for the shape boundary. The density of vertices is irregular along the boundary, so the arc-lengths between them are not generally equal. Because the shape... | I think this will do it. You should be able to reproduce this result by just copy-pasting the code below.
* You will need to have the latitude and longitude data in a file called `longitude and latitude.txt`. You can copy-paste the original sample data which is included below the code.
* If you have mplotlib it will a... |
I am trying to iterate over multiple ranges to create a multidimensional ndarray from another | 19,898,403 | 3 | 2013-11-11T03:33:15Z | 19,898,433 | 7 | 2013-11-11T03:37:57Z | [
"python",
"arrays",
"numpy",
"multidimensional-array"
] | I have:
```
>>> import numpy as np
>>> a = np.arange(25).reshape(5, 5)
>>> a
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
```
How do I get an array which is the sum of a number and the number below it:
```
array([[7,... | Use slices to pick out (1) all but the last row of the array and (2) all but the first row of the array. Then add them.
```
>>> a[:-1,:] + a[1:,:]
array([[ 5, 7, 9, 11, 13],
[15, 17, 19, 21, 23],
[25, 27, 29, 31, 33],
[35, 37, 39, 41, 43]])
``` |
How to use WTForms in Ajax validation? | 19,898,967 | 11 | 2013-11-11T04:42:12Z | 19,919,440 | 10 | 2013-11-12T01:47:58Z | [
"python",
"flask",
"wtforms",
"flask-wtforms"
] | I accustomed of using WTForms by means of Flask-WTF in my flask application. Doing server side validation is trivial. But how do I leverage this server validation to become a field level, ajax, client side validation? So, when user tab to another input fields, my application can directly goes on validating it and give ... | A possible solution is as follows:
* On the client side you attach a handler to the `blur` event in all the controls in the form.
* Each time the blur event occurs you run a Javascript function that collects the values of all the fields and then submits them as an ajax POST request.
* On the server the view function t... |
Python not catching MemoryError | 19,899,910 | 6 | 2013-11-11T06:09:04Z | 19,909,648 | 10 | 2013-11-11T15:13:58Z | [
"python",
"exception-handling",
"out-of-memory"
] | I've wrapped some code that can run out of memory with a try/except block. However, though a MemoryError is generated, it is not caught.
I have the following code:
```
while True:
try:
self.create_indexed_vocab( vocab )
self.reset_weights()
break;
except MemoryE... | **Note that because of the underlying memory management architecture (Câs malloc() function), the interpreter may not always be able to completely recover from this situation; it nevertheless raises an exception so that a stack traceback can be printed, in case a run-away program was the cause.**
(See [the docs](htt... |
text alignment in xlwt with easyxf | 19,900,972 | 5 | 2013-11-11T07:28:06Z | 19,919,695 | 11 | 2013-11-12T02:17:23Z | [
"python",
"xlwt"
] | I am using xlwt, excel sheet generation module for python. Basically I am trying to use some styles for the text. The coloring part works fine .i.e.
```
import xlwt
workbook = xlwt.Workbook(encoding='ascii')
worksheet = workbook.add_sheet('Test sheet')
worksheet.write(0, 0, "Hello World", xlwt.easyxf("pattern: patte... | It was as simple as adding align: horiz right
```
import xlwt
workbook = xlwt.Workbook(encoding='ascii')
worksheet = workbook.add_sheet('Test sheet')
worksheet.write(0, 0, "Hello World", xlwt.easyxf("pattern: pattern solid, fore_color yellow; font: color white; align: horiz right"))
worksheet.save()
``` |
What is the pythonic way to avoid shadowing variables? | 19,902,127 | 11 | 2013-11-11T08:45:35Z | 19,902,439 | 27 | 2013-11-11T09:03:35Z | [
"python",
"variables",
"scope"
] | I often have the following code which either leads to variable shadowing or to a multiplication of local variables
```
def whenadult(age):
return 18 - age
age = 5
needtowait = whenadult(age)
```
`age` has the same logical role both when passed to the function as in the main code so I would like to avoid creating... | The fact that the local variable (and function parameter) `age` happens to have the same name as a variable somewhere else in your program is irrelevant. The whole point of local variables is that they only live within the local scope of the function they're defined in.
The fact that the local variable has the same na... |
Transactions and sqlalchemy | 19,904,176 | 5 | 2013-11-11T10:35:15Z | 19,917,334 | 8 | 2013-11-11T22:35:34Z | [
"python",
"insert",
"transactions",
"sqlalchemy"
] | I am trying to figure out how to insert many (in the order of 100k) records into a db using sqlalchemy in python3. Everything points to using transactions, however I am slightly confused as to how that is done.
Some pages state that you get a transaction from connection.begin(), others places say it is session.begin() ... | I highly suggest that you do both tutorials before continuing on your trip with SQLAlchemy. They are really helpful and explain many concepts. Afterwards, I suggest you read [Using the Session](http://docs.sqlalchemy.org/en/rel_0_9/orm/session.html) as this then goes on to explain how the session fits into all of this.... |
Delete Pandas DataFrame row where column value is < 0 | 19,905,927 | 2 | 2013-11-11T12:04:20Z | 19,906,474 | 14 | 2013-11-11T12:32:45Z | [
"python",
"pandas"
] | I already read the answers in [this](http://stackoverflow.com/questions/18172851/deleting-dataframe-row-in-pandas-based-on-column-value) thread but it doesn't answer my exact problem.
My DataFrame looks like this
```
Lady in the Water The Night Listener Just My Luck Correlation
Claudia Puig ... | ```
df = df[df['Correlation'] >= 0]
``` |
Reading serial data in realtime in Python | 19,908,167 | 12 | 2013-11-11T13:58:08Z | 19,909,287 | 15 | 2013-11-11T14:56:36Z | [
"python",
"python-2.7",
"serial-port",
"pyserial"
] | I am using a script in Python to collect data from a PIC microcontroller via serial port at 2Mbps.
The PIC works with perfect timing at 2Mbps, also the FTDI usb-serial port works great at 2Mbps (both verified with oscilloscope)
Im sending messages (size of about 15 chars) about 100-150x times a second and the number ... | You can use `inWaiting()` to get the amount of bytes available at the input queue.
Then you can use `read()` to read the bytes, something like that:
```
While True:
bytesToRead = ser.inWaiting()
ser.read(bytesToRead)
```
Why not to use `readline()` **at this case** from Docs:
```
Read a line which is termin... |
What is this #ifdef __GNUC__ about? | 19,908,922 | 9 | 2013-11-11T14:36:50Z | 19,909,505 | 7 | 2013-11-11T15:07:16Z | [
"c++",
"python",
"visual-studio",
"gnu"
] | I've found these lines in the `libmagic` code, (sourceforge.net/projects/libmagic/files/latest/download). What do they mean? What's the python equivalent?
```
#ifdef __GNUC__
__attribute__((unused))
#endif
```
**What does `__GNUC__` mean?**
so it seems to check whether GCC compiler is installed, [What means \_\_CC\_A... | It's common in the compilers to define some macros to determine what compiler they are, what version is that, ... A portable C++ code uses that macros to find out that it can use a specific feature or not.
> What does **GNUC** mean?
It indicates I'm a GNU compiler and you can use GNU extensions. [[1]](http://gcc.gnu.... |
Loading Base64 String into Python Image Library | 19,908,975 | 7 | 2013-11-11T14:39:52Z | 19,911,883 | 11 | 2013-11-11T17:04:24Z | [
"python",
"django",
"image",
"base64",
"python-imaging-library"
] | I'm sending images as base64 string through ajax to django. In my django view I need to resize the image and save it in the file system.
Here is a base64 string(simplified):
```
data:image/jpeg;base64,/9j/4AAQSkZJRg-it-keeps-going-for-few-more-lines=
```
I tried to open this in PIL using the below python code:
```
... | **SOLUTION:**
Saving the opened PIL image to a file-like object solves the issue.
```
pic = cStringIO.StringIO()
image_string = cStringIO.StringIO(base64.b64decode(request.POST['file']))
image = Image.open(image_string)
image.save(pic, image.format, quality = 100)
pic.seek(0)
return HttpResponse(pic, content_type='im... |
how to find most frequent string element in numpy ndarray? | 19,909,167 | 6 | 2013-11-11T14:50:30Z | 19,909,411 | 9 | 2013-11-11T15:02:57Z | [
"python",
"python-3.x",
"numpy"
] | Is their any way to find most frequent string element in numpy ndarray?
```
A= numpy.array(['a','b','c']['d','d','e']])
result should be 'd'
``` | If you want a numpy answer you can use `np.unique`:
```
>>> unique,pos = np.unique(A,return_inverse=True) #Finds all unique elements and their positions
>>> counts = np.bincount(pos) #Count the number of each unique element
>>> maxpos = counts.argmax() #Finds the positions of t... |
How to load a custom JS file in Django admin home? | 19,910,450 | 6 | 2013-11-11T15:51:14Z | 19,910,749 | 9 | 2013-11-11T16:05:46Z | [
"javascript",
"python",
"django"
] | I have a heavily customized Django admin where it's very simple to load a custom JS file for each of my ModelAdmins:
```
class MyModelAdmin(admin.ModelAdmin):
class Media:
js = ('js/admin/mymodel.js',)
```
But how do I do this for the admin "homepage," where all my admin models are listed?
**Update #1**:... | You can override `templates/admin/index.html` and add the JavaScript in the block `extrahead`:
```
{% extends "admin/index.html" %}
{% block extrahead %}
# add a <script> tag here with your JavaScript
{% endblock %}
``` |
Create a typewriter-effect animation for strings in Python | 19,911,346 | 4 | 2013-11-11T16:35:46Z | 19,911,446 | 7 | 2013-11-11T16:40:04Z | [
"python",
"python-3.x"
] | Just like in the movies and in games, the location of a place comes up on screen as if it's being typed live. I want to make a game about escaping a maze in python. At the start of the game it gives the background information of the game:
```
line_1 = "You have woken up in a mysterious maze"
line_2 = "The building has... | Because you tagged your question with python 3 I will provide a python 3 solution:
1. Change your end character of print to an empty string: `print(..., end='')`
2. Add `sys.stdout.flush()` to make it print instantly (because the output is buffered)
Final code:
```
from time import sleep
import sys
for x in line_1:... |
How do I toggle a boolean array in Python? | 19,912,866 | 4 | 2013-11-11T18:03:39Z | 19,912,898 | 9 | 2013-11-11T18:05:42Z | [
"python",
"arrays",
"boolean",
"toggle"
] | Say I have the following array:
```
[True, True, True, True]
```
How do I toggle the state of each element in this array?
Toggling would give me:
```
[False, False, False, False]
```
Similarly, if I have:
```
[True, False, False, True]
```
Toggling would give me:
```
[False, True, True, False]
```
I know the m... | Using `not` is still the best way. You just need a [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) to go with it:
```
>>> x = [True, True, True, True]
>>> [not y for y in x]
[False, False, False, False]
>>> x = [False, True, True, False]
>>> [not y for y in x]
[True, F... |
How do I escape a colon in Python format() when using kwargs? | 19,913,504 | 9 | 2013-11-11T18:43:50Z | 19,913,567 | 8 | 2013-11-11T18:47:27Z | [
"python",
"string-formatting"
] | I have a dictionary with a colon in a key that I wish to print. Unfortunately the colon character is used for formatting, so I need to somehow escape it.
For example:
```
>>> d = {'hello': 'world', 'with:colon': 'moo'}
>>> '{hello}'.format(**d)
'world'
>>> '{with:colon}'.format(**d)
KeyError: 'with'
>>> '{with\:co... | According to [the documentation](http://docs.python.org/2/library/string.html#format-string-syntax), what you are asking is simply not possible. Specifically,
> Because arg\_name is not quote-delimited, it is not possible to specify arbitrary dictionary keys (e.g., the strings `'10'` or `':-]'`) within a format string... |
No Unicode in `__all__` for a package's `__init__`? | 19,913,653 | 6 | 2013-11-11T18:51:49Z | 19,913,680 | 9 | 2013-11-11T18:53:21Z | [
"python",
"python-2.7",
"unicode",
"python-import"
] | Are Unicode literals not allowed in `__all__` in Python 2.7.5? I've got an `__init__.py` file with `from __future__ import unicode_literals` at the top, along with coding utf-8. (There are also some unicode strings in it, hence the future import.)
To ensure that only some of the modules are visible when imported using... | No, unicode values are not allowed in `__all__`, because in Python 2 names are strings, not unicode values.
Your indeed have to encode all strings in `__all__` or not use unicode literals. You could do so as a separate step:
```
__all__ = ['SomeClass']
__all__ = [n.encode('ascii') for n in __all__]
```
In Python 3, ... |
Pandas conditional creation of a series/dataframe column | 19,913,659 | 45 | 2013-11-11T18:52:06Z | 19,913,845 | 79 | 2013-11-11T19:03:15Z | [
"python",
"pandas"
] | I have a dataframe along the lines of the below:
```
Type Set
1 A Z
2 B Z
3 B X
4 C Y
```
I want to add another column to the dataframe (or generate a series) of the same length as the dataframe (= equal number of records/rows) which sets a colour g... | ```
df['color'] = np.where(df['Set']=='Z', 'green', 'red')
```
---
For example,
```
import pandas as pd
import numpy as np
df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
df['color'] = np.where(df['Set']=='Z', 'green', 'red')
print(df)
```
yields
```
Set Type color
0 Z A green
1 Z B gr... |
Pandas conditional creation of a series/dataframe column | 19,913,659 | 45 | 2013-11-11T18:52:06Z | 24,074,316 | 9 | 2014-06-06T04:43:52Z | [
"python",
"pandas"
] | I have a dataframe along the lines of the below:
```
Type Set
1 A Z
2 B Z
3 B X
4 C Y
```
I want to add another column to the dataframe (or generate a series) of the same length as the dataframe (= equal number of records/rows) which sets a colour g... | Another way in which this could be achieved is
```
df['color'] = df.Set.map( lambda x: 'red' if x == 'Z' else 'green')
``` |
Pandas conditional creation of a series/dataframe column | 19,913,659 | 45 | 2013-11-11T18:52:06Z | 31,173,785 | 25 | 2015-07-02T00:27:06Z | [
"python",
"pandas"
] | I have a dataframe along the lines of the below:
```
Type Set
1 A Z
2 B Z
3 B X
4 C Y
```
I want to add another column to the dataframe (or generate a series) of the same length as the dataframe (= equal number of records/rows) which sets a colour g... | List comprehension is another way to create another column conditionally. If your working with object dtypes in columns, like in your example, list comps typically out perform most other methods.
Example list comp:
```
df['color'] = ['red' if x == 'Z' else 'green' for x in df['Set']]
```
**%timeit tests:**
```
impo... |
Applying function with multiple arguments to create a new pandas column | 19,914,937 | 30 | 2013-11-11T20:07:30Z | 19,915,115 | 10 | 2013-11-11T20:17:21Z | [
"python",
"pandas"
] | I want to create a new column in a `pandas` data frame by applying a function to two existing columns. Following this [answer](http://stackoverflow.com/a/14603893/2327821) I've been able to create a new column when I only need one column as an argument:
```
import pandas as pd
df = pd.DataFrame({"A": [10,20,30], "B": ... | This solves the problem:
```
df['newcolumn'] = df.A * df.B
```
You could also do:
```
def fab(row):
return row['A'] * row['B']
df['newcolumn'] = df.apply(fab, axis=1)
``` |
Applying function with multiple arguments to create a new pandas column | 19,914,937 | 30 | 2013-11-11T20:07:30Z | 19,922,732 | 44 | 2013-11-12T06:52:41Z | [
"python",
"pandas"
] | I want to create a new column in a `pandas` data frame by applying a function to two existing columns. Following this [answer](http://stackoverflow.com/a/14603893/2327821) I've been able to create a new column when I only need one column as an argument:
```
import pandas as pd
df = pd.DataFrame({"A": [10,20,30], "B": ... | You can go with @greenAfrican example, if it's possible for you to rewrite your function. But if you don't want to rewrite your function, you can wrap it into anonymous function inside apply, like this:
```
>>> def fxy(x, y):
... return x * y
>>> df['newcolumn'] = df.apply(lambda x: fxy(x['A'], x['B']), axis=1)
>... |
Applying function with multiple arguments to create a new pandas column | 19,914,937 | 30 | 2013-11-11T20:07:30Z | 19,976,286 | 19 | 2013-11-14T11:17:46Z | [
"python",
"pandas"
] | I want to create a new column in a `pandas` data frame by applying a function to two existing columns. Following this [answer](http://stackoverflow.com/a/14603893/2327821) I've been able to create a new column when I only need one column as an argument:
```
import pandas as pd
df = pd.DataFrame({"A": [10,20,30], "B": ... | Alternatively, you can use numpy underlying function:
```
>>> import numpy as np
>>> df = pd.DataFrame({"A": [10,20,30], "B": [20, 30, 10]})
>>> df['new_column'] = np.multiply(df['A'], df['B'])
>>> df
A B new_column
0 10 20 200
1 20 30 600
2 30 10 300
```
or vectorize arbitrary fu... |
Drawing a graph with NetworkX on a Basemap | 19,915,266 | 3 | 2013-11-11T20:26:19Z | 19,938,484 | 8 | 2013-11-12T19:46:05Z | [
"python",
"networkx",
"matplotlib-basemap"
] | I want to plot a graph on a map where the nodes would be defined by coordinates (lat, long) and have some value associated.
I have been able to plot points as a scatterplot on a basemap but can't seem to find how to plot a graph on the map.
Thanks.
**EDIT**: I have added code on how I plotted the points on a basemap... | Here is one way to do it:
```
import networkx as nx
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap as Basemap
m = Basemap(
projection='merc',
llcrnrlon=-130,
llcrnrlat=25,
urcrnrlon=-60,
urcrnrlat=50,
lat_ts=0,
resolution='i',
su... |
How exactly is Python Bytecode Run in CPython? | 19,916,729 | 30 | 2013-11-11T21:53:57Z | 19,916,892 | 15 | 2013-11-11T22:05:53Z | [
"python",
"cpython",
"python-internals"
] | I am trying to understand how Python works (because I use it all the time!). To my understanding, when you run something like python script.py, the script is converted to bytecode and then the interpreter/VM/CPythonâreally just a C Programâreads in the python bytecode and executes the program accordingly.
How is t... | Yes, your understanding is correct. There is basically (very basically) a giant switch statement inside the CPython interpreter that says "if the current opcode is so and so, do this and that".
<http://hg.python.org/cpython/file/3.3/Python/ceval.c#l790>
Other implementations, like Pypy, have JIT compilation, i.e. the... |
How exactly is Python Bytecode Run in CPython? | 19,916,729 | 30 | 2013-11-11T21:53:57Z | 19,917,906 | 10 | 2013-11-11T23:17:37Z | [
"python",
"cpython",
"python-internals"
] | I am trying to understand how Python works (because I use it all the time!). To my understanding, when you run something like python script.py, the script is converted to bytecode and then the interpreter/VM/CPythonâreally just a C Programâreads in the python bytecode and executes the program accordingly.
How is t... | If you want to see the bytecode of some code (whether source code, a live function object or code object, etc.), the [`dis`](http://docs.python.org/3/library/dis.html) module will tell you exactly what you need. For example:
```
>>> dis.dis('i/3')
1 0 LOAD_NAME 0 (i)
3 LOAD_CON... |
How to use PYTHONPATH | 19,917,492 | 36 | 2013-11-11T22:45:56Z | 19,917,556 | 10 | 2013-11-11T22:50:42Z | [
"python",
"unix"
] | How can I make any use of PYTHONPATH? When I try to run a script in the path the file is not
found. When I cd to the directory holding the script the script runs. So what good is the
PYTHONPATH?
```
$ echo $PYTHONPATH
:/home/randy/lib/python
$ tree -L 1 '/home/randy/lib/python'
/home/randy/lib/python
âââ gbmx_... | You're confusing PATH and PYTHONPATH. You need to do this:
```
export PATH=$PATH:/home/randy/lib/python
```
PYTHONPATH is used by the python interpreter to determine which modules to load.
PATH is used by the shell to determine which executables to run. |
How to use PYTHONPATH | 19,917,492 | 36 | 2013-11-11T22:45:56Z | 19,917,565 | 49 | 2013-11-11T22:51:15Z | [
"python",
"unix"
] | How can I make any use of PYTHONPATH? When I try to run a script in the path the file is not
found. When I cd to the directory holding the script the script runs. So what good is the
PYTHONPATH?
```
$ echo $PYTHONPATH
:/home/randy/lib/python
$ tree -L 1 '/home/randy/lib/python'
/home/randy/lib/python
âââ gbmx_... | I think you're a little confused. PYTHONPATH sets the search path for **importing** python modules, not for executing them like you're trying.
> PYTHONPATH Augment the default search path for module files. The
> format is the same as the shellâs PATH: one or more directory
> pathnames separated by os.pathsep (e.g. c... |
How to use PYTHONPATH | 19,917,492 | 36 | 2013-11-11T22:45:56Z | 19,917,658 | 15 | 2013-11-11T22:58:12Z | [
"python",
"unix"
] | How can I make any use of PYTHONPATH? When I try to run a script in the path the file is not
found. When I cd to the directory holding the script the script runs. So what good is the
PYTHONPATH?
```
$ echo $PYTHONPATH
:/home/randy/lib/python
$ tree -L 1 '/home/randy/lib/python'
/home/randy/lib/python
âââ gbmx_... | `PYTHONPATH` only affects `import` statements, not the top-level Python interpreter's lookup of python files given as arguments.
Needing `PYTHONPATH` to be set is not a great idea - as with anything dependent on environment variables, replicating things consistently across different machines gets tricky. Better is to ... |
Comparing two pandas dataframes for differences | 19,917,545 | 9 | 2013-11-11T22:50:01Z | 19,918,849 | 16 | 2013-11-12T00:40:20Z | [
"python",
"python-2.7",
"pandas"
] | I've got a script updating 5-10 columns worth of data , but sometimes the start csv will be identical to the end csv so instead of writing an identical csvfile I want it to do nothing...
How can I compare two dataframes to check if they're the same or not?
```
csvdata = pandas.read_csv('csvfile.csv')
csvdata_old = cs... | You also need to be careful to create a copy of the DataFrame, otherwise the csvdata\_old will be updated with csvdata (since it points to the same object):
```
csvdata_old = csvdata.copy()
```
To check whether they are equal, you can [use assert\_frame\_equal as in this answer](http://stackoverflow.com/questions/193... |
matplotlib advanced bar plot | 19,917,587 | 8 | 2013-11-11T22:53:30Z | 19,919,397 | 15 | 2013-11-12T01:42:44Z | [
"python",
"graph",
"matplotlib",
"plot"
] | I need to recreate a chart similar to the one below created in Excel. I was hoping to use matplotlib, but can't seem to find any examples or reference for how to do a chart like this. I need to have bars colored based on a performance threshold, and also display the threshold. Can anyone point me in the right direction... | I gotta run, but here's something to get you started:
```
import numpy as np
import matplotlib
matplotlib.rcParams['text.usetex'] = False
import matplotlib.pyplot as plt
import pandas
df = pandas.DataFrame(np.random.uniform(size=37)*100, columns=['A'])
threshold = 75
fig, ax = plt.subplots(figsize=(8,3))
good = df['... |
Starting supervisord as root or not? | 19,918,177 | 16 | 2013-11-11T23:39:04Z | 19,918,243 | 14 | 2013-11-11T23:44:22Z | [
"python",
"startup",
"supervisord"
] | Supervisor is running on 3.0:
```
pip freeze | grep supervisor
supervisor==3.0
```
When starting supervisord from the command line:
```
sudo $VIRTENV/supervisord --nodaemon --configuration $PATH_TO_CONFIG/supervisord.conf
```
I get this error:
```
2013-11-11 23:30:50,205 CRIT Supervisor running as root (no user in... | Supervisord switches to UNIX user account before any processing.
You need to specify what kind of user account it should use, run the daemon as root but specify user in the config file
Example:
```
[program:myprogram]
command=gunicorn --worker-class socketio.sgunicorn.GeventSocketIOWorker app.wsgi:application -b 127... |
In Python, what is a good way to round towards zero in integer division? | 19,919,387 | 10 | 2013-11-12T01:41:40Z | 19,919,450 | 8 | 2013-11-12T01:48:58Z | [
"python",
"rounding",
"division",
"negative-number",
"integer-division"
] | ```
1/2
```
gives
```
0
```
as it should. However,
```
-1/2
```
gives
```
-1
```
, but I want it to round towards 0 (i.e. I want -1/2 to be 0), regardless of whether it's positive or negative. What is the best way to do that? | Do floating point division then convert to an int. No extra modules needed.
```
>>> int(float(-1)/2)
0
>>> int(float(-3)/2)
-1
>>> int(float(1)/2)
0
>>> int(float(3)/2)
1
``` |
where can i find the source file of 'admin.site.urls'? | 19,919,547 | 3 | 2013-11-12T01:59:18Z | 21,247,209 | 9 | 2014-01-21T00:58:36Z | [
"python",
"django",
"django-admin",
"admin"
] | In my urls.py, I have a line of codes of ('include(admin.site.urls). But I cannot find the source file in the setup dir of python like ..\site-packages\django\contrib\admin Where are they? | In python, modules can be loaded from within a package's `__init__.py`; it doesn't need to be a file in the same directory.
If you look in `django/contrib/admin/__init__.py` you will see:
`from django.contrib.admin.sites import AdminSite, site`
So then if you look in `django/contrib/admin/sites.py` you will see:
`si... |
How to Bootstrap numpy installation in setup.py | 19,919,905 | 13 | 2013-11-12T02:41:49Z | 21,621,689 | 15 | 2014-02-07T07:24:20Z | [
"python",
"numpy",
"setuptools",
"bootstrapping"
] | I have a project which has a C extension which requires numpy. Ideally, I'd like whoever downloads my project to just be able to run `python setup.py install` or use one call to `pip`. The problem I have is that in my `setup.py` I need to import numpy to get the location of the headers, but I'd like numpy to be just a ... | The following works at least with numpy1.8 and python{2.6,2.7,3.3}:
```
from setuptools import setup
from setuptools.command.build_ext import build_ext as _build_ext
class build_ext(_build_ext):
def finalize_options(self):
_build_ext.finalize_options(self)
# Prevent numpy from thinking it is still... |
Maximum and minimum caps for list values in Python | 19,922,611 | 4 | 2013-11-12T06:44:20Z | 19,922,627 | 7 | 2013-11-12T06:45:40Z | [
"python",
"list"
] | I have a list of values and I'd like to set the maximum value of any element in the list to 255 and the minimum value to 0 while leaving those within the range unchanged.
```
oldList = [266, 40, -15, 13]
newList = [255, 40, 0, 13]
```
Currently I'm doing
```
for i in range(len(oldList)):
if oldList[i] > 255:
... | Use [`min`](http://docs.python.org/2/library/functions.html#min), [`max`](http://docs.python.org/2/library/functions.html#max) functions:
```
>>> min(266, 255)
255
>>> max(-15, 0)
0
```
---
```
>>> oldList = [266, 40, -15, 13]
>>> [max(min(x, 255), 0) for x in oldList]
[255, 40, 0, 13]
``` |
Finding the middle of three numbers | 19,922,939 | 2 | 2013-11-12T07:05:16Z | 19,922,963 | 8 | 2013-11-12T07:06:23Z | [
"python",
"function",
"python-2.7"
] | I'm looking for alternative or more concise ways to return the middle of three unique values. What I have right now is a function:
```
def middle(x, y, z):
if x > y and x < z:
return x
if y > x and y < z:
return y
return z
```
Anything better? | ```
def middle(x, y, z):
return sorted([x, y, z])[1]
```
This should return the middle number. But if you actually meant maximum number
```
def maximum(x, y, z):
return max([x, y, z])
```
**Edit:** As suggested by abarnert in the comments section, instead of `y>x and x<z` use `x < y < z`, which is more reada... |
Django orm get latest for each group | 19,923,877 | 16 | 2013-11-12T08:04:18Z | 19,924,129 | 15 | 2013-11-12T08:21:11Z | [
"python",
"django",
"orm"
] | I am using django 1.6 with Mysql
I have this models
```
class Student(models.Model):
username = models.CharField(max_length=200,unique = True)
class Score(models.Model)
student = models.ForeignKey(Student)
date = models.DateTimeField()
score = models.IntegerField()
```
Now i want to get the late... | If your DB is postgres which supports [`distinct()`](https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.distinct) on field you can try
```
Score.objects.order_by('student__username', '-date').distinct('student__username')
``` |
Django orm get latest for each group | 19,923,877 | 16 | 2013-11-12T08:04:18Z | 19,930,802 | 17 | 2013-11-12T13:43:36Z | [
"python",
"django",
"orm"
] | I am using django 1.6 with Mysql
I have this models
```
class Student(models.Model):
username = models.CharField(max_length=200,unique = True)
class Score(models.Model)
student = models.ForeignKey(Student)
date = models.DateTimeField()
score = models.IntegerField()
```
Now i want to get the late... | This should work on Django 1.2+ and MySQL:
```
Score.objects.annotate(max_date=Max('student__score__date')).filter(date=F('max_date'))
``` |
Python Multiprocessing: Handling Child Errors in Parent | 19,924,104 | 15 | 2013-11-12T08:20:00Z | 19,929,767 | 7 | 2013-11-12T12:54:11Z | [
"python",
"error-handling",
"multiprocessing"
] | I am currently playing around with multiprocessing and queues.
I have written a piece of code to export data from mongoDB, map it into a relational (flat) structure, convert all values to string and insert them into mysql.
Each of these steps is submitted as a process and given import/export queues, safe for the mongo... | I don't know standard practice but what I've found is that to have reliable multiprocessing I design the methods/class/etc. specifically to work with multiprocessing. Otherwise you never really know what's going on on the other side (unless I've missed some mechanism for this).
Specifically what I do is:
* Subclass `... |
Django 1.6 and Celery 3.0 memory leaks | 19,925,264 | 6 | 2013-11-12T09:22:00Z | 19,931,261 | 7 | 2013-11-12T14:03:42Z | [
"python",
"django",
"celery",
"django-celery",
"django-1.6"
] | After upgrading Django to 1.6, my celery worker is eating up RAM.
Seems that the memory allocated for the workers isn't released and grows after every task.
Related Settings:
```
# DB:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'somedb',
'USER': ... | It turns out the memory leak was not directly caused by the Django upgrade or Celery.
After a lot of digging around I found that, surprisingly, the celery worker memory leak happens because I upgraded **django-debug-toolbar** from `0.9.4` to `0.11.0` (which is needed for Django 1.6 compatibility).
Still no idea what ... |
Python equivalent of Java StringBuffer? | 19,926,089 | 35 | 2013-11-12T10:00:47Z | 19,926,210 | 8 | 2013-11-12T10:06:18Z | [
"java",
"python",
"stringbuffer"
] | Is there anything in Python like Java's `StringBuffer`? Since strings are immutable in Python too, editing them in loops would be inefficient. | Depends on what you want to do. If you want a mutable sequence, the builtin `list` type is your friend, and going from str to list and back is as simple as:
```
mystring = "abcdef"
mylist = list(mystring)
mystring = "".join(mylist)
```
If you want to build a large string using a for loop, the pythonic way is usual... |
Python equivalent of Java StringBuffer? | 19,926,089 | 35 | 2013-11-12T10:00:47Z | 19,926,932 | 32 | 2013-11-12T10:41:17Z | [
"java",
"python",
"stringbuffer"
] | Is there anything in Python like Java's `StringBuffer`? Since strings are immutable in Python too, editing them in loops would be inefficient. | [Efficient String Concatenation in Python](http://www.skymind.com/~ocrow/python_string/) is a rather old article and its main statement that the naive concatenation is far slower than joining is not valid anymore, because this part has been optimized in CPython since then:
> CPython implementation detail: If s and t a... |
Inserting a degree symbol into python plot | 19,926,246 | 7 | 2013-11-12T10:07:54Z | 19,926,367 | 12 | 2013-11-12T10:13:13Z | [
"python",
"matplotlib",
"symbols"
] | This is a really simple problem but its escaping me. I'm just trying to insert a degree symbol into the titles and legends of my python plot. Code is below. Thanks.
```
from numpy import *
import numpy as np
import matplotlib.pyplot as plt
theta1 = linspace(0,60,610)
theta2 = linspace(0,45,460)
theta3 = linspace(45,9... | Use LaTeX Style. For Example: `$^\circ$ Text` would produce `°Text`
See the [matplotlib documentation](http://matplotlib.org/users/mathtext.html) for more information about printing (especially mathematical expression)
In your case the code has to be: `plt.xlabel('Manufactured Ply Angle $^\circ$')`
Latex part of ex... |
Issue with easy_install-2.7 | 19,926,683 | 10 | 2013-11-12T10:29:45Z | 19,926,770 | 16 | 2013-11-12T10:34:05Z | [
"python",
"python-2.7",
"pip",
"easy-install"
] | After installing easy\_install and trying to use it to then install a python package it fails.
```
[root@server]# easy_install-2.7 pip
Searching for pip
Reading http://pypi.python.org/simple/pip/
Download error on http://pypi.python.org/simple/pip/: unknown url type: https -- Some packages may not be found!
```
I see... | Install the OpenSSL development package and then reinstall Python 2.7, in order to enable SSL (and hence HTTPS) support. |
Django, ImportError: cannot import name Celery, possible circular import? | 19,926,750 | 25 | 2013-11-12T10:33:11Z | 19,942,749 | 37 | 2013-11-13T00:18:44Z | [
"python",
"django",
"celery",
"importerror"
] | I went through this example here:
<http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html>
All my tasks are in files called tasks.py.
After updating celery and adding the file from the example django is throwing the following error, no matter what I try:
```
ImportError: cannot import name Cele... | Adding the following lines to cloud/celery.py:
```
import celery
print celery.__file__
```
gave me the file itself and not the celery module from the library. After renaming celery.py to celeryapp.py and adjusting the imports all errors were gone.
Note:
That leads to a change in starting the worker:
```
celery wor... |
Django, ImportError: cannot import name Celery, possible circular import? | 19,926,750 | 25 | 2013-11-12T10:33:11Z | 28,814,849 | 14 | 2015-03-02T16:34:51Z | [
"python",
"django",
"celery",
"importerror"
] | I went through this example here:
<http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html>
All my tasks are in files called tasks.py.
After updating celery and adding the file from the example django is throwing the following error, no matter what I try:
```
ImportError: cannot import name Cele... | With Django 1.7.5, Celery 3.1.17, and Python 2.7.6 I found that I was still getting these `ImportError: cannot import name Celery`. But only when running tests under PyCharm 4.0.4.
I found that a solution was **not** to rely on `from __future__ import absolute_import` as described in [First Steps with Django](http://d... |
Size of figure when using plt.subplots | 19,932,553 | 8 | 2013-11-12T15:00:58Z | 19,932,721 | 8 | 2013-11-12T15:08:14Z | [
"python",
"layout",
"matplotlib",
"subplot"
] | I'm having some trouble trying to change the figure size when using `plt.subplots`. With the following code, I just get the standard size graph with all my subplots bunched in (there's ~100) and obviously just an extra empty figuresize . I've tried using `tight_layout`, but to no avail.
```
def plot(reader):
chann... | You can remove your initial `plt.figure()`. When calling `plt.subplots()` a new figure is created, so you first call doesn't do anything.
The subplots command in the background will call `plt.figure()` for you, and any keywords will be passed along. So just add the `figsize` keyword to the `subplots()` command:
```
d... |
NameError: name 'datetime' is not defined | 19,934,248 | 14 | 2013-11-12T16:14:02Z | 19,934,262 | 28 | 2013-11-12T16:14:32Z | [
"python",
"datetime"
] | I'm teaching myself Python and was just "exploring". Google says that datetime is a global variable but when I try to find todays date in the terminal I receive the NameError in the question title?
```
mynames-MacBook:pythonhard myname$ python
Enthought Canopy Python 2.7.3 | 64-bit | (default, Aug 8 2013, 05:37:06)
... | You need to import the module [`datetime`](http://docs.python.org/2/library/datetime.html) first:
```
>>> import datetime
```
After that it works:
```
>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)
``` |
Django global name 'PageNotAnInteger' is not defined | 19,936,801 | 2 | 2013-11-12T18:13:41Z | 19,936,828 | 7 | 2013-11-12T18:14:49Z | [
"python",
"django",
"django-views",
"django-rest-framework"
] | I have a strange issue. I have a view that is returning some JSON through a serializer and paginator from Django REST Framework.
My view looks like this (returning all objects in the Countries model):
```
@api_view(['GET'])
def country_list(request):
"""
List all countries
"""
if request.method == 'GE... | You should import it first:
```
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
``` |
Python: Pandas filter string data based on its string length | 19,937,362 | 6 | 2013-11-12T18:43:16Z | 19,939,399 | 17 | 2013-11-12T20:38:41Z | [
"python",
"string",
"csv",
"filter"
] | I like to filter out data whose string length is not equal to 10.
If I try to filter out any row whose column A's or B's string length is not equal to 10, I tried this.
```
df=pd.read_csv('filex.csv')
df.A=ciq.A.apply(lambda x: x if len(x)== 10 else np.nan)
df.B=ciq.B.apply(lambda x: x if len(x)== 10 else np.nan)
... | ```
import pandas as pd
df = pd.read_csv('filex.csv')
df['A'] = df['A'].astype('str')
df['B'] = df['B'].astype('str')
mask = (df['A'].str.len() == 10) & (df['B'].str.len() == 10)
df = df.loc[mask]
print(df)
```
Applied to filex.csv:
```
A,B
123,abc
1234,abcd
1234567890,abcdefghij
```
the code above prints
```
... |
So what is the story with 4 quotes? | 19,937,615 | 5 | 2013-11-12T18:57:06Z | 19,937,653 | 11 | 2013-11-12T18:59:10Z | [
"python",
"string",
"python-2.7",
"quotes"
] | I was experimenting in the python shell with the type() operator. I noted that:
```
type('''' string '''')
```
returns an error which is trouble scanning the string
yet:
```
type(''''' string ''''')
```
works fine and responds that a string was found.
What is going on? does it have to do with the fact that `type(... | You are ending a string with 3 quotes, plus *one* extra. This works:
```
>>> ''''string'''
"'string"
```
In other words, Python sees 3 quotes, then the string ends at the *next* 3 quotes. Anything that follows after that is *not* part of the string anymore.
Python also concatenates strings that are placed one after ... |
Installing Python module with pip | 19,939,365 | 11 | 2013-11-12T20:36:53Z | 20,040,531 | 8 | 2013-11-18T05:12:08Z | [
"python",
"import",
"module",
"scrapy"
] | I'm trying to install a module called Scrapy. I installed it using
```
pip install Scrapy
```
I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening?
EDIT: Here is th... | Are you using Homebrew or MacPorts or something? As @J.F.Sebastian said, it sounds like you are having issues mixing the default python that comes with OS X, and one that is installed via a package manager... Try `/usr/local/opt/python/bin/python2.7 -m scrapy` and see if that throws an `ImportError`.
If that works, th... |
Understanding Django-LDAP authentication | 19,940,466 | 14 | 2013-11-12T21:40:54Z | 19,941,014 | 17 | 2013-11-12T22:12:11Z | [
"python",
"django",
"authentication",
"ldap",
"django-auth-ldap"
] | I am new to Django and have been assigned the task of implementing a user authentication system with LDAP as the backend. I guess the [documentation](http://pythonhosted.org/django-auth-ldap/authentication.html) assumes that the end developer has enough experience in Django to be able to understand and implement such a... | This page might have what you are looking for: <http://pythonhosted.org/django-auth-ldap/> concerning the LDAP backend. You are lucky that one exists, so you don't have to code an auth backend yourself :-)
Basically django.contrib.auth.models already has a User object that contains everything you need about the user. ... |
Cannot get minor grid lines to appear in matplotlib figure | 19,940,518 | 4 | 2013-11-12T21:44:12Z | 19,940,830 | 10 | 2013-11-12T22:01:56Z | [
"python",
"numpy",
"matplotlib",
"pyserial",
"graphing"
] | Ok so I have the code below for real-time graphing some data from an embedded device received over serial. It's not meant to be a production tool but rather an internal eng tool, hence it's not terribly user-friendly. The problem is that no matter what I do, I can't get minor grid lines to appear, even though here they... | Unfortunately, `ax.grid` is a bit confusing in this regard. (This is a design bug / common gotcha.) It turns the minor grid on, but the minor ticks are still turned off.
What you need to do is call `plt.minorticks_on` or `ax.minorticks_on` in addition to calling `ax.grid(True, which='both')`. |
Inverse of Hamming Distance | 19,941,079 | 19 | 2013-11-12T22:16:18Z | 19,941,659 | 17 | 2013-11-12T22:54:31Z | [
"python",
"string",
"algorithm",
"bioinformatics",
"hamming-distance"
] | \*This is a brief introduction, the specific question is in bold at the last paragraph.
I'm trying to generate all strings with a given Hamming Distance to solve efficiently a bioinformatic assignment.
The idea is, given a string (ie. 'ACGTTGCATGTCGCATGATGCATGAGAGCT'), the length of the word to search (ie. 4) and the... | ```
def mutations(word, hamming_distance, charset='ATCG'):
for indices in itertools.combinations(range(len(word)), hamming_distance):
for replacements in itertools.product(charset, repeat=hamming_distance):
mutation = list(word)
for index, replacement in zip(indices, replacements):
... |
Python multiple repeat Error | 19,942,314 | 10 | 2013-11-12T23:40:48Z | 19,942,456 | 16 | 2013-11-12T23:52:53Z | [
"python",
"regex"
] | I'm trying to determine whether a term appear in a string.
Before and after the term must appear a space, and a standard suffix also allowed.
Example:
```
term: google
string: "I love google!!! "
result: found
term: dog
string: "I love dogs "
result: found
```
I'm trying the following code:
```
regexPart1 = "\s... | The problem is that, in a non-raw string, `\"` is `"`.
You get lucky with all of your other unescaped backslashesâ`\s` is the same as `\\s`, not `s`; `\(` is the same as `\\(`, not `(`, and so on. But you should never rely on getting lucky, or assuming that you know the whole list of Python escape sequences by heart... |
Interactive Python: cannot get `%lprun` to work, although line_profiler is imported properly | 19,942,653 | 15 | 2013-11-13T00:10:33Z | 19,944,435 | 30 | 2013-11-13T03:02:10Z | [
"python",
"profiling",
"ipython",
"spyder",
"magic-function"
] | # Problem
Most iPython "magic functions" work fine for me right off the bat: `%hist`, `%time`, `%prun`, etc. However, I noticed that `%lprun` could not be found with iPython as I'd installed it originally.
# Attempt to Resolve
I then discovered that I should install the `line_profiler` module. I have installed this ... | To make `%lprun` work, you need to load the extension into your session, using this command:
```
In [1]: %load_ext line_profiler
```
Check out [this notebook](http://nbviewer.ipython.org/3062428) to see some examples that use the magic.
Besides, if you are working with Spyder, there is also a third-party `line_profi... |
Type checking: an iterable type that is not a string | 19,943,654 | 8 | 2013-11-13T01:42:21Z | 19,944,281 | 10 | 2013-11-13T02:46:27Z | [
"python",
"python-3.x",
"typechecking"
] | To explain better, consider this simple type checker function:
```
from collections import Iterable
def typecheck(obj):
return not isinstance(obj, str) and isinstance(obj, Iterable)
```
If `obj` is an iterable type other than `str`, it returns `True`. However, if `obj` is a `str` or a non-iterable type, it return... | In **python 2.x**, Checking for the `__iter__` attribute was helpful (though not always wise), because iterables should have this attribute, but strings did not.
```
def typecheck(obj): return hasattr(myObj, '__iter__')
```
The down side was that `__iter__` was not a truely Pythonic way to do it: Some objects might i... |
Is it possible to change jira issue status with python-jira? | 19,945,179 | 6 | 2013-11-13T04:15:38Z | 19,945,470 | 7 | 2013-11-13T04:43:06Z | [
"python",
"jira",
"jira-rest-api",
"python-jira"
] | I want to change jira issue status with python-jira.The python-jira API is <http://jira-python.readthedocs.org/en/latest/> .I can't find any way to do this.
I was trying to use `issue.update(status="Closed")`.But it didn't work.I found Issue status and workflow in <https://developer.atlassian.com/display/JIRADEV/Issue+... | I ran into this as well, and unfortunately JIRA's incredible flexibility also makes it a PITA sometimes.
To change the status on a ticket, you need to make a [transition](https://confluence.atlassian.com/display/JIRA/Configuring+Workflow#ConfiguringWorkflow-Whatisatransition?), which moves it from one status to the ne... |
Typecasting not works for 08 and 09 | 19,945,462 | 2 | 2013-11-13T04:42:39Z | 19,945,474 | 9 | 2013-11-13T04:43:22Z | [
"python",
"python-2.7"
] | While typecasting in python I got an error.
```
int(01)
int(02)
int(03)
int(04)
int(05)
int(06)
int(07)
```
Above all works fine.
But when I do same for bellow -:
```
int(08)
```
and
```
int(09)
```
I am getting error i.e
```
SyntaxError: invalid token
```
I know, this typecasting is not correct for converting... | Numbers starting with 0 are considered as octal data. Octal numbers can't have number more than 7.
To fix this, you can convert the data to string and pass the base explicitly like this
```
print int("09", 10)
```
**Output**
```
9
``` |
"2+2=5" Python edition | 19,952,367 | 5 | 2013-11-13T11:19:05Z | 19,952,469 | 11 | 2013-11-13T11:23:03Z | [
"python",
"python-2.7"
] | Can somebody explain this tricky output:
```
>>> not(type(1.01)) == type(1) # Why does the expression evaluates to True!?
True
>>> not(type(1.01))
False
>>> False == type(1)
False
```
What happens there? And why this happens?
**Answer:**
When I asked question I treated `not` as a function, but actually `not` isn't a... | Python is parsing
```
not(type(1.01)) == type(1)
```
as
```
not ((type(1.01)) == type(1))
```
(Note carefully the parentheses.)
The [operator precedence table](http://docs.python.org/2/reference/expressions.html#operator-precedence) shows `not` has less precedence than `==`. So the `==` operator is causing `type(1... |
Error when looping to produce subplots | 19,953,348 | 4 | 2013-11-13T12:05:16Z | 19,953,764 | 17 | 2013-11-13T12:25:21Z | [
"python",
"matplotlib",
"dataframe",
"subplot"
] | I have a question about an error I receive when looping to plot multiple subplots from a data frame.
My data frame has many columns, of which I loop over to have a subplot of each column.
This is my **code**
```
def plot(df):
channels=[]
for i in df:
channels.append(i)
fig, ax = plt.subplots(le... | If you plot multiple subplots, the `plt.subplots()` returns the axes in an array, that array allows indexing like you do with `ax[plot]`. When only 1 subplot is created, by default it returns the axes itself, not the axes within an array.
So your error occurs when `len(channels)` equals 1. You can suppress this behavi... |
How to get the resolution of a monitor in Pygame? | 19,954,469 | 5 | 2013-11-13T12:58:45Z | 19,954,583 | 16 | 2013-11-13T13:04:41Z | [
"python",
"window",
"pygame",
"resolution",
"dimensions"
] | I'm just wondering if it is possible for me to get the resolution of a monitor in Pygame and then use these dimensions to create a window so that launching the program detects the monitor resolution and then automatically fits the window to the screen in fullscreen.
I am currently using `pygame.display.set_mode((AN_IN... | You can use `pygame.display.Info()`:
The [docs](http://www.pygame.org/docs/ref/display.html#pygame.display.Info) say:
> current\_h, current\_h: Width and height of the current video mode, or
> of the
> desktop mode if called before the display.set\_mode is called.
> (current\_h, current\_w are available since SDL 1.2... |
Python Checking a string's first and last character | 19,954,593 | 28 | 2013-11-13T13:05:20Z | 19,954,617 | 12 | 2013-11-13T13:06:25Z | [
"python",
"string",
"python-2.7"
] | can anyone please explain what is wrong with this code?
```
str1='"xxx"'
print str1
if str1[:1].startswith('"'):
if str1[:-1].endswith('"'):
print "hi"
else:
print "condition fails"
else:
print "bye"
```
The output I got is:
```
Condition fails
```
but I expected it to print `hi` instead... | You are testing against the string **minus the last character**:
```
>>> '"xxx"'[:-1]
'"xxx'
```
Note how the last character, the `"`, is not part of the output of the slice.
I think you wanted just to test against the last character; use `[-1:]` to slice for just the last element.
However, there is no need to slic... |
Python Checking a string's first and last character | 19,954,593 | 28 | 2013-11-13T13:05:20Z | 19,954,619 | 42 | 2013-11-13T13:06:26Z | [
"python",
"string",
"python-2.7"
] | can anyone please explain what is wrong with this code?
```
str1='"xxx"'
print str1
if str1[:1].startswith('"'):
if str1[:-1].endswith('"'):
print "hi"
else:
print "condition fails"
else:
print "bye"
```
The output I got is:
```
Condition fails
```
but I expected it to print `hi` instead... | When you say `[:-1]` you are stripping the last element. Instead of slicing the string, you can apply `startswith` and `endswith` on the string object itself like this
```
if str1.startswith('"') and str1.endswith('"'):
```
So the whole program becomes like this
```
>>> str1 = '"xxx"'
>>> if str1.startswith('"') and... |
Python Checking a string's first and last character | 19,954,593 | 28 | 2013-11-13T13:05:20Z | 19,954,673 | 8 | 2013-11-13T13:08:56Z | [
"python",
"string",
"python-2.7"
] | can anyone please explain what is wrong with this code?
```
str1='"xxx"'
print str1
if str1[:1].startswith('"'):
if str1[:-1].endswith('"'):
print "hi"
else:
print "condition fails"
else:
print "bye"
```
The output I got is:
```
Condition fails
```
but I expected it to print `hi` instead... | You should either use
```
if str1[0] == '"' and str1[-1] == '"'
```
or
```
if str1.startswith('"') and str1.endswith('"')
```
but not slice and check startswith/endswith together, otherwise you'll slice off what you're looking for... |
Fit a curve for data made up of two distinct regimes | 19,955,686 | 7 | 2013-11-13T13:57:48Z | 19,958,372 | 17 | 2013-11-13T15:54:58Z | [
"python",
"numpy",
"matplotlib",
"scipy",
"curve-fitting"
] | I'm looking for a way to plot a curve through some experimental data. The data shows a small linear regime with a shallow gradient, followed by a steep linear regime after a threshold value.
My data is here: <http://pastebin.com/H4NSbxqr>

I could fit the da... | If you don't have a particular reason to believe that linear + exponential is the true underlying cause of your data, then I think a fit to two lines makes the most sense. You can do this by making your fitting function the maximum of two lines, for example:
```
import numpy as np
import matplotlib.pyplot as plt
from ... |
error: command 'gcc' failed with exit status 1 on CentOS | 19,955,775 | 12 | 2013-11-13T14:02:58Z | 19,955,857 | 12 | 2013-11-13T14:07:35Z | [
"python",
"linux",
"bash",
"centos"
] | I'm trying to install lxml package on CentOS using `sudo pip install lxml` and its throwing this error right at the end:
## error:
```
error: command 'gcc' failed with exit status 1
---------------------------------------
Command /usr/bin/python -c "import setuptools;__file__='/tmp/pip-build-root/lxml/setup.py';exe... | Is gcc installed?
```
sudo yum install gcc
``` |
error: command 'gcc' failed with exit status 1 on CentOS | 19,955,775 | 12 | 2013-11-13T14:02:58Z | 19,956,055 | 12 | 2013-11-13T14:16:41Z | [
"python",
"linux",
"bash",
"centos"
] | I'm trying to install lxml package on CentOS using `sudo pip install lxml` and its throwing this error right at the end:
## error:
```
error: command 'gcc' failed with exit status 1
---------------------------------------
Command /usr/bin/python -c "import setuptools;__file__='/tmp/pip-build-root/lxml/setup.py';exe... | I bet you have to install `libxml2-devel` or `libxml++-devel` or even `python-devel`. But it is only a wild guess, not seeing the actual error from the log file. But it seems `gcc` is missing either a header file or a library file. |
Make a copy of a set and exclude one item | 19,956,878 | 2 | 2013-11-13T14:52:49Z | 19,956,928 | 7 | 2013-11-13T14:55:06Z | [
"python",
"set"
] | Im trying to make a set based in another set, and exclude only one item...
(do a for loop inside another for loop with an object that is inside a set, but not iterate with itself on the second loop)
Code:
```
for animal in self.animals:
self.exclude_animal = set((animal,))
self.new_animals = set(self.animals)... | `set.discard()` removes *one* item from the set, but you pass in a whole set object.
You need to remove the element **itself**, not another set with the element inside:
```
self.new_animals.discard(animal)
```
Demo:
```
>>> someset = {1, 2, 3}
>>> someset.discard({1})
>>> someset.discard(2)
>>> someset
set([1, 3])
... |
install beautiful soup using pip | 19,957,194 | 21 | 2013-11-13T15:06:32Z | 19,957,214 | 57 | 2013-11-13T15:07:43Z | [
"python",
"python-2.7",
"beautifulsoup",
"pip"
] | I am trying to install BeautifulSoup using `pip` in Python 2.7. I keep getting an error message, and can't understand why.
I followed the instructions to install pip, which was installed to the following directory: `c:\Python27\Scripts\pip.exe`, then I tried adding it to the path, and running the `pip install package`... | `pip` is a *command line tool*, not Python syntax.
In other words, run the command in your console, *not* in the Python interpreter:
```
pip install beautifulsoup4
```
You may have to use the full path:
```
C:\Python27\Scripts\pip install beautifulsoup4
```
or even
```
C:\Python27\Scripts\pip.exe install beautifu... |
How to implement 'in' and 'not in' for Pandas dataframe | 19,960,077 | 53 | 2013-11-13T17:11:07Z | 19,960,116 | 122 | 2013-11-13T17:13:39Z | [
"python",
"pandas",
"dataframe",
"sql-function"
] | How can I achieve the equivalents of SQL's `IN` and `NOT IN`?
I have a list with the required values.
Here's the scenario:
```
df = pd.DataFrame({'countries':['US','UK','Germany','China']})
countries = ['UK','China']
# pseudo-code:
df[df['countries'] not in countries]
```
My current way of doing this is as follows:... | You can use `something.isin(somewhere)` and `~something.isin(somewhere)`:
```
>>> df
countries
0 US
1 UK
2 Germany
3 China
>>> countries
['UK', 'China']
>>> df.countries.isin(countries)
0 False
1 True
2 False
3 True
Name: countries, dtype: bool
>>> df[df.countries.isin(countries)]
... |
Pelican 3.3 pelican-quickstart error "ValueError: unknown locale: UTF-8" | 19,961,239 | 139 | 2013-11-13T18:10:50Z | 19,961,403 | 424 | 2013-11-13T18:19:45Z | [
"python",
"python-2.7",
"pelican"
] | When I was trying to use pelican3.3, I typed the commend "pelican-quickstart", some errors showed up.
These are the errors:
```
(PelicanEnv)59-127-113-90:myblog Richo$ pelican-quickstart
Traceback (most recent call last):
File "/Users/Richo/Dropbox/Github/PelicanEnv/bin/pelican-quickstart", line 9, in <module>
... | You could try a solution posted [here](https://coderwall.com/p/-k_93g) or [here](http://patrick.arminio.info/blog/2012/02/fix-valueerror-unknown-locale-utf8/). Basically, add some lines to your ~/.bash\_profile:
```
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
```
There is an outstanding [bug report](https://bug... |
Construct pandas DataFrame from list of tuples | 19,961,490 | 27 | 2013-11-13T18:24:29Z | 19,961,557 | 32 | 2013-11-13T18:28:06Z | [
"python",
"python-2.7",
"pandas"
] | I have a list of tuples like
```
data = [
('r1', 'c1', avg11, stdev11),
('r1', 'c2', avg12, stdev12),
('r2', 'c1', avg21, stdev21),
('r2', 'c2', avg22, stdev22)
]
```
and I would like to put them into a pandas DataFrame with rows named by the first column and columns named by the 2nd column. It seems the way to take ... | You can pivot your DataFrame after creating:
```
>>> df = pd.DataFrame(data)
>>> df.pivot(index=0, columns=1, values=2)
# avg DataFrame
1 c1 c2
0
r1 avg11 avg12
r2 avg21 avg22
>>> df.pivot(index=0, columns=1, values=3)
# stdev DataFrame
1 c1 c2
0
r1 stdev11 ... |
Construct pandas DataFrame from list of tuples | 19,961,490 | 27 | 2013-11-13T18:24:29Z | 19,961,872 | 16 | 2013-11-13T18:44:56Z | [
"python",
"python-2.7",
"pandas"
] | I have a list of tuples like
```
data = [
('r1', 'c1', avg11, stdev11),
('r1', 'c2', avg12, stdev12),
('r2', 'c1', avg21, stdev21),
('r2', 'c2', avg22, stdev22)
]
```
and I would like to put them into a pandas DataFrame with rows named by the first column and columns named by the 2nd column. It seems the way to take ... | I submit that it is better to leave your data stacked as it is:
```
df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])
# Possibly also this if these can always be the indexes:
# df = df.set_index(['R_Number', 'C_Number'])
```
Then it's a bit more intuitive to say
```
df.set_index(['R_Number... |
Flask RESTful cross-domain issue with Angular: PUT, OPTIONS methods | 19,962,699 | 16 | 2013-11-13T19:31:03Z | 19,981,560 | 13 | 2013-11-14T15:24:16Z | [
"python",
"ajax",
"angularjs",
"flask",
"flask-restful"
] | I've developed a small write-only REST api with Flask Restful that accepts PUT request from a handful of clients that can potentially have changing IP addresses. My clients are embedded Chromium clients running an AngularJS front-end; they authenticate with my API with a simple magic key -- it's sufficient for my very ... | I resolved the issue by rewriting my Flask backend to answer with an Access-Control-Allow-Origin header in my PUT response. Furthermore, I created an OPTIONS handler in my Flask app to answer the options method by following what I read in the http RFC.
The return on the PUT method looks like this:
```
return restful.... |
Flask RESTful cross-domain issue with Angular: PUT, OPTIONS methods | 19,962,699 | 16 | 2013-11-13T19:31:03Z | 27,423,922 | 11 | 2014-12-11T13:23:16Z | [
"python",
"ajax",
"angularjs",
"flask",
"flask-restful"
] | I've developed a small write-only REST api with Flask Restful that accepts PUT request from a handful of clients that can potentially have changing IP addresses. My clients are embedded Chromium clients running an AngularJS front-end; they authenticate with my API with a simple magic key -- it's sufficient for my very ... | With the [Flask-CORS](https://github.com/wcdolphin/flask-cors) module, you can do cross-domain requests **without changing your code**.
```
from flask.ext.cors import CORS
app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
```
<https://pypi.python.org/pypi/Flask-Cors> |
Flask RESTful cross-domain issue with Angular: PUT, OPTIONS methods | 19,962,699 | 16 | 2013-11-13T19:31:03Z | 28,923,164 | 7 | 2015-03-08T04:41:26Z | [
"python",
"ajax",
"angularjs",
"flask",
"flask-restful"
] | I've developed a small write-only REST api with Flask Restful that accepts PUT request from a handful of clients that can potentially have changing IP addresses. My clients are embedded Chromium clients running an AngularJS front-end; they authenticate with my API with a simple magic key -- it's sufficient for my very ... | You can use the after\_request hook:
```
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
... |
Django import error - no module named django.conf.urls.defaults | 19,962,736 | 81 | 2013-11-13T19:32:50Z | 19,962,822 | 170 | 2013-11-13T19:38:22Z | [
"python",
"django",
"graphite",
"django-1.6"
] | I am trying to run statsd/graphite which uses django 1.6.
While accessing graphite URL, I get django module error
> File "/opt/graphite/webapp/graphite/urls.py", line 15, in
> from django.conf.urls.defaults import \*
> ImportError: No module named defaults
However, I do not find **defaults** django package inside `/... | `django.conf.urls.defaults` [has been removed in Django 1.6](https://docs.djangoproject.com/en/dev/internals/deprecation/#deprecation-removed-in-1-6). If the problem was in your own code, you would fix it by changing the import to
```
from django.conf.urls import patterns, url, include
```
However, in your case the p... |
Flask request.json to dict | 19,963,647 | 10 | 2013-11-13T20:27:02Z | 19,965,016 | 11 | 2013-11-13T21:44:59Z | [
"python",
"json",
"jquery",
"dictionary",
"flask"
] | Im struggling with JQuery ajax methods and Flask, trying to make an ajax call to retrieve some form.
My js code looks like this:
```
$.ajax({
type: 'POST',
url: '/projects/dummyName',
data: JSON.stringify("{'ajax': 'True'}"),
contentType: 'application/json;charset=UTF-8',
dataType: ... | The data is being put into request.json because of the mimetype of the request. I believe you are looking for [`get_json`](http://flask.pocoo.org/docs/api/#flask.Request.get_json).
```
@app.route('/projects/<name>', methods=['GET', 'POST'])
def projects(name=None):
req_json = request.get_json()
print(req_json[... |
python Decimal - checking if integer | 19,965,018 | 4 | 2013-11-13T21:45:09Z | 19,965,088 | 12 | 2013-11-13T21:48:54Z | [
"python",
"format",
"decimal"
] | I am using the Decimal library in python, and printing out the values using
format(value,'f') , where value is a Decimal.
I get numbers in the form 10.00000, which refelcts the precision on the decimal.
I know that float supports is\_integer, but there seems to be a lack of a similar api for decimals. I was wondering i... | You could use the modulo operation to check if there is a non-integer remainder:
```
>>> Decimal('3.14') % 1 == 0
False
>>> Decimal('3') % 1 == 0
True
>>> Decimal('3.0') % 1 == 0
True
``` |
python reduce to find the union of sets | 19,965,680 | 5 | 2013-11-13T22:23:20Z | 19,965,900 | 10 | 2013-11-13T22:36:48Z | [
"python",
"dictionary",
"functional-programming",
"set",
"fold"
] | I am trying to find the union of set of sets. Specifically I want the union of the list of nodes for each key in the dictionary of `networkx` graphs called `periodic_gs`. I would like to use the `reduce` function as it seems reasonable to take the union of all `periodic_gs[x].nodes()` where `x` is a key of `periodic_gs... | You can use `set.union` like this:
```
>>> lis = [{1, 2, 3, 4}, {3, 4, 5}, {7, 3, 6}]
>>> set().union(*lis)
set([1, 2, 3, 4, 5, 6, 7])
```
Using `reduce`:
```
>>> reduce(set.union, lis)
set([1, 2, 3, 4, 5, 6, 7])
```
For your code this should do it:
```
set().union(*(x.nodes() for x in periodic_gs.values()))
reduc... |
Pandas: filling missing values by mean in each group | 19,966,018 | 11 | 2013-11-13T22:43:25Z | 19,966,142 | 11 | 2013-11-13T22:51:24Z | [
"python",
"pandas"
] | This should be straightforward, but the closest thing I've found is this post:
[pandas: Filling missing values within a group](http://stackoverflow.com/questions/18265930/pandas-filling-missing-values-within-a-group), and I still can't solve my problem....
Suppose I have the following dataframe
```
df = pd.DataFrame(... | One way would be to use `transform`:
```
>>> df
name value
0 A 1
1 A NaN
2 B NaN
3 B 2
4 B 3
5 B 1
6 C 3
7 C NaN
8 C 3
>>> df["value"] = df.groupby("name").transform(lambda x: x.fillna(x.mean()))
>>> df
name value
0 A 1
1 A 1
2 ... |
PyQt5: How can I connect a QPushButton to a slot? | 19,966,056 | 5 | 2013-11-13T22:46:13Z | 19,967,110 | 11 | 2013-11-14T00:15:29Z | [
"python",
"qt",
"signals-slots",
"pyqt5"
] | Okay, so pretty much every tutorial/understandable-written-in-human-language-documentation is for PyQt4. But, PyQt5 changed how the whole 'connect button to a slot' works, and I still can't figure it out how to do it.
I did a quick gui in QtDesigner, and I have a QPushButton and a label. When I click the button, I wan... | I don't know where you got the idea that "PyQt5 changed how the whole 'connect button to a slot' works", but it is completely and utterly wrong. There have been no such changes, as can be readily seen from the official PyQt documentation:
* [PyQt4 Signals & Slots documentation](http://pyqt.sourceforge.net/Docs/PyQt4/n... |
CORS error on same domain? | 19,966,707 | 9 | 2013-11-13T23:39:34Z | 19,966,772 | 16 | 2013-11-13T23:45:22Z | [
"javascript",
"python",
"ajax",
"cross-domain",
"cors"
] | I'm running into a weird CORS issue right now.
Here's the error message:
```
XMLHttpRequest cannot load http://localhost:8666/routeREST/select?q=[...]
Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin
```
Two servers:
* localhost:8666/routeREST/ : this is a simple Python Bottle server.
* l... | It is only considered to be the same if the *protocol*, *host* **and** *port* is the same: [Same Origin Policy](http://www.w3.org/Security/wiki/Same_Origin_Policy)
If you want to enable it you must follow [cors](http://www.w3.org/TR/cors/) by adding headers. Mozilla has [examples](https://developer.mozilla.org/en-US/d... |
Comparing string and unicode in Python 2.7.5 | 19,967,399 | 6 | 2013-11-14T00:42:48Z | 19,967,470 | 7 | 2013-11-14T00:49:32Z | [
"python",
"python-2.7",
"python-unicode"
] | I wonder why when I make:
```
a = [u'k',u'Ä',u'Ä
']
```
and then type:
```
'k' in a
```
I get `True`, while:
```
'Ä' in a
```
will give me `False`?
It really gives me headache and it seems someone made this on purpose to make people mad... | **And why is this?**
In Python 2.x, you can't compare unicode to string directly for non-ascii characters. This will raise a warning:
```
Warning (from warnings module):
File "__main__", line 1
UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
... |
Python BeautifulSoup findAll by "class" attribute | 19,969,056 | 9 | 2013-11-14T03:36:31Z | 19,969,067 | 8 | 2013-11-14T03:37:49Z | [
"python",
"web-scraping",
"beautifulsoup"
] | I want to do the following code, which is what BS documentation says to do, the only problem is that the word "class" isn't just a word. It can be found inside HTML, but it's also a python keyword which causes this code to throw an error.
So how do I do the following?
```
soup.findAll('ul', class="score")
``` | Here is how to do it:
```
soup.find_all('ul', {'class':"score"})
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.