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, get milliseconds since epoch, millisecond accuracy (not seconds*1000) | 18,169,099 | 17 | 2013-08-11T05:37:00Z | 18,170,448 | 16 | 2013-08-11T09:15:25Z | [
"python"
] | How can I get the number of milliseconds since epoch?
Note that I want the actual milliseconds, not seconds multiplied by 1000. I am comparing times for stuff that takes less than a second and need millisecond accuracy. (I have looked at lots of answers and they all seem to have a \*1000)
I am comparing a time that I... | I see many people suggesting `time.time()`. While `time.time()` is an accurate way of measuring the actual time of day, *it is not guaranteed to give you millisecond precision!* From the documentation:
> Note that even though the time is always returned as a floating point number, not all systems provide time with a b... |
UnicodeDecodeError when reading CSV file in Pandas with Python | 18,171,739 | 37 | 2013-08-11T12:06:25Z | 18,172,249 | 60 | 2013-08-11T13:10:22Z | [
"python",
"csv",
"pandas",
"unicode"
] | I'm running a program which is processing 30,000 similar files. A random number of them are stopping and producing this error...
```
File "C:\Importer\src\dfman\importer.py", line 26, in import_chr
data = pd.read_csv(filepath, names=fields)
File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 400... | `read_csv` takes an `encoding` option to deal with files in different formats. I mostly use `read_csv('file', encoding = "ISO-8859-1")`, or alternatively `encoding = utf8` for reading, and generally `utf-8` for `to_csv`.
You can also use the [alias](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) `'latin1'` instead of `... |
Scraping a JSON response with Scrapy | 18,171,835 | 9 | 2013-08-11T12:20:55Z | 18,172,776 | 22 | 2013-08-11T14:05:14Z | [
"python",
"json",
"web-scraping",
"scrapy"
] | How do you use Scrapy to scrape web requests that return JSON? For example, the JSON would look like this:
```
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
... | It's the same as using Scrapy's `HtmlXPathSelector` for html responses. The only difference is that you should use `json` module to parse the response:
```
class MySpider(BaseSpider):
...
def parse(self, response):
jsonresponse = json.loads(response.body_as_unicode())
item = MyItem()
... |
Efficient calculation of Fibonacci series | 18,172,257 | 15 | 2013-08-11T13:11:22Z | 18,172,463 | 40 | 2013-08-11T13:34:39Z | [
"python",
"performance",
"algorithm",
"fibonacci"
] | I'm working on a [Project Euler](https://projecteuler.net) problem: the one about the sum of the even Fibonacci numbers.
My code:
```
def Fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return Fibonacci(n-1) + Fibonacci(n-2)
list1 = [x for x in range(39)]
list2 = [i ... | Yes. The primitive recursive solution takes *a lot* of time. The reason for this is that for each number calculated, it needs to calculate all the previous numbers more than once. Take a look at the following image.

It represents calculati... |
Efficient calculation of Fibonacci series | 18,172,257 | 15 | 2013-08-11T13:11:22Z | 23,462,371 | 20 | 2014-05-04T22:39:01Z | [
"python",
"performance",
"algorithm",
"fibonacci"
] | I'm working on a [Project Euler](https://projecteuler.net) problem: the one about the sum of the even Fibonacci numbers.
My code:
```
def Fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return Fibonacci(n-1) + Fibonacci(n-2)
list1 = [x for x in range(39)]
list2 = [i ... | This is a very fast algorithm and it can find n-th Fibonacci number much faster than simple iterative approach presented in other answers, it is quite advanced though:
```
def fib(n):
v1, v2, v3 = 1, 1, 0 # initialise a matrix [[1,1],[1,0]]
for rec in bin(n)[3:]: # perform fast exponentiation of the matrix... |
Deleting DataFrame row in Pandas based on column value | 18,172,851 | 120 | 2013-08-11T14:14:57Z | 18,173,074 | 203 | 2013-08-11T14:38:31Z | [
"python",
"pandas"
] | I have the following DataFrame:
```
daysago line_race rating rw wrating
line_date
2007-03-31 62 11 56 1.000000 56.000000
2007-03-10 83 11 67 1.000000 67.000000
2007-02-10 111 9 66 1.0... | If I'm understanding correctly, it should be as simple as:
```
df = df[df.line_race != 0]
``` |
Deleting DataFrame row in Pandas based on column value | 18,172,851 | 120 | 2013-08-11T14:14:57Z | 18,173,088 | 23 | 2013-08-11T14:40:32Z | [
"python",
"pandas"
] | I have the following DataFrame:
```
daysago line_race rating rw wrating
line_date
2007-03-31 62 11 56 1.000000 56.000000
2007-03-10 83 11 67 1.000000 67.000000
2007-02-10 111 9 66 1.0... | The best way to do this is with boolean masking:
```
In [56]: df
Out[56]:
line_date daysago line_race rating raw wrating
0 2007-03-31 62 11 56 1.000 56.000
1 2007-03-10 83 11 67 1.000 67.000
2 2007-02-10 111 9 66 1.000 66.000
3 2007-... |
Deleting DataFrame row in Pandas based on column value | 18,172,851 | 120 | 2013-08-11T14:14:57Z | 24,489,602 | 56 | 2014-06-30T11:56:43Z | [
"python",
"pandas"
] | I have the following DataFrame:
```
daysago line_race rating rw wrating
line_date
2007-03-31 62 11 56 1.000000 56.000000
2007-03-10 83 11 67 1.000000 67.000000
2007-02-10 111 9 66 1.0... | But for any future bypassers you could mention that `df = df[df.line_race != 0]` doesn't do anything when trying to filter for `None`/missing values.
Does work:
```
df = df[df.line_race != 0]
```
Doesn't do anything:
```
df = df[df.line_race != None]
```
Does work:
```
df = df[df.line_race.notnull()]
``` |
XML Declaration standalone="yes" lxml | 18,173,983 | 5 | 2013-08-11T16:12:06Z | 18,174,094 | 9 | 2013-08-11T16:24:14Z | [
"python",
"xml",
"parsing",
"xml-parsing",
"lxml"
] | I have an xml I am parsing, making some changes and saving out to a new file. It has the declaration `<?xml version="1.0" encoding="utf-8" standalone="yes"?>` which I would like to keep. When I am saving out my new file I am loosing the `standalone="yes"` bit. How can I keep it in?
Here is my code:
```
templateXml = "... | You can pass `standalone` keyword argument to `tostring()`:
```
etree.tostring(tree, pretty_print = True, xml_declaration = True, encoding='UTF-8', standalone="yes")
``` |
'dict' object is not callable | 18,174,632 | 5 | 2013-08-11T17:23:08Z | 18,253,391 | 10 | 2013-08-15T13:13:16Z | [
"python",
"django",
"elasticsearch",
"django-haystack"
] | I use django and elasticseach inside for search engine,Everything worked out,but recently have this error
when i want change everything in database, for example when i wan't to create an new user from django admin have this error:
```
Environment:
Request Method: POST
Request URL: http://localhost:8000/admin/auth/us... | You are using an early release of the `requests` library. The API for the `.json` attribute changed; since at least 1.0 of the library it is now a function.
The `pyelastic` requires `requests` 1.0 or newer; upgrade the library. |
Python : Soap using requests | 18,175,489 | 24 | 2013-08-11T18:51:35Z | 26,506,633 | 39 | 2014-10-22T11:41:16Z | [
"python",
"soap",
"python-requests"
] | Is it possible to use pythons `requests` library to send SOAP request ?
Are there any examples follow that may help ?
I have not been able to successfully send SOAP request using `requests`.
Thanks | It is indeed possible.
Here is an example calling the Weather SOAP Service using plain requests lib:
```
import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
... |
Python Multiprocessing Process or Pool for what I am doing? | 18,176,178 | 17 | 2013-08-11T20:08:22Z | 18,176,257 | 18 | 2013-08-11T20:17:32Z | [
"python",
"multithreading",
"asynchronous",
"multiprocessing"
] | I'm new to multiprocessing in Python and trying to figure out if I should use Pool or Process for calling two functions async. The two functions I have make curl calls and parse the information into a 2 separate lists. Depending on the internet connection, each function could take about 4 seconds each. I realize that t... | The two scenarios you listed accomplish the same thing but in slightly different ways.
The first scenario starts two separate processes (call them P1 and P2) and starts P1 running `foo` and P2 running `bar`, and then waits until both processes have finished their respective tasks.
The second scenario starts two proce... |
Python Multiprocessing Process or Pool for what I am doing? | 18,176,178 | 17 | 2013-08-11T20:08:22Z | 18,176,299 | 7 | 2013-08-11T20:22:10Z | [
"python",
"multithreading",
"asynchronous",
"multiprocessing"
] | I'm new to multiprocessing in Python and trying to figure out if I should use Pool or Process for calling two functions async. The two functions I have make curl calls and parse the information into a 2 separate lists. Depending on the internet connection, each function could take about 4 seconds each. I realize that t... | Since you're fetching data from curl calls you are IO-bound. In such case [grequests](https://github.com/kennethreitz/grequests) might come in handy. These are really neither processes nor threads but coroutines - lightweight threads. This would allow you to send asynchronously HTTP requests, and then use `multiprocess... |
ImportError: No module named matplotlib.pyplot | 18,176,591 | 20 | 2013-08-11T20:54:59Z | 18,176,743 | 9 | 2013-08-11T21:13:50Z | [
"python",
"matplotlib"
] | I am currently practicing matplotlib. This is the first example I practice.
```
#!/usr/bin/python
import matplotlib.pyplot as plt
radius = [1.0, 2.0, 3.0, 4.0]
area = [3.14159, 12.56636, 28.27431, 50.26544]
plt.plot(radius, area)
plt.show()
```
When I run this script with `python ./plot_test.py`, it shows plot cor... | You have two pythons installed on your machine, one is the standard python that comes with Mac OSX and the second is the one you installed with ports (this is the one that has `matplotlib` installed in its library, the one that comes with macosx does not).
```
/usr/bin/python
```
Is the standard mac python and since ... |
ImportError: No module named matplotlib.pyplot | 18,176,591 | 20 | 2013-08-11T20:54:59Z | 29,335,193 | 17 | 2015-03-29T21:40:17Z | [
"python",
"matplotlib"
] | I am currently practicing matplotlib. This is the first example I practice.
```
#!/usr/bin/python
import matplotlib.pyplot as plt
radius = [1.0, 2.0, 3.0, 4.0]
area = [3.14159, 12.56636, 28.27431, 50.26544]
plt.plot(radius, area)
plt.show()
```
When I run this script with `python ./plot_test.py`, it shows plot cor... | `pip` will make your life easy!
Step 1: Install pip - Check if you have pip already simply by writing pip in the python console. If you don't have pip, get a python script called get-pip.py , via here: <https://pip.pypa.io/en/latest/installing.html> or directly here: <https://bootstrap.pypa.io/get-pip.py> (You may hav... |
How to get name of exception that was caught in Python? | 18,176,602 | 25 | 2013-08-11T20:56:51Z | 18,176,682 | 47 | 2013-08-11T21:06:46Z | [
"python",
"exception",
"exception-handling"
] | How can I get the name of an exception that was raised in Python?
e.g.,
```
try:
foo = bar
except Exception as exception:
name_of_exception = ???
assert name_of_exception == 'NameError'
print "Failed with exception [%s]" % name_of_exception
```
For example, I am catching multiple (or all) exceptions,... | Here are two different ways to get the name of the exception:
1. `type(exception).__name__`
2. `exception.__class__.__name__`
e.g.,
```
try:
foo = bar
except Exception as exception:
assert type(exception).__name__ == 'NameError'
assert exception.__class__.__name__ == 'NameError'
``` |
Create an empty data frame with index from another data frame | 18,176,933 | 6 | 2013-08-11T21:35:34Z | 18,176,957 | 7 | 2013-08-11T21:37:43Z | [
"python",
"indexing",
"pandas"
] | I've got a data frame **df1** with multiple columns and rows. Simple example:
```
TIME T1 T2
1 10 100
2 20 200
3 30 300
```
I'd like to create an empty data frame **df2** and later on, add new columns with the calculation results.
For this moment my code looks like this:
```
df1=pd.r... | ```
df2 = pd.DataFrame(index=df1.index)
```
This will create a DataFrame with no columns but just an index, and it will be the same index as in the df1. |
Assign a range to a variable (Python) | 18,177,919 | 3 | 2013-08-12T00:00:58Z | 18,177,933 | 8 | 2013-08-12T00:03:21Z | [
"python"
] | Whenever I try to assign a range to a variable like so:
```
Var1 = range(10, 50)
```
Then try to print the variable:
```
Var1 = range(10, 50)
print(Var1)
```
It simply prints 'range(10, 50)' instead of all the numbers in the list. Why is this? | Thats because `range` returns a range object in Python 3. Put it in `list` to make it do what you want:
```
>>> Var1 = range(10, 50)
>>> print(list(Var1))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
>... |
Can i add help text in django model fields | 18,178,310 | 4 | 2013-08-12T01:12:07Z | 18,185,109 | 11 | 2013-08-12T10:49:49Z | [
"python",
"django",
"django-models"
] | I have the Student detail page where have the all student data shown in log nested format.
Now in the form i know i can add the help text . But now the manager wants that when we show the detail page then there should be hover over help on each field.
Now i am confused where should i enter 50-100 words help text for ... | Yes you can! Just like your form, you can add `help_text` to your model fields. |
Perl equivalent idiom for Python's warnings module | 18,179,381 | 4 | 2013-08-12T04:02:17Z | 18,179,419 | 10 | 2013-08-12T04:08:45Z | [
"python",
"perl",
"warnings"
] | I need to port some code from Python to Perl. The Python code makes simple use of the [warnings](http://docs.python.org/2/library/warnings.html) module, e.g.
```
warnings.warn("Hey I'm a warning.")
```
I've been googling around quite a bit but it's unclear to me what the equivalent Perl idiom might be. How would a Pe... | To write a message to `STDERR`, simply use the built-in [`warn`](http://perldoc.perl.org/functions/warn.html) function.
```
warn "Hey I'm a warning.";
```
But you should *also* use Perl's [`warnings`](http://perldoc.perl.org/warnings.html) module, as well as [`strict`](http://perldoc.perl.org/strict.html) because the... |
New line in python print() function | 18,179,606 | 12 | 2013-08-12T04:37:34Z | 18,179,618 | 26 | 2013-08-12T04:39:16Z | [
"python",
"python-2.7",
"printing",
"newline"
] | I am using python 2.7.3, and I am a beginner, so please don't use complicated language.
I am trying to write a script which prints the hex byte values of any user-defined file. It is working properly with one problem: the values are being printed on a new line each. Below is my code, is it possible to print it with spa... | First of all `print` isn't a function in Python 2, it is a statement.
To suppress the automatic newline add a trailing `,`(comma). Now a space will be used instead of a newline.
Demo:
```
print 1,
print 2
```
**output:**
```
1 2
```
Or use Python 3's [`print()` function](http://docs.python.org/3.1/whatsnew/3.0.ht... |
New line in python print() function | 18,179,606 | 12 | 2013-08-12T04:37:34Z | 18,179,899 | 15 | 2013-08-12T05:11:41Z | [
"python",
"python-2.7",
"printing",
"newline"
] | I am using python 2.7.3, and I am a beginner, so please don't use complicated language.
I am trying to write a script which prints the hex byte values of any user-defined file. It is working properly with one problem: the values are being printed on a new line each. Below is my code, is it possible to print it with spa... | This does almost everything you want:
```
f = open('data.txt', 'rb')
while True:
char = f.read(1)
if not char: break
print "{:02x}".format(ord(char)),
```
With data.txt created like this:
```
f = open('data.txt', 'wb')
f.write("ab\r\ncd")
f.close()
```
I get the following output:
```
61 62 0d 0a 63 64... |
finding a set of ranges that a number fall in | 18,179,680 | 3 | 2013-08-12T04:47:05Z | 18,179,727 | 8 | 2013-08-12T04:51:24Z | [
"python",
"algorithm"
] | I have a 200k lines list of number ranges like start\_position,stop position.
The list includes all kinds of overlaps in addition to nonoverlapping ones.
the list looks like this
* [3,5]
* [10,30]
* [15,25]
* [5,15]
* [25,35]
* ...
I need to find the ranges that a given number fall in. And will repeat it for 100k nu... | It seems a range coverage problem. Since you have a large amount queries to process, you need to give the result as quickly as possible. There is an algorithm relating to this problem, you can take a look at the [Segment Tree](http://en.wikipedia.org/wiki/Segment_tree).
The idea is to build a Segment Tree first based ... |
Group dictionary key values in python | 18,180,145 | 7 | 2013-08-12T05:34:12Z | 18,180,813 | 11 | 2013-08-12T06:33:24Z | [
"python",
"python-2.7",
"dictionary"
] | I have the following dictionary
```
mylist = [{'tpdt': '0.00', 'tmst': 45.0, 'tmdt': 45.0, 'pbc': 30, 'remarks': False, 'shift': 1, 'ebct': '0.00', 'tmcdt': '0.00', 'mc_no': 'KA20'},
{'tpdt': '0.00', 'tmst': 45.0, 'tmdt': 45.0, 'pbc': 30, 'remarks': False, 'shift': 1, 'ebct': '0.00', 'tmcdt': '0.00', 'mc_no... | You can use `itertools.groupby`:
```
>>> for key, group in itertools.groupby(mylist, lambda item: item["mc_no"]):
... print key, sum([item["tmst"] for item in group])
...
KA20 90.0
KA23 110.0
```
Note that for `groupby` to work properly, `mylist` has to be sorted by the grouping key:
```
from operator import it... |
set difference for pandas | 18,180,763 | 8 | 2013-08-12T06:29:51Z | 18,184,990 | 13 | 2013-08-12T10:43:19Z | [
"python",
"pandas"
] | A simple pandas question:
Is there a `drop_duplicates()` functionality to drop every row involved in the duplication?
An equivalent question is the following: Does pandas have a set difference for dataframes?
For example:
```
In [5]: df1 = pd.DataFrame({'col1':[1,2,3], 'col2':[2,3,4]})
In [6]: df2 = pd.DataFrame({... | Bit convoluted but if you want to totally ignore the index data. Convert the contents of the dataframes to sets of tuples containing the columns:
```
ds1 = set([ tuple(line) for line in df1.values.tolist()])
ds2 = set([ tuple(line) for line in df2.values.tolist()])
```
This step will get rid of any duplicates in the ... |
set difference for pandas | 18,180,763 | 8 | 2013-08-12T06:29:51Z | 27,579,192 | 7 | 2014-12-20T10:15:25Z | [
"python",
"pandas"
] | A simple pandas question:
Is there a `drop_duplicates()` functionality to drop every row involved in the duplication?
An equivalent question is the following: Does pandas have a set difference for dataframes?
For example:
```
In [5]: df1 = pd.DataFrame({'col1':[1,2,3], 'col2':[2,3,4]})
In [6]: df2 = pd.DataFrame({... | ```
from pandas import DataFrame
df1 = DataFrame({'col1':[1,2,3], 'col2':[2,3,4]})
df2 = DataFrame({'col1':[4,2,5], 'col2':[6,3,5]})
print df2[~df2.isin(df1).all(1)]
print df2[(df2!=df1)].dropna(how='all')
print df2[~(df2==df1)].dropna(how='all')
``` |
What's the Pythonic way to write an auto-closing class? | 18,180,810 | 5 | 2013-08-12T06:33:09Z | 18,180,867 | 8 | 2013-08-12T06:36:57Z | [
"python"
] | I'm a noob with Python, but I've written an auto-close function like this..
```
@contextmanager
def AutoClose(obj):
try:
yield obj
finally:
obj.Close()
```
I have three classes that have a Close() method that this function can be used with. Is this the most Pythonic solution? Should I be doing... | What you're doing looks totally fine and Pythonic. Although, the `contextlib` standard library already has something similar, but you'll have to rename your `Close` methods to `close`.
```
import contextlib
with contextlib.closing(thing):
print thing
```
I would recommend using this instead. After all, the recomm... |
What's the Pythonic way to write an auto-closing class? | 18,180,810 | 5 | 2013-08-12T06:33:09Z | 18,181,067 | 9 | 2013-08-12T06:51:56Z | [
"python"
] | I'm a noob with Python, but I've written an auto-close function like this..
```
@contextmanager
def AutoClose(obj):
try:
yield obj
finally:
obj.Close()
```
I have three classes that have a Close() method that this function can be used with. Is this the most Pythonic solution? Should I be doing... | Most pythonic solution is to define methods [`__enter__` and `__exit__`](http://docs.python.org/2/reference/datamodel.html#with-statement-context-managers) methods in your class:
```
class Foo(object):
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.fd = op... |
Does pytest parametrized test work with unittest class based tests? | 18,182,251 | 14 | 2013-08-12T08:14:29Z | 18,187,731 | 16 | 2013-08-12T13:04:03Z | [
"python",
"unit-testing",
"py.test"
] | I've been trying to add parametrized `@pytest.mark.parametrize` tests to a class based unittest.
```
class SomethingTests(unittest.TestCase):
@pytest.mark.parametrize(('one', 'two'), [
(1, 2), (2, 3)])
def test_default_values(self, one, two):
assert one == (two + 1)
```
But the parametrized st... | According to [pytest documentation](http://pytest.org/latest/unittest.html):
> *unittest.TestCase* methods cannot directly receive fixture function
> arguments as implementing that is likely to inflict on the ability to
> run general *unittest.TestCase* test suites. |
Django FBV's "render_to_response" equivalent in Class-Based-View? | 18,185,824 | 2 | 2013-08-12T11:27:45Z | 18,186,090 | 8 | 2013-08-12T11:42:42Z | [
"python",
"django",
"django-class-based-views"
] | I am now in the process of converting all my Django Function-based-views in to Class-based-views...
So this is my original code:
**views.py**
```
def search(request):
if 'q' in request.GET:
q = request.GET['q']
if q:
result = Post.objects.filter(title__icontains=q)
varia... | ```
class PostSearch(TemplateView):
template_name = 'search.html'
def get_context_data(self, **kwargs):
context = super(PostSearch, self).get_context_data(**kwargs)
q = self.request.GET.get('q')
if q:
context['result'] = Post.objects.filter(title__icontains=q)
return... |
Why would running scheduled tasks with Celery be preferable over crontab? | 18,187,751 | 26 | 2013-08-12T13:05:09Z | 18,190,019 | 25 | 2013-08-12T14:45:03Z | [
"python",
"django",
"celery",
"django-celery"
] | Considering Celery is already a part of the stack to run task queues (i.e. it is not being added just for running crons, that seems an overkill IMHO ).
How can its "periodic tasks" feature be beneficial as a replacement for crontab ?
Specifically looking for following points.
* Major pros/cons over crontab
* Use case... | I've been using cron for a production website, and have switched to celery on a current project.
I'm far more into celery than cron, here is why:
* Celery + Celerybeat has finer granularity than cron. Cron cannot run more than once a minute, while celery can (I have a task run every 90 seconds which checks an email qu... |
Is the Session object from Python's Requests library thread safe? | 18,188,044 | 22 | 2013-08-12T13:19:02Z | 20,457,621 | 11 | 2013-12-08T19:04:50Z | [
"python",
"thread-safety",
"connection-pooling",
"python-requests"
] | Python's popular [Requests](http://docs.python-requests.org/en/latest/) library is said to be thread-safe on its home page, but no further details are given. If I call `requests.session()`, can I then safely pass this object to multiple threads like so:
```
session = requests.session()
for i in xrange(thread_count):
... | After reviewing the source of [`requests.session`](https://github.com/kennethreitz/requests/blob/master/requests/sessions.py), I'm going to say the session object might be thread-safe, depending on the implementation of CookieJar being used.
`Session.prepare_request` reads from `self.cookies`, and `Session.send` calls... |
How to re-raise an exception in nested try/except blocks? | 18,188,563 | 16 | 2013-08-12T13:42:39Z | 18,188,660 | 28 | 2013-08-12T13:47:35Z | [
"python",
"exception",
"nested",
"raise"
] | I know that if I want to re-raise an exception, I simple use `raise` without arguments in the respective `except` block. But given a nested expression like
```
try:
something()
except SomeError as e:
try:
plan_B()
except AlsoFailsError:
raise e # I'd like to raise the SomeError as if plan_... | You can store the exception type, value, and traceback in local variables and use the [three-argument form of `raise`](http://docs.python.org/2.7/reference/simple_stmts.html#the-raise-statement):
```
try:
something()
except SomeError:
t, v, tb = sys.exc_info()
try:
plan_B()
except AlsoFailsErro... |
Using python's mock patch.object to change the return value of a method called within another method | 18,191,275 | 16 | 2013-08-12T15:46:28Z | 18,393,879 | 20 | 2013-08-23T02:49:29Z | [
"python",
"unit-testing",
"mocking",
"patch"
] | Is it possible to mock a return value of a function called within another function I am trying to test? I would like the mocked method (which will be called in many methods I'm testing) to returned my specified variables each time it is called. For example:
```
class Foo:
def method_1():
results = uses_some... | There are two ways you can do this; with patch and with patch.object
Patch assumes that you are not directly importing the object but that it is being used by the object you are testing as in the following
```
#foo.py
def some_fn():
return 'some_fn'
class Foo(object):
def method_1(self):
return some_... |
matplotlib contour plot: proportional colorbar levels in logarithmic scale | 18,191,867 | 9 | 2013-08-12T16:16:58Z | 18,199,714 | 11 | 2013-08-13T02:29:49Z | [
"python",
"numpy",
"matplotlib",
"contour",
"colorbar"
] | Would it be possible to have levels of the colorbar in log scale like in the image below?

Here is some sample code where it could be implemented:
```
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm
delta = 0.... | I propose to generate a pseudo colorbar as follows (see comments for explanations):
```
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm
import matplotlib.gridspec as gridspec
delta = 0.025
x = y = np.arange(0, 3.01, delta)
X, Y = np.meshgrid(x, y)
Z1 = plt.mlab.bivariate_norm... |
Python unicode equal comparison failed | 18,193,305 | 27 | 2013-08-12T17:43:42Z | 18,194,343 | 36 | 2013-08-12T18:43:25Z | [
"python",
"unicode"
] | This question is linked to [Searching for Unicode characters in Python](http://stackoverflow.com/questions/18043041/searching-for-unicode-characters-in-python/18043155)
I read unicode text file using python codecs
```
codecs.open('story.txt', 'rb', 'utf-8-sig')
```
And was trying to search strings in it. But i'm get... | You may use the `==` operator to compare unicode objects for equality.
```
>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>>
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>>
```
But, your error message indicates... |
Default buffer size for a file | 18,194,374 | 10 | 2013-08-12T18:44:43Z | 18,194,856 | 15 | 2013-08-12T19:12:35Z | [
"python",
"file",
"rhel6"
] | The [documentation](http://docs.python.org/2/library/functions.html#open) states that the default value for buffering is: `If omitted, the system default is used`. I am currently on Red Hat Linux 6, but I am not able to figure out the default buffering that is set for the system.
Can anyone please guide me as to how d... | Since you linked to the 2.7 docs, I'm assuming you're using 2.7. (In Python 3.x, this all gets a lot simpler, because a lot more of the buffering is exposed at the Python level.)
All `open` actually does (on POSIX systems) is call `fopen`, and then, if you've passed anything for `buffering`, `setvbuf`. Since you're no... |
How do I sum tuples in a list where the first value is the same? | 18,194,712 | 3 | 2013-08-12T19:04:08Z | 18,194,750 | 11 | 2013-08-12T19:06:45Z | [
"python"
] | I have a list of stocks and positions as tuples. Positive for buy, negative for sell. Example:
`p = [('AAPL', 50), ('AAPL', -50), ('RY', 100), ('RY', -43)]`
How can I sum the positions of stocks, to get the current holdings?
`Result = [(AAPL, 0), (RY, 57)]` | How about this? You can read about [`collections.defaultdict`](http://docs.python.org/2/library/collections.html#collections.defaultdict).
```
>>> from collections import defaultdict
>>> testDict = defaultdict(int)
>>> p = [('AAPL', 50), ('AAPL', -50), ('RY', 100), ('RY', -43)]
>>> for key, val in p:
testDict[... |
Python's Logical Operator AND | 18,195,322 | 9 | 2013-08-12T19:38:41Z | 18,195,382 | 16 | 2013-08-12T19:42:14Z | [
"python",
"operator-keyword"
] | I'm a little confused with the results I'm getting with the logical operators in Python. I'm a beginner and studying with the use of a few books, but they don't explain in as much detail as I'd like.
here is my own code:
```
five = 5
two = 2
print five and two
>> 2
```
It seems to be just outputting the two variab... | Python Boolean operators return the last value evaluated, not True/False. The [docs](http://docs.python.org/2/reference/expressions.html#boolean-operations) have a good explanation of this:
> The expression `x and y` first evaluates `x`; if `x` is `false`, its value is returned; otherwise, `y` is evaluated and the res... |
Why a calling function in python contains variable equal to value? | 18,195,391 | 3 | 2013-08-12T19:42:43Z | 18,195,474 | 11 | 2013-08-12T19:47:30Z | [
"python"
] | I have started to learn python, and I would like to ask you about something which I considered a little magic in this language.
I would like to note that before learning python I worked with PHP and there I haven't noticed that.
What's going on - I have noticed that some call constructors or methods in Python are in ... | These are called [keyword arguments](http://docs.python.org/2/tutorial/controlflow.html#keyword-arguments), and they're usually used to make the call more readable.
They can also be used to pass the arguments in a different order from the declared parameters, or to skip over some default parameters but pass arguments ... |
Set Matplotlib colorbar size to match graph | 18,195,758 | 33 | 2013-08-12T20:06:52Z | 18,195,921 | 52 | 2013-08-12T20:15:55Z | [
"python",
"image",
"matplotlib"
] | I cannot get the colorbar on imshow graphs like this one to be the same height as the graph, short of using Photoshop after the fact. How do I get the heights to match? | You can do this easily with a matplotlib [AxisDivider](http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html#axesdivider).
The example from the linked page also works without using subplots:
```
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
plt.... |
Set Matplotlib colorbar size to match graph | 18,195,758 | 33 | 2013-08-12T20:06:52Z | 26,720,422 | 38 | 2014-11-03T18:18:07Z | [
"python",
"image",
"matplotlib"
] | I cannot get the colorbar on imshow graphs like this one to be the same height as the graph, short of using Photoshop after the fact. How do I get the heights to match? | This combination (and values near to these) seems to "magically" work for me to keep the colorbar scaled to the plot, no matter what size the display.
```
plt.colorbar(im,fraction=0.046, pad=0.04)
```
It also does not require sharing the axis which can get the plot out of square. |
How to conditionally update DataFrame column in Pandas | 18,196,203 | 13 | 2013-08-12T20:35:01Z | 18,196,299 | 25 | 2013-08-12T20:40:21Z | [
"python",
"pandas"
] | With this DataFrame, how can I conditionally set `rating` to 0 when `line_race` is equal to zero?
```
line_track line_race rating foreign
25 MTH 10 84 False
26 MTH 6 88 False
27 TAM 5 87 False
28 GP 2 86 False
29 ... | ```
df.loc[df['line_race'] == 0, 'rating'] = 0
``` |
How can I show a PyQt modal dialog and get data out of its controls once its closed? | 18,196,799 | 8 | 2013-08-12T21:12:57Z | 18,202,709 | 14 | 2013-08-13T07:06:18Z | [
"python",
"qt",
"dialog",
"pyqt",
"modal-dialog"
] | For a built-in dialog like QInputDialog, I've read that I can do this:
```
text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog', 'Enter your name:')
```
How can I emulate this behavior using a dialog that I design myself in Qt Designer? For instance, I would like to do:
```
my_date, my_time, ok = MyCustomDateT... | Here is simple class you can use to prompt for date:
```
class DateDialog(QDialog):
def __init__(self, parent = None):
super(DateDialog, self).__init__(parent)
layout = QVBoxLayout(self)
# nice widget for editing the date
self.datetime = QDateTimeEdit(self)
self.datetime.s... |
How can I show a PyQt modal dialog and get data out of its controls once its closed? | 18,196,799 | 8 | 2013-08-12T21:12:57Z | 25,892,137 | 16 | 2014-09-17T13:35:57Z | [
"python",
"qt",
"dialog",
"pyqt",
"modal-dialog"
] | For a built-in dialog like QInputDialog, I've read that I can do this:
```
text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog', 'Enter your name:')
```
How can I emulate this behavior using a dialog that I design myself in Qt Designer? For instance, I would like to do:
```
my_date, my_time, ok = MyCustomDateT... | I tried to edit the answer of [hluk](https://stackoverflow.com/users/454171/hluk) with the changes below but it got rejected, not sure why because it got some clear bugs as far is I can see.
bugfix 1: removed *self.* from *self.layout.addWidget(self.buttons)*
bugfix 2: connected OK and Cancel buttons to its correct a... |
Cumsum reset at NaN | 18,196,811 | 5 | 2013-08-12T21:14:20Z | 18,197,296 | 8 | 2013-08-12T21:54:33Z | [
"python",
"numpy",
"pandas",
"cumsum"
] | If I have a `pandas.core.series.Series` named `ts` of either 1's or NaN's like this:
```
3382 NaN
3381 NaN
...
3369 NaN
3368 NaN
...
15 1
10 NaN
11 1
12 1
13 1
9 NaN
8 NaN
7 NaN
6 NaN
3 NaN
4 1
5 1
2 NaN
1 NaN
0 NaN
```
I would like to calculate cumsum of th... | Here's a slightly more pandas-onic way to do it:
```
v = Series([1, 1, 1, nan, 1, 1, 1, 1, nan, 1], dtype=float)
n = v.isnull()
a = ~n
c = a.cumsum()
index = c[n].index # need the index for reconstruction after the np.diff
d = Series(np.diff(np.hstack(([0.], c[n]))), index=index)
v[n] = -d
result = v.cumsum()
```
No... |
python dict, find value closest to x | 18,197,359 | 6 | 2013-08-12T21:59:18Z | 18,197,419 | 8 | 2013-08-12T22:03:46Z | [
"python",
"python-3.x"
] | say I have a dict like this :
```
d = {'a': 8.25, 'c': 2.87, 'b': 1.28, 'e': 12.49}
```
and I have a value
```
v = 3.19
```
I want to say something like :
```
x = "the key with the value CLOSEST to v"
```
Which would result in
```
x = 'c'
```
Any hints on how to approach this? | Use [`min(iter, key=...)`](http://docs.python.org/2/library/functions.html#min)
```
target = 3.19
key, value = min(dict.items(), key=lambda (_, v): abs(v - target))
``` |
Have bash script execute multiple programs as separate processes | 18,197,395 | 3 | 2013-08-12T22:01:49Z | 18,197,431 | 8 | 2013-08-12T22:04:53Z | [
"python",
"linux",
"bash",
"scripting"
] | As the title suggests how do I write a bash script that will execute for example 3 different Python programs as separate processes? And then am I able to gain access to each of these processes to see what is being logged onto the terminal?
Edit: Thanks again. I forgot to mention that I'm aware of appending `&` but I'm... | You can run a job in the background like this:
```
command &
```
This allows you to start multiple jobs in a row without having to wait for the previous one to finish.
If you start multiple background jobs like this, they will all share the same `stdout` (and `stderr`), which means their output is likely to get inte... |
Postgresql: "database does not exist" | 18,197,941 | 2 | 2013-08-12T22:49:32Z | 18,198,979 | 7 | 2013-08-13T00:49:54Z | [
"python",
"django",
"postgresql"
] | Following the postgresql installation instructions for Mac, I recently created a db and launched the server. Everything looks like it's working fine.
```
/opt/local/lib/postgresql93/bin/postgres -D /opt/local/var/db/postgresql93/defaultdb
LOG: database system was shut down at 2013-08-12 15:36:09 PDT
LOG: database sy... | `initdb` creates a **cluster** that is a global data directory (the path after the `-D`). This data directory is a container for a collection of databases plus the information shared across the databases (like the table of users or the database journal files).
There is only one cluster per PostgreSQL installation but a... |
Getting the integer index of a Pandas DataFrame row fulfilling a condition? | 18,199,288 | 10 | 2013-08-13T01:31:08Z | 18,199,337 | 13 | 2013-08-13T01:38:30Z | [
"python",
"numpy",
"pandas"
] | I have the following DataFrame:
```
a b c
b
2 1 2 3
5 4 5 6
```
As you can see, column `b` is used as an index. I want to get the ordinal number of the row fulfilling `('b' == 5)`, which in this case would be `1`.
The column being tested can be either an index column (as with `b` in this case) or a regula... | You could use [np.where](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html#numpy-where) like this:
```
import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(1,7).reshape(2,3),
columns = list('abc'),
index=pd.Series([2,5], name='b'))
print(df)
# a ... |
Getting the integer index of a Pandas DataFrame row fulfilling a condition? | 18,199,288 | 10 | 2013-08-13T01:31:08Z | 35,138,807 | 9 | 2016-02-01T19:35:48Z | [
"python",
"numpy",
"pandas"
] | I have the following DataFrame:
```
a b c
b
2 1 2 3
5 4 5 6
```
As you can see, column `b` is used as an index. I want to get the ordinal number of the row fulfilling `('b' == 5)`, which in this case would be `1`.
The column being tested can be either an index column (as with `b` in this case) or a regula... | Use [Index.get\_loc](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_loc.html) instead.
Reusing @unutbu's set up code, you'll achieve the same results.
```
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame(np.arange(1,7).reshape(2,3),
columns = list('abc')... |
error: could not create '/Library/Python/2.7/site-packages/xlrd': Permission denied | 18,199,853 | 24 | 2013-08-13T02:47:39Z | 23,789,994 | 83 | 2014-05-21T17:22:28Z | [
"python",
"installation",
"xlrd"
] | I'm trying to install xlrd on mac 10.8.4 to be able to read excel files through python.
I have followed the instructions on <http://www.simplistix.co.uk/presentations/python-excel.pdf>
I did this:
1. unzipped the folder to desktop
2. in terminal, cd to the unzipped folder
3. $ python setup.py install
This is what I... | Try `python setup.py install --user`
Don't use `sudo` as suggested above, as
1. You're allowing arbitrary untrusted code off the internet to be run as root,
2. Passing the --user flag to install will install it to a user owned directory. Your normal non-root user won't be able to acess the files installed by `sudo pi... |
How to convert ndarray to array? | 18,200,052 | 6 | 2013-08-13T03:08:47Z | 18,200,108 | 11 | 2013-08-13T03:17:12Z | [
"python",
"numpy",
"multidimensional-array"
] | I'm using pandas.Series and np.ndarray.
The code is like this
```
>>> t
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
>>> pandas.Series(t)
Exception: Data must be 1-dimensional
>>>
```
And I trie to convert it into 1-dimensional array:
```
>>> tt = t.reshape((1,-1))
>>> tt
array([[ 0., 0... | An alternative is to use [np.ravel](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html):
```
>>> np.zeros((3,3)).ravel()
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0.])
```
The importance of `ravel` over `flatten` is `ravel` only copies data if necessary and usually returns a view, while `flatt... |
get the last sunday and saturday's date in python | 18,200,530 | 2 | 2013-08-13T04:11:00Z | 18,200,686 | 9 | 2013-08-13T04:26:46Z | [
"python",
"date",
"datetime"
] | Looking to leverage `datetime` to get the date of beginning and end of the previous week, sunday to saturday.
So, if it's 8/12/13 today, I want to define a function that prints:
`Last Sunday was 8/4/2013 and last Saturday was 8/10/2013`
How do I go about writing this?
EDIT: okay, so there seems to be some question ... | [datetime.date.weekday](http://docs.python.org/2/library/datetime.html#datetime.date.weekday) returns `0` for Monday. You need to adjust that.
Try following:
```
>>> import datetime
>>> today = datetime.date.today()
>>> today
datetime.date(2013, 8, 13)
>>> idx = (today.weekday() + 1) % 7 # MON = 0, SUN = 6 -> SUN = 0... |
Sending multiple values for one name urllib2 | 18,201,752 | 4 | 2013-08-13T06:02:28Z | 18,201,922 | 7 | 2013-08-13T06:15:31Z | [
"python",
"html",
"request",
"urllib2"
] | im trying so submit a webpage that has checkboxes and i need up to 10 of these checkboxes checked
the problem is when i try to assign them to one name in a dict it only assigns the last one not all 10
so how can i do this here is the request code:
```
forms = {"_ref_ck": ref,
"type": "create",
"sel... | The problem has nothing to do with `urlencode`; it's that a Python dict can't hold multiple values for the same key. You can see this by `print`ing out `forms` before you send itâthere's only one value there for `selected_items[]`. That one value gets encoded just fine.
As [the documentation](http://docs.python.org/... |
Django : Can we use .exclude() on .get() in django querysets | 18,202,440 | 6 | 2013-08-13T06:49:52Z | 18,202,741 | 12 | 2013-08-13T07:07:54Z | [
"python",
"django",
"django-models"
] | Can we use
```
MyClass.objects.get(description='hi').exclude(status='unknown')
``` | Your code works as expected if you do the `exclude()` before the `get()`:
```
MyClass.objects.exclude(status='unknown').get(description='hi')
```
As @Burhan Khalid points out, the call to `.get` will only succeed if the resulting query returns exactly one row.
You could also use the [`Q` object](https://docs.djangop... |
RuntimeError on windows trying python multiprocessing | 18,204,782 | 19 | 2013-08-13T08:59:14Z | 18,205,006 | 26 | 2013-08-13T09:10:38Z | [
"python",
"windows",
"multiprocessing"
] | I am trying my very first formal python program using Threading and Multiprocessing on a windows machine. I am unable to launch the processes though, with python giving the following message. The thing is, I am not launching my threads in the **main** module. The threads are handled in a separate module inside a class.... | On Windows the subprocesses will import (i.e. execute) the main module at start. You need to protect the main code like this to avoid creating subprocesses recursively:
```
import parallelTestModule
if __name__ == '__main__':
extractor = parallelTestModule.ParallelExtractor()
extractor.runInParallel(numPr... |
How to check a remote path is a file or a directory? | 18,205,731 | 4 | 2013-08-13T09:44:41Z | 18,205,869 | 13 | 2013-08-13T09:50:03Z | [
"python",
"paramiko"
] | i am using `SFTPClient` to download files from the remote server. But i cann't to know the remote path is a file or a directoty. if the remote path is a directory i need to handle this directory recursive.
this is my code:
```
def downLoadFile(sftp, remotePath, localPath):
for file in sftp.listdir(remotePath):
... | `os.path.isfile()` and `os.path.isdir()` only work on **local** filenames.
I'd use the `sftp.listdir_attr()` function instead and load full `SFTPAttributes` objects, and inspect their `st_mode` attribute with the `stat` module utility functions:
```
import stat
def downLoadFile(sftp, remotePath, localPath):
for ... |
OpenCV Python: Draw minAreaRect ( RotatedRect not implemented) | 18,207,181 | 13 | 2013-08-13T10:52:21Z | 18,208,020 | 22 | 2013-08-13T11:35:25Z | [
"python",
"opencv"
] | Are there any helper methods to draw a rotated rectangle that is returned by [cv2.minAreaRect()](http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=minarearect#cv2.minAreaRect) presumably as `((x1,y1),(x2,y2),angle)`? [cv2.rectangle()](http://docs.opencv.org/modules/core... | Haha, I just had the same question and found the following
<http://opencvpython.blogspot.in/2012/06/contours-2-brotherhood.html>
[Python OpenCV Box2D](http://stackoverflow.com/questions/11779100/python-opencv-box2d)
```
rect = cv2.minAreaRect(cnt)
box = cv2.cv.BoxPoints(rect)
box = np.int0(box)
cv2.drawContours(im,[... |
Python Requests - Post a zip file with multipart/form-data | 18,208,109 | 3 | 2013-08-13T11:39:13Z | 18,208,225 | 8 | 2013-08-13T11:44:03Z | [
"python",
"post",
"python-requests"
] | I'm playing around with the Python Requests module that has so far been a delight.
However, I've run into an issue whilst attempting to post a zip file using multipart/form-data.
I'm using Digest authentication and have been able to successfully post other file types e.g. .xls etc.
I'm creating a post request using:... | As far as `requests` is concerned, there is **no difference** between a zip file and any other binary blob of data.
Your *server* is broken here; it is cutting of the connection when you send it a zip file. That is not something `requests` can do anything about.
You may want to test against `http://httpbin.org/` when... |
Overriding and customizing "django.contrib.auth.views.login" | 18,208,346 | 3 | 2013-08-13T11:49:50Z | 18,208,495 | 8 | 2013-08-13T11:56:46Z | [
"python",
"django"
] | I'm trying to add a "keep me logged in" check box to Django's default login view.
Here is what I'm doing:
**urls.py**
```
url(r'^login/$',
myuser_login,
{'template_name': 'app_registration/login.html', 'authentication_form': MyAuthenticationForm},
name='auth_login',
),
```
**views.py**
```
from django.... | All django views must return `HttpResponse`. Your view isn't returning anything.
You should return like this
```
def myuser_login(request, *args, **kwargs):
if request.method == 'POST':
if not request.POST.get('remember', None):
request.session.set_expiry(0)
return login(request, *args, *... |
Flask view return error "View function did not return a response" | 18,211,942 | 5 | 2013-08-13T14:32:49Z | 18,211,982 | 13 | 2013-08-13T14:34:26Z | [
"python",
"flask"
] | I have a view that calls a function to get the response. However, it gives the error `View function did not return a response`. How do I fix this?
```
from flask import Flask
app = Flask(__name__)
def hello_world():
return 'test'
@app.route('/hello', methods=['GET', 'POST'])
def hello():
hello_world()
if __... | The following does not return a response:
```
@app.route('/hello', methods=['GET', 'POST'])
def hello():
hello_world()
```
You mean to say...
```
@app.route('/hello', methods=['GET', 'POST'])
def hello():
return hello_world()
```
Note the addition of `return` in this fixed function. |
Using mock to patch a celery task in Django unit tests | 18,212,131 | 14 | 2013-08-13T14:40:59Z | 19,867,636 | 13 | 2013-11-08T20:04:30Z | [
"python",
"django",
"unit-testing",
"mocking",
"celery"
] | I'm trying to use the python mock library to patch a Celery task that is run when a model is saved in my django app, to see that it's being called correctly.
Basically, the task is defined inside `myapp.tasks`, and is imported at the top of my models.py-file like so:
`from .tasks import mytask`
...and then runs on `... | The issue that you are having is unrelated to the fact that this is a Celery task. You just happen to be patching the wrong thing. ;)
Specifically, you need to find out which view or other file is importing "mytask" and patch it over there, so the relevant line would look like this:
```
with patch('myapp.myview.mytas... |
Using mock to patch a celery task in Django unit tests | 18,212,131 | 14 | 2013-08-13T14:40:59Z | 29,269,211 | 14 | 2015-03-26T00:46:45Z | [
"python",
"django",
"unit-testing",
"mocking",
"celery"
] | I'm trying to use the python mock library to patch a Celery task that is run when a model is saved in my django app, to see that it's being called correctly.
Basically, the task is defined inside `myapp.tasks`, and is imported at the top of my models.py-file like so:
`from .tasks import mytask`
...and then runs on `... | The `@task` decorator replaces the function with a `Task` object (see [documentation](http://celery.readthedocs.org/en/latest/_modules/celery/app/task.html)). If you mock the task itself you'll replace the (somewhat magic) `Task` object with a `MagicMock` and it won't schedule the task at all. Instead mock the `Task` o... |
How to identify a generator vs list comprehension | 18,212,160 | 6 | 2013-08-13T14:42:01Z | 18,212,201 | 9 | 2013-08-13T14:43:38Z | [
"python",
"list-comprehension",
"generator-expression"
] | I have this:
```
>>> sum( i*i for i in xrange(5))
```
My question is, in this case **am I passing a list comprehension or a generator object** to sum ? How do I tell that? Is there a general rule around this?
Also remember **sum by itself needs a pair of parentheses to surround its arguments. I'd think that the pare... | You are passing in a [generator expression](http://docs.python.org/2/reference/expressions.html#generator-expressions).
A [list comprehension is specified with square brackets](http://docs.python.org/2/reference/expressions.html#list-displays) (`[...]`). A list comprehension builds a *list object* first, so it uses sy... |
How do populate a Tkinter optionMenu with items in a list | 18,212,645 | 4 | 2013-08-13T15:02:56Z | 18,213,202 | 9 | 2013-08-13T15:27:38Z | [
"python",
"list",
"tkinter",
"optionmenu"
] | "I want to populate option menus in Tkinter with items from various lists, how do i do that? In the code below it treats the entire list as one item in the menu. I tried to use a for statement to loop through the list but it only gave me the value 'a' several times.
```
from Tkinter import *
def print_it(event):
pr... | `lst` in your code is a list with a single string.
Use a list with multiple menu names, and specify them as follow:
```
....
lst = ["a","b","c","d","e","f"]
OptionMenu(root, var, *lst, command=print_it).pack()
....
``` |
How to fill rainbow color under a curve in Python matplotlib | 18,215,276 | 6 | 2013-08-13T17:13:48Z | 18,215,927 | 9 | 2013-08-13T17:53:00Z | [
"python",
"matplotlib"
] | I want to fill rainbow color under a curve. Actually the function matplotlib.pyplot.fill\_between can fill area under a curve with a single color.
```
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 100, 50)
y = -(x-50)**2 + 2500
plt.plot(x,y)
plt.fill_between(x,y, color='green')
plt.show()
```
... | This is pretty easy to hack if you want "fill" with a series of rectangles:
```
import numpy as np
import pylab as plt
def rect(x,y,w,h,c):
ax = plt.gca()
polygon = plt.Rectangle((x,y),w,h,color=c)
ax.add_patch(polygon)
def rainbow_fill(X,Y, cmap=plt.get_cmap("jet")):
plt.plot(X,Y,lw=0) # Plot so th... |
extracting days from a numpy.timedelta64 value | 18,215,317 | 24 | 2013-08-13T17:17:13Z | 18,215,499 | 49 | 2013-08-13T17:28:41Z | [
"python",
"numpy",
"pandas"
] | I am using pandas/python and I have two date time series s1 and s2, that have been generated using the 'to\_datetime' function on a field of the df containing dates/times.
When I subtract s1 from s2
> s3 = s2 - s1
I get a series, s3, of type
> timedelta64[ns]
```
0 385 days, 04:10:36
1 57 days, 22:54:00
2 ... | You can convert it to a timedelta with a day precision. To extract the integer value of days you divide it with a timedelta of one day.
```
>>> x = np.timedelta64(2069211000000000, 'ns')
>>> days = x.astype('timedelta64[D]')
>>> days / np.timedelta64(1, 'D')
23
```
Or, as @PhillipCloud suggested, just `days.astype(in... |
How should functions be tested for equality or identity? | 18,216,597 | 15 | 2013-08-13T18:34:08Z | 18,217,024 | 9 | 2013-08-13T18:59:12Z | [
"python"
] | I would like to be able to test whether two callable objects are the same or not. I would prefer identity semantics (using the "is" operator), but I've discovered that when methods are involved, something different happens.
```
#(1) identity and equality with a method
class Foo(object):
def bar(self):
pass... | Python doesn't keep a canonical `foo.bar` object for every instance `foo` of class `Foo`. Instead, a method object is created when Python evaluates `foo.bar`. Thus,
```
foo.bar is not foo.bar
```
but Python implements an `__eq__` method for method objects that will compare the underlying functions and the instances t... |
Reloading a Python extension module from IPython | 18,216,906 | 13 | 2013-08-13T18:51:04Z | 18,266,786 | 12 | 2013-08-16T06:03:01Z | [
"python",
"python-3.x",
"ipython",
"cython"
] | Using Cython, I am developing an extension module which gets build as an .so file. I then test it using IPython. During development, I frequently need to make changes and rebuild. I also need to exit the IPython shell and reenter all commands. Reimporting the module with
```
import imp
imp.reload(Extension)
```
does ... | C extensions cannot be reloaded without restarting the process (see [this official Python bug](http://bugs.python.org/issue1144263) for more info).
Since you are already using IPython, I might recommend using one of the two-process interfaces such as the Notebook or QtConsole, if it's acceptable to you. These allow yo... |
how to convert characters like \x22 into string | 18,219,398 | 5 | 2013-08-13T21:18:09Z | 18,219,433 | 13 | 2013-08-13T21:21:07Z | [
"python",
"encoding",
"ascii"
] | I have a string that looks like this:
```
"{\\x22username\\x22:\\x229\\x22,\\x22password\\x22:\\x226\\x22,\\x22id\\x22:\\x222c8bfa56-f5d9\\x22, \\x22FName\\x22:\\x22AnkQcAJyrqpg\\x22}"
```
as far as I understand `\x22` is `"`. So how could I convert this into a readable JSON with quotes around keys and values? | Decode from `string_escape`:
```
>>> import json
>>> value = "{\\x22username\\x22:\\x229\\x22,\\x22password\\x22:\\x226\\x22,\\x22id\\x22:\\x222c8bfa56-f5d9\\x22, \\x22FName\\x22:\\x22AnkQcAJyrqpg\\x22}"
>>> value.decode('string_escape')
'{"username":"9","password":"6","id":"2c8bfa56-f5d9", "FName":"AnkQcAJyrqpg"}'
>>... |
How multiply and sum two colums with group by in django | 18,219,473 | 8 | 2013-08-13T21:22:46Z | 18,220,269 | 11 | 2013-08-13T22:25:44Z | [
"python",
"sql",
"django",
"django-models",
"group-by"
] | I need to do the following query in Django:
```
SELECT sum(T.width * T.height) as amount
FROM triangle T
WHERE T.type = 'normal'
GROUP BY S.color
```
How can I do this using your django ORM?
I tried this:
```
Triangle.objects.filter(type='normal').\
extra(select={'total':'width*height'}).\
... | Here's what you can do:
```
Triangle.objects.filter(type="normal").values('color').annotate(amount=Sum('id', field="width * height")
```
This will produce the following query (I've simplified for readability):
```
SELECT color, sum(width * height) as amount
FROM triangle
WHERE type = 'normal'
GROUP BY color
```
No... |
Bulk insert huge data into SQLite using Python | 18,219,779 | 5 | 2013-08-13T21:46:14Z | 18,219,842 | 7 | 2013-08-13T21:51:39Z | [
"python",
"sqlite3"
] | I read this: [Importing a CSV file into a sqlite3 database table using Python](http://stackoverflow.com/questions/2887878/importing-a-csv-file-into-a-sqlite3-database-table-using-python)
and it seems that everyone suggests using line-by-line reading instead of using bulk .import from SQLite. However, that will make th... | Sqlite can do [tens of thousands of inserts per second](https://www.sqlite.org/faq.html#q19), just make sure to do all of them in a single transaction by surrounding the inserts with BEGIN and COMMIT. (executemany() does this automatically.)
As always, don't optimize before you know speed will be a problem. Test the e... |
Bulk insert huge data into SQLite using Python | 18,219,779 | 5 | 2013-08-13T21:46:14Z | 18,219,864 | 9 | 2013-08-13T21:53:08Z | [
"python",
"sqlite3"
] | I read this: [Importing a CSV file into a sqlite3 database table using Python](http://stackoverflow.com/questions/2887878/importing-a-csv-file-into-a-sqlite3-database-table-using-python)
and it seems that everyone suggests using line-by-line reading instead of using bulk .import from SQLite. However, that will make th... | Divide your data into chunks on the fly using generator expressions, make inserts inside the transaction. Here's a quote from [sqlite optimization FAQ](http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html):
> Unless already in a transaction, each SQL statement has a new
> transaction started for it. This is ... |
Bulk insert huge data into SQLite using Python | 18,219,779 | 5 | 2013-08-13T21:46:14Z | 32,239,587 | 9 | 2015-08-27T02:11:55Z | [
"python",
"sqlite3"
] | I read this: [Importing a CSV file into a sqlite3 database table using Python](http://stackoverflow.com/questions/2887878/importing-a-csv-file-into-a-sqlite3-database-table-using-python)
and it seems that everyone suggests using line-by-line reading instead of using bulk .import from SQLite. However, that will make th... | Since this is the top result on a Google search I thought it might be nice to update this question.
From the [python sqlite docs](https://docs.python.org/2/library/sqlite3.html#sqlite3-controlling-transactions) you can use
```
import sqlite3
persons = [
("Hugo", "Boss"),
("Calvin", "Klein")
]
con = sqlite3.... |
Python adding space between characters in string. Most efficient way | 18,221,436 | 8 | 2013-08-14T00:36:20Z | 18,221,460 | 17 | 2013-08-14T00:39:10Z | [
"python",
"string"
] | Say I have a string `s = 'BINGO'`; I want to iterate over the string to produce `'B I N G O'`.
This is what I did:
```
result = ''
for ch in s:
result = result + ch + ' '
print(result[:-1]) # to rid of space after O
```
Is there a more efficient way to go about this? | ```
s = "BINGO"
print(" ".join(s))
```
Should do it. |
Python adding space between characters in string. Most efficient way | 18,221,436 | 8 | 2013-08-14T00:36:20Z | 18,221,508 | 11 | 2013-08-14T00:46:04Z | [
"python",
"string"
] | Say I have a string `s = 'BINGO'`; I want to iterate over the string to produce `'B I N G O'`.
This is what I did:
```
result = ''
for ch in s:
result = result + ch + ' '
print(result[:-1]) # to rid of space after O
```
Is there a more efficient way to go about this? | ```
s = "BINGO"
print(s.replace("", " ")[1: -1])
```
Timings below
```
$ python -m timeit -s's = "BINGO"' 's.replace(""," ")[1:-1]'
1000000 loops, best of 3: 0.584 usec per loop
$ python -m timeit -s's = "BINGO"' '" ".join(s)'
100000 loops, best of 3: 1.54 usec per loop
``` |
Kivy: BoxLayout vs. GridLayout | 18,222,194 | 2 | 2013-08-14T02:16:50Z | 18,237,038 | 9 | 2013-08-14T16:17:22Z | [
"python",
"kivy"
] | `BoxLayout(orientation='vertical')` vs. `GridLayout(cols=1)`:
They both do the same thing, no? Is there a reason to choose one over the other? | The differences involves size and position.
In general, **`GridLayout` (`cols: 1`) is always going to keep the elements in one column**, whereas **there is more flexibility to organize individual widgets when you use `BoxLayout` (`orientation: 'vertical'`)**.
Here is a very simple example of something you can do with... |
How can I easily convert FORTRAN code to Python code (real code, not wrappers) | 18,222,561 | 9 | 2013-08-14T03:03:30Z | 18,224,191 | 8 | 2013-08-14T05:57:10Z | [
"python",
"fortran",
"code-translation"
] | I have a numerical library in FORTRAN (I believe FORTRAN IV) and I want to convert it to Python code. I want real source code that I can import on any Python virtual machine --- Windows, MacOS-X, Linux, Android. I started to do this by hand, but there are about 1,000 routines in the library, so that's not a reasonable ... | ***edit**: added information on numpy*
Such a tool exists for [Fortran to Lisp](http://trac.common-lisp.net/f2cl/), or [Fortran to C](http://www.netlib.org/f2c/), or even [Fortran to Java](http://icl.cs.utk.edu/f2j/). But you will never have a Fortran to Python tool, for a simple reason: unlike Fortran, Lisp or C, **P... |
How to use 'in' in Python with length constraint | 18,224,362 | 3 | 2013-08-14T06:09:25Z | 18,224,410 | 9 | 2013-08-14T06:13:08Z | [
"python"
] | ```
ss = ''
for word in ['this','his','is','s']: # Attach the words
if word not in ss: # if they are not already present
ss = ss + word + ' ' # to ss(substring) AFTER ss.
```
It gives output as:
```
'this '
```
But I want to get:
```
'this his is s '
```
How ... | ```
ss = []
for word in ['this', 'his', 'is', 's']:
if word not in ss:
ss.append(word)
ss = ' '.join(ss)
``` |
Why inserting keys in order into a python dict is faster than doint it unordered | 18,224,822 | 5 | 2013-08-14T06:39:07Z | 18,225,048 | 7 | 2013-08-14T06:53:00Z | [
"python",
"performance",
"dictionary"
] | I've been creating huge dicts (millions of entries) and I've noticed that if I create them with the keys in order it is much faster.
I imagine that it has something to do with collisions with the hash function, but can someone explain why is it happening and if it is consistent among versions of python?
Here you have... | I'm almost certain this is what's going on: when you first create otest, you're storing the strings in memory in order. When you create utest, you the strings point to the same memory buffers, except that now those locations that are all out-of-order. This kills cache performance on the unordered test cases.
Here's th... |
TabError in Python 3 | 18,225,712 | 4 | 2013-08-14T07:32:58Z | 25,471,681 | 8 | 2014-08-24T12:28:32Z | [
"python",
"python-3.x"
] | Given the following interpreter session:
```
>>> def func(depth,width):
... if (depth!=0):
... for i in range(width):
... print(depth,i)
... func(depth-1,width)
File "<stdin>", line 5
func(depth-1,width)
^
TabError: inconsistent use of tabs and spaces in indentation
```
Can s... | TL;DR: never indent Python code with `TAB`
---
In Python 2, [the interpretation of `TAB` is as if it is converted to spaces using 8-space tab stops](http://stackoverflow.com/a/2034527/918959); that is that each `TAB` furthers the indentation by 1 to 8 spaces so that the resulting indentation is divisible by 8.
Howev... |
How to display html content through flask messages? | 18,225,713 | 7 | 2013-08-14T07:33:08Z | 18,226,946 | 8 | 2013-08-14T08:41:30Z | [
"python",
"flask"
] | I understand that `flash()` takes only string and displays that in the redirected page.
I m trying to send html through flash
```
message = "<h1>Voila! Platform is ready to used</h1>"
flash(message)
return render_template('output.html')
```
**output.html**
```
<div class="flashes">
{% for message in get_flashed_me... | Use the [`safe` filter](http://flask.pocoo.org/docs/templating/#controlling-autoescaping):
```
<div class="flashes">
{% for message in get_flashed_messages()%}
{{ message|safe }}
{% endfor %}
</div>
``` |
How to display html content through flask messages? | 18,225,713 | 7 | 2013-08-14T07:33:08Z | 20,895,019 | 17 | 2014-01-03T01:29:23Z | [
"python",
"flask"
] | I understand that `flash()` takes only string and displays that in the redirected page.
I m trying to send html through flash
```
message = "<h1>Voila! Platform is ready to used</h1>"
flash(message)
return render_template('output.html')
```
**output.html**
```
<div class="flashes">
{% for message in get_flashed_me... | Using `{{message|safe}}` will work, but also opens up the door for an attacker to inject malicious HTML or Javascript into your page, also known an an XSS attack. More info [here](http://flask.pocoo.org/docs/security/#xss) if you're interested.
Where possible, a more secure approach is to [wrap your string in a Markup... |
In Python, how do I find the index of an sub-item given a list? | 18,227,341 | 2 | 2013-08-14T09:01:10Z | 18,227,384 | 9 | 2013-08-14T09:02:50Z | [
"python",
"list"
] | Given the list:
```
li = ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
```
How do I find the (first) index containing the string `amp`? Note that `amp` is contained the word `example`.
FYI, this works: `li.index("example")`
But this does not: `li.index("amp")` | You can use a generator expression with [`next`](http://docs.python.org/2/library/functions.html#next) and [`enumerate`](http://docs.python.org/2/library/functions.html#enumerate):
```
>>> next((i for i,x in enumerate(li) if 'amp' in x), None)
5
```
This will return `None` if no such item was found. |
oct2py - Calling an octave function using threads in python | 18,228,093 | 3 | 2013-08-14T09:35:17Z | 18,998,800 | 7 | 2013-09-25T07:30:24Z | [
"python",
"multithreading",
"octave"
] | I was trying to call an Octave function from a python program using two threads. My octave code is just to see how it works -
testOctave.m
```
function y = testOctave(i)
y = i;
end
```
And the python program just tries to call it
```
from oct2py import octave
import thread
def func(threadName,i) :
print "he... | oct2py creator here. When you import octave from oct2py you are importing a convenience instance of the Oct2Py class. If you want to use multiple threads, you must import Oct2Py and instantiate it either within your threaded function or pre-allocate and pass it as an argument to the function. Each instance of Oct2Py us... |
Python pickle/unpickle a list to/from a file | 18,229,082 | 9 | 2013-08-14T10:19:30Z | 18,229,269 | 22 | 2013-08-14T10:28:06Z | [
"python",
"file-io",
"pickle"
] | I have a list that looks like this:
```
a = [['a string', [0, 0, 0], [22, 'bee sting']], ['see string',
[0, 2, 0], [22, 'd string']]]
```
and am having problems saving it and retrieving it.
I can save it ok using pickle:
```
with open('afile','w') as f:
pickle.dump(a,f)
```
but get the following error whe... | Decided to make it as an answer. pickle.load method expects to get a file like object, but you are providing a string instead, and therefore an exception. So instead of:
```
pickle.load('afile')
```
you should do:
```
pickle.load(open('afile', 'rb'))
``` |
Python pickle/unpickle a list to/from a file | 18,229,082 | 9 | 2013-08-14T10:19:30Z | 18,229,564 | 8 | 2013-08-14T10:41:24Z | [
"python",
"file-io",
"pickle"
] | I have a list that looks like this:
```
a = [['a string', [0, 0, 0], [22, 'bee sting']], ['see string',
[0, 2, 0], [22, 'd string']]]
```
and am having problems saving it and retrieving it.
I can save it ok using pickle:
```
with open('afile','w') as f:
pickle.dump(a,f)
```
but get the following error whe... | To add to @ Rapolas K's answer:
I found that I had problems with the file not closing so used this method:
```
with open('afile','rb') as f:
pickle.load(f)
``` |
python profiling using line_profiler - clever way to remove @profile statements on-the-fly? | 18,229,628 | 7 | 2013-08-14T10:44:33Z | 18,229,685 | 8 | 2013-08-14T10:47:18Z | [
"python",
"profiling",
"decorator"
] | I want to use the excellent [line\_profiler](http://pythonhosted.org/line_profiler), but only some of the time. To make it work I add
```
@profile
```
before every function call, e.g.
```
@profile
def myFunc(args):
blah
return
```
and execute
```
kernprof.py -l -v mycode.py args
```
But I don't want to ha... | Instead of *removing* the `@profile` decorator lines, provide your own pass-through no-op version.
You can add the following code to your project somewhere:
```
import __builtin__
try:
__builtin__.profile
except AttributeError:
# No line profiler, provide a pass-through version
def profile(func): return ... |
Could not find a version that satisfies the requirement pytz | 18,230,956 | 52 | 2013-08-14T11:50:07Z | 18,319,230 | 74 | 2013-08-19T17:03:30Z | [
"python",
"pip",
"virtualenv",
"pytz"
] | I have a problem installing [pytz](http://pytz.sourceforge.net/) in virtualenv.
```
Downloading/unpacking pytz
Could not find a version that satisfies the requirement pytz (from versions: 2009r, 2008b, 2009f, 2008c, 2007g, 2011g, 2005m, 2011e, 2007f, 2011k, 2007k, 2006j, 2008h, 2008i, 2011e, 2008a, 2009e, 2006g, 201... | This error occurs when installing `pytz` using pip v1.4 or newer, due to this change in behaviour:
> ## [Pre-release Versions](http://pip.readthedocs.org/en/1.4.1/logic.html#pre-release-versions)
>
> Starting with v1.4, pip will only install stable versions as specified by [PEP426](http://www.python.org/dev/peps/pep-0... |
Best way to return a value from a python script | 18,231,415 | 19 | 2013-08-14T12:11:47Z | 18,231,470 | 43 | 2013-08-14T12:14:18Z | [
"python",
"return",
"return-value"
] | I wrote a script in python that takes a few files, runs a few tests and counts the number of total\_bugs while writing new files with information for each (bugs+more).
To take a couple files from current working directory:
> myscript.py -i input\_name1 input\_name2
When that job is done, I'd like the script to 'retu... | If you want your script to **return** values, just do `return [1,2,3]` from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:
# Return values (from a wrapping-function)
(again, this would have to be run by a separate Python script an... |
pandas: convert datetime to end-of-month | 18,233,107 | 9 | 2013-08-14T13:28:48Z | 18,233,876 | 13 | 2013-08-14T14:01:15Z | [
"python",
"pandas"
] | I have written a function to convert pandas datetime dates to month-end:
```
import pandas
import numpy
import datetime
from pandas.tseries.offsets import Day, MonthEnd
def get_month_end(d):
month_end = d - Day() + MonthEnd()
if month_end.month == d.month:
return month_end # 31/March + MonthEnd() ret... | Revised, converting to period and then back to timestamp does the trick
```
In [104]: df = DataFrame(dict(date = [Timestamp('20130101'),Timestamp('20130131'),Timestamp('20130331'),Timestamp('20130330')],value=randn(4))).set_index('date')
In [105]: df
Out[105]:
value
date
2013-01-01 -0.... |
Using Python to count the number of business days in a month? | 18,233,122 | 2 | 2013-08-14T13:29:20Z | 18,234,274 | 7 | 2013-08-14T14:18:18Z | [
"python",
"date"
] | I am trying to write a Python script that will calculate how many business days are in the current month. For instance if `month = August` then `businessDays = 22`.
Here is my code for discovering the month:
```
def numToMonth( num ):
months = ["January", "February", "March", "April", "May", "June", "July", "Augus... | This is a long-winded way, but at least it works and doesn't require anything other than the standard modules.
```
import datetime
now = datetime.datetime.now()
holidays = [datetime.date(2013, 8, 14)] # you can add more here
businessdays = 0
for i in range(1, 32):
try:
thisdate = datetime.date(now.year, n... |
Python multithreaded print statements delayed until all threads complete execution | 18,234,469 | 6 | 2013-08-14T14:27:38Z | 18,234,593 | 7 | 2013-08-14T14:33:06Z | [
"python",
"multithreading"
] | I have a piece of code below that creates a few threads to perform a task, which works perfectly well on its own. However I'm struggling to understand why the print statements I call in my function do not execute until all threads complete and the `print 'finished'` statement is called. I would expect them to be called... | This happens due to stdout buffering. You still can flush the buffers:
```
import sys
print 'starting'
sys.stdout.flush()
```
You can find more info on this issue [here](http://stackoverflow.com/questions/107705/python-output-buffering) and [here](http://stackoverflow.com/questions/230751/how-to-flush-output-of-pyth... |
Is it possible to create a repeatable stream of random numbers? | 18,234,781 | 4 | 2013-08-14T14:40:23Z | 18,234,903 | 8 | 2013-08-14T14:45:08Z | [
"python"
] | Per [How to generate a repeatable random number sequence?](http://stackoverflow.com/questions/9023660/how-to-generate-a-repeatable-random-number-sequence) it's possible to set the state of the random module such that you can expect the subsequent calls to randint to return the same number.
One limitation I see with th... | It doesn't have to maintain state at the module level -- see the docs for the [`random` module](http://docs.python.org/2/library/random.html):
> The functions supplied by this module are actually bound methods of a
> hidden instance of the `random.Random` class. You can instantiate your
> own instances of Random to ge... |
AES - Encryption with Crypto (node-js) / decryption with Pycrypto (python) | 18,236,761 | 11 | 2013-08-14T16:04:34Z | 18,236,762 | 10 | 2013-08-14T16:04:34Z | [
"python",
"node.js",
"cryptography",
"pycrypto"
] | I'm writing this question + answer because I struggled a lot (maybe because of a lack of experience), got lost in many different ways of encrypting/decrypting things with node or python.
I thought maybe my case could help people in the future.
What I needed to do:
* Get data from a form, encrypt them using Crypto (n... | So we started from the "How can i decrypt... OpenSSL" 's answer.
* We needed to modify the encryption script which gave:
```
crypto = require "crypto"
[...]
var iv = new Buffer('asdfasdfasdfasdf')
var key = new Buffer('asdfasdfasdfasdfasdfasdfasdfasdf')
var cipher = crypto.createCipheriv('aes-256-cbc', ke... |
Pandas Data Frame Plotting | 18,237,453 | 6 | 2013-08-14T16:39:31Z | 18,237,847 | 8 | 2013-08-14T16:59:49Z | [
"python",
"matplotlib",
"plot",
"pandas"
] | I have this Pandas DataFrame

which gives me this:

How do I
1. Make a new figure,
2. Add the title to the figure "Title Here"
3. Somehow create a mapping so that instead of the lab... | ```
import matplotlib.pyplot as plt
# 1, 4
f = plt.figure(figsize=(10, 10)) # Change the size as necessary
# 2
dataframe.plot(ax=f.gca()) # figure.gca means "get current axis"
plt.title('Title here!', color='black')
# 3
# Not sure :(
``` |
Pandas Data Frame Plotting | 18,237,453 | 6 | 2013-08-14T16:39:31Z | 18,238,538 | 8 | 2013-08-14T17:37:04Z | [
"python",
"matplotlib",
"plot",
"pandas"
] | I have this Pandas DataFrame

which gives me this:

How do I
1. Make a new figure,
2. Add the title to the figure "Title Here"
3. Somehow create a mapping so that instead of the lab... | You can use the [`rename`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.html) DataFrame method:
```
In [1]: df = pd.DataFrame(np.random.randn(7, 5),
index=['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
columns=[29, 30, 31, 32, 33]... |
DBSCAN in scikit-learn of Python: save the cluster points in an array | 18,237,479 | 5 | 2013-08-14T16:40:38Z | 18,240,583 | 18 | 2013-08-14T19:28:37Z | [
"python",
"cluster-analysis",
"scikit-learn",
"dbscan"
] | following the example [Demo of DBSCAN clustering algorithm](http://scikit-learn.org/stable/auto_examples/cluster/plot_dbscan.html#example-cluster-plot-dbscan-py) of Scikit Learning i am trying to store in an array the x, y of each clustering class
```
import numpy as np
from sklearn.cluster import DBSCAN
from sklearn ... | The first cluster is `X[labels == 0]`, etc.:
```
clusters = [X[labels == i] for i in xrange(n_clusters_)]
```
and the outliers are
```
outliers = X[labels == -1]
``` |
Django Generic Relations error: "cannot resolve keyword 'content_object' into field" | 18,239,030 | 6 | 2013-08-14T18:04:50Z | 18,239,502 | 11 | 2013-08-14T18:29:29Z | [
"python",
"django",
"django-class-based-views"
] | I'm using Django's Generic Relations to define Vote model for Question and Answer models.
Here is my vote model:
**models.py**
```
class Vote(models.Model):
user_voted = models.ForeignKey(MyUser)
is_upvote = models.BooleanField(default=True)
# Generic foreign key
content_type = models.ForeignKey(Con... | `content_object` is a sort of read-only attribute that will retrieve the object specified by fields `content_type` and `object_id`. You should replace your code by the following:
```
from django.contrib.contenttypes.models import ContentType
type = ContentType.objects.get_for_model(object)
vote, created = Vote.objects... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.