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 |
|---|---|---|---|---|---|---|---|---|---|
HeartBleed python test script | 23,033,219 | 7 | 2014-04-12T16:39:02Z | 23,033,261 | 12 | 2014-04-12T16:42:11Z | [
"python",
"security",
"openssl",
"heartbleed-bug"
] | I came across [this Python script](https://gist.github.com/takeshixx/10107280) that tests the server for the HeartBleed vulnerability:
Would someone be able to explain the content of the "hello", what is being sent and how was this content constructed?
I am not trying to use this script maliciously. I was asked to te... | `hello` and `hb` define bytestrings in a more readable fashion.
The `h2bin(x)` function does all the work:
```
def h2bin(x):
return x.replace(' ', '').replace('\n', '').decode('hex')
```
so the string of hex digits has all whitespace removed, then is decoded from hex to bytes:
```
>>> '16 03 02 00 dc'.replace('... |
Sorting Counter collection in python with secondary term (tie breaker) | 23,033,625 | 7 | 2014-04-12T17:15:31Z | 23,033,745 | 11 | 2014-04-12T17:25:00Z | [
"python",
"sorting",
"python-3.x",
"counter"
] | I have a `Counter` in `Python 3.3.x` which I want to sort.
I know I can use `.most_common(x)` but I want the keys to be sorted alphabetically in case of same value.
Is there a way I can do this ? Setting this kind of a 'tie breaker' ? | [`collections.Counter`](https://docs.python.org/2/library/collections.html#collections.Counter) is actually a dictionary and they rely on hashing technique, so we really cannot access them by order. Since accessing by order is not possible, sorting a dictionary is out of question. But you can convert that to a list of ... |
How to test Python 3.4 asyncio code? | 23,033,939 | 38 | 2014-04-12T17:43:33Z | 23,036,785 | 25 | 2014-04-12T22:14:14Z | [
"python",
"unit-testing",
"python-3.x",
"python-unittest",
"python-asyncio"
] | What's the best way to write unit tests for code using the Python 3.4 `asyncio` library? Assume I want to test a TCP client (`SocketConnection`):
```
import asyncio
import unittest
class TestSocketConnection(unittest.TestCase):
def setUp(self):
self.mock_server = MockServer("localhost", 1337)
self... | I temporarily solved the problem using a decorator inspired by Tornado's [gen\_test](http://www.tornadoweb.org/en/stable/testing.html#tornado.testing.gen_test):
```
def async_test(f):
def wrapper(*args, **kwargs):
coro = asyncio.coroutine(f)
future = coro(*args, **kwargs)
loop = asyncio.get... |
How to test Python 3.4 asyncio code? | 23,033,939 | 38 | 2014-04-12T17:43:33Z | 23,642,269 | 27 | 2014-05-13T21:55:32Z | [
"python",
"unit-testing",
"python-3.x",
"python-unittest",
"python-asyncio"
] | What's the best way to write unit tests for code using the Python 3.4 `asyncio` library? Assume I want to test a TCP client (`SocketConnection`):
```
import asyncio
import unittest
class TestSocketConnection(unittest.TestCase):
def setUp(self):
self.mock_server = MockServer("localhost", 1337)
self... | `async_test`, suggested by Marvin Killing, definitely can help -- as well as direct calling `loop.run_until_complete()`
But I also strongly recommend to recreate new event loop for every test and directly pass loop to API calls (at least `asyncio` itself accepts `loop` keyword-only parameter for every call that need i... |
Django rest framework user registration? | 23,034,696 | 9 | 2014-04-12T18:51:41Z | 27,886,026 | 8 | 2015-01-11T10:25:31Z | [
"python",
"django",
"rest",
"serialization",
"django-rest-framework"
] | I am following [this tutorial](http://richardtier.com/2014/02/25/django-rest-framework-user-endpoint/comment-page-1/#comment-39) but facing these problems I can't fix:
1. Upon registering user, I can not log in with that user to the api because the password is not hashed
"Invalid password format or unknown hashing ... | I tried the accepted answer in DRF 3.0.2 and it didn't work. The password was not being hashed.
Instead, override the create method in your model serializer
```
def create(self, validated_data):
user = User(email=validated_data['email'], username=validated_data['username'])
user.set_password(valid... |
Ubuntu : Unable to correct problems, you have held broken packages | 23,035,310 | 6 | 2014-04-12T19:47:33Z | 23,038,484 | 9 | 2014-04-13T02:34:06Z | [
"python",
"django",
"ubuntu",
"mod-wsgi"
] | trying to install this, I am getting the 'Unable to correct problems, you have held broken packages' error message.
# Apache version
Server version: Apache/2.4.2 (Ubuntu)
Server built: Jun 27 2012 07:23:35
```
# aptitude install libapache2-mod-wsgi
The following NEW packages will be installed:
apache2.2-common{ab... | **Option 1:** You can try:
```
sudo apt-get upgrade
```
The 'upgrade' option tries to solve all dependencies in installed packages. Often this is enough to solve broken packages
**Option 2**: If your package was installed from a 'deb' file and not from repositories, it may be that the new one you are trying to insta... |
Equivalent of `return` for Python generators | 23,036,049 | 3 | 2014-04-12T20:59:49Z | 23,036,066 | 7 | 2014-04-12T21:01:43Z | [
"python",
"coding-style",
"generator",
"yield"
] | Sometimes, when rewriting recursive functions as generators, I miss the brevity of `return`.
```
"""
Returns a list of all length n strings that can be made out of a's and/or b's.
"""
def ab_star(n):
if n == 0:
return [""]
results = []
for s in ab_star(n - 1):
results.append("a" + s)
... | Don't miss `return`, use it.
You can `return` right after you `yield`.
```
def ab_star(n):
if n == 0:
yield ""
return
for s in ab_star(n - 1):
yield "a" + s
yield "b" + s
```
---
An alternative is to use `return` in both cases, where the first case returns a sequence of lengt... |
Asterisk symbol in Python | 23,036,308 | 4 | 2014-04-12T21:25:38Z | 23,036,324 | 9 | 2014-04-12T21:26:33Z | [
"python",
"operators",
"operator-overloading"
] | I was researching some different ways to approach the classic FizzBuzz problem, and stumbled across this:
```
for i in xrange(1, n+1):
print "Fizz"*(i%3 == 0) + "Buzz"*(i%5 == 0) or i
```
Are the asterisks shorthand for an `if` statement? If so, is this notation specific to `print`?
Thanks in advance. | The asterisk in Python is actually just the standard multiplication operator `*`. It maps to the [`__mul__`](https://docs.python.org/2/reference/datamodel.html#object.__mul__) method of the object it's operated on, and thus can be overloaded to have custom meanings. This has nothing to do whatsoever with `if` or `print... |
Distributed lock manager for Python | 23,036,990 | 8 | 2014-04-12T22:39:42Z | 23,227,631 | 11 | 2014-04-22T18:39:21Z | [
"python",
"python-2.7"
] | I have a bunch of servers with multiple instances accessing a resource that has a hard limit on requests per second.
I need a mechanism to lock the access on this resource for all servers and instances that are running.
There is a restful distributed lock manager I found on github: <https://github.com/thefab/restful-... | My first idea was using Redis. But there are more great tools and some are even lighter, so my solution builds on zmq. For this reason you do not have to run Redis, it is enough to run small Python script.
# Requirements Review
Let me review your requirements before describing solution.
* limit number of request to ... |
Python Boto: How do you specify a subnet id AND a security group? | 23,037,291 | 8 | 2014-04-12T23:18:42Z | 23,042,901 | 10 | 2014-04-13T12:43:28Z | [
"python",
"amazon-web-services",
"amazon-ec2",
"boto"
] | I am trying to laucnh an instance using boto. The instance needs to be launched on a specific subnet within my VPC and also in a specific security group within my vpc.
The following code successfully launches an instance in my VPC on the correct subnet:
```
conn.run_instances(
image_id=base_ami,
key_n... | Because you are launching into a VPC, you must specify the security groups by their ID rather than their name. Names are valid only in "classic" EC2. So, if the security group in question had an ID of `sg-12345678` you could use a command like this:
```
reservation = conn.run_instances(
image_id=base_ami,
key_... |
Matplotlib: change (main) plot legend label text (closed) | 23,037,548 | 5 | 2014-04-12T23:53:48Z | 23,037,647 | 14 | 2014-04-13T00:07:15Z | [
"python",
"matplotlib",
"pandas",
"label",
"legend"
] | So far I have been able to label the subplots just fine but I'm having an issue with the main one...
Here's the relevant part of my code:
```
data_BS_P = data[channels[0]]
data_BS_R = data[channels[1]]
data_BS_Y = data[channels[2]]
plot_BS_P = data_BS_P.plot() #data_BS_P is a pandas dataframe
axBS = plot_BS_P.gca()
a... | You need to gain access of the `legend()` object and use `set_text()` to change the text values, a simple example:
```
plt.plot(range(10), label='Some very long label')
plt.plot(range(1,11), label='Short label')
L=plt.legend()
L.get_texts()[0].set_text('make it short')
plt.savefig('temp.png')
```
![enter image descri... |
Confusing error when trying to run Python script | 23,038,549 | 4 | 2014-04-13T02:45:39Z | 23,038,562 | 13 | 2014-04-13T02:47:42Z | [
"python",
"bash"
] | I'm trying to run this simple Python code (a.py):
```
# list test
import time
class List(object):
class Cons(object):
def __init__(self, x, tail):
self.x= x
self.tail=tail
class Nil(object):
def __init__(self):
pass
@classmethod
def cons(cls, cons):
return List(cons, None)
@clas... | You are missing the python shebang, `#!/usr/bin/env python`. Add this as the first line to tell the OS to run your file as a python script and not as a shell script.
Alternatively, run `python ./a.py` |
Accessing python list in javascript as an array | 23,038,710 | 5 | 2014-04-13T03:16:41Z | 23,039,331 | 8 | 2014-04-13T05:07:02Z | [
"javascript",
"python",
"flask"
] | I have this in my flask views.py
```
def showpage():
...
test = [1,2,3,4,5,6]
return render_template("sample.html",test=test)
```
I have this in my sample .html
```
<script> var counts = {{test}}; </script>
```
This gives me a empty counts variable. How can I get the counts same as the tes... | 1. When you insert variable to template `{{ test }}` it take object representation. For list of int `[1,2,3,4,5,6]` it will be rendered as `[1, 2, 3, 4, 5, 6]`, so it is valid javascript array, but this method not safe complex objects without javascript-like representation, for example, test = [1,2,3,4,5,any] will rend... |
How does heapq.nlargest work? | 23,038,756 | 5 | 2014-04-13T03:24:10Z | 23,038,826 | 7 | 2014-04-13T03:35:34Z | [
"python",
"algorithm",
"heap",
"time-complexity"
] | I was looking at [this pycon talk, 34:30](http://pyvideo.org/video/2571/all-your-ducks-in-a-row-data-structures-in-the-s) and the speaker says that getting the `t` largest elements of a list of `n` elements can be done in `O(t + n)`.
How is that possible? My understanding is that creating the heap will be `O(n)`, but ... | The speaker is wrong in this case. The actual cost is `O(n * log(t))`. Heapify is called only on the first `t` elements of the iterable. That's `O(t)`, but is insignificant if `t` is much smaller than `n`. Then all the remaining elements are added to this "little heap" via `heappushpop`, one at a time. That takes `O(lo... |
What is the purpose of bare asterix in function arguments? | 23,038,767 | 15 | 2014-04-13T03:25:49Z | 23,039,209 | 13 | 2014-04-13T04:45:48Z | [
"python",
"function",
"python-3.x",
"arguments",
"keyword-argument"
] | I've seen this SO question (this is not a duplicate): [Python bare asterisk in function argument](http://stackoverflow.com/questions/14301967/python-bare-asterisk-in-function-argument)
In python-3.x you can add a bare `*` to the function arguments, this means that (quote from [docs](https://docs.python.org/3/reference... | [PEP 3102](http://www.python.org/dev/peps/pep-3102/) explains the rationale pretty clearly: the point is to allow functions to accept various "options" that are essentially orthogonal in nature. Specifying these positionally is awkward both on the defining and calling side, since they don't have any obvious "priority" ... |
How to simply have python print "\xaa\xbb\xcc\xdd" as 0xddccbbaa? | 23,039,054 | 6 | 2014-04-13T04:17:14Z | 23,039,063 | 8 | 2014-04-13T04:20:08Z | [
"python",
"hex"
] | I believe I'm misunderstanding something that should probably be simple.
I'm trying to accept arguments passed to a python script. The type of argument I'm expecting is somewhere along the lines of `"\xaa\xbb\xcc\xdd"`, and it keeps converting it to binary(i think?) instead of actually allowing me to print it out just... | Some demonstrations with [`struct`](https://docs.python.org/2/library/struct.html):
```
x = b"\xaa\xbb\xcc\xdd"
import struct
struct.unpack('I',x)
Out[3]: (3721182122,)
y = struct.unpack('I',x)
y[0]
Out[5]: 3721182122
hex(y[0])
Out[6]: '0xddccbbaa'
```
Essentially: treat the bytestring as a little-endian 4-byte ... |
For loop item unpacking | 23,039,485 | 7 | 2014-04-13T05:31:58Z | 23,041,609 | 22 | 2014-04-13T10:31:54Z | [
"python",
"performance",
"for-loop",
"iterable-unpacking"
] | Once, after watching Mike Muller's performance optimization tutorial (I think [this one](https://www.youtube.com/watch?v=Bs6-sai1fKE)), one thought started to live in my head: if performance matters, minimize accessing items in the loop by index, e. g. if you need to access `x[1]` multiple times in a loop `for x in l` ... | To answer your questions we can check the bytecode generated by the two functions using the `dis` module:
```
In [5]: def no_unpacking():
...: s = []
...: for item in SEQUENCE:
...: s.append(item[0] + item[1])
...: return s
...:
...:
...: def unpacking():
...: s = []... |
FreqDist in NLTK not sorting output | 23,042,699 | 2 | 2014-04-13T12:23:56Z | 27,464,892 | 16 | 2014-12-13T23:50:38Z | [
"python",
"nlp",
"nltk"
] | I'm new to Python and I'm trying to teach myself language processing. NLTK in python has a function called FreqDist that gives the frequency of words in a text, but for some reason it's not working properly.
This is what the tutorial has me write:
```
fdist1 = FreqDist(text1)
vocabulary1 = fdist1.keys()
vocabulary1[:... | From [NLTK's GitHub](https://github.com/nltk/nltk/issues/390#issuecomment-53171900):
> FreqDist in NLTK3 is a wrapper for collections.Counter; Counter provides `most_common()` method to return items in order. `FreqDist.keys()` method is provided by standard library; it is not overridden. I think it is good we're becom... |
python beautifulsoup new_tag: assign class as an attribute | 23,042,963 | 4 | 2014-04-13T12:50:11Z | 23,043,358 | 10 | 2014-04-13T13:31:38Z | [
"python",
"beautifulsoup"
] | I'm new to both python and beautifulsoup, so maybe there is a simple answer I can't find.
When I call `.new_tag('name')` I also can assign attributes like `.new_tag('a', href='#', id='link1')`
But I can't assign class this way, because it is reserved word. Also I can't add name this way, because it's used as keyword ... | You are right - class is a python reserved word and cannot be used as a keyword argument because the language parser complains.
There's a way around this - you can give the function keyword arguments through a dictionary preceded by `**`.
That way "class" is just another string and wont collide with the reserved word ... |
Python name 'os' is not defined | 23,048,129 | 3 | 2014-04-13T20:35:40Z | 23,048,156 | 25 | 2014-04-13T20:37:54Z | [
"python",
"import"
] | I am trying to run this python module
```
from settings import PROJECT_ROOT
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME' : os.path.join(BASE_DIR, 'db_name.sqlite3'),
}
}
# Make this unique, and don't share it with anybody.
S... | Just add:
```
import os
```
in the beginning, before:
```
from settings import PROJECT_ROOT
```
This will import the python's module **os**, which apparently is used later in the code of your module without being imported. |
Manage empty list/invalid input when finding max/min value of list (Python) | 23,048,944 | 18 | 2014-04-13T21:59:46Z | 27,757,418 | 20 | 2015-01-03T17:16:32Z | [
"python",
"list",
"error-handling",
"max",
"min"
] | I'm finding max value and min value of a list by using `max(list)` and `min(list)` in Python. However, I wonder how to manage empty lists.
For example if the list is an empty list `[]`, the program raises `'ValueError: min() arg is an empty sequence'` but I would like to know how to make the program just print `'empty... | In Python 3.4, a `default` keyword argument has been added to the `min` and `max` functions. This allows a value of your choosing to be returned in if the functions are used on an empty list (or other iterable):
```
>>> min([], default='no elements')
'no elements'
```
If the `default` keyword if not given, a `ValueEr... |
Manage empty list/invalid input when finding max/min value of list (Python) | 23,048,944 | 18 | 2014-04-13T21:59:46Z | 31,437,974 | 22 | 2015-07-15T18:10:56Z | [
"python",
"list",
"error-handling",
"max",
"min"
] | I'm finding max value and min value of a list by using `max(list)` and `min(list)` in Python. However, I wonder how to manage empty lists.
For example if the list is an empty list `[]`, the program raises `'ValueError: min() arg is an empty sequence'` but I would like to know how to make the program just print `'empty... | Specifying a default in earlier versions of Python:
```
max(list or [0])
max(list or ['empty list'])
``` |
Python 3 list(dictionary.keys()) raises error. What am I doing wrong? | 23,050,172 | 4 | 2014-04-14T00:33:23Z | 23,050,282 | 13 | 2014-04-14T00:47:02Z | [
"python",
"django",
"python-3.x"
] | Dictionary:
```
error['extras'] = {'expiration_month': 'Invalid field [expiration_month] - Missing field "expiration_month"'}
```
Code:
```
list(error['extras'].keys())
```
Result:
```
*** Error in argument: "(error['extras'].keys())"
```
If its relevant, I'm running this code in a django process that's paused by... | I believe the problem is that `list` [is a pdb debugger command](https://docs.python.org/2/library/pdb.html#debugger-commands). The documentation states the following:
> Commands that the debugger doesnât recognize are assumed to be Python
> statements and are executed in the context of the program being
> debugged.... |
Open files in 'rt' and 'wt' modes | 23,051,062 | 32 | 2014-04-14T02:33:02Z | 23,051,095 | 61 | 2014-04-14T02:36:51Z | [
"python",
"file",
"file-io"
] | Several times here on SO I've seen people using `rt` and `wt` modes for reading and writing files.
For example:
```
with open('input.txt', 'rt') as input_file:
with open('output.txt', 'wt') as output_file:
...
```
I don't see the modes [documented](https://docs.python.org/2/library/functions.html#open... | `t` refers to the text mode. There is no difference between `r` and `rt` or `w` and `wt` since text mode is the default.
Documented [here](https://docs.python.org/3/library/functions.html#open):
```
Character Meaning
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open... |
Python list-comprehension for words that do not consist solely of digits | 23,051,294 | 9 | 2014-04-14T03:02:10Z | 23,051,313 | 14 | 2014-04-14T03:04:55Z | [
"python",
"list",
"list-comprehension"
] | At a high level, what I'm trying to accomplish is:
```
given a list of words, return all the words that do not consist solely of digits
```
My first thought of how to do that is:
```
import string
result = []
for word in words:
for each_char in word:
if each_char not in string.digit:
result.a... | Why not just check the whole string for `isdigit()`:
```
>>> words = ['foo', '123', 'foo123']
>>> [word for word in words if not word.isdigit()]
['foo', 'foo123']
```
Or, turn the logic other way and use `any()`:
```
>>> [word for word in words if any(not char.isdigit() for char in word)]
['foo', 'foo123']
```
`any... |
Open files in "rock&roll" mode | 23,051,502 | 14 | 2014-04-14T03:31:44Z | 23,051,518 | 15 | 2014-04-14T03:33:00Z | [
"python",
"file",
"python-3.x",
"python-2.x"
] | I'm wondering what is going on with the file `open()` mode validation (Python2.7):
```
>>> with open('input.txt', 'illegal') as f:
... for line in f:
... print line
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: mode string must begin with one of 'r', 'w', 'a' or ... | The previous traceback explains it nicely:
> "ValueError: mode string must **begin with** one of 'r', 'w', 'a' or 'U'"
"rock&roll" begins with `"r"`, so it's apparently legal. |
Open files in "rock&roll" mode | 23,051,502 | 14 | 2014-04-14T03:31:44Z | 23,051,528 | 16 | 2014-04-14T03:34:09Z | [
"python",
"file",
"python-3.x",
"python-2.x"
] | I'm wondering what is going on with the file `open()` mode validation (Python2.7):
```
>>> with open('input.txt', 'illegal') as f:
... for line in f:
... print line
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: mode string must begin with one of 'r', 'w', 'a' or ... | The Python 2.x `open` function essentially delegates its work to the C library `fopen` function. On my system, the documentation for `fopen` contains:
> The argument `mode` points to a string beginning with one of the following sequences (Additional characters may follow these sequences.):
Your `ock&roll` is consider... |
Error: 1>0 and print("yes") | 23,053,897 | 2 | 2014-04-14T07:02:53Z | 23,053,937 | 10 | 2014-04-14T07:04:50Z | [
"python",
"python-2.x"
] | Python:
```
1>0 and print("yes")
```
SyntaxError: invalid syntax at 'print'
Could anyone tell why? Thanks! | In Python 2 print is a statement and it cannot used as an expression.
To use the Python 3's print function in Python 2 you need to import it first:
```
from __future__ import print_function
```
**Demo:**
```
>>> 1>0 and print("yes")
File "<ipython-input-2-0714eacbdec3>", line 1
1>0 and print("yes")
... |
Why is cffi so much quicker than numpy? | 23,056,057 | 9 | 2014-04-14T09:04:05Z | 23,058,665 | 12 | 2014-04-14T11:15:55Z | [
"python",
"c",
"numpy",
"pypy",
"python-cffi"
] | I have been playing around with writing cffi modules in python, and their speed is making me wonder if I'm using standard python correctly. It's making me want to switch to C completely! Truthfully there are some great python libraries I could never reimplement myself in C so this is more hypothetical than anything rea... | Numpy is slower than C for two reasons: the Python overhead (probably similar to cffi) and generality. Numpy is designed to deal with arrays of arbitrary dimensions, in a bunch of different data types. Your example with cffi was made for a 2D array of floats. The cost was writing several lines of code vs `.sum()`, 6 ch... |
Does the SVM in sklearn support incremental (online) learning? | 23,056,460 | 14 | 2014-04-14T09:24:16Z | 23,063,481 | 15 | 2014-04-14T15:00:50Z | [
"python",
"machine-learning",
"scikit-learn",
"svm"
] | I am currently in the process of designing a recommender system for text articles (a binary case of 'interesting' or 'not interesting'). One of my specifications is that it should continuously update to changing trends.
From what I can tell, the best way to do this is to make use of machine learning algorithm that sup... | While online algorithms for SVMs do exist, it has become important to specify if you want kernel or linear SVMs, as many efficient algorithms have been developed for the special case of linear SVMs.
For the linear case, if you use the [SGD classifier in scikit-learn](http://scikit-learn.org/stable/modules/sgd.html#sgd... |
Does the SVM in sklearn support incremental (online) learning? | 23,056,460 | 14 | 2014-04-14T09:24:16Z | 31,486,380 | 8 | 2015-07-17T23:57:51Z | [
"python",
"machine-learning",
"scikit-learn",
"svm"
] | I am currently in the process of designing a recommender system for text articles (a binary case of 'interesting' or 'not interesting'). One of my specifications is that it should continuously update to changing trends.
From what I can tell, the best way to do this is to make use of machine learning algorithm that sup... | Maybe it's me being naive but I think it is worth mentioning how to actually update the [sci-kit SGD classifier](http://scikit-learn.org/stable/modules/sgd.html#sgd) when you present your data incrementally:
```
clf = linear_model.SGDClassifier()
x1 = some_new_data
y1 = the_labels
clf.partial_fit(x1,y1)
x2 = some_newe... |
clone element with beautifulsoup | 23,057,631 | 10 | 2014-04-14T10:21:10Z | 23,058,678 | 15 | 2014-04-14T11:16:34Z | [
"python",
"beautifulsoup"
] | I have to copy a part of one document to another, but I don't want to modify the document I copy from.
If I use `.extract()` it removes the element from the tree. If I just append selected element like `document2.append(document1.tag)` it still removes the element from document1.
As I use real files I can just not sa... | There is no native clone function in BeautifulSoup in versions before 4.4 (released July 2015); you'd have to create a deep copy yourself, which is tricky as each element maintains links to the rest of the tree.
To clone an element and all its elements, you'd have to copy all attributes and *reset* their parent-child ... |
How to get all mappings between two lists? | 23,058,028 | 18 | 2014-04-14T10:42:25Z | 23,058,314 | 22 | 2014-04-14T10:56:54Z | [
"python",
"list",
"combinatorics",
"itertools"
] | We have two lists, A and B:
```
A = ['a','b','c']
B = [1, 2]
```
Is there a pythonic way to build the set of all maps between A and B containing 2^n (here 2^3=8)? That is:
```
[(a,1), (b,1), (c,1)]
[(a,1), (b,1), (c,2)]
[(a,1), (b,2), (c,1)]
[(a,1), (b,2), (c,2)]
[(a,2), (b,1), (c,1)]
[(a,2), (b,1), (c,2)]
[(a,2), (... | You can do this with [`itertools.product`](https://docs.python.org/2/library/itertools.html#itertools.product) and [`zip`](https://docs.python.org/2/library/functions.html#zip)
```
from itertools import product
print [zip(A, item) for item in product(B, repeat=len(A))]
```
**Output**
```
[[('a', 1), ('b', 1), ('c', ... |
How to get all mappings between two lists? | 23,058,028 | 18 | 2014-04-14T10:42:25Z | 23,058,319 | 11 | 2014-04-14T10:57:02Z | [
"python",
"list",
"combinatorics",
"itertools"
] | We have two lists, A and B:
```
A = ['a','b','c']
B = [1, 2]
```
Is there a pythonic way to build the set of all maps between A and B containing 2^n (here 2^3=8)? That is:
```
[(a,1), (b,1), (c,1)]
[(a,1), (b,1), (c,2)]
[(a,1), (b,2), (c,1)]
[(a,1), (b,2), (c,2)]
[(a,2), (b,1), (c,1)]
[(a,2), (b,1), (c,2)]
[(a,2), (... | ```
import itertools as it
A = ['a','b','c']
B = [1, 2]
for i in it.product(*([B]*len(A))):
print(list(zip(A, i)))
```
outputs:
```
[('a', 1), ('b', 1), ('c', 1)]
[('a', 1), ('b', 1), ('c', 2)]
[('a', 1), ('b', 2), ('c', 1)]
[('a', 1), ('b', 2), ('c', 2)]
[('a', 2), ('b', 1), ('c', 1)]
[('a', 2), ('b', 1), ('c'... |
Plot histogram with colors taken from colormap | 23,061,657 | 14 | 2014-04-14T13:39:18Z | 23,062,183 | 12 | 2014-04-14T14:01:32Z | [
"python",
"matplotlib",
"histogram"
] | I want to plot a simple 1D histogram where the bars should follow the color-coding of a given colormap.
Here's an `MWE`:
```
import numpy as n
import matplotlib.pyplot as plt
# Random gaussian data.
Ntotal = 1000
data = 0.05 * n.random.randn(Ntotal) + 0.5
# This is the colormap I'd like to use.
cm = plt.cm.get_cma... | The `hist` command returns a list of patches, so you can iterate over them and set their color like so:
```
import numpy as n
import matplotlib.pyplot as plt
# Random gaussian data.
Ntotal = 1000
data = 0.05 * n.random.randn(Ntotal) + 0.5
# This is the colormap I'd like to use.
cm = plt.cm.get_cmap('RdYlBu_r')
# P... |
No minor grid lines on the x-axis only | 23,062,203 | 4 | 2014-04-14T14:02:41Z | 23,062,259 | 7 | 2014-04-14T14:05:26Z | [
"python",
"matplotlib"
] | I'm trying to product a plot in which the y-axis has both major and minor gridlines, while the x-axis has only major gridlines.
It's straightforward enough to disable minor grid lines on *both* axes, like so:
```
axes.grid(False, which='minor')
```
But I can't find a way of applying this to only one axis. Am I missi... | ```
axes.yaxis.grid(True, which='minor')
```
Similarly
```
axes.xaxis.grid(False, which='minor')
``` |
SQLalchemy: alembic bulk_insert() fails | 23,063,248 | 2 | 2014-04-14T14:49:21Z | 23,176,543 | 8 | 2014-04-19T23:00:17Z | [
"python",
"mysql",
"sqlalchemy",
"alembic"
] | Before you flag this as a duplicate:
I did take a look at this [question/answer](http://stackoverflow.com/questions/15725859/sqlalchemy-alembic-bulk-insert-fails-str-object-has-no-attribute-autoincre), and I did do what it suggests, but when I do add this code:
```
permslookup = sa.Table('permslookup',
sa.Column(... | For error #1, not enough information. Need a stack trace.
For #2, bulk\_insert() receives the Table object, not a string name, as the argument.
see <http://alembic.readthedocs.org/en/latest/ops.html#alembic.operations.Operations.bulk_insert>:
```
from alembic import op
from datetime import date
from sqlalchemy.sql i... |
Optimizing strings in Cython | 23,064,141 | 8 | 2014-04-14T15:32:30Z | 23,082,626 | 10 | 2014-04-15T11:40:56Z | [
"python",
"string",
"performance",
"optimization",
"cython"
] | I'm trying to demonstrate to our group the virtues of Cython for enhancing Python performance. I have shown several benchmarks, all that attain speed up by just:
1. Compiling the existing Python code.
2. Using cdef to static type variables, particular in inner loops.
However, much of our code does string manipulation... | I suggest you do your operations on `cpython.array.array`s. The best documentation is the C API and the Cython source, which I'm too lazy to link to.
```
from cpython cimport array
def cfuncA():
cdef str a
cdef int i,j
for j in range(1000):
a = ''.join([chr(i) for i in range(127)])
def cfuncB():
... |
Get date and time when photo was taken from EXIF data using PIL | 23,064,549 | 8 | 2014-04-14T15:50:30Z | 23,064,792 | 13 | 2014-04-14T16:01:15Z | [
"python",
"python-imaging-library",
"exif"
] | I can [get the EXIF data from an image](http://stackoverflow.com/questions/4764932/in-python-how-do-i-read-the-exif-data-for-an-image) using PIL, but how can I get the date and time that the photo was taken? | Found the answer eventually, the tag I needed was [36867](http://www.awaresystems.be/imaging/tiff/tifftags/privateifd/exif/datetimeoriginal.html):
```
from PIL import Image
def get_date_taken(path):
return Image.open(path)._getexif()[36867]
``` |
Compiler problems with pip during numpy install under Windows 8.1, 7 Enterprise and 7 Home Editions | 23,064,899 | 17 | 2014-04-14T16:07:00Z | 23,099,820 | 8 | 2014-04-16T04:10:58Z | [
"python",
"windows",
"numpy",
"pip",
"python-3.4"
] | I am unable to install numpy via pip install numpy on my computer running Python 3.4 due to various errors I receive linked to compilation issues (This is only the case on a 64-bit installation of Python).
This is a problem that has been reported extensively and I had [a related question](http://stackoverflow.com/ques... | I was able to reproduce all these errors in Windows 7 Professional (64 bit).
Your final issue (Broken toolchain) is caused by more manifest related issues. I was able to work around this by changing the following line (in msvc9compiler.py):
```
mfinfo = self.manifest_get_embed_info(target_desc, ld_args)
```
to
```
... |
flask-sqlalchemy max value of column | 23,067,750 | 3 | 2014-04-14T18:41:25Z | 23,068,709 | 7 | 2014-04-14T19:34:01Z | [
"python",
"sqlalchemy",
"flask",
"flask-sqlalchemy"
] | Lets say I have a user model as such
```
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.... | You could order by numLogins and take the first result, but that won't work if multiple people have the same number. Instead, find the max number, then find all users with than number.
```
max_logins = db.session.query(db.func.max(User.numLogins)).scalar()
users = db.session.query(User).filter(User.numLogins == max_lo... |
Using __slots__ under PyPy | 23,068,076 | 8 | 2014-04-14T18:58:30Z | 23,070,074 | 11 | 2014-04-14T20:46:23Z | [
"python",
"performance",
"pypy",
"slots"
] | I have this simple code that helped me to measure how classes with `__slots__` perform (taken from [here](http://stackoverflow.com/a/1336890/771848)):
```
import timeit
def test_slots():
class Obj(object):
__slots__ = ('i', 'l')
def __init__(self, i):
self.i = i
self.l = [... | In each of the 10,000 or so iterations of the `timeit` code, the class is recreated from scratch. Creating classes is probably not a well-optimized operation in PyPy; even worse, doing so will probably discard all of the optimizations that the JIT learned about the previous incarnation of the class. PyPy tends to be sl... |
Django Rest Framework - How to test ViewSet? | 23,072,730 | 12 | 2014-04-15T00:38:22Z | 23,091,705 | 8 | 2014-04-15T18:34:35Z | [
"python",
"django",
"django-rest-framework"
] | I'm having trouble testing a ViewSet:
```
class ViewSetTest(TestCase):
def test_view_set(self):
factory = APIRequestFactory()
view = CatViewSet.as_view()
cat = Cat(name="bob")
cat.save()
request = factory.get(reverse('cat-detail', args=(cat.pk,)))
response = view(re... | I think I found the correct syntax, but not sure if it is conventional (still new to Django):
```
def test_view_set(self):
request = APIRequestFactory().get("")
cat_detail = CatViewSet.as_view({'get': 'retrieve'})
cat = Cat.objects.create(name="bob")
response = cat_detail(request, pk=cat.pk)
self.a... |
Why don't monkey-patched methods get passed a reference to the instance? | 23,073,716 | 5 | 2014-04-15T02:36:23Z | 23,073,756 | 7 | 2014-04-15T02:40:27Z | [
"python",
"oop",
"python-3.x",
"self",
"monkeypatching"
] | See this example for a demonstration:
```
>>> class M:
def __init__(self): self.x = 4
>>> sample = M()
>>> def test(self):
print(self.x)
>>> sample.test = test
>>> sample.test()
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
sample.test()
TypeError: test() missing 1 re... | The `test` method you are assigning to `sample.test` is not bound to the `sample` object. You need to manually bind it like this
```
import types
sample.test = types.MethodType(test, sample)
sample.test()
# 4
``` |
What does this use of << mean in Python | 23,074,266 | 2 | 2014-04-15T03:40:42Z | 23,074,284 | 7 | 2014-04-15T03:43:00Z | [
"python",
"pyparsing"
] | I ran across this use of '<<' in a Python example using the pyparsing module:
`whereExpression << whereCondition + ZeroOrMore( ( and_ | or_ ) + whereExpression )`
It clearly isn't a binary left shift operator, but I don't find it described in any Python reference. Can someone explain it? Thank you. | Like any operator, `<<` can be overloaded by classes to define their own behavior. The example you give looks like it's from code using [pyparsing](http://pyparsing.wikispaces.com/). This is a parser library that overloads operators in this way. The `<<` here updates the content of a previously-defined placeholder toke... |
Cannot save matplotlib animation with ffmpeg | 23,074,484 | 9 | 2014-04-15T04:07:38Z | 23,098,090 | 13 | 2014-04-16T02:44:52Z | [
"python",
"animation",
"matplotlib"
] | I am trying to save a simple matplotlib animation from [Jake Vanderplas](http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/), but I keep getting `OSError: [Errno 13] Permission denied`.
I should note that I made two small modifications to Jake Vanderplas's example. I installed ffmpeg from MacPorts... | So it turns out there were two issues.
Issue #1: The path to ffmpeg was wrong. I thought I needed to provide the path to the directory that ffmpeg resides in, but I needed to provide the path all the way to the ffmpeg binary.
Issue #2: Prior to testing out my code to generate videos, I sometimes would import a module... |
Python: how to edit an installed package? | 23,075,397 | 9 | 2014-04-15T05:36:05Z | 23,075,617 | 12 | 2014-04-15T05:52:40Z | [
"python",
"pip"
] | I installed some package via `pip install something`. I want to edit the source code for the package `something`. Where is it (on ubuntu 12.04) and how do I make it reload each time I edit the source code and run it?
Currently I am editing the source code, and then running python setup.py again and again, which turns ... | Actually, you should never edit an installed package, instead you should install a forked version of package.
If you need to edit the code frequently, you had better not install the package via `pip install something` and edit the code in '.../site\_packages/...'
Instead you should put the source code under a develop... |
How is the self argument magically passed to instance methods? | 23,082,509 | 4 | 2014-04-15T11:35:57Z | 23,082,576 | 8 | 2014-04-15T11:38:51Z | [
"python",
"self"
] | I'm doing the code academy stream and I have a little experience in Ruby. I don't understand why the `check_angles(self)` function needs the `self` parameter.
The reason I'm confused is that I don't understand what is passing the self parameter to the function when it is called. it seems like the function call (the la... | The way this works in Python is that once you instantiate a class `Foo` with a method `bar(self)`, the function used to create the method is wrapped in an object of type `instancemethod` which "binds" it to the instance, so that calling `foo_inst.bar()` actually calls `Foo.bar(foo_inst)`.
```
class Foo(object):
de... |
How to "test" NoneType in python? | 23,086,383 | 83 | 2014-04-15T14:16:07Z | 23,086,405 | 129 | 2014-04-15T14:16:46Z | [
"python",
"nonetype"
] | I have a method that sometimes returns a NoneType value. So how can I question a variable that is a NoneType? I need to use ***if*** method, for example
```
if not new:
new = '#'
```
I know that is the wrong way and I hope you understand what I meant. | > So how can I question a variable that is a NoneType?
Use `is` operator, like this
```
if variable is None:
```
**Why this works?**
Since [`None`](https://docs.python.org/2/library/constants.html#None) is the sole singleton object of [`NoneType`](https://docs.python.org/2/library/types.html#types.NoneType) in Pyth... |
How to "test" NoneType in python? | 23,086,383 | 83 | 2014-04-15T14:16:07Z | 23,086,670 | 12 | 2014-04-15T14:28:12Z | [
"python",
"nonetype"
] | I have a method that sometimes returns a NoneType value. So how can I question a variable that is a NoneType? I need to use ***if*** method, for example
```
if not new:
new = '#'
```
I know that is the wrong way and I hope you understand what I meant. | ```
if variable is None:
print 'Is None'
```
--
```
if variable is not None:
print 'Isn\'t None'
``` |
Installing pip for Python 3.4 - Mac OS X | 23,088,527 | 3 | 2014-04-15T15:45:47Z | 23,164,662 | 9 | 2014-04-19T01:13:36Z | [
"python",
"osx",
"python-2.7",
"pip",
"osx-mavericks"
] | as you know the Mac comes with Python pre-installed, mine has the 2.7 version. I installed Python 3.4. I installed **pip** using the command
**sudo easy\_install**
however it gets installed to the 2.7 version of Python and all the packages i download therefore get installed to the 2.7 version.
Is there a way to install... | I installed Python 3.4 for my Mac from this page:
<https://www.python.org/download/>
It installed pip automatically, but it's called `pip3`, not `pip`. Type `which pip3` at the console to find it. |
Stop nosetests from printing logging information? | 23,095,206 | 6 | 2014-04-15T21:51:20Z | 23,159,887 | 11 | 2014-04-18T18:22:47Z | [
"python",
"django",
"nosetests"
] | How do I prevent nosetests from interspersing logging output inside the output from its tests? I've just adding logging to my Django code like this:
```
import logging
logger = logging.getLogger(__name__)
def home_page(request, template):
device = get_device_capabilities(request)
device_type = get_device_type... | Thanks to those who provided an answer to my question. I chose not to implement amezhenin's solution as it was too different from how I run my tests and I didn't want to change. Oleksiy's solutions got rid of some logging messages but not all of them. I didn't quite get what gardenunez was getting at but that's my faul... |
Django AUTHENTICATION_BACKENDS import error | 23,095,951 | 3 | 2014-04-15T22:50:32Z | 23,099,867 | 7 | 2014-04-16T04:15:23Z | [
"python",
"django",
"django-authentication",
"django-settings"
] | What is the proper way to import a custom backend in settings.py? I currently have the following in settings.py:
```
AUTHENTICATION_BACKENDS = ('apps.apployment_site.auth.CustomAuth')
```
where apployment\_site is the app, auth is file name, and CustomAuth is the class name.
In my view, I get: `ImportError: a doesn'... | make sure it's a tuple:
```
AUTHENTICATION_BACKENDS = ('apps.apployment_site.auth.CustomAuth',)
```
note the comma at the end |
Python removing all negative values in array | 23,096,417 | 3 | 2014-04-15T23:37:26Z | 23,096,448 | 13 | 2014-04-15T23:40:22Z | [
"python",
"arrays",
"numpy"
] | What is the most efficient way to remove negative elements in an array? I have tried `numpy.delete` and [Remove all specific value from array](http://stackoverflow.com/questions/13032448/remove-all-specific-value-from-array) and code of the form `x[x != i]`.
For:
```
import numpy as np
x = np.array([-2, -1.4, -1.1, 0... | ```
In [2]: x[x >= 0]
Out[2]: array([ 0. , 1.2, 2.2, 3.1, 4.4, 8.3, 9.9, 10. , 14. , 16.2])
``` |
computing frequencies in a nested list | 23,098,468 | 2 | 2014-04-16T03:28:38Z | 23,098,482 | 7 | 2014-04-16T03:30:53Z | [
"python",
"list"
] | I'm trying to compute the frequencies of words using a dictionary in a nested lists. Each nested list is a sentence broken up into each word. Also, I want to delete proper nouns and lower case words at the beginning of the sentence. Is it even possible to get ride of proper nouns?
```
x = [["Hey", "Kyle","are", "you",... | Since your data is nested, you can flatten it with `chain.from_iterable` like this
```
from itertools import chain
from collections import Counter
print Counter(chain.from_iterable(x))
# Counter({'doing': 2, 'Kyle': 2, 'what': 1, 'timeis': 1, 'am': 1, 'Hey': 1, 'I': 1, 'are': 1, 'it': 1, 'you': 1, 'fine': 1})
```
If ... |
Running infinite loops using threads in python | 23,100,704 | 2 | 2014-04-16T05:27:19Z | 23,102,874 | 9 | 2014-04-16T07:35:07Z | [
"python",
"multithreading",
"opencv",
"matplotlib"
] | My program is designed in the following way:
1. First part of the program takes real time values from a sensor and plots it using **Matplotlib.** This has to be done for long durations. And also, it logs information into a database.
2. The second part is the IP Camera. I have to get the input from an IP Camera and dis... | As far as I understood your question, you have two different tasks that you want them to perform continuously. Now regarding your questions:
> *how do I go about running two infinite loops?*
You can create two different threads that will run these infinite loops for you. The first thread will perform your task1 and s... |
Pythonic random list of booleans of length n with exactly k Trues | 23,101,223 | 5 | 2014-04-16T06:03:16Z | 23,101,312 | 7 | 2014-04-16T06:08:42Z | [
"python",
"list",
"random"
] | Say we want a list of `n` `0`/`1` elements with exactly `k` instances of `1`. Is there a one line comprehension or a more pythonic way to do this than the following?
```
def random_include(n, k):
ret = []
to_include = set(random.sample([i for i in range(n)], k))
for i in range(n):
if i in to_inclu... | Here's a one-line solution.
```
output = sorted([1] * k + [0] * (n - k), key=lambda k: random.random())
``` |
How to scrape a website which requires login using python and beautifulsoup? | 23,102,833 | 13 | 2014-04-16T07:33:29Z | 23,103,784 | 17 | 2014-04-16T08:20:04Z | [
"python",
"web-scraping",
"beautifulsoup"
] | If I want to scrape a website that requires login with password first, how can I start scraping it with python using beautifulsoup4 library? Below is what I do for websites that do not require login.
```
from bs4 import BeautifulSoup
import urllib2
url = urllib2.urlopen("http://www.python.org")
content = url.... | You can use mechanize:
```
import mechanize
from bs4 import BeautifulSoup
import urllib2
import cookielib
cj = cookielib.CookieJar()
br = mechanize.Browser()
br.set_cookiejar(cj)
br.open("https://id.arduino.cc/auth/login/")
br.select_form(nr=0)
br.form['username'] = 'username'
br.form['password'] = 'password.'
br.s... |
How to write DataFrame to postgres table? | 23,103,962 | 10 | 2014-04-16T08:29:32Z | 23,104,436 | 20 | 2014-04-16T08:52:13Z | [
"python",
"postgresql",
"pandas",
"sqlalchemy"
] | There is *DataFrame.to\_sql* method, but it works only for mysql, sqlite and oracle databases. I cant pass to this method postgres connection or sqlalchemy engine. | Starting from pandas 0.14 (released end of May 2014), postgresql is supported. The `sql` module now uses `sqlalchemy` to support different database flavors. You can pass a sqlalchemy engine for a postgresql database (see [docs](http://pandas.pydata.org/pandas-docs/stable/io.html#io-sql)). E.g.:
```
from sqlalchemy imp... |
PySide: QWidget does not draw background color | 23,104,051 | 6 | 2014-04-16T08:33:47Z | 23,113,643 | 7 | 2014-04-16T15:21:27Z | [
"python",
"stylesheet",
"pyside",
"background-color",
"qwidget"
] | I am using PySide 1.2.1 with Python 2.7 and I need a widget to draw a colored background.
In Qt Designer I created a simple window consisting of a label, a widget containing three other items and another label. For the widget containing the button, radio button and checkbox I set the `styleSheet` property to `backgroun... | Set the [WA\_StyledBackground](http://qt-project.org/doc/qt-4.8/qt.html#WidgetAttribute-enum) attribute on the container widget:
```
ui = MainWindow()
ui.setupUi(mainwindow)
ui.widget.setAttribute(QtCore.Qt.WA_StyledBackground, True)
``` |
Unicodedecodeerror with runserver | 23,109,244 | 2 | 2014-04-16T12:17:14Z | 23,109,559 | 7 | 2014-04-16T12:31:20Z | [
"python",
"django",
"python-3.x"
] | After setting up all what `django` requires, I tried the `runserver` command and I caught an error:
> **UnicodeDecodeError**: 'utf-8' codec can't decode byte 0xcf in position
> 8: invalid continuation byte
From:
```
c:\sue>python manage.py runserver
Validating models...
0 errors found
April 16, 2014 - 15:02:42
Djan... | This sounds like [this Python issue](http://bugs.python.org/issue9377). If your computer name has non-ASCII characters this will fail. You may:
1. Issue the runserver command with explicit host and port: `python manage.py runserver 127.0.0.1:8000`
2. Change your computer name to a string that only contains ASCII chara... |
How to dynamically build a JSON object with Python? | 23,110,383 | 51 | 2014-04-16T13:06:52Z | 23,110,401 | 130 | 2014-04-16T13:07:33Z | [
"python",
"json"
] | I am new to Python and I am playing with JSON data. I would like to dynamically build a JSON object by adding some key-value to an existing JSON object.
I tried the following but I get `TypeError: 'str' object does not support item assignment`:
```
import json
json_data = json.dumps({})
json_data["key"] = "value"
p... | You build the object **before** encoding it to a JSON string:
```
data = {}
data['key'] = 'value'
json_data = json.dumps(data)
```
JSON is a *serialization* format, textual data *representing* a structure. It is not, itself, that structure. |
Websockets in Flask | 23,111,654 | 17 | 2014-04-16T13:59:44Z | 23,123,127 | 43 | 2014-04-17T01:40:23Z | [
"python",
"websocket",
"flask",
"uwsgi",
"gevent"
] | I'm currently researching websocket support in Python and am a bit confused with the offerings.
On one hand it's possible to use [Flask + gevent](https://gist.github.com/lrvick/1185629). On the other hand, uwsgi has [socket support](http://uwsgi-docs.readthedocs.org/en/latest/WebSockets.html) and at last there is an e... | In regular HTTP requests the connections between client and server are short-lived, a client connects to the server, sends a request, receives the response and then closes the connection. In this model the server can serve a large number of clients using a small number of workers. The concurrency model in this situatio... |
Pandas DataFrame stored list as string: How to convert back to list? | 23,111,990 | 7 | 2014-04-16T14:12:55Z | 23,112,008 | 9 | 2014-04-16T14:13:31Z | [
"python",
"string",
"list",
"pandas",
"dataframe"
] | I have an *n*-by-*m* Pandas DataFrame `df` defined as follows. (I know this is not the best way to do it. It makes sense for what I'm trying to do in my actual code, but that would be TMI for this post so just take my word that this approach works in my particular scenario.)
```
>>> df = DataFrame(columns=['col1'])
>>... | As you pointed out, this can commonly happen when saving and loading pandas DataFrames as `.csv` files, which is a text format.
In your case this happened because list objects have a string representation, allowing them to be stored as `.csv` files. Loading the `.csv` will then yield that string representation.
If yo... |
Using Flask, how do I modify the Cache-Control header for ALL output? | 23,112,316 | 8 | 2014-04-16T14:25:40Z | 23,115,561 | 22 | 2014-04-16T16:53:28Z | [
"python",
"http",
"flask"
] | I tried using this
```
@app.after_request
def add_header(response):
response.headers['Cache-Control'] = 'max-age=300'
return response
```
But this causes a duplicate Cache-Control header to appear. I only want max-age=300, NOT the max-age=1209600 line!
```
$ curl -I http://my.url.here/
HTTP/1.1 200 OK
Date: ... | Use the [`request.cache_control` object](http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.ETagResponseMixin.cache_control) object; this is a [`ResponseCacheControl()` instance](http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.ResponseCacheControl) letting you set various cache attributes... |
ANTIALIAS vs BICUBIC in PIL(Python Image Library)? | 23,113,163 | 4 | 2014-04-16T15:00:54Z | 23,209,568 | 8 | 2014-04-22T02:56:30Z | [
"python",
"image",
"image-processing",
"python-imaging-library",
"interpolation"
] | I am using PIL to resize my images, my case is to scale up the original image.
I am confused about the algorithm used with `resample=ANTIALIAS'.
According to the document below, `ANTIALIAS` seems to be the best while scaling down. I wonder In which case can `BICUBIC` win?(some of my test case shows bicubic is better ... | I've now gone through the source to figure out the details. I'm not terribly pleased by what I saw.
First, `BICUBIC`. There are a number of formulas which can be classified as bicubic, the most common of these being the Catmull-Rom interpolation. That's not what PIL uses. Don Mitchell and Arun Netravali wrote a paper ... |
Write dictionary values in an excel file | 23,113,231 | 4 | 2014-04-16T15:03:45Z | 23,113,609 | 7 | 2014-04-16T15:19:42Z | [
"python",
"arrays",
"python-3.x",
"dictionary"
] | I have a dictionary with multiple values for each key. I add the values using the following code:
```
d.setdefault(key, []).append(values)
```
The key value correspondence looks like this:
```
a -el1,el2,el3
b -el1,el2
c -el1
```
I need to loop thru the dictionary and write in an excel file:
```
Column 1 Column 2... | It seems like you want something like this:
```
import xlsxwriter
workbook = xlsxwriter.Workbook('data.xlsx')
worksheet = workbook.add_worksheet()
d = {'a':['e1','e2','e3'],'b':['e1','e2'],'c':['e1']}
row = 0
col = 0
for key in d.keys():
row += 1
worksheet.write(row, col, key)
for item in d[key]:
... |
All Permutations of a String in Python (Recursive) | 23,116,911 | 6 | 2014-04-16T18:04:36Z | 23,117,430 | 11 | 2014-04-16T18:31:24Z | [
"python",
"recursion",
"permutation"
] | I need a kick in the head on this one. I have the following recursive function defined:
```
def perms(s):
if(len(s)==1):
return s
res = ''
for x in xrange(len(s)):
res += s[x] + perms(s[0:x] + s[x+1:len(s)])
return res + '\n'
```
perms("abc") currently returns:
```
abccb
bacca
cabba
```
The desir... | **There you go (recursive permutation):**
```
def Permute(string):
if len(string) == 0:
return ['']
prevList = Permute(string[1:len(string)])
nextList = []
for i in range(0,len(prevList)):
for j in range(0,len(string)):
newString = prevList[i][0:j]+string[0]+prevList[i][j:le... |
Python super __init__ inheritance | 23,117,717 | 11 | 2014-04-16T18:45:45Z | 23,117,744 | 22 | 2014-04-16T18:47:43Z | [
"python",
"python-2.7",
"super"
] | I have the following Python 2.7 code:
```
class Frame:
def __init__(self, image):
self.image = image
class Eye(Frame):
def __init__(self, image):
super(Eye, self).__init__()
self.some_other_defined_stuff()
```
I'm trying to extend the `__init__()` method so that when I instantiate an ... | There are two errors here:
1. `super()` only works for [new-style classes](https://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes); use `object` as a base class for `Frame` to make it use new-style semantics.
2. You still need to call the overridden method with the right arguments; pass in `i... |
How to install python opencv through Conda? | 23,119,413 | 49 | 2014-04-16T20:23:19Z | 24,567,275 | 31 | 2014-07-04T05:31:39Z | [
"python",
"opencv",
"anaconda",
"conda"
] | I'm trying to install opencv for python through anaconda, but I can't seem to figure this out.
I tried
```
conda install opencv
conda install cv2
```
I also tried searching
```
conda search cv
```
No cigar. I ran across this which lists opencv as an included package:
<http://docs.continuum.io/anaconda/pkgs.html>
... | Doesn't seem like the page you linked includes opencv anymore. (Funny, I do recall it being included at a previous point as well.)
In any case, installation of OpenCV into Anaconda, although unavailable through conda, is pretty trivial. You just need to download one file.
1. Download OpenCV from <http://opencv.org/do... |
How to install python opencv through Conda? | 23,119,413 | 49 | 2014-04-16T20:23:19Z | 27,052,223 | 41 | 2014-11-21T00:30:00Z | [
"python",
"opencv",
"anaconda",
"conda"
] | I'm trying to install opencv for python through anaconda, but I can't seem to figure this out.
I tried
```
conda install opencv
conda install cv2
```
I also tried searching
```
conda search cv
```
No cigar. I ran across this which lists opencv as an included package:
<http://docs.continuum.io/anaconda/pkgs.html>
... | `conda install opencv` currently works for me. This is worth trying first before consulting other solutions. |
How to install python opencv through Conda? | 23,119,413 | 49 | 2014-04-16T20:23:19Z | 27,650,299 | 42 | 2014-12-25T19:55:25Z | [
"python",
"opencv",
"anaconda",
"conda"
] | I'm trying to install opencv for python through anaconda, but I can't seem to figure this out.
I tried
```
conda install opencv
conda install cv2
```
I also tried searching
```
conda search cv
```
No cigar. I ran across this which lists opencv as an included package:
<http://docs.continuum.io/anaconda/pkgs.html>
... | You can install it using binstar:
```
conda install -c https://conda.binstar.org/menpo opencv
``` |
How to install python opencv through Conda? | 23,119,413 | 49 | 2014-04-16T20:23:19Z | 30,281,466 | 29 | 2015-05-16T22:39:01Z | [
"python",
"opencv",
"anaconda",
"conda"
] | I'm trying to install opencv for python through anaconda, but I can't seem to figure this out.
I tried
```
conda install opencv
conda install cv2
```
I also tried searching
```
conda search cv
```
No cigar. I ran across this which lists opencv as an included package:
<http://docs.continuum.io/anaconda/pkgs.html>
... | I have summarized my now fully working solution [OpenCV-Python - How to install OpenCV-Python package to Anaconda (Windows)](http://mathalope.co.uk/2015/05/07/opencv-python-how-to-install-opencv-python-package-to-anaconda-windows/). Nevertheless I've copied and pasted the important bits to this post.
---
Currently, I... |
How to install python opencv through Conda? | 23,119,413 | 49 | 2014-04-16T20:23:19Z | 33,447,770 | 24 | 2015-10-31T03:32:33Z | [
"python",
"opencv",
"anaconda",
"conda"
] | I'm trying to install opencv for python through anaconda, but I can't seem to figure this out.
I tried
```
conda install opencv
conda install cv2
```
I also tried searching
```
conda search cv
```
No cigar. I ran across this which lists opencv as an included package:
<http://docs.continuum.io/anaconda/pkgs.html>
... | This worked for me (on Ubuntu and conda 3.18.3):
```
conda install --channel https://conda.anaconda.org/menpo opencv3
```
The command above was what was shown to me when I ran the following:
```
anaconda show menpo/opencv3
```
This was the output:
```
To install this package with conda run:
conda install --ch... |
How to install python opencv through Conda? | 23,119,413 | 49 | 2014-04-16T20:23:19Z | 35,056,306 | 10 | 2016-01-28T08:28:58Z | [
"python",
"opencv",
"anaconda",
"conda"
] | I'm trying to install opencv for python through anaconda, but I can't seem to figure this out.
I tried
```
conda install opencv
conda install cv2
```
I also tried searching
```
conda search cv
```
No cigar. I ran across this which lists opencv as an included package:
<http://docs.continuum.io/anaconda/pkgs.html>
... | To install opencv in Anaconda start up the Anaconda command prompt
and install the opencv with
```
conda install -c https://conda.anaconda.org/menpo opencv3
```
Test that it works in your Anaconda Spyder or IPython console with
```
import cv2
```
You can also check the installed version using
```
cv2.__version__
`... |
python requests - POST Multipart/form-data without filename in HTTP request | 23,120,974 | 12 | 2014-04-16T22:03:01Z | 23,131,823 | 24 | 2014-04-17T11:23:43Z | [
"python",
"http",
"python-requests"
] | I am trying to replicate the following POST request using the requests module in python:
```
POST /example/asdfas HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-U... | The solution is to use tuples when passing parameters to the files argument:
```
import requests
requests.post('http://example.com/example/asdfas', files={'value_1': (None, '12345'), 'value_2': (None, '67890')})
```
Works as expected:
```
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate, compress',
'Content-Leng... |
Python's str() function not actually a function? | 23,123,155 | 4 | 2014-04-17T01:44:13Z | 23,123,212 | 10 | 2014-04-17T01:51:04Z | [
"python"
] | I was under the impression that something like `str(5)` is calling the `str` function on the integer `5`. But when you type `str` into the interpreter:
```
>>> str
<class 'str'>
```
So `str` is actually a class, which makes code like `if type(a) is str` make more sense. But then why is `str` listed under "Built-in Fu... | Listing it as a function is a bit of a simplification, yes. But remember that classes are callable\* â that's how you create an instance of a class!
If it helps you any, think of `str(5)` as **constructing** a string from the number `5`.
Note that all of the other built-in types exist the same way: `int()`, `float(... |
Google Analytics reports API - Insufficient Permission 403 | 23,128,964 | 3 | 2014-04-17T09:07:18Z | 24,274,077 | 8 | 2014-06-17T22:06:54Z | [
"python",
"django",
"python-2.7",
"google-analytics-api",
"http-status-code-403"
] | I am trying to access data from google-analytics. I am following the guide and is able to gauthorize my user and get the code from oauth.
When I try to access data from GA I only get 403 Insufficient Permission back. Do I somehow have to connect my project in Google API console to my analytics project? How would I do ... | Had the same problem, but now is solved.
Use View ID Not account ID, the 'View ID', can be found in the Admin->Profiles->Profile Settings tab
UPDATE
now, if you have more a account , you must go: Admin -> Select account -> under View-> click on View Settings |
Django/Celery multiple queues on localhost - routing not working | 23,129,967 | 4 | 2014-04-17T09:55:45Z | 23,221,737 | 12 | 2014-04-22T13:59:55Z | [
"python",
"django",
"celery",
"celerybeat"
] | I followed celery [docs](http://celery.readthedocs.org/en/latest/userguide/routing.html#manual-routing) to define 2 queues on my dev machine.
My celery settings:
```
CELERY_ALWAYS_EAGER = True
CELERY_TASK_RESULT_EXPIRES = 60 # 1 mins
CELERYD_CONCURRENCY = 2
CELERYD_MAX_TASKS_PER_CHILD = 4
CELERYD_PREFETCH_MULTIPLIER... | Ok, so i figured it out. Following is my whole setup, settings and how to run celery, for those who might be wondering about same thing as my question did.
**Settings**
```
CELERY_TIMEZONE = TIME_ZONE
CELERY_ACCEPT_CONTENT = ['json', 'pickle']
CELERYD_CONCURRENCY = 2
CELERYD_MAX_TASKS_PER_CHILD = 4
CELERYD_PREFETCH_M... |
split list into 2 lists corresponding to every other element | 23,130,300 | 2 | 2014-04-17T10:11:53Z | 23,130,317 | 8 | 2014-04-17T10:12:41Z | [
"python"
] | I know there are many chunky ways to do this, but I am looking for a slick pythonic way to accomplish the following. Given a list of numbers:
```
a = [0,1,2,3,4,5,6,7,8,9]
```
split this list into 2 lists corresponding to every other element:
```
b = [0,2,4,6,8]
c = [1,3,5,7,9]
``` | You want:
```
b = a[::2] # Start at first element, then every other.
```
and:
```
c = a[1::2] # Start at second element, then every other.
```
So now we have what we want:
```
>>> print(b)
[0, 2, 4, 6, 8]
>>> print(c)
[1, 3, 5, 7, 9]
``` |
How to force scrapy to crawl duplicate url? | 23,131,283 | 6 | 2014-04-17T10:57:12Z | 23,131,785 | 14 | 2014-04-17T11:21:56Z | [
"python",
"web-crawler",
"scrapy"
] | I am learning [Scrapy](http://scrapy.org/) a web crawling framework.
by default it does not crawl duplicate urls or urls which scrapy have already crawled.
How to make Scrapy to crawl duplicate urls or urls which have already crawled?
I tried to find out on internet but could not find relevant help.
I found `DUPE... | You're probably looking for the `dont_filter=True` argument on `Request()`.
See <http://doc.scrapy.org/en/latest/topics/request-response.html#request-objects> |
Matplotlib: get and set axes position | 23,137,991 | 6 | 2014-04-17T15:59:19Z | 23,138,286 | 19 | 2014-04-17T16:12:02Z | [
"python",
"matplotlib",
"axes",
"subplot"
] | In matlab, it's straightforward to get and set the position of an existing axes on the figure:
```
pos = get(gca(), 'position')
set(gca(), 'position', pos)
```
How do I do this in Matplotlib?
I need this for two related reasons:
These are the specific problems I'm trying to solve:
* I have a column of subplots... | Setting axes position is similar in Matplotlib. You can use the get\_position and set\_position methods of the [axes.](http://matplotlib.org/api/axes_api.html)
```
import matplotlib.pyplot as plt
ax = plt.subplot(111)
pos1 = ax.get_position() # get the original position
pos2 = [pos1.x0 + 0.3, pos1.y0 + 0.3, pos1.wi... |
Pip regular expression search | 23,138,238 | 4 | 2014-04-17T16:09:53Z | 23,176,674 | 12 | 2014-04-19T23:17:42Z | [
"python",
"regex",
"pip",
"packages"
] | I need to find all packages on `PyPI` that match a particular regular expression:
```
^django-.*?admin.*$
```
Basically, the package name should start with `django-` and have `admin` word after. For example, the following packages should match:
```
django-redis-admin
django-admin-ckeditor
django-admintools-bootstra... | aleckxe, I believe this is the one-liner you are looking for.
```
pip search django | grep -P "^django-(?=[-\w]*?admin)[-\w]+"
```
As suggested by chromate in the comment below, you could easily pipe to sort for a sorted list if you wished.
```
pip search django | grep -P "^django-(?=[-\w]*?admin)[-\w]+" | sort
```
... |
How do I find out what key failed in Python KeyError? | 23,139,024 | 15 | 2014-04-17T16:51:53Z | 23,139,085 | 31 | 2014-04-17T16:55:32Z | [
"python",
"python-3.x"
] | If I catch a `KeyError`, how can I tell what lookup failed?
```
def POIJSON2XML (location_node, POI_JSON):
try:
man_JSON = POI_JSON["FastestMan"]
woman_JSON = POI_JSON["FastestWoman"]
except KeyError:
# How can I tell what key ("FastestMan" or "FastestWoman") caused the error?
LogErrorMessage ("PO... | Take the current exception (I used it `as e` in this case); then for a `KeyError` the first argument is the key that raised the exception. Therefore we can do:
```
except KeyError as e: # One would do it as 'KeyError, e:' in Python 2.
cause = e.args[0]
```
With that, you have the offending key stored in `cause`. |
Dates in the xaxis for a matplotlib plot with imshow | 23,139,595 | 4 | 2014-04-17T17:24:56Z | 23,142,190 | 8 | 2014-04-17T19:50:20Z | [
"python",
"datetime",
"matplotlib",
"plot",
"imshow"
] | So I am new to programming with matplotlib. I have created a color plot using imshow() and an array. At first the axis were just the row and column number of my array. I used extent = (xmin,xmax,ymin,ymax) to get the x-axis in unix time and altitude, respectively.
I want to change the x-axis from unix time (982376726,... | I have put together some example code which should help you with your problem.
The code first generates some randomised data using `numpy.random`. It then calculates your x-limits and y-limits where the x-limits will be based off of two unix timestamps given in your question and the y-limits are just generic numbers.
... |
Django Get All Users | 23,139,657 | 12 | 2014-04-17T17:28:01Z | 23,139,674 | 27 | 2014-04-17T17:28:55Z | [
"python",
"django"
] | I am just starting out with Django and I am messing around just trying to pull a full list of users from postgres.
I used the following code:
```
group = Group.objects.get(name="Admins")
usersList = group.user_set.all()
```
How could you pull all users? I don't want to have to pick or assign a group.
```
group = Gr... | ```
from django.contrib.auth.models import User
users = User.objects.all()
``` |
difference between plt.draw() and plt.show() in matplotlib | 23,141,452 | 9 | 2014-04-17T19:06:11Z | 23,141,491 | 15 | 2014-04-17T19:08:32Z | [
"python",
"matplotlib"
] | I was wondering why some people put a `plt.draw()` into their code before the `plt.show()`. For my code, the behavior of the `plt.draw()` didn't seem to change anything about the output. I did a search on the internet but couldn't find anything useful.
(assuming we imported `pyplot` as `from matplotlib import pyplot a... | [`plt.show()`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.show) will display the current figure that you are working on.
[`plt.draw()`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.draw) will re-draw the figure. This allows you to work in interactive mode and, should you have changed yo... |
python and pandas - how to access a column using iterrows | 23,145,928 | 9 | 2014-04-18T01:12:06Z | 23,146,038 | 20 | 2014-04-18T01:26:10Z | [
"python",
"pandas"
] | wowee.....how to use iterrows with python and pandas? If I do a row iteration should I not be able to access a col with row['COL\_NAME']?
Here are the col names:
```
print df
Int64Index: 152 entries, 0 to 151
Data columns:
Date 152 non-null values
Time 152 non-null values
Time Zone 152 non-nu... | `iterrows` gives you `(index, row)` tuples rather than just the rows, so you should be able to access the columns in basically the same way you were thinking if you just do:
```
for index, row in df.iterrows():
print row['Date']
``` |
iterrows pandas get next rows value | 23,151,246 | 12 | 2014-04-18T09:26:44Z | 23,151,722 | 7 | 2014-04-18T09:57:41Z | [
"python",
"pandas",
"next"
] | I have a df in pandas
```
import pandas as pd
df = pd.DataFrame(['AA', 'BB', 'CC'], columns = ['value'])
```
I want to iterate over rows in df. For each row i want row`s value and next row`s value
Something like(it does not work):
```
for i, row in df.iterrows():
print row['value']
i1, row1 = next(df.iterr... | Firstly, your "messy way" is ok, there's nothing wrong with using indices into the dataframe, and this will not be too slow. iterrows() itself isn't terribly fast.
A version of your first idea that would work would be:
```
row_iterator = df.iterrows()
_, last = row_iterator.next() # take first item from row_iterator... |
How to update sqlalchemy orm object by a python dict | 23,152,337 | 5 | 2014-04-18T10:34:54Z | 23,152,604 | 12 | 2014-04-18T10:51:59Z | [
"python",
"orm",
"sqlalchemy"
] | the dict's key names are mapping to the sqlalchemy object attrs
ex:
```
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
```
can update from id = 3, `{name: "diana"}` or id = 15, `{name: "ma... | You can use `setattr()` to update attributes on an existing SQLAlchemy object dynamically:
```
user = session.query(User).get(someid)
for key, value in yourdict.iteritems():
setattr(user, key, value)
``` |
How to make Scrapy show user agent per download request in log? | 23,152,739 | 4 | 2014-04-18T10:59:46Z | 23,219,821 | 10 | 2014-04-22T12:37:43Z | [
"python",
"web-scraping",
"scrapy",
"web-crawler",
"user-agent"
] | I am learning [Scrapy](http://scrapy.org/), a web crawling framework.
I know I can set `USER_AGENT` in `settings.py` file of the Scrapy project. When I run the Scrapy, I can see the `USER_AGENT`'s value in `INFO` logs.
This `USER_AGENT` gets set in every download request to the server I want to crawl.
But I am usin... | You can add logging to [solution](http://tangww.com/2013/06/UsingRandomAgent/) you're using:
```
#!/usr/bin/python
#-*-coding:utf-8-*-
import random
from scrapy import log
from scrapy.contrib.downloadermiddleware.useragent import UserAgentMiddleware
class RotateUserAgentMiddleware(UserAgentMiddleware):
def __ini... |
How to make Scrapy show user agent per download request in log? | 23,152,739 | 4 | 2014-04-18T10:59:46Z | 27,426,323 | 10 | 2014-12-11T15:24:28Z | [
"python",
"web-scraping",
"scrapy",
"web-crawler",
"user-agent"
] | I am learning [Scrapy](http://scrapy.org/), a web crawling framework.
I know I can set `USER_AGENT` in `settings.py` file of the Scrapy project. When I run the Scrapy, I can see the `USER_AGENT`'s value in `INFO` logs.
This `USER_AGENT` gets set in every download request to the server I want to crawl.
But I am usin... | Just FYI.
I've implemented a simple [`RandomUserAgentMiddleware` middleware](https://github.com/alecxe/scrapy-fake-useragent) based on [`fake-useragent`](https://pypi.python.org/pypi/fake-useragent).
Thanks to `fake-useragent`, you don't need to configure the list of User-Agents - it picks them up [based on browser u... |
Decrypting Chromium cookies | 23,153,159 | 9 | 2014-04-18T11:26:01Z | 23,727,331 | 11 | 2014-05-18T22:04:00Z | [
"python",
"c++",
"google-chrome",
"cookies",
"chromium"
] | I'm trying to use Chromium cookies in Python, because Chromium encrypts its cookies using AES (with CBC) I need to reverse this.
I can recover the AES key from OS X's Keychain (it's stored in Base 64):
```
security find-generic-password -w -a Chrome -s Chrome Safe Storage
# From Python:
python -c 'from subprocess imp... | You're on the right track! I've been working on this for a few days and finally figured it out. (Many thanks to the OP for the helpful links to the Chromium source.)
I've put up a [post](http://n8henrie.com/2014/05/decrypt-chrome-cookies-with-python/) with a little more detail and a working script, but here is the bas... |
Django: Generic detail view must be called with either an object pk or a slug | 23,154,525 | 8 | 2014-04-18T12:49:31Z | 23,155,078 | 15 | 2014-04-18T13:22:31Z | [
"python",
"django"
] | Getting this error when submitting the form associated with this view. Not sure what exactly is the problem, considering I have a form with a very similar structure and it works fine.
```
#views.py
class Facture_Creer(SuccessMessageMixin, CreateView):
model = Facture
template_name = "facturation/nouvelle_factu... | You need to pass an object identifier (pk or slug) so your views know which object they're operating on.
Just to take an example from your `urls.py`:
```
url(r'^facture/ajouter/$', Facture_Creer.as_view(), name='facture_creer'),
url(r'^facture/modifier/(?P<pk>\d+)/$', Facture_Update.as_view(), name='facture_update'),... |
How can I get all the plain text from a website with Scrapy? | 23,156,780 | 6 | 2014-04-18T15:03:05Z | 23,157,062 | 10 | 2014-04-18T15:18:56Z | [
"python",
"html",
"xpath",
"web-scraping",
"scrapy"
] | I would like to have all the text visible from a website, after the HTML is rendered. I'm working in Python with Scrapy framework.
With `xpath('//body//text()')` I'm able to get it, but with the HTML tags, and I only want the text. Any solution for this? Thanks ! | The easiest option would be to [`extract`](http://doc.scrapy.org/en/latest/topics/selectors.html#scrapy.selector.Selector.extract) `//body//text()` and [`join`](https://docs.python.org/2/library/string.html#string.join) everything found:
```
''.join(sel.select("//body//text()").extract()).strip()
```
where `sel` is a... |
Sort a Python date string list | 23,158,766 | 2 | 2014-04-18T17:09:48Z | 23,158,811 | 10 | 2014-04-18T17:12:35Z | [
"python",
"sorting",
"python-2.7"
] | I have a list:
```
a = ['7-Mar-14', '10-Mar-14', '11-Mar-14', '14-Mar-14', '15-Mar-14', '17-Mar-14', '22-Mar-14', '23-Mar-14', '25-Mar-14', '1-Nov-13', '5-Nov-13', '8-Nov-13', '23-Nov-13', '24-Nov-13', '25-Nov-13', '26-Nov-13', '3-Dec-13', '9-Dec-13', '13-Dec-13', '9-Jan-14', '17-Jan-14', '20-Jan-14', '8-Feb-14', '9-F... | You can use [`list.sort`](https://docs.python.org/2/howto/sorting.html#sortinghowto) and [`datetime.datetime.strptime`](https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime):
```
>>> from datetime import datetime
>>> a = ['7-Mar-14', '10-Mar-14', '11-Mar-14', '14-Mar-14', '15-Mar-14', '17-Mar-14'... |
How to get every single permutation of a string? | 23,159,200 | 4 | 2014-04-18T17:37:33Z | 23,159,276 | 8 | 2014-04-18T17:42:23Z | [
"python",
"string",
"algorithm",
"permutation"
] | I know how to get the permutations of just the plain string in python:
```
>>> from itertools import permutations
>>> perms = [''.join(p) for p in permutations('stack')]
>>> print perms
...
```
But how would I get the permutations of `'stac'`, `'stak'`, `'sack'`, `'stck'`, `'stc'`, `'st'`, and so forth? My desired ou... | This is one way of doing it with [itertools.permutations](https://docs.python.org/2.7/library/itertools.html#itertools.permutations):
```
from itertools import permutations
s = 'pet'
print [''.join(p) for i in range(1, len(s)+1) for p in permutations(s, i)]
```
Output:
```
['p', 'e', 't', 'pe', 'pt', 'ep', 'et', 'tp... |
Python argparse AssertionError | 23,159,845 | 9 | 2014-04-18T18:20:06Z | 23,159,976 | 7 | 2014-04-18T18:27:50Z | [
"python",
"argparse"
] | I just started using argparse module. I wrote the following reduced snippet to demonstrate an issue I'm having.
```
from argparse import ArgumentParser
if __name__ == '__main__':
parser = ArgumentParser('Test argparse. This string needs to be relatively long to trigger the issue.')
parser.add_argument('-f', '... | There is an extra space after `--out` in the code. Change:
```
parser.add_argument('-o', '--out ', help='b', required = True)
```
to:
```
parser.add_argument('-o', '--out', help='b', required = True)
```
The underlying cause of the problem is an `assert` check within the Python
code that only occurs when Python att... |
What happens if an object's __hash__ changes? | 23,161,035 | 23 | 2014-04-18T19:38:37Z | 23,161,141 | 15 | 2014-04-18T19:45:30Z | [
"python",
"hashcode"
] | In Python, I know that the value `__hash__` returns for a given object is supposed to be the same for the lifetime of that object. But, out of curiosity, what happens if it isn't? What sort of havoc would this cause?
```
class BadIdea(object):
def __hash__(self):
return random.randint(0, 10000)
```
I know `__co... | Your main problem would indeed be with dicts and sets. If you insert an object into a dict/set, and that object's hash changes, then when you try to retrieve that object you will end up looking in a *different* spot in the dict/set's underlying array and hence won't find the object. This is precisely why dict keys shou... |
What happens if an object's __hash__ changes? | 23,161,035 | 23 | 2014-04-18T19:38:37Z | 23,161,218 | 8 | 2014-04-18T19:50:04Z | [
"python",
"hashcode"
] | In Python, I know that the value `__hash__` returns for a given object is supposed to be the same for the lifetime of that object. But, out of curiosity, what happens if it isn't? What sort of havoc would this cause?
```
class BadIdea(object):
def __hash__(self):
return random.randint(0, 10000)
```
I know `__co... | There's a great post on Github about it: [What happens when you mess with hashing](https://github.com/sympy/sympy/wiki/What-happens-when-you-mess-with-hashing).
First, you need to know that Python expects (quoted from the article):
* The hash of an object does not change across the object's lifetime (in other words, a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.