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 Socket Receive Large Amount of Data | 17,667,903 | 16 | 2013-07-16T04:16:13Z | 17,668,009 | 31 | 2013-07-16T04:27:25Z | [
"python",
"sockets"
] | When I try to receive larger amounts of data it gets cut off and I have to press enter to get the rest of the data. At first I was able to increase it a little bit but it still won't receive all of it. As you can see I have increased the buffer on the conn.recv() but it still doesn't get all of the data. It cuts it off... | TCP/IP is a *stream-based* protocol, not a *message-based* protocol. There's no guarantee that every `send()` call by one peer results in a single `recv()` call by the other peer receiving the exact data sentâit might receive the data piece-meal, split across multiple `recv()` calls, due to packet fragmentation.
You... |
Remove \n or \t from a given string | 17,667,923 | 4 | 2013-07-16T04:18:46Z | 17,667,941 | 9 | 2013-07-16T04:21:03Z | [
"python",
"string"
] | How can I strip a string with all `\n` and `\t` in python other than using `strip()`?
I want to format a string like `"abc \n \t \t\t \t \nefg"` to `"abcefg`"?
```
result = re.match("\n\t ", "abc \n\t efg")
print result
```
and result is `None` | It looks like you also want to remove spaces. You can do something like this,
```
>>> import re
>>> s = "abc \n \t \t\t \t \nefg"
>>> s = re.sub('\s+', '', s)
>>> s
'abcefg'
```
Another way would be to do,
```
>>> s = "abc \n \t \t\t \t \nefg"
>>> s = s.translate(None, '\t\n ')
>>> s
'abcefg'
``` |
What is the point of setLevel in a python logging handler? | 17,668,633 | 21 | 2013-07-16T05:26:22Z | 17,668,861 | 21 | 2013-07-16T05:43:45Z | [
"python",
"logging"
] | Let's say I have the following code:
```
import logging
import logging.handlers
a = logging.getLogger('myapp')
h = logging.handlers.RotatingFileHandler('foo.log')
h.setLevel(logging.DEBUG)
a.addHandler(h)
# The effective log level is still logging.WARN
print a.getEffectiveLevel()
a.debug('foo message')
a.warn('warn... | It allows finer control. By default the root logger has `WARNING` level set, this means that it wont print messages with lower level(no matter how the handlers' levels are set!). But, if you set the root logger's level to `DEBUG`, indeed the message get sent to the log file:
```
import logging
import logging.handlers
... |
What is the point of setLevel in a python logging handler? | 17,668,633 | 21 | 2013-07-16T05:26:22Z | 17,668,948 | 8 | 2013-07-16T05:50:01Z | [
"python",
"logging"
] | Let's say I have the following code:
```
import logging
import logging.handlers
a = logging.getLogger('myapp')
h = logging.handlers.RotatingFileHandler('foo.log')
h.setLevel(logging.DEBUG)
a.addHandler(h)
# The effective log level is still logging.WARN
print a.getEffectiveLevel()
a.debug('foo message')
a.warn('warn... | In Python logging there are two different concepts: the level that the logger logs at and the level that the handler actually activates.
When a call to log is made, what is basically happening is:
```
if self.level <= loglevel:
for handler in self.handlers:
handler(loglevel, message)
```
While each of th... |
Finding Proper Nouns using NLTK WordNet | 17,669,952 | 13 | 2013-07-16T06:57:32Z | 17,672,491 | 25 | 2013-07-16T09:13:57Z | [
"python",
"nltk",
"wordnet"
] | Is there any way to find proper nouns using NLTK WordNet?Ie., Can i tag Possessive nouns using nltk Wordnet ? | I don't think you need WordNet to find proper nouns, I suggest using the Part-Of-Speech tagger `pos_tag`.
**To find Proper Nouns, look for the `NNP` tag:**
```
from nltk.tag import pos_tag
sentence = "Michael Jackson likes to eat at McDonalds"
tagged_sent = pos_tag(sentence.split())
# [('Michael', 'NNP'), ('Jackson'... |
Python 2: insert existing list inside of new explicit list definition | 17,670,457 | 3 | 2013-07-16T07:24:52Z | 17,670,480 | 7 | 2013-07-16T07:26:15Z | [
"python",
"list"
] | This may not be possible, but if it is, it'd be convenient for some code I'm writing:
```
ListOne = ['jumps', 'over', 'the']
ListTwo = ['The', 'quick', 'brown', 'fox', ListOne, 'lazy', 'dog!']
```
If I do this, I'll end up with ListOne being a single item being a list inside of ListTwo.
But instead, I want to expand... | You can just use the `+` operator to concatenate lists:
```
ListOne = ['jumps', 'over', 'the']
ListTwo = ['The', 'quick', 'brown', 'fox'] + ListOne + ['lazy', 'dog!']
```
`ListTwo` will be:
```
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']
``` |
Composition - Reference to another class in Python | 17,671,242 | 3 | 2013-07-16T08:07:44Z | 17,671,333 | 8 | 2013-07-16T08:13:26Z | [
"python"
] | In my example below in Python, object x 'has-an' object y. I'd like to be able to invoke methods of x from y.
I'm able to achieve it using @staticmethod, however I'm discouraged to do that.
Is there any way(s) to reference the whole Object x from Object y?
```
class X(object):
def __init__(self):
self.c... | You need to store a reference to the object which has the instance of a Y object:
```
class X(object):
def __init__(self):
self.count = 5
self.y = Y(self) #create a y passing in the current instance of x
def add2(self):
self.count += 2
class Y(object):
def __init__(self,parent):
... |
How to subtract values from dictionaries | 17,671,875 | 6 | 2013-07-16T08:43:42Z | 17,671,932 | 11 | 2013-07-16T08:45:52Z | [
"python",
"dictionary"
] | I have two dictionaries in Python:
```
d1 = {'a': 10, 'b': 9, 'c': 8, 'd': 7}
d2 = {'a': 1, 'b': 2, 'c': 3, 'e': 2}
```
I want to substract values between dictionaries d1-d2 and get the result:
```
d3 = {'a': 9, 'b': 7, 'c': 5, 'd': 7 }
```
Now I'm using two loops but this solution is not too fast
```
for x,i in e... | Use [`collections.Counter`](http://docs.python.org/2/library/collections.html#collections.Counter). The syntax is very easy:
```
>>> from collections import Counter
>>> d1 = Counter({'a': 10, 'b': 9, 'c': 8, 'd': 7})
>>> d2 = Counter({'a': 1, 'b': 2, 'c': 3, 'e': 2})
>>> d3 = d1 - d2
>>> print d3
Counter({'a': 9, 'b':... |
How to subtract values from dictionaries | 17,671,875 | 6 | 2013-07-16T08:43:42Z | 17,672,180 | 12 | 2013-07-16T08:57:36Z | [
"python",
"dictionary"
] | I have two dictionaries in Python:
```
d1 = {'a': 10, 'b': 9, 'c': 8, 'd': 7}
d2 = {'a': 1, 'b': 2, 'c': 3, 'e': 2}
```
I want to substract values between dictionaries d1-d2 and get the result:
```
d3 = {'a': 9, 'b': 7, 'c': 5, 'd': 7 }
```
Now I'm using two loops but this solution is not too fast
```
for x,i in e... | I think a very Pythonic way would be using [dict comprehension](http://www.python.org/dev/peps/pep-0274/):
```
d3 = {key: d1[key] - d2.get(key, 0) for key in d1.keys()}
```
Note that this only works in Python 2.7+ or 3. |
Django random value for Model field | 17,672,437 | 2 | 2013-07-16T09:11:17Z | 17,672,477 | 7 | 2013-07-16T09:13:24Z | [
"python",
"django",
"django-models",
"django-orm"
] | So I am able to generate a random id using uuid
So far so good
But when I try to database i get same value
```
def f():
d = uuid4()
str = d.hex
return str[0:16]
```
---
```
class Q(models.Model):
a = models.CharField(max_length=150)
b = models.IntegerField(max_length=25)
c = models.IntegerField(ma... | You should not call the function that you are passing to `default`:
```
e = models.CharField(max_length=18, default=f, unique=True)
```
FYI, according to [docs](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.default), you should pass a value or a callable:
> The default value for the... |
Pymongo API TypeError: Unhashable dict | 17,674,100 | 4 | 2013-07-16T10:25:35Z | 17,674,225 | 7 | 2013-07-16T10:32:25Z | [
"python",
"api",
"mongodb",
"pymongo"
] | I'm writing an API for my software so that it is easier to access mongodb.
I have this line:
```
def update(self, recid):
self.collection.find_and_modify(query={"recid":recid}, update={{ "$set": {"creation_date":str( datetime.now() ) }}} )
```
Which throws `TypeError: Unhashable type: 'dict'`.
This func... | It's simple, you have added extra/redundant curly braces, try this:
```
self.collection.find_and_modify(query={"recid":recid},
update={"$set": {"creation_date": str(datetime.now())}})
```
UPD (explanation, assuming you are on python>=2.7):
The error occurs because python thinks you a... |
Kivy how to rotate a picture | 17,674,736 | 4 | 2013-07-16T10:57:21Z | 17,699,932 | 12 | 2013-07-17T12:35:44Z | [
"python",
"kivy"
] | i'm trying to rotate some pictures i have to show on the screen, these picture are inside a stacklayout, and i need to show them as Portrait instead of landscape,i'm using the Image Widget
Thanks | The previous 2 answer of toto\_tico is a way to do, but i would rather create a new widget for it, and use it:
```
Builder.load_string('''
<RotatedImage>:
canvas.before:
PushMatrix
Rotate:
angle: root.angle
axis: 0, 0, 1
origin: root.center
canvas.after:
... |
Python webdriver to handle pop up browser windows which is not an alert | 17,676,036 | 5 | 2013-07-16T12:02:39Z | 29,052,586 | 13 | 2015-03-14T18:25:48Z | [
"python",
"selenium",
"webdriver"
] | I am working on a web application, in which clicking on some link another popup windows appears. The pop windows is not an alert but its a form with various fields to be entered by user and click "Next".
How can I handle/automate this popup windows using selenium.
Summary :-
1. Click on the hyperlink (url) - "CLICK ... | Switching to a popup is challenging for at least two separate reasons:
1. The one that many people know, which is that you need to use `driver.switch_to.window(window_handle)` both when the popup appears, so that you can find elements in the popup window, and after the popup is closed, so that you can find elements ba... |
Tkinter assign button command in loop with lambda | 17,677,649 | 16 | 2013-07-16T13:19:05Z | 17,677,768 | 21 | 2013-07-16T13:24:43Z | [
"python",
"loops",
"button",
"lambda",
"tkinter"
] | I'm trying to create a few buttons (with a for) like so:
```
def a(self, name):
print name
users = {"Test":"127.0.0.0", "Test2":"128.0.0.0"}
row = 1
for name in users:
user_button = Tkinter.Button(self.root,
text=name,
command=lambda: self.a(na... | The problem is your lamba in the for loop. Your lambda is using the `name` variable, but the `name` variable gets reassigned each time through the for loop. So in the end, all of the buttons get the last value that `name` was assigned to in the for loop. To avoid this you can use default keyword parameters in your lamb... |
Flask instanciation app = Flask() | 17,678,850 | 4 | 2013-07-16T14:10:01Z | 17,679,360 | 7 | 2013-07-16T14:30:09Z | [
"python",
"flask",
"init"
] | I intentionally removed **name** in app = Flask(**name**) and I get this error:
```
Traceback (most recent call last):
File "routes.py", line 4, in <module>
app = Flask()
TypeError: __init__() takes at least 2 arguments (1 given)
```
this is my code from [nettuts](http://net.tutsplus.com/tutorials/python... | `__init__` is akin to a constructor in python - its the function which gets called when you create a new instance of an object, in this case the `Flask` application object.
App objects need an `import_name`, which is the first argument you pass to the `Flask` constructor. You can read more about that [here](http://fla... |
Flask instanciation app = Flask() | 17,678,850 | 4 | 2013-07-16T14:10:01Z | 17,680,146 | 8 | 2013-07-16T15:00:44Z | [
"python",
"flask",
"init"
] | I intentionally removed **name** in app = Flask(**name**) and I get this error:
```
Traceback (most recent call last):
File "routes.py", line 4, in <module>
app = Flask()
TypeError: __init__() takes at least 2 arguments (1 given)
```
this is my code from [nettuts](http://net.tutsplus.com/tutorials/python... | If you understand the concept of class and objects, then `__init__` is the constructor which initializes an instance of the class. In this case, the class is Flask and when you do the following, you are initializing the instance of a Flask object:
```
app = Flask(__name__)
```
Now your question, "Where is this init m... |
Pandas DataFrame Groupby two columns and get counts | 17,679,089 | 23 | 2013-07-16T14:19:44Z | 17,679,517 | 27 | 2013-07-16T14:37:33Z | [
"python",
"pandas",
"dataframe"
] | I have a pandas dataframe in the following format:
```
df = pd.DataFrame([[1.1, 1.1, 1.1, 2.6, 2.5, 3.4,2.6,2.6,3.4,3.4,2.6,1.1,1.1,3.3], list('AAABBBBABCBDDD'), [1.1, 1.7, 2.5, 2.6, 3.3, 3.8,4.0,4.2,4.3,4.5,4.6,4.7,4.7,4.8], ['x/y/z','x/y','x/y/z/n','x/u','x','x/u/v','x/y/z','x','x/u/v/b','-','x/y','x/y/z','x','x/u/v... | You are looking for [`size`](http://pandas.pydata.org/pandas-docs/stable/groupby.html#aggregation):
```
In [11]: df.groupby(['col5', 'col2']).size()
Out[11]:
col5 col2
1 A 1
D 3
2 B 2
3 A 3
C 1
4 B 1
5 B 2
6 B 1
dtype: int64
```
---
... |
Pandas DataFrame Groupby two columns and get counts | 17,679,089 | 23 | 2013-07-16T14:19:44Z | 17,679,980 | 18 | 2013-07-16T14:53:30Z | [
"python",
"pandas",
"dataframe"
] | I have a pandas dataframe in the following format:
```
df = pd.DataFrame([[1.1, 1.1, 1.1, 2.6, 2.5, 3.4,2.6,2.6,3.4,3.4,2.6,1.1,1.1,3.3], list('AAABBBBABCBDDD'), [1.1, 1.7, 2.5, 2.6, 3.3, 3.8,4.0,4.2,4.3,4.5,4.6,4.7,4.7,4.8], ['x/y/z','x/y','x/y/z/n','x/u','x','x/u/v','x/y/z','x','x/u/v/b','-','x/y','x/y/z','x','x/u/v... | Followed by @Andy's answer, you can do following to solve your second question:
```
In [56]: df.groupby(['col5','col2']).size().reset_index().groupby('col2')[[0]].max()
Out[56]:
0
col2
A 3
B 2
C 1
D 3
``` |
Does Python intern strings? | 17,679,861 | 6 | 2013-07-16T14:49:09Z | 17,680,240 | 7 | 2013-07-16T15:04:14Z | [
"python",
"memoization",
"string-interning"
] | In Java, explicitly declared Strings are interned by the JVM, so that subsequent declarations of the same String results in two pointers to the same String instance, rather than two separate (but identical) Strings.
For example:
```
public String baz() {
String a = "astring";
return a;
}
public String bar() ... | This is called interning, and yes, Python does do this to some extent, for shorter strings created as string literals. See [Python string interning](http://stackoverflow.com/q/15541404) for some discussion.
Interning is runtime dependent, there is no standard for it. Interning is always a trade-off between memory use ... |
Python regular expression not matching | 17,680,631 | 5 | 2013-07-16T15:21:42Z | 17,680,674 | 10 | 2013-07-16T15:23:15Z | [
"python",
"regex"
] | This is one of those things where I'm sure I'm missing something simple, but... In the sample program below, I'm trying to use Python's RE library to parse the string "line" to get the floating-point number just before the percent sign, i.e. "90.31". But the code always prints "no match".
I've tried a couple other reg... | `match` only matches from the *beginning* of the string. Your code works fine if you do `pct_re.search(line)` instead. |
Python ssh using Tor proxy | 17,681,031 | 6 | 2013-07-16T15:40:44Z | 17,760,495 | 11 | 2013-07-20T08:52:33Z | [
"python",
"ssh",
"paramiko",
"tor"
] | I would like to be able to send data through Tor when I use ssh from Python scripts. Tor works as expected when I use an OpenSSH client to manually ssh to the host. This is my ssh config file. I use connect-proxy with ProxyCommand to route the connections through Tor (again, this works fine via a standard OpenSSH clien... | You need to create `ProxyCommand` (a socket-like object) and pass it to `client.connect()`
```
import paramiko
conf = paramiko.SSHConfig()
conf.parse(open('/home/user/.ssh/config'))
host = conf.lookup('host')
print host
proxy = paramiko.ProxyCommand(host['proxycommand'])
client = paramiko.SSHClient()
client.set_mis... |
How make dns queries in dns-python as dig (with aditional records section)? | 17,681,230 | 5 | 2013-07-16T15:50:07Z | 17,695,103 | 11 | 2013-07-17T08:42:50Z | [
"python",
"dns",
"dig",
"dnspython"
] | I trying use `dns python` and want get all records with `ANY` type query:
```
import dns.name
import dns.message
import dns.query
domain = 'google.com'
name_server = '8.8.8.8'
domain = dns.name.from_text(domain)
if not domain.is_absolute():
domain = domain.concatenate(dns.name.root)
request = dns.message.make_q... | I found solution, I made request as `dig`:
```
import dns.name
import dns.message
import dns.query
import dns.flags
domain = 'google.com'
name_server = '8.8.8.8'
ADDITIONAL_RDCLASS = 65535
domain = dns.name.from_text(domain)
if not domain.is_absolute():
domain = domain.concatenate(dns.name.root)
request = dns.m... |
Extract email sub-strings from large document | 17,681,670 | 3 | 2013-07-16T16:10:01Z | 17,681,902 | 24 | 2013-07-16T16:20:33Z | [
"python",
"string"
] | I have a very large .txt file with hundreds of thousands of email addresses scattered throughout. They all take the format:
```
...<[email protected]>...
```
What is the best way to have Python to cycle through the entire .txt file looking for a all instances of a certain @domain string, and then grab the entirety of t... | This [code](https://developers.google.com/edu/python/regular-expressions) extracts the email addresses in a string. Use it while reading line by line
```
>>> import re
>>> line = "why people don't know what regex are? let me know [email protected]"
>>> match = re.search(r'[\w\.-]+@[\w\.-]+', line)
>>> match.gr... |
Unable to retrieve files from send_from_directory() in flask | 17,681,762 | 3 | 2013-07-16T16:13:53Z | 17,681,884 | 9 | 2013-07-16T16:19:44Z | [
"python",
"flask"
] | I have a html file which references static object like this
```
<img src="img/snacks.png">
<link href="css/bluestrap.css" rel="stylesheet">
```
Hence the browser tries to call this via and flask fails to do so
```
http://127.0.0.1:5000/img/snacks.png
```
There are lots of such references across multiple files hence... | In production, you don't want to serve static files using the flask server. I suggest you use a proper web server to do that.
For dev, since you don't want to use `url_for`, you can try to initialize your flask app as below. This way, flask knows where your static files are.
```
app = Flask(__name__, static_folder='s... |
Scatter plot and Color mapping in Python | 17,682,216 | 22 | 2013-07-16T16:36:31Z | 17,682,382 | 41 | 2013-07-16T16:45:31Z | [
"python",
"matplotlib"
] | I have a range of points x and y stored in numpy arrays.
Those represent x(t) and y(t) where t=0...T-1
I am plotting a scatter plot using
```
import matplotlib.pyplot as plt
plt.scatter(x,y)
plt.show()
```
I would like to have a colormap representing the time (therefore coloring the points depending on the index in... | Here is an example
```
import numpy as np
import matplotlib.pyplot as plt
x = np.random.rand(100)
y = np.random.rand(100)
t = np.arange(100)
plt.scatter(x, y, c=t)
plt.show()
```
Here you are setting the color based on the index, `t`, which is just an array of `[1, 2, ..., 100]`.
 is thread-safe. Let me explain it:
I have
```
d = defaultdict(list)
```
which creates list for missing keys ... | It is thread safe, *in this specific case*.
To know why it is important to understand when Python switches threads. CPython only allows switching between threads between Python bytecode steps. This is where the GIL comes in; every N byte code instructions the lock is released and a thread switch can take place.
The `... |
How to add a calculated field to a Django model | 17,682,567 | 16 | 2013-07-16T16:54:36Z | 17,682,694 | 29 | 2013-07-16T17:01:12Z | [
"python",
"django-models",
"django-admin"
] | I have a simple `Employee` model that includes `firstname`, `lastname` and `middlename` fields.
On the admin side and likely elsewhere, I would like to display that as:
```
lastname, firstname middlename
```
To me the logical place to do this is in the model by creating a calculated field as such:
```
from django.d... | That's not something you do as a field. Even if that syntax worked, it would only give the value when the class was defined, not at the time you access it. You should do this as a method, and you can use the `@property` decorator to make it look like a normal attribute.
```
@property
def name(self):
return ''.join... |
How to add a calculated field to a Django model | 17,682,567 | 16 | 2013-07-16T16:54:36Z | 17,683,916 | 20 | 2013-07-16T18:07:37Z | [
"python",
"django-models",
"django-admin"
] | I have a simple `Employee` model that includes `firstname`, `lastname` and `middlename` fields.
On the admin side and likely elsewhere, I would like to display that as:
```
lastname, firstname middlename
```
To me the logical place to do this is in the model by creating a calculated field as such:
```
from django.d... | Ok... Daniel Roseman's answer seemed like it should have worked. As is always the case, you find what your looking for *after you post the question*.
From the [django 1.5 docs I found this example](https://docs.djangoproject.com/en/1.5/topics/db/models/#model-methods) that worked right out of the box. Thanks to all fo... |
How to convert a pandas DataFrame subset of columns AND rows into a numpy array? | 17,682,613 | 33 | 2013-07-16T16:56:52Z | 17,682,662 | 64 | 2013-07-16T16:59:49Z | [
"python",
"arrays",
"numpy",
"pandas",
"scikit-learn"
] | I'm wondering if there is a simpler, memory efficient way to select a subset of rows and columns from a pandas DataFrame.
For instance, given this dataframe:
```
df = DataFrame(np.random.rand(4,5), columns = list('abcde'))
print df
a b c d e
0 0.945686 0.000710 0.909158 ... | Use its value directly:
```
In [79]: df[df.c > 0.5][['b', 'e']].values
Out[79]:
array([[ 0.98836259, 0.82403141],
[ 0.337358 , 0.02054435],
[ 0.29271728, 0.37813099],
[ 0.70033513, 0.69919695]])
``` |
How to convert a pandas DataFrame subset of columns AND rows into a numpy array? | 17,682,613 | 33 | 2013-07-16T16:56:52Z | 17,682,665 | 15 | 2013-07-16T17:00:01Z | [
"python",
"arrays",
"numpy",
"pandas",
"scikit-learn"
] | I'm wondering if there is a simpler, memory efficient way to select a subset of rows and columns from a pandas DataFrame.
For instance, given this dataframe:
```
df = DataFrame(np.random.rand(4,5), columns = list('abcde'))
print df
a b c d e
0 0.945686 0.000710 0.909158 ... | Perhaps something like this for the first problem, you can simply access the columns by their names:
```
>>> df = pd.DataFrame(np.random.rand(4,5), columns = list('abcde'))
>>> df[df['c']>.5][['b','e']]
b e
1 0.071146 0.132145
2 0.495152 0.420219
```
For the second problem:
```
>>> df[df['c']>.... |
Python - Detect if remote computer is on | 17,682,818 | 5 | 2013-07-16T17:06:49Z | 17,683,510 | 11 | 2013-07-16T17:44:36Z | [
"python",
"udp",
"heartbeat"
] | So, I have an application in Python, but I want to know if the computer (which is running the application) is on, from another remote computer.
Is there any way to do this? I was thinking to use UDP packets, to send some sort of keep-alive, using a counter. Ex. every 5 mins the client sends an UDP 'keep-alive' packet ... | If your goal actually is to test whether a specific service is running on the remote machine, you could test if the network port that this service should run on is reachable. Example:
```
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect(('hostname', 22))
print "Port 22 reachab... |
Join string before, between, and after | 17,683,062 | 8 | 2013-07-16T17:19:40Z | 17,683,215 | 12 | 2013-07-16T17:27:08Z | [
"python",
"string"
] | Suppose I have this list:
```
lis = ['a','b','c','d']
```
If I do `'x'.join(lis)` the result is:
```
'axbxcxd'
```
What would be a clean, simple way to get this output?
```
'xaxbxcxdx'
```
I could write a helper function:
```
def joiner(s, it):
return s+s.join(it)+s
```
and call it like `joiner('x',lis)` wh... | ```
>>> '{1}{0}{1}'.format(s.join(lis), s)
'xaxbxcxdx'
``` |
Why must I explicitly inherit object for slots to work as advertised? | 17,683,629 | 3 | 2013-07-16T17:51:03Z | 17,683,670 | 10 | 2013-07-16T17:53:27Z | [
"python"
] | A colleague of mine recently showed me the following session:
```
>>> class Foo:
... __slots__ = ['x']
... def __init__(self):
... self.x = "x"
...
>>> f = Foo()
>>> f.x
'x'
>>> f.y = 1
>>> class Bar(object):
... __slots__ = ['x']
... def __init__(self):
... self.x = "x"
...
>... | It does say it, just not very explicitly:
> The default can be overridden by defining \_\_slots\_\_ in a new-style class definition.
In Python 2, when you inherit from `object`, you're creating a new-style class. If you don't, it's an old-style class. |
Python convert csv to xlsx | 17,684,610 | 16 | 2013-07-15T10:21:28Z | 17,684,679 | 29 | 2013-07-16T18:51:52Z | [
"python",
"excel",
"file",
"csv",
"xlsx"
] | In [this post](http://superuser.com/questions/301431/how-to-batch-convert-csv-to-xls-xlsx) there is a Python example to convert from csv to xls.
However, my file has more than 65536 rows so xls does not work. If I name the file xlsx it doesnt make a difference. Is there a Python package to convert to xlsx? | Here's an example using [xlsxwriter](https://xlsxwriter.readthedocs.org/en/latest):
```
import os
import glob
import csv
from xlsxwriter.workbook import Workbook
for csvfile in glob.glob(os.path.join('.', '*.csv')):
workbook = Workbook(csvfile + '.xlsx')
worksheet = workbook.add_worksheet()
with open(csv... |
Python convert csv to xlsx | 17,684,610 | 16 | 2013-07-15T10:21:28Z | 26,456,641 | 9 | 2014-10-19T23:42:36Z | [
"python",
"excel",
"file",
"csv",
"xlsx"
] | In [this post](http://superuser.com/questions/301431/how-to-batch-convert-csv-to-xls-xlsx) there is a Python example to convert from csv to xls.
However, my file has more than 65536 rows so xls does not work. If I name the file xlsx it doesnt make a difference. Is there a Python package to convert to xlsx? | With my library `pyexcel`, you can do it in one command line:
```
from pyexcel.cookbook import merge_all_to_a_book
import pyexcel.ext.xlsx # needed to support xlsx format, pip install pyexcel-xlsx
import glob
merge_all_to_a_book(glob.glob("your_csv_directory/*.csv"), "output.xlsx")
```
Each csv will have its own sh... |
Is there a Python function that checks if a generator is started? | 17,684,908 | 6 | 2013-07-16T19:03:04Z | 17,712,835 | 7 | 2013-07-18T01:05:10Z | [
"python",
"generator"
] | I try to define a generator function `mycount()` that can be reset with the generator function `send(0)` as in the example below. Everything works fine, except when I use `send(0)` on a new generator object that hasn't started yet. In this case it gives a `TypeError`. Is there any function that checks if the generator ... | To avoid sending a non-`None` value to a just-started generator, you need to call `next` or `send(None)` first. I agree with the others that David Beazley's [coroutine decorator](http://dabeaz.com/coroutines/coroutine.py) (in python 3.x you need to call to `__next__()` function instead of `next()`) is a great option. T... |
NLTK for Persian | 17,684,930 | 6 | 2013-07-16T19:04:15Z | 22,017,922 | 13 | 2014-02-25T14:58:26Z | [
"python",
"nlp",
"nltk"
] | How to use functions of NLTK for Persian?
For example: 'concordance'. When I use 'concordance', the answer is 'not match', however there is the parameter of concordance in my text.
the input is very simple .it contains of "hello Ø³ÙØ§Ù
".when parameter of 'concordance' is 'hello' the answer is correct ,but , if it's... | Strongly recommended python Persian library for NLP: <https://github.com/sobhe/hazm>
Usage:
```
>>> from __future__ import unicode_literals
>>> from hazm import Normalizer
>>> normalizer = Normalizer()
>>> normalizer.normalize('Ø§ØµÙØ§Ø ÙÙÙØ³Ù ÙØ§ Ù Ø§Ø³ØªÙØ§Ø¯Ù از ÙÛÙ
âÙØ§ØµÙ٠پردازش را Ø... |
How do I test Django QuerySets are equal? | 17,685,023 | 6 | 2013-07-16T19:09:54Z | 17,685,136 | 10 | 2013-07-16T19:15:35Z | [
"python",
"django",
"django-testing"
] | I am trying to test my Django views. This view passes a QuerySet to the template:
```
def merchant_home(request, slug):
merchant = Merchant.objects.get(slug=slug)
product_list = merchant.products.all()
return render_to_response('merchant_home.html',
{'merchant': merchant,
... | Use [assertQuerysetEqual](https://docs.djangoproject.com/en/1.9/topics/testing/tools/#django.test.TransactionTestCase.assertQuerysetEqual), which is built to compare the two querysets for you. You will need to subclass Django's `django.test.TestCase` for it to be available in your tests. |
in python: using a list of file paths with the 'with' keyword | 17,685,106 | 3 | 2013-07-16T19:14:00Z | 17,685,152 | 8 | 2013-07-16T19:16:25Z | [
"python"
] | If I want to work with two files I can write:
```
with open(fname1, 'r') as f1, open(fname2, 'r') as f2:
# do stuff with f1 and f2
```
But what if I have a list of paths (say, from glob.glob)? Can I do something analogous in a list comprehension? I have in mind something like:
```
with [open(path, 'r') for path ... | The object of a `with` statement must be a context manager. So, no, you can't do this with a list, but you might be able to do it with a custom container.
See: <http://docs.python.org/2/library/contextlib.html>
Or, for 3.3+ there's this: <http://docs.python.org/dev/library/contextlib.html#contextlib.ExitStack> (Note,... |
Keeping file attributes on a copy | 17,685,217 | 6 | 2013-07-16T19:20:05Z | 17,685,271 | 9 | 2013-07-16T19:22:54Z | [
"python",
"file-attributes"
] | I have the situation whereby I want to keep the original attributes on a file (the file creation date etc). Normally when you copy files in Windows, the copy that you make gets new 'modified' dates etc. I have come accross the `shutil.copy` command â although this doesn't keep the file attributes the same.
I found t... | If you look at the documentation for `shutil`, you'll immediately find the [`copy2`](http://docs.python.org/3.3/library/shutil.html#shutil.copy2) function, which is:
> Identical to `copy()` except that `copy2()` also attempts to preserve all file metadata.
In recent versions of Python, there's a whole slew of functio... |
Get the number of friends a facebook user has | 17,685,860 | 3 | 2013-07-16T19:59:43Z | 17,747,967 | 7 | 2013-07-19T13:57:22Z | [
"python",
"facebook",
"api",
"facebook-graph-api"
] | I have 2 unrelated questions.
1. How many posts does facebook allow you to get with an api?
2. Using facepy, facebook, or any other api, how do I get the number of friends a user has? (This user is not my friend). The user id is provided.
This is how I currently get the number of my friends with facebook api:
```
>>... | This is intentional behaviour. There was a [bug report](https://developers.facebook.com/bugs/356511554434996) filed for this problem, and this was the official Facebook response:
> This is intentional, you cannot retrieve friends lists for non-users of the app.
I suspect that if you used a userid of someone that had ... |
Function changes list values and not variable values in Python | 17,686,596 | 4 | 2013-07-16T20:42:52Z | 17,686,659 | 8 | 2013-07-16T20:47:18Z | [
"python",
"list",
"function",
"variables",
"nested-lists"
] | Let's take a simple code:
```
y = [1,2,3]
def plusOne(y):
for x in range(len(y)):
y[x] += 1
return y
print plusOne(y), y
a = 2
def plusOne2(a):
a += 1
return a
print plusOne2(a), a
```
Values of 'y' change but value 'a' stays the same. I have already learned that it's because one is muta... | Python variables contain pointers, or references, to objects. All values (even integers) are objects, and assignment changes the variable to point to a different object. It does not store a new value *in* the variable, it changes the variable to refer or point to a different object. For this reason many people say that... |
In Python how do I create variable length combinations or permutations? | 17,686,649 | 3 | 2013-07-16T20:46:33Z | 17,686,734 | 7 | 2013-07-16T20:50:53Z | [
"python",
"python-3.x",
"combinations",
"list-comprehension"
] | Lets say I have an array called arr = [1,2,3,4]
How can I generate all the possible combinations with minimum 2 arguments that end up looking like
```
[1,2]
[1,3]
[1,4]
[1,2,3]
[1,2,4]
[1,2,3, 4]
[2,3]
[2,4]
```
and so on and so forth? Nothing Im trying works. I cant seem to use itertools.combinations or permutation... | How about:
```
(x for l in range(2, len(arr)) for x in itertools.combinations(arr, l))
```
or
```
[x for l in range(2, len(arr)) for x in itertools.combinations(arr, l)]
```
if you need the list.
This is the equivalent of the following nested loop
```
res = []
for l in range(2, len(arr)):
for x in itertools.c... |
How to obtain the same font(-style, -size etc.) in matplotlib output as in latex output? | 17,687,213 | 20 | 2013-07-16T21:20:39Z | 18,633,695 | 13 | 2013-09-05T10:18:12Z | [
"python",
"matplotlib",
"tex"
] | I have one `.tex`-document in which one graph is made by the python module `matplotlib`. What I want is, that the graph blends in to the document as good as possible. So I want the characters used in the graph to look exactly like the other same characters in the rest of the document.
My first try looks like this (the... | The difference in the fonts can be caused by incorrect parameter setting out pictures with matplotlib or wrong its integration into the final document.
I think problem in *text.latex.preamble: \usepackage{lmodern}*. This thing works very badly and even developers do not guarantee its workability, [how you can find here... |
Learn python the hard way - exercise 36 function problems | 17,688,643 | 4 | 2013-07-16T23:27:14Z | 17,688,675 | 10 | 2013-07-16T23:30:18Z | [
"python"
] | I'm learning to code through learn python the hard way, and I've recently gotten stuck for the first time. For this exercise we're supposed to write our own game. I did so, but for some reason whenever I run it the right\_room() function exits after I put in an answer, instead of proceeding to the next room. Any help w... | It looks like you're trying to assign to the `next` variable, but you used the equality check operator (`==`). |
In Pandas how do I convert a string of date strings to datetime objects and put them in a DataFrame? | 17,690,738 | 35 | 2013-07-17T03:46:44Z | 17,690,795 | 34 | 2013-07-17T03:53:47Z | [
"python",
"datetime",
"pandas"
] | ```
import pandas as pd
date_stngs = ('2008-12-20','2008-12-21','2008-12-22','2008-12-23')
a = pd.Series(range(4),index = (range(4)))
for idx, date in enumerate(date_stngs):
a[idx]= pd.to_datetime(date)
```
This code bit produces error:
> TypeError:" 'int' object is not iterable"
Can anyone tell me how to get ... | ```
>>> import pandas as pd
>>> date_stngs = ('2008-12-20','2008-12-21','2008-12-22','2008-12-23')
>>> a = pd.Series([pd.to_datetime(date) for date in date_stngs])
>>> a
0 2008-12-20 00:00:00
1 2008-12-21 00:00:00
2 2008-12-22 00:00:00
3 2008-12-23 00:00:00
```
**UPDATE**
Use pandas.to\_datetime(pd.Series... |
In Pandas how do I convert a string of date strings to datetime objects and put them in a DataFrame? | 17,690,738 | 35 | 2013-07-17T03:46:44Z | 17,690,868 | 30 | 2013-07-17T04:00:54Z | [
"python",
"datetime",
"pandas"
] | ```
import pandas as pd
date_stngs = ('2008-12-20','2008-12-21','2008-12-22','2008-12-23')
a = pd.Series(range(4),index = (range(4)))
for idx, date in enumerate(date_stngs):
a[idx]= pd.to_datetime(date)
```
This code bit produces error:
> TypeError:" 'int' object is not iterable"
Can anyone tell me how to get ... | ```
In [46]: pd.to_datetime(pd.Series(date_stngs))
Out[46]:
0 2008-12-20 00:00:00
1 2008-12-21 00:00:00
2 2008-12-22 00:00:00
3 2008-12-23 00:00:00
dtype: datetime64[ns]
```
## Update: benchmark
```
In [43]: dates = [(dt.datetime(1960, 1, 1)+dt.timedelta(days=i)).date().isoformat() for i in range(20000)]
In... |
Why python designed as str(None) return 'None' instead of an empty string? | 17,691,111 | 9 | 2013-07-17T04:25:40Z | 17,691,187 | 9 | 2013-07-17T04:35:38Z | [
"python"
] | In some other languages I knows, the intuitive result of a null to string conversion should be an empty string.
Why Python is designed to make 'None' be sort of special string?
And this can lead to extra work when checking a return value from a function
```
result = foo() # foo will return None if failure
if result i... | Checking if a string has characters in it by checking `len(str(result))` is definitely not pythonic (see <http://www.python.org/dev/peps/pep-0008/>).
```
result = foo() # foo will return None if failure
if result:
# deal with result.
pass
```
`None` and `''` coerce to the boolean `False`.
---
If you are re... |
Get count of values across columns-Pandas DataFrame | 17,691,447 | 20 | 2013-07-17T04:58:55Z | 17,692,156 | 25 | 2013-07-17T05:58:05Z | [
"python",
"pandas",
"dataframe"
] | I have a Pandas DataFrame like following:
```
A B C
0 192.168.2.85 192.168.2.85 124.43.113.22
1 192.248.8.183 192.248.8.183 192.168.2.85
2 192.168.2.161 NaN 192.248.8.183
3 66.249.74.52 NaN 192.168.2.161
4 NaN NaN 66.2... | [stack](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html) it first and then use [value\_counts](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html):
```
In [14]: df.stack().value_counts()
Out[14]:
192.248.8.183 3
192.168.2.85 3
66.249.74... |
range in jinja2 inside a for loop | 17,691,838 | 11 | 2013-07-17T05:32:27Z | 17,691,875 | 25 | 2013-07-17T05:36:11Z | [
"python",
"loops",
"jinja2"
] | I have a nested list. I need to iterate through a list and keep it in for loop as shown below.
```
{% for alpha in list %}
<div id="{{ loop.index }}">
<div class='sidebar-one'>
{% for beta in list[0][2:] %} #I want to iterate through list[0][2:] till list[n][2:]
<p> {{ beta[0][0] }}... | It's just like Python:
```
{% for n in range(n) %}
{% for line in check[n][2:] %}
<p> {{ beta[0][0] }} </p>
{% endfor %}
{% endfor %}
``` |
Removing digits from a file | 17,693,318 | 2 | 2013-07-17T07:05:57Z | 17,693,429 | 8 | 2013-07-17T07:12:18Z | [
"python"
] | I have a file of the form:
```
car1 auto1 automobile1 machine4 motorcar1
bridge1 span5
road1 route2
```
But I want to remove the integers so that my file looks like:
```
car auto automobile machine motorcar
bridge span
road route
```
I am trying to read the file character by character, and if a character is a digit... | Using [regular expressions](http://www.regular-expressions.info/tutorial.html):
```
import re
import fileinput
for line in fileinput.input("your_file.txt", inplace=True):
print re.sub("\d+", "", line),
```
note: fileinput is a nice module for working with files.
Edit: for better performance/less flexibility you... |
why Python 3 needs wrap dict.items with list() | 17,695,456 | 14 | 2013-07-17T09:00:04Z | 17,695,716 | 10 | 2013-07-17T09:10:36Z | [
"python",
"python-3.x",
"2to3"
] | I'm using Python 3. I've just install some Python IDE and curious about following code warning:
```
features = { ... }
for k, v in features.items():
print("%s=%s" % (k, v))
```
Warning is: *"For Python3 support should look like ... `list(features.items())` "*
Also there is mention about this <http://docs.python.... | In Python 2, the methods `items()`, `keys()` and `values()` used to "take a snapshot" of the dictionary contents and return it as a list. It meant that if the dictionary changed while you were iterating over the list, the contents in the list would *not* change.
In Python 3, these methods return a [view object](http:/... |
why Python 3 needs wrap dict.items with list() | 17,695,456 | 14 | 2013-07-17T09:00:04Z | 17,695,808 | 16 | 2013-07-17T09:15:08Z | [
"python",
"python-3.x",
"2to3"
] | I'm using Python 3. I've just install some Python IDE and curious about following code warning:
```
features = { ... }
for k, v in features.items():
print("%s=%s" % (k, v))
```
Warning is: *"For Python3 support should look like ... `list(features.items())` "*
Also there is mention about this <http://docs.python.... | You can safely ignore this "extra precautions" warning: your code will work the same *even without `list`* on both versions of Python. It would run differently if you needed a list (but this is not the case): in fact, `features.items()` is a *list* in Python 2, but a *[view](http://docs.python.org/3.3/library/stdtypes... |
Fatal error while compiling PyQt5: Python.h does not exist | 17,698,877 | 7 | 2013-07-17T11:43:15Z | 18,088,696 | 29 | 2013-08-06T19:19:40Z | [
"python",
"qt",
"installation",
"pyqt",
"qt5"
] | I'm trying to install PyQt5 on my Ubuntu 12.04 box. So after downloading it from [here](http://www.riverbankcomputing.co.uk/software/pyqt/download5) I untarred it, ran `python configure.py` and `make`. Make however, results in the following:
```
cd qpy/ && ( test -f Makefile || /opt/qt5/bin/qmake /home/kram/Downloads/... | The problem is that the include path for all python headers in every Makefile will be pointing to `/usr/local/include/python2.7` , which should have been `/usr/include/python2.7`
There are 2 possible solutions for this. Either you can change all the occurrence of this in every Makefile or else you can create a symlink... |
Pandas: Convert DataFrame Column Values Into New Dataframe Indices and Columns | 17,698,975 | 3 | 2013-07-17T11:47:54Z | 17,699,049 | 7 | 2013-07-17T11:51:02Z | [
"python",
"pandas"
] | I have a dataframe that looks like this:
```
a b c
0 1 10
1 2 10
2 2 20
3 3 30
4 1 40
4 3 10
```
The dataframe above as default (0,1,2,3,4...) indices. I would like to convert it into a dataframe that looks like this:
```
1 2 3
0 10 0 0
1 0 10 0
2 0 20 0
3 0 ... | You can use the `pivot` method for this.
See the docs: <http://pandas.pydata.org/pandas-docs/stable/reshaping.html#reshaping-by-pivoting-dataframe-objects>
An example:
```
In [1]: import pandas as pd
In [2]: df = pd.DataFrame({'a':[0,1,2,3,4,4], 'b':[1,2,2,3,1,3], 'c':[10,10,20,3
0,40,10]})
In [3]: df
Out[3]:
a... |
Python NumPy log2 vs MATLAB | 17,702,065 | 9 | 2013-07-17T14:08:55Z | 17,702,094 | 7 | 2013-07-17T14:10:10Z | [
"python",
"matlab",
"numpy"
] | I'm a Python newbie coming from using MATLAB extensively. I was converting some code that uses `log2` in MATLAB and I used the NumPy `log2` function and got a different result than I was expecting for such a small number. I was surprised since the precision of the numbers *should* be the same (i.e. MATLAB double vs Num... | No. There is nothing wrong with the code, it is just because floating points cannot be represented perfectly on our computers. Always use an epsilon value to allow a range of error while checking float values. Read [**The Floating Point Guide**](http://floating-point-gui.de/basic/) and [this](http://docs.oracle.com/cd/... |
Convert Pandas series containing string to boolean | 17,702,272 | 8 | 2013-07-17T14:18:00Z | 17,702,833 | 12 | 2013-07-17T14:41:08Z | [
"python",
"boolean",
"pandas"
] | I have a DataFrame named `df` as
```
Order Number Status
1 1668 Undelivered
2 19771 Undelivered
3 100032108 Undelivered
4 2229 Delivered
5 00056 Undelivered
```
I would like to convert the `Status` column to boolean (`True` when Status is Delivered and `False` when Stat... | You can just use `map`:
```
In [7]: df = pd.DataFrame({'Status':['Delivered', 'Delivered', 'Undelivered',
'SomethingElse']})
In [8]: df
Out[8]:
Status
0 Delivered
1 Delivered
2 Undelivered
3 SomethingElse
In [9]: d = {'Delivered': True, 'Undelivered': Fals... |
sqlalchemy generic foreign key (like in django ORM) | 17,703,239 | 10 | 2013-07-17T14:57:30Z | 17,757,700 | 11 | 2013-07-20T01:19:49Z | [
"python",
"django",
"sqlalchemy",
"generic-foreign-key"
] | Does sqlalchemy have something like django's GenericForeignKey? And is it right to use generic foreign fields.
My problem is: I have several models (for example, Post, Project, Vacancy, nothing special there) and I want to add comments to each of them. And I want to use only one Comment model. Does it worth to? Or sho... | The simplest pattern which I use most often is that you actually have separate Comment tables for each relationship. This may seem frightening at first, but it doesn't incur any additional code versus using any other approach - the tables are created automatically, and the models are referred to using the pattern `Post... |
Writing Python lists to columns in csv | 17,704,244 | 14 | 2013-07-17T15:40:11Z | 17,704,312 | 18 | 2013-07-17T15:43:13Z | [
"python",
"list",
"csv"
] | I have 5 lists, all of the same length, and I'd like to write them to 5 columns in a CSV. So far, I can only write one to a column with this code:
```
with open('test.csv', 'wb') as f:
writer = csv.writer(f)
for val in test_list:
writer.writerow([val])
```
If I add another `for` loop, it just writes t... | change them to rows
```
rows = zip(list1,list2,list3,list4,list5)
```
then just
```
for row in rows:
writer.writerow(row)
``` |
Pandas dataframe: Check if data is monotonically decreasing | 17,704,408 | 9 | 2013-07-17T15:46:40Z | 17,705,498 | 8 | 2013-07-17T16:38:32Z | [
"python",
"pandas"
] | I have a pandas dataframe like this:
```
Balance Jan Feb Mar Apr
0 9.724135 0.389376 0.464451 0.229964 0.691504
1 1.114782 0.838406 0.679096 0.185135 0.143883
2 7.613946 0.960876 0.220274 0.788265 0.606402
3 0.144517 0.800086 0.287874 0.223539 0.206002
4 1.332838 0.430... | You could use one of the `is_monotonic` functions from algos:
```
In [10]: months = ['Jan', 'Feb', 'Mar', 'Apr']
In [11]: df.loc[:, months].apply(lambda x: pd.algos.is_monotonic_float64(-x)[0],
axis=1)
Out[11]:
0 False
1 True
2 False
3 True
4 False
dtype: bool
`... |
Why increment an indexed array behave as documented in numpy user documentation? | 17,704,605 | 4 | 2013-07-17T15:55:39Z | 17,705,724 | 7 | 2013-07-17T16:50:48Z | [
"python",
"numpy",
"scipy"
] | **The example**
The documentation about [assigning value to indexed arrays](http://docs.scipy.org/doc/numpy/user/basics.indexing.html#assigning-values-to-indexed-arrays) shows an example with unexpected results for those naive programmers.
```
>>> x = np.arange(0, 50, 10)
>>> x
array([ 0, 10, 20, 30, 40])
>>> x[np.ar... | The problem is the second example you give is not the same as the first. It's easier to understand if you look at the value of `x[np.array([1, 1, 3, 1])] + 1` separately, which numpy calculates in both your examples.
The value of `x[np.array([1, 1, 3, 1])] + 1` is what you had expected: `array([11, 11, 31, 11])`.
```... |
python os.environ, os.putenv, /usr/bin/env | 17,705,419 | 9 | 2013-07-17T16:34:12Z | 17,705,935 | 8 | 2013-07-17T17:03:24Z | [
"python"
] | I want to ensure `os.system('env')` not contain some specific variable `myname`
which is export in `~/.bashrc` as `export myname=csj`
Therefore, I wrote below python code:
```
import os
def print_all():
print "os.environ['myname']=%s" % os.environ.get('myname')
print "os.getenv('myname')=%s" % os.getenv('myn... | From the [docs](http://docs.python.org/2/library/os#os.environ):
> **Note:** Calling putenv() directly does not change os.environ, so itâs better to modify os.environ.
For `unsetenv` there is a similar warining:
> however, calls to unsetenv() donât update os.environ, so it is actually preferable to delete items ... |
summing the number of occurrences per day pandas | 17,706,109 | 6 | 2013-07-17T17:12:57Z | 17,706,350 | 9 | 2013-07-17T17:27:32Z | [
"python",
"pandas",
"dataframe"
] | I have a data set like so in a pandas dataframe.
```
score
timestamp
2013-06-29 00:52:28+00:00 -0.420070
2013-06-29 00:51:53+00:00 -0.445720
2013-06-28 16:40:43+00:00 0.508161
2013-06-28 15:10:30+00:00 0.921474
2013-06-28 ... | If your `timestamp` index is a `DatetimeIndex`:
```
import io
import pandas as pd
content = '''\
timestamp score
2013-06-29 00:52:28+00:00 -0.420070
2013-06-29 00:51:53+00:00 -0.445720
2013-06-28 16:40:43+00:00 0.508161
2013-06-28 15:10:30+00:00 0.921474
2013-06-28 15:10:17+00:00 ... |
how to add path with module to python? | 17,706,310 | 7 | 2013-07-17T17:25:27Z | 26,458,859 | 8 | 2014-10-20T05:04:21Z | [
"python",
"v8",
"gyp"
] | I try to build V8 javascript engine.
When I try to invoke the command `python build/git_v8`, I get error:
```
File build/gyp_v8, line 48 in < module >
import gyp
ImportError: No module named GYP
```
How I can tell python where search GYP module and what is the correct path to the module in the folder GYP?
My ve... | Install the module will be fine.
```
git clone https://chromium.googlesource.com/external/gyp
cd gyp
sudo ./setup.py install
```
enjoy it. |
Iterating over PyoDBC result without fetchall() | 17,707,264 | 2 | 2013-07-17T18:17:51Z | 17,707,643 | 8 | 2013-07-17T18:36:55Z | [
"python",
"sql",
"pyodbc"
] | I'm trying to process a very large query with pyodbc and I need to iterate over the rows without loading them all at once with fetchall().
Is there a good and principled way to do this? | Sure - use a `while` loop with `fetchone`.
<http://code.google.com/p/pyodbc/wiki/Cursor#fetchone>
```
row = cursor.fetchone()
while row is not None:
# do something
row = cursor.fetchone()
``` |
Changing a value in one list changes the values in another list with a different memory ID | 17,707,742 | 3 | 2013-07-17T18:43:33Z | 17,707,800 | 8 | 2013-07-17T18:46:27Z | [
"python",
"python-2.7"
] | I have been beating my head against a wall over this problem. I create a list and make 4 copies, only one of which shares the same memory index. If I change the original list, is somehow changes 3 of those copies as well, 2 of which have a different memory index. Only if I make a list using the same command as the orig... | That's because you are just creating a shallow copy. You need to create a deep copy instead.
As per [copy](http://docs.python.org/2/library/copy.html) module doc:
> * A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in
> the original.
... |
get thread ID or name in python 2.6 | 17,707,775 | 4 | 2013-07-17T18:45:05Z | 17,707,910 | 7 | 2013-07-17T18:51:44Z | [
"python",
"multithreading"
] | I am trying to get thread ID or name in python 2.6 I follow examples but I get errors
like
global name 'currentThread' is not defined
global name 'current\_thread' is not defined
(I tried both currentThread and current\_thread)
Here is my code :
```
vim f3Q.py
1 import Queue
2 from threading import Thread
3
... | You haven't imported `threading`, only `Thread`.
Either import `threading`, or import `current_thread` directly:
```
1 import Queue
2 from threading import Thread, current_thread
3
4 def do_work(item):
5 try:
6 print current_thread()
``` |
how to create a date object in python representing a set number of days | 17,708,823 | 2 | 2013-07-17T19:42:00Z | 17,708,884 | 9 | 2013-07-17T19:46:16Z | [
"python",
"datetime"
] | I would like to define a variable to be a datetime object representing the number of days that is entered by the user. For example.
```
numDays = #input from user
deltaDatetime = #this is what I'm trying to figure out how to do
str(datetime.datetime.now() + deltaDatetime)
```
This code would print out a datetime repr... | It's fairly straightforward using timedelta from the standard datetime library:
```
import datetime
numDays = 5 # heh, removed the 'var' in front of this (braincramp)
print datetime.datetime.now() + datetime.timedelta(days=numDays)
``` |
I want to create a column of value_counts in my pandas dataframe | 17,709,270 | 11 | 2013-07-17T20:08:43Z | 17,709,453 | 23 | 2013-07-17T20:20:02Z | [
"python",
"merge",
"pandas"
] | I am more familiar with R but I wanted to see if there was a way to do this in pandas. I want to create a count of unique values from one of my dataframe columns and then add a new column with those counts to my original data frame. I've tried a couple different things. I created a pandas series and then calculated cou... | ```
df['Counts'] = df.groupby(['Color'])['Value'].transform('count')
```
For example,
```
In [102]: df = pd.DataFrame({'Color': 'Red Red Blue'.split(), 'Value': [100, 150, 50]})
In [103]: df
Out[103]:
Color Value
0 Red 100
1 Red 150
2 Blue 50
In [104]: df['Counts'] = df.groupby(['Color'])['Value'... |
ValueError: numpy.dtype has the wrong size, try recompiling | 17,709,641 | 64 | 2013-07-17T20:30:55Z | 18,369,312 | 43 | 2013-08-21T23:32:22Z | [
"python",
"numpy",
"install",
"pandas",
"statsmodels"
] | I just installed pandas and statsmodels package on my python 2.7
When I tried "import pandas as pd", this error message comes out.
Can anyone help? Thanks!!!
```
numpy.dtype has the wrong size, try recompiling
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\analytics\ext\python27\li... | (to expand a bit on my comment)
Numpy developers follow in general a policy of keeping a backward compatible binary interface (ABI). However, the ABI is not forward compatible.
What that means:
A package, that uses numpy in a compiled extension, is compiled against a specific version of numpy. Future version of nump... |
ValueError: numpy.dtype has the wrong size, try recompiling | 17,709,641 | 64 | 2013-07-17T20:30:55Z | 27,999,688 | 34 | 2015-01-17T12:57:38Z | [
"python",
"numpy",
"install",
"pandas",
"statsmodels"
] | I just installed pandas and statsmodels package on my python 2.7
When I tried "import pandas as pd", this error message comes out.
Can anyone help? Thanks!!!
```
numpy.dtype has the wrong size, try recompiling
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\analytics\ext\python27\li... | For me (Mac OS X Maverics, Python 2.7)
```
easy_install --upgrade numpy
```
helped. After this you can install up-to-date packages *pandas*, *scikit-learn*, e.t.c. using **pip**:
```
pip install pandas
``` |
ValueError: numpy.dtype has the wrong size, try recompiling | 17,709,641 | 64 | 2013-07-17T20:30:55Z | 35,476,539 | 18 | 2016-02-18T08:42:17Z | [
"python",
"numpy",
"install",
"pandas",
"statsmodels"
] | I just installed pandas and statsmodels package on my python 2.7
When I tried "import pandas as pd", this error message comes out.
Can anyone help? Thanks!!!
```
numpy.dtype has the wrong size, try recompiling
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\analytics\ext\python27\li... | I found it to be a simple version being outdated or mismatch and was fixed with:
```
pip install --upgrade numpy
pip install --upgrade scipy
pip install --upgrade pandas
```
Or might work with the one liner:
```
pip install --upgrade numpy scipy pandas
``` |
Process large data in python | 17,710,748 | 6 | 2013-07-17T21:38:51Z | 17,710,855 | 15 | 2013-07-17T21:47:39Z | [
"python"
] | I need to process some data that is a few hundred times bigger than RAM. I would like to read in a large chunk, process it, save the result, free the memory and repeat. Is there a way to make this efficient in python? | The general key is that you want to process the file iteratively.
If you're just dealing with a text file, this is trivial: `for line in f:` only reads in one line at a time. (Actually it buffers things up, but the buffers are small enough that you don't have to worry about it.)
If you're dealing with some other spec... |
pip: pulling updates from remote git repository | 17,710,947 | 11 | 2013-07-17T21:53:52Z | 17,710,982 | 8 | 2013-07-17T21:56:22Z | [
"python",
"git",
"github",
"pip",
"scikit-learn"
] | I installed [scikit-learn](https://github.com/scikit-learn/scikit-learn) from GitHub a couple of weeks ago:
```
pip install git+git://github.com/scikit-learn/scikit-learn@master
```
I went to GitHub and there have been several changes to the master branch since then.
How can I update my local installation of `scikit... | `pip` searches for the library in the Python package index. Your version is newer than the newest one in there, so pip won't update it.
You'll have to reinstall from Git:
```
$ pip install git+git://github.com/scikit-learn/scikit-learn@master
``` |
Why does Python operator.itemgetter work given a comma separated list of numbers as indices, but not when the same list is packaged in a variable? | 17,711,485 | 5 | 2013-07-17T22:37:33Z | 17,711,521 | 16 | 2013-07-17T22:40:46Z | [
"python"
] | Here is a demonstration of the issue I'm having. I'm fairly new to Python, so I'm pretty sure I'm overlooking something very obvious.
```
import operator
lista=["a","b","c","d","e","f"]
print operator.itemgetter(1,3,5)(lista)
>> ('b', 'd', 'f')
columns=1,3,5
print operator.itemgetter(columns)(lista)
>> TypeError: li... | This isn't about itemgetter, but about function calling syntax. These are different things:
```
operator.itemgetter(1, 3, 5)
operator.itemgetter((1, 3, 5))
```
The first one gets you item #1, item #3, and item #5. The second one gets you item #(1, 3, 5). (Which may make sense for a dictionary, but not for a list.)
... |
Organizing data read from Excel to Pandas DataFrame | 17,711,585 | 6 | 2013-07-17T22:47:00Z | 17,720,996 | 7 | 2013-07-18T10:29:55Z | [
"python",
"excel",
"pandas"
] | My goal with this script is to:
1.read timseries data in from excel file (>100,000k rows) as well as headers (Labels, Units)
2.convert excel numeric dates to best datetime object for pandas dataFrame
3.Be able to use timestamps to reference rows and series labels to reference columns
So far I used xlrd to read the exc... | You can use pandas directly here, I usually like to create a dictionary of DataFrames (with keys being the sheet name):
```
In [11]: xl = pd.ExcelFile("C:\GreenCSV\Calgary\CWater.xlsx")
In [12]: xl.sheet_names # in your example it may be different
Out[12]: [u'Sheet1', u'Sheet2', u'Sheet3']
In [13]: dfs = {sheet: xl... |
Pandas: Sorting columns by their mean value | 17,712,163 | 10 | 2013-07-17T23:44:15Z | 17,712,440 | 16 | 2013-07-18T00:14:06Z | [
"python",
"pandas"
] | I have a dataframe in Pandas, I would like to sort its columns (i.e. get a new dataframe, or a view) according to the mean value of its columns (or e.g. by their std value). The documentation talks about [sorting by label or value](http://pandas.pydata.org/pandas-docs/stable/basics.html#sorting-by-index-and-value), but... | You can use the [`mean`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mean.html) DataFrame method and the Series [`order`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.order.html) method:
```
In [11]: df = pd.DataFrame(np.random.randn(4,4), columns=list('ABCD'))
In [12... |
Python - Generator case where nothing to return | 17,713,094 | 8 | 2013-07-18T01:41:23Z | 17,713,141 | 7 | 2013-07-18T01:47:02Z | [
"python",
"for-loop",
"generator"
] | I have a generator like so:
```
def iterate_my_objects_if_something(self):
for x in self.my_objects:
if x.something:
yield x
```
Which I call like so:
```
for x in self.iterate_my_objects_if_something():
pass
```
In the case where there is nothing to return, this tries to iterate over No... | Just do a simple check:
```
def iterate_my_objects_if_something(self):
if self.my_objects:
for x in self.my_objects:
if x.something:
yield x
``` |
How to return a dictionary | Python | 17,713,683 | 5 | 2013-07-18T02:49:01Z | 17,713,787 | 7 | 2013-07-18T03:00:01Z | [
"python",
"python-3.x"
] | I have a .txt file with the following lines in it:
```
23;Pablo;SanJose
45;Rose;Makati
```
I have this program:
```
file = open("C:/Users/renato/Desktop/HTML Files/myfile2.txt")
def query(id):
for line in file:
table = {}
(table["ID"],table["name"],table["city"]) = line.split(";")
if id ... | What's going on is that you're returning right after the first line of the file doesn't match the id you're looking for. You have to do this:
```
def query(id):
for line in file:
table = {}
(table["ID"],table["name"],table["city"]) = line.split(";")
if id == int(table["ID"]):
f... |
A better way to accept multiple request types in a single view method? | 17,716,436 | 9 | 2013-07-18T06:48:13Z | 17,730,089 | 9 | 2013-07-18T17:21:25Z | [
"python",
"flask"
] | I'm trying to expose an API to various request methods (GET, url x-www-form-urlencoded POST, and json POST):
```
@app.route('/create', methods=['GET', 'POST'])
def create_file():
if request.method == 'GET':
n = request.args.get('n')
t = request.args.get('t')
if request.method == 'POST':
... | Does this look better? It is a bit cleaner in my opinion, if you can accept moving the JSON POST request to a different route (which you really should do anyway).
```
def _create_file(n, t):
try:
n = int(n)
except:
n = 1
...
@app.route('/create')
def create_file():
n = request.args.get... |
Django CSRF Cookie Not Set | 17,716,624 | 18 | 2013-07-18T06:58:55Z | 19,008,548 | 42 | 2013-09-25T15:04:56Z | [
"python",
"django"
] | I have some problem for a while now, I'm experiencing CSRF Cookie not set. Please look at the codes below
## Python
```
def deposit(request,account_num):
if request.method == 'POST':
account = get_object_or_404(account_info,acct_number=account_num)
form_=AccountForm(request.POST or None, instance=account)
... | This can also occur if `CSRF_COOKIE_SECURE = True` is set and you are accessing the site non-securely. |
Django CSRF Cookie Not Set | 17,716,624 | 18 | 2013-07-18T06:58:55Z | 38,663,331 | 8 | 2016-07-29T16:17:19Z | [
"python",
"django"
] | I have some problem for a while now, I'm experiencing CSRF Cookie not set. Please look at the codes below
## Python
```
def deposit(request,account_num):
if request.method == 'POST':
account = get_object_or_404(account_info,acct_number=account_num)
form_=AccountForm(request.POST or None, instance=account)
... | ```
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def your_view(request):
if request.method == "POST":
# do something
return HttpResponse("Your response")
``` |
django - How to set default value for DecimalField in django 1.3? | 17,718,355 | 10 | 2013-07-18T08:27:32Z | 17,718,387 | 17 | 2013-07-18T08:29:48Z | [
"python",
"django",
"django-models"
] | One of my model's field looks like this:
```
total_amount = models.DecimalField(max_digits=20,decimal_places=4,default=Decimal('0.0000'))
```
but when I run this command `python manage.py syncdb`, it shows this error:
```
NameError: name 'Decimal' is not defined
```
I have imported `from django.db import models`, d... | You need to import Decimal.
```
from decimal import Decimal
``` |
Determine free RAM in Python | 17,718,449 | 8 | 2013-07-18T08:33:07Z | 17,718,729 | 10 | 2013-07-18T08:46:58Z | [
"python",
"memory-management"
] | I would like my python script to use all the free RAM available but no more (for efficiency reasons). I can control this by reading in only a limited amount of data but I need to know how much RAM is free at run-time to get this right. It will be run on a variety of Linux systems. Is it possible to determine the free R... | On Linux systems I use this from time to time:
```
def memory():
"""
Get node total memory and memory usage
"""
with open('/proc/meminfo', 'r') as mem:
ret = {}
tmp = 0
for i in mem:
sline = i.split()
if str(sline[0]) == 'MemTotal:':
ret['... |
matplotlib: draw major tick labels under minor labels | 17,718,827 | 3 | 2013-07-18T08:52:04Z | 17,719,672 | 8 | 2013-07-18T09:31:59Z | [
"python",
"matplotlib",
"plot",
"axis-labels"
] | This seems like it should be easy - but I can't see how to do it:
I have a plot with time on the X-axis. I want to set two sets of ticks, minor ticks showing the hour of the day and major ticks showing the day/month. So I do this:
```
# set date ticks to something sensible:
xax = ax.get_xaxis()
xax.set_major_locator(... | You can use `axis` method `set_tick_params()` with the keyword `pad`. Compare following example.
```
import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as dates
# make up some data
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(100)]
y = [i+random.gauss(0,... |
asyncore.dispatcher in python: when are the handle_closed and handle_read executed? | 17,720,099 | 2 | 2013-07-18T09:51:33Z | 18,037,281 | 7 | 2013-08-03T21:01:22Z | [
"python",
"sockets",
"asyncore"
] | There are two files: server.py and client.py, both written with the help of asyncore.dispatcher
***Server.py***
```
import asyncore, socket
class Server(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
... | ## Asyncore talk
The `handle_read()` in server.py will never be called.
*But why?! It's a server class...*
Yes, but `Server` class uses its socket for **listening** any non-established connections. Any reads on it go to `handle_accept()`, where actual channel sockets (connected to some endpoint) should be given to n... |
pymongo default database connection | 17,720,926 | 7 | 2013-07-18T10:27:06Z | 18,423,493 | 12 | 2013-08-24T21:53:11Z | [
"python",
"mongodb",
"pymongo"
] | I need to connect to MongoDB from my Python code, the only thing I have is a url. Per [mongo URL doc](http://docs.mongodb.org/manual/reference/connection-string/) I can specify database name:
```
mongodb://host/db_name
```
Now I would like to use exactly database specified from URL and don't want to parse it manually... | PyMongo/MongoClient does (now) provide a `get_default_database()` method:
```
from pymongo import MongoClient
client = MongoClient("mongodb://host/db_name")
db = client.get_default_database()
``` |
Is it possible that Scrapy to get plain text from raw html data directly instead of using xPath selectors? | 17,721,782 | 11 | 2013-07-18T11:08:47Z | 17,722,635 | 13 | 2013-07-18T11:48:49Z | [
"python",
"html",
"web-scraping",
"scrapy",
"web-crawler"
] | For example:
```
scrapy shell http://scrapy.org/
content = hxs.select('//*[@id="content"]').extract()[0]
print content
```
then,I got following raw html codes:
```
<div id="content">
<h2>Welcome to Scrapy</h2>
<h3>What is Scrapy?</h3>
<p>Scrapy is a fast high-level screen scraping and web crawling
... | Scrapy doesn't have such functionality built-in. [html2text](https://github.com/aaronsw/html2text) is what you are looking for.
Here's a sample spider that scrapes [wikipedia's python page](http://en.wikipedia.org/wiki/Python_%28programming_language%29), gets first paragraph using xpath and converts html into plain te... |
Is it possible that Scrapy to get plain text from raw html data directly instead of using xPath selectors? | 17,721,782 | 11 | 2013-07-18T11:08:47Z | 17,727,287 | 10 | 2013-07-18T15:09:29Z | [
"python",
"html",
"web-scraping",
"scrapy",
"web-crawler"
] | For example:
```
scrapy shell http://scrapy.org/
content = hxs.select('//*[@id="content"]').extract()[0]
print content
```
then,I got following raw html codes:
```
<div id="content">
<h2>Welcome to Scrapy</h2>
<h3>What is Scrapy?</h3>
<p>Scrapy is a fast high-level screen scraping and web crawling
... | Another solution using `lxml.html`'s `tostring()` with parameter `method="text"`. `lxml` is used in Scrapy internally. (parameter `encoding=unicode` is usually what you want.)
See <http://lxml.de/api/lxml.html-module.html> for details.
```
from scrapy.spider import BaseSpider
import lxml.etree
import lxml.html
class... |
Python: How do i use itertools? | 17,722,989 | 4 | 2013-07-18T12:06:40Z | 17,723,031 | 7 | 2013-07-18T12:08:10Z | [
"python"
] | I am trying to make a list containing all possible variations of 1 and 0. like for example if I have just two digits I want a list like this:
```
[[0,0], [0,1], [1,0], [1,1]]
```
But if I decide to have 3 digits I want to have a list like this:
```
[[0,0,0], [0,0,1], [0,1,0], [0,1,1], [1,0,0], [1,0,1], [1,1,0], [1,1... | itertools.product(.., repeat=n)
```
>>> import itertools
>>> list(itertools.product((0,1), repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
```
[Python Module Index](http://docs.python.org/2/py-modindex.html) contains links for standard library modules documentation. |
What's the difference between hasattr() and 'attribute' in dir()? | 17,723,569 | 2 | 2013-07-18T12:34:11Z | 17,723,673 | 7 | 2013-07-18T12:37:44Z | [
"python"
] | For example:
```
>>> s = 'string'
>>> hasattr(s, 'join')
True
>>> 'join' in dir(s)
True
```
[Python documentation](http://docs.python.org/3/library/functions.html#hasattr) says that `hasattr` is implemented calling `getattr` and seeing whether it raises an exception or not. However, that leads to a great overhead, si... | It is not quite the same thing. `dir()` is a diagnostic tool that *omits* attributes that `getattr()` and `hasattr()` would find.
From the [`dir()` documentation](http://docs.python.org/3/library/functions.html#dir):
> The default `dir()` mechanism behaves differently with different types of objects, as it attempts t... |
Why are lists linked in Python in a persistent way? | 17,723,840 | 2 | 2013-07-18T12:45:48Z | 17,723,951 | 10 | 2013-07-18T12:49:56Z | [
"python",
"list",
"immutability"
] | A variable is set. Another variable is set to the first. The first changes value. The second does not. This has been the nature of programming since the dawn of time.
```
>>> a = 1
>>> b = a
>>> b = b - 1
>>> b
0
>>> a
1
```
I then extend this to Python lists. A list is declared and appended. Another list is declared... | Python variables are actually **not** variables but **references** to objects (similar to pointers in C). There is a very good explanation of that for beginners in <http://foobarnbaz.com/2012/07/08/understanding-python-variables/>
One way to convince yourself about this is to try this:
```
a=[1,2,3]
b=a
id(a)
6861732... |
Why are lists linked in Python in a persistent way? | 17,723,840 | 2 | 2013-07-18T12:45:48Z | 17,723,975 | 9 | 2013-07-18T12:51:12Z | [
"python",
"list",
"immutability"
] | A variable is set. Another variable is set to the first. The first changes value. The second does not. This has been the nature of programming since the dawn of time.
```
>>> a = 1
>>> b = a
>>> b = b - 1
>>> b
0
>>> a
1
```
I then extend this to Python lists. A list is declared and appended. Another list is declared... | Variable binding in Python works this way: you assign an object to a variable.
```
a = 4
b = a
```
Both point to `4`.
```
b = 9
```
Now `b` points to somewhere else.
Exactly the same happens with lists:
```
a = []
b = a
b = [9]
```
Now, `b` has a new value, while `a` has the old one.
Till now, everything is cle... |
Boxplots in matplotlib: Markers and outliers | 17,725,927 | 20 | 2013-07-18T14:12:51Z | 17,726,418 | 16 | 2013-07-18T14:33:21Z | [
"python",
"matplotlib",
"statistics",
"boxplot"
] | I have some questions about [boxplots](http://matplotlib.org/examples/pylab_examples/boxplot_demo.html) in matplotlib:
**Question A**. What do the markers that I highlighted below with **Q1**, **Q2**, and **Q3** represent? I believe **Q1** is maximum and **Q3** are outliers, but what is **Q2**?
 gives the default whiskers at 1.5 IQR:
```
boxplot(x, notch=False, sym='+', vert=True, whis=1.5,
positions=None, widths=None, p... |
Boxplots in matplotlib: Markers and outliers | 17,725,927 | 20 | 2013-07-18T14:12:51Z | 20,096,945 | 11 | 2013-11-20T13:11:01Z | [
"python",
"matplotlib",
"statistics",
"boxplot"
] | I have some questions about [boxplots](http://matplotlib.org/examples/pylab_examples/boxplot_demo.html) in matplotlib:
**Question A**. What do the markers that I highlighted below with **Q1**, **Q2**, and **Q3** represent? I believe **Q1** is maximum and **Q3** are outliers, but what is **Q2**?
![enter image descript... | In addition to seth answer (since the documentation is not very precise regarding this):
Q1 (the wiskers) are placed at the maximum value below 75% + 1.5 IQR
(minimum value of 25% - 1.5 IQR)
This is the code that computes the whiskers position:
```
# get high extreme
iq = q3 - q1
hi_val = q3 ... |
Boxplots in matplotlib: Markers and outliers | 17,725,927 | 20 | 2013-07-18T14:12:51Z | 23,324,730 | 30 | 2014-04-27T14:39:20Z | [
"python",
"matplotlib",
"statistics",
"boxplot"
] | I have some questions about [boxplots](http://matplotlib.org/examples/pylab_examples/boxplot_demo.html) in matplotlib:
**Question A**. What do the markers that I highlighted below with **Q1**, **Q2**, and **Q3** represent? I believe **Q1** is maximum and **Q3** are outliers, but what is **Q2**?
![enter image descript... | A picture is worth a thousand words. Note that the outliers (the `+` markers in your plot) are simply points **outside** of the wide `[(Q1-1.5 IQR), (Q3+1.5 IQR)]` margin below.
 |
Re assign a list efficiently | 17,726,407 | 4 | 2013-07-18T14:32:54Z | 17,726,443 | 14 | 2013-07-18T14:34:19Z | [
"python",
"performance",
"list"
] | This is a `MWE` of the re-arrainging I need to do:
```
a = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
b = [[], [], []]
for item in a:
b[0].append(item[0])
b[1].append(item[1])
b[2].append(item[2])
```
which makes `b` lool like this:
```
b = [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
```
I.e., every... | There is a *much* better way to transpose your rows and columns:
```
b = zip(*a)
```
Demo:
```
>>> a = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
>>> zip(*a)
[(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]
```
`zip()` takes multiple sequences as arguments and pairs up elements from each to form new lists. By passing in ... |
py.test: how to get the current test's name from the setup method? | 17,726,954 | 7 | 2013-07-18T14:55:47Z | 34,732,269 | 11 | 2016-01-11T22:25:24Z | [
"python",
"py.test"
] | I am using py.test and wonder if/how it is possible to retrieve the name of the currently executed test within the `setup` method that is invoked before running each test. Consider this code:
```
class TestSomething(object):
def setup(self):
test_name = ...
def teardown(self):
pass
def t... | You can also do this using the [Request Fixture](https://pytest.org/latest/builtin.html#_pytest.python.FixtureRequest) like this:
```
def test_name1(request):
testname = request.node.name
assert testname == 'test_name1'
``` |
How to specify dependencies when creating the setup.py file for a python package | 17,727,398 | 10 | 2013-07-18T15:14:13Z | 17,727,473 | 16 | 2013-07-18T15:17:16Z | [
"python",
"package",
"setup.py"
] | The python doc for "Writing the Setupscript (<http://docs.python.org/2/distutils/setupscript.html>) mentions that dependencies can be specified under section
> **> 2.4. Relationships between Distributions and Packages**
>
> [...] These relationships can be specified using keyword arguments to
> the distutils.core.setu... | Ignore `distutils`. If you want to create a package that specifies dependencies for a tool like `pip` to go out and find for you, you need to base your `setup.py` of off [`setuptools`](https://setuptools.readthedocs.io/en/latest/) instead.
`setuptools` dependencies are listed in [`install_requires`](https://setuptools... |
What does '*** Oldest frame' mean in ipdb? | 17,727,993 | 5 | 2013-07-18T15:39:19Z | 17,728,053 | 8 | 2013-07-18T15:41:40Z | [
"python",
"python-3.x",
"pdb",
"ipdb"
] | I am trying to make http requests to a server and examine the content I get back. However, when I try poking around the `HTTPResponse object` with `ipdb`, I keep getting `*** Oldest frame` and I cant run any of the functions on the object that I should be able to run. Here is the block of code doing to fetching, and th... | `u` is the PDB command to traverse stack frames. You are in the 'uppermost' frame already. `help u` will tell you more about it:
> ```
> u(p)
> Move the current frame one level up in the stack trace
> (to an older frame).
> ```
The command is closely related to `d(own)` and `w(here)`:
> ```
> d(own)
> Move the curre... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.