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
C array vs NumPy array
21,920,884
8
2014-02-20T22:15:48Z
21,928,877
17
2014-02-21T08:15:42Z
[ "python", "c", "arrays", "numpy", "cython" ]
In terms of performance (algebraic operations, lookup, caching, etc.), is there a difference between **C arrays** (which can be exposed as a C array, or a `cython.view.array` [Cython array], or a memoryview of the aforementioned two) and a **NumPy arrays** (which in Cython should have no Python overhead) Edit: I shou...
My knowledge on this is still imperfect, but this may be helpful. I ran some informal benchmarks to show what each array type is good for and was intrigued by what I found. Though these array types are different in many ways, if you are doing heavy computation with large arrays, you should be able to get similar perfo...
Binning a numpy array
21,921,178
9
2014-02-20T22:34:22Z
21,921,301
13
2014-02-20T22:42:12Z
[ "python", "arrays", "numpy", "pandas", "scipy" ]
I have a numpy array which contains time series data. I want to bin that array into equal partitions of a given length (it is fine to drop the last partition if it is not the same size) and then calculate the mean of each of those bins. I suspect there is numpy, scipy, or pandas functionality to do this. example: ``...
Just use `reshape` and then `mean(axis=1)`. As the simplest possible example: ``` import numpy as np data = np.array([4,2,5,6,7,5,4,3,5,7]) print data.reshape(-1, 2).mean(axis=1) ``` More generally, we'd need to do something like this to drop the last bin when it's not an even multiple: ``` import numpy as np wi...
is it possible to use variables from 2 instances together inside a method?
21,921,733
3
2014-02-20T23:09:30Z
21,921,761
8
2014-02-20T23:11:47Z
[ "python", "class" ]
I'm sorry if I phrased this wrong, but I will try my best to explain what I want to do. Is it possible to do this in Python - ``` class Character(): strength, skill = 0, 0 def foo(self, strength, skill): if c1.strength > c2.strength: #something here c1 = Character() c2 = Character() c1....
You could just pass the other instance: ``` def foo(self, other_character): if self.strength > other_character.strength: #something here c1 = Character() c2 = Character() c1.strength = 15 c2.strength = 13 c1.foo(c2) ```
Add minor gridlines to matplotlib plot using seaborn
21,923,463
10
2014-02-21T01:35:51Z
21,924,612
12
2014-02-21T03:17:08Z
[ "python", "matplotlib", "seaborn" ]
I'm a fan of the Seaborn package for making nice-looking plots using Matplotlib. But I can't seem to figure out how to show minor gridlines in my plots. ``` import numpy as np import matplotlib.pyplot as plt import seaborn as sbn x = np.linspace(0, 2 * np.pi, 100) y = np.sin(x) fig, ax = plt.subplots(1, 1) ax.scatte...
Wound up combining CT Zhu's answer with tcaswell's hint: ``` import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sbn x = np.linspace(0, 2 * np.pi, 100) y = np.sin(x) fig, ax = plt.subplots(1, 1) ax.scatter(x, y) ax.get_xaxis().set_minor_locator(mpl.ticker.AutoMinorLocator()...
correlation between arrays in python
21,923,577
3
2014-02-21T01:46:04Z
21,923,626
10
2014-02-21T01:49:27Z
[ "python", "arrays", "vector", "correlation" ]
I have 2 arrays. ``` a1 = [1,2,4] a2 = [3,4,5] ``` how would I find the correlation between these 2 arrays using python. In matlab, you would do: ``` corr(a1,a2) ``` How to do this in python?
You need [`numpy.corrcoef`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.corrcoef.html): ``` In [8]: np.corrcoef(a1,a2) Out[8]: array([[ 1. , 0.98198051], [ 0.98198051, 1. ]]) ```
Convert Django Model object to dict with all of the fields intact
21,925,671
53
2014-02-21T05:02:36Z
29,088,221
21
2015-03-16T22:37:54Z
[ "python", "django", "dictionary", "django-models" ]
How does one convert a django Model object to a dict with **all** of its fields? All ideally includes foreign keys and fields with editable=False. Let me elaborate. Let's say I have a django model like the following: ``` from django.db import models class OtherModel(models.Model): pass class SomeModel(models.Model)...
There are many ways to convert instance to a dictionary, with varying degrees of corner case handling and closeness to the desired result. --- ## 1. `instance.__dict__` ``` instance.__dict__ ``` which returns ``` {'_reference1_cache': <OtherModel: OtherModel object>, '_state': <django.db.models.base.ModelState at...
Login to Facebook using python requests
21,928,368
16
2014-02-21T07:48:19Z
21,930,636
18
2014-02-21T09:43:52Z
[ "python", "facebook", "facebook-login", "python-requests" ]
I'm trying to find a way to automatically login to Facebook without browser using Python. I experimented with "requests" lib. Tried several ways: ``` URL = 'http://m.facebook.com' requests.get(URL, auth = ('[email protected]', 'mypassword')) ``` ... ``` form_data = {'email': '[email protected]', 'pass' : ...
You need to send a complete form. The easiest way to find out what Facebook expects is to use something like [Google Chrome's developer tools](https://developers.google.com/chrome-developer-tools/) to monitor your web requests. To make your life easier I've monitored my own login on Facebook, and reproduced it below (...
convert variables into dictonaries
21,928,735
3
2014-02-21T08:07:15Z
21,928,815
8
2014-02-21T08:12:32Z
[ "python", "python-3.x", "dictionary" ]
I have something like this where trade\_date, effective\_date and termination\_date are date values: ``` tradedates = dict(((k, k.strftime('%Y-%m-%d')) for k in (trade_date,effective_date,termination_date))) ``` I get this: ``` {datetime.date(2005, 7, 25): '2005-07-25', datetime.datetime(2005, 7, 27, 11, 26, 38)...
Using [`vars`](http://docs.python.org/3/library/functions.html#vars): ``` >>> import datetime >>> >>> trade_date = datetime.date(2005, 7, 25) >>> effective_date = datetime.datetime(2005, 7, 27, 11, 26, 38) >>> termination_date = datetime.datetime(2010, 7, 26, 11, 26, 38) >>> >>> d = vars() # You can access the variabl...
Being forced to pass an object itself when calling class methods - am I doing it wrong?
21,929,319
4
2014-02-21T08:40:36Z
21,929,357
9
2014-02-21T08:42:26Z
[ "python", "class" ]
If I made some sort of function like this: ``` class Counter: def __init__(self): self._count = 0 def count(self) -> int: self._count += 1 return self._count def reset(self) -> None: self._count = 0 ``` and put this in the python shell: ``` >>> s = Counter >>> s.count() ...
``` s = Counter ``` This doesn't create an instance of the `Counter` class. It assigns the `Counter` class to the variable `s`. This means that you're trying to call an instance method on the class itself in the second line. If you want to create an instance of the `Counter` class, you should write: ``` s = Counter(...
How to match specific characters only?
21,931,098
2
2014-02-21T10:03:38Z
21,931,528
7
2014-02-21T10:20:44Z
[ "python", "regex" ]
Here I am try to match the specific characters in a string, ``` ^[23]*$ ``` Here my cases, 1. `2233` --> **Match** 2. `22` --> Not Match 3. `33` --> Not Match 4. `2435` --> Not Match 5. `2322` --> **Match** 6. `323` --> **Match** I want to match the string with correct regular expression. I mean 1,5,6 cases needed....
How about: ``` (2+3|3+2)[23]*$ ``` String must either: * start with one or more 2s, contain a 3, followed by any mix of 2 or 3 only * start with one or more 3s, contain a 2, followed by any mix of 2 or 3 only **Update: to parameterize the pattern** To parameterize this pattern, you could do something like: ``` x ...
Repeat each value of an array two times (numpy)
21,931,786
2
2014-02-21T10:30:24Z
21,931,854
8
2014-02-21T10:33:32Z
[ "python", "arrays", "numpy" ]
Let `A` be a numpy array like : ``` A = np.array([1, 2, 3, 4, 5]) ``` I want to find the cleaner way to produce a new array with each value repeated two times: ``` B = np.array([1, 1, 2, 2, 3, 3, 4, 4, 5, 5]) ``` **Do you think this is the simpler way to do it ?** ``` import numpy as np B = np.tile(A,2).reshape(2,...
Use [repeat()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html) ``` In [1]: import numpy as np In [2]: A = np.array([1, 2, 3, 4, 5]) In [3]: np.repeat(A,2) Out[3]: array([1, 1, 2, 2, 3, 3, 4, 4, 5, 5]) ```
How to change legend fontname in matplotlib
21,933,187
7
2014-02-21T11:28:19Z
22,253,266
8
2014-03-07T14:48:21Z
[ "python", "matplotlib", "legend", "legend-properties" ]
I would like to display a font in Times New Roman in the legend of a matplotlib plot. I have changed all other tick labels/axis labels/titles to Times New Roman, and have searched the documentation but I can only find how to change the font size in a legend using the `prop` argument in `pyplot.legend()` Thank you Of ...
This wasn't showing up in google results so I'm going to post it as an answer. The rc parameters for font can be used to set a single default font. Solution for anyone else with the same issue: `import matplotlib as mpl` `mpl.rc('font',family='Times New Roman')`
Run function from the command line and pass arguments to function
21,934,880
2
2014-02-21T12:46:34Z
21,934,949
7
2014-02-21T12:49:31Z
[ "python" ]
I'm using similar approach to call python function from my shell script: ``` python -c 'import foo; print foo.hello()' ``` But I don't know how in this case I can pass arguments to python script and also is it possible to call function with parameters from command line?
``` python -c 'import foo, sys; print foo.hello(); print(sys.argv[1])' "This is a test" ``` or ``` echo "Wham" | python -c 'print(raw_input(""));' ``` There's also [argparse](http://docs.python.org/3/library/argparse.html) (py3 link) that could be used to capture arguments, such as the `-c` which also can be found a...
Blocking and Non Blocking subprocess calls
21,936,597
21
2014-02-21T14:02:55Z
21,936,682
29
2014-02-21T14:07:07Z
[ "python", "python-2.7", "subprocess" ]
I'm completely confused between `subprocess.call()` , `subprocess.Popen()`, `subprocess.check_call()`. Which is blocking and which is not ? What I mean to say is if I use `subprocess.Popen()` whether the parent process waits for the child process to `return`/`exit` before it keep on its execution. How does `shell=Tr...
`Popen` is nonblocking. `call` and `check_call` are blocking. You can make the `Popen` instance block by calling its `wait` or `communicate` method. If you look in [the source code](http://hg.python.org/cpython/file/005d0678f93c/Lib/subprocess.py#l527), you'll see `call` calls `Popen(...).wait()`, which is why it is b...
Python cx_Freeze name __file__ is not defined
21,937,695
4
2014-02-21T14:54:21Z
22,270,293
12
2014-03-08T14:03:09Z
[ "python", "python-module", "cx-freeze", "setup.py" ]
I have a python script which gets an image from the internet, downloads it, sets as desktop background and updates after on minute. The problem is most likely cx\_Freeze not including the os module, as the same code with absolute paths works fine. My code also works perfectly, until it goes through freezing. It works b...
Source: <http://cx-freeze.readthedocs.org/en/latest/faq.html> Your old line: ``` dir = path.dirname(__file__) ``` Substitute this with the following lines to run your script both frozen or unfrozen: ``` if getattr(sys, 'frozen', False): # frozen dir_ = os.path.dirname(sys.executable) else: # unfrozen ...
Defining multiple plots to be animated with a for loop in matplotlib
21,937,976
2
2014-02-21T15:07:22Z
21,938,297
8
2014-02-21T15:23:00Z
[ "python", "animation", "matplotlib" ]
[Thanks to Jake Vanderplas](http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/), I know how to start to code an animated plot with [`matplotlib`](http://matplotlib.org/). Here is a sample code: ``` from matplotlib import pyplot as plt from matplotlib import animation fig = plt.figure() ax = plt....
First I will post you the solution, then some explanations: ``` from matplotlib import pyplot as plt from matplotlib import animation fig = plt.figure() ax = plt.axes(xlim=(0, 2), ylim=(0, 100)) N = 4 lines = [plt.plot([], [])[0] for _ in range(N)] def init(): for line in lines: line.set_data([], [...
How do I convert a numpy array into a pandas dataframe?
21,938,932
10
2014-02-21T15:49:07Z
21,940,107
15
2014-02-21T16:41:56Z
[ "python", "numpy", "pandas" ]
I would like to have the 3 columns of a numpy array ``` px[:,:,0] px[:,:,1] px[:,:,0] ``` into a pandas Dataframe. Should I use? ``` df = pd.DataFrame(px, columns=['R', 'G', 'B']) ``` Thank you Hugo
You need to reshape your array first, try this: ``` px2 = px.reshape((-1,3)) df = pd.DataFrame({'R':px2[:,0],'G':px2[:,1],'B':px2[:,2]}) ```
matplotlib: render into buffer / access pixel data
21,939,658
4
2014-02-21T16:21:43Z
21,940,031
7
2014-02-21T16:38:29Z
[ "python", "opengl", "matplotlib" ]
I want to use plots generated with matplotlib as textures in OpenGL. The OpenGL backends for matplotlib I came across so far are either immature or discontinued, so I want to avoid them. My current approach is to save figures into temporary .png files from which I assemble texture atlases. However, I would prefer to a...
Sure, just use `fig.canvas.tostring_rgb()` to dump the rgb buffer to a string. Similarly, there's `fig.canvas.tostring_argb()` if you need the alpha channel, as well. If you want to dump the buffer to a file, there's `fig.canvas.print_rgb` and `fig.canvas.print_rgba` (or equivalently, `print_raw`, which is rgba). Yo...
Python Image distortion
21,940,911
2
2014-02-21T17:17:45Z
21,946,077
7
2014-02-21T22:02:01Z
[ "python", "numpy", "pillow" ]
I'm trying to apply a ripple effect to an image in python. I found Pillow's im.transform(im.size, Image.MESH,.... is it possible? Maybe I have to load the image with numpy and apply the algorithm. I also found this: <http://www.pygame.org/project-Water+Ripples-1239-.html> ![ripple](http://i.stack.imgur.com/iIWa0.png) ...
You could use `np.roll` to rotate each row or column according to some sine function. ``` from scipy.misc import lena import numpy as np import matplotlib.pyplot as plt img = lena() A = img.shape[0] / 3.0 w = 2.0 / img.shape[1] shift = lambda x: A * np.sin(2.0*np.pi*x * w) for i in range(img.shape[0]): img[:,i...
Django delete unused media files
21,941,503
8
2014-02-21T17:45:36Z
28,986,328
7
2015-03-11T12:13:02Z
[ "python", "django", "django-admin" ]
I have a django project in which the admins are able to upload media. As items sell, they are deleted from the site, thus removing their entry in the MySQL database. The images associated with the item, however, remain on the file system. This isn't neccessarily bad behavior - I don't mind keeping files around in case ...
Try [django-cleanup](https://github.com/un1t/django-cleanup), it automatically invokes delete method on FileField when you remove model. ``` pip install django-cleanup ``` settings.py ``` INSTALLED_APPS = ( ... 'django_cleanup', # should go after your apps ) ```
python ValueError: invalid literal for float()
21,943,877
9
2014-02-21T19:49:09Z
21,944,112
8
2014-02-21T20:03:04Z
[ "python", "literals" ]
I have a script which reads temperature data from a device, as follows: ``` def get_temp(socket, channels): data = {} for ch in channels: socket.sendall('KRDG? %s\n' % ch) time.sleep(0.2) temp = socket.recv(32).rstrip('\r\n') data[ch] = float(temp) ``` and for the longest tim...
I would all but guarantee that the issue is some sort of non-printing character that's present in the value you pulled off your socket. It looks like you're using Python 2.x, in which case you can check for them with this: ``` print repr(temp) ``` You'll likely see something in there that's escaped in the form `\x00`...
How list all fields of an class in Python (and no methods)?
21,945,067
6
2014-02-21T21:00:26Z
21,945,124
13
2014-02-21T21:03:58Z
[ "python", "python-2.7", "introspection" ]
Suppose `o` is a Python object, and I want all of the fields of `o`, without any methods or `__stuff__`. How can this be done? I've tried things like: ``` [f for f in dir(o) if not callable(f)] [f for f in dir(o) if not inspect.ismethod(f)] ``` but these return the same as `dir(o)`, presumably because `dir` gives a...
You can get it via the `__dict__` attribute, or the [built-in `vars`](http://docs.python.org/3/library/functions.html#vars) function, which is just a shortcut: ``` >>> class A(object): ... foobar = 42 ... def __init__(self): ... self.foo = 'baz' ... self.bar = 3 ... def method(self, arg): ....
show untested functions with coverage
21,945,295
5
2014-02-21T21:13:39Z
21,948,102
8
2014-02-22T00:51:56Z
[ "python", "coverage.py" ]
with [coverage](https://github.com/nedbat/coveragepy), I can get the percent of untested functions ``` coverage run setup.py test ; coverage report ``` like this ``` Name Stmts Miss Cover ------------------------------------------------- script 565 278 51% s...
If you run `coverage report -m` it will display the uncovered lines in the output under the missing column: ``` Name Stmts Miss Cover Missing ------------------------------------------------------- my_program 20 4 80% 33-35, 39 my_other_module 56 ...
PEP8: continuation line over-indented for visual indent
21,947,121
12
2014-02-21T23:16:43Z
21,947,157
15
2014-02-21T23:20:41Z
[ "python" ]
I have this line of code which goes over the line and when testing for pep8 errors I get: line too long. So to try and fix this I used slash('\') but then I get continuation line over-indented for visual indent. What can I do to fix this? ![enter image description here](http://i.stack.imgur.com/osXJl.png) Things I've...
The line-extending backslash has the issue of having trailing whitespace that can break your code. This is a popular fix and is PEP8-compliant: ``` if (first_index < 0 or second_index > self._number_of_plates - 1): ```
When does Python create new list objects for empty lists?
21,948,712
14
2014-02-22T02:10:15Z
21,948,757
12
2014-02-22T02:15:53Z
[ "python", "list", "empty-list", "object-identity" ]
The following makes sense to me: ``` >>> [] is [] False ``` Given that lists are mutable, I would expect `[]` to be a new empty list object every time it appears in an expression. Using this explanation however, the following surprises me: ``` id([]) == id([]) True ``` Why? What is the explanation?
In the first example, `[]` is not `[]` precisely *because* the lists are mutable. If they weren't, they could safely map to the same one without issue. In the second example, `id([])` creates a list, gets the id, and deallocates the list. The second time around it creates a list *again*, but "puts it in the same place...
Python re a extra underscore
21,948,789
2
2014-02-22T02:20:29Z
21,948,819
9
2014-02-22T02:24:28Z
[ "python" ]
The test: ``` import re m = re.match(r'\d*[a-zA-z]+', '123abc_2_1_4') print(m.group()) ``` I expect the result is '123abc' but it is '123abc\_'. Why there is a extra underscore? PS. I test under python 3.3.4 and python 2.7.6 (windows x64)
The regexp should be: ``` r'\d*[a-zA-Z]+' ^ ``` If you look at an [ASCII chart](http://www.asciitable.com/), you'll see a number of punctuation characters between the uppercase and lowercase letters, and you were matching them as well as letters.
WTForms: two forms on the same page?
21,949,452
6
2014-02-22T03:58:01Z
21,953,184
11
2014-02-22T10:47:34Z
[ "python", "forms", "flask", "wtforms", "flask-wtforms" ]
I have a dynamic web-page that should process two forms: a **login form** and a **register form**. I am using WTForms to process the two forms but I am having some trouble making it work, since both forms are being rendered to the same page. The following is the code for the **login** form of my webpage: ``` PYTHON: ...
This is a bit confusing, because you render index.html on both index() and register(), and both register the same route (`@application.route('/index')`). When you submit your form to `/index`, only one of them only ever get called. You can either * put all your logic in one index function and see which form (if any) i...
Python list comprehensions: set all elements in an array to 0 or 1
21,949,539
5
2014-02-22T04:10:27Z
21,949,549
9
2014-02-22T04:11:50Z
[ "python", "list", "list-comprehension" ]
I've been trying to come up with a one line list comprehension to do the following: Given an array of integers and a single integer, call it int1, I want to create a new array of only 0's and 1's such that the new array has a 1 if there was an int1 at that position in the original array else 0. Is there a way to have ...
Simply convert the boolean to `int`, with [`int`](http://docs.python.org/2/library/functions.html#int) function, like this ``` array2 = [int(x == 4) for x in array1] ``` **Output** ``` [0, 1, 0, 1, 0, 0, 1, 0] ``` This works because, in Python, [Boolean is a subclass of `int`](http://docs.python.org/2/library/funct...
Setting the limits on a colorbar in matplotlib
21,952,100
5
2014-02-22T09:00:30Z
21,952,347
7
2014-02-22T09:25:28Z
[ "python", "matplotlib", "colorbar" ]
I have seen so many examples that just don't apply to my case. What I would like to do is set a simple minimum and maximum value for a colorbar. Setting a range for an image cmap is easy but this does not apply the same range to the minimum and maximum values of the colorbar. The code below may explain: ``` triang = T...
[I propose you incorporate you plot in a fig](http://stackoverflow.com/questions/12570627/getting-a-matplotlib-colorbar-tick-outside-data-limits-for-use-with-boundaries-k) and get inspiration from this sample using the colorbar ``` data = np.tile(np.arange(4), 2) fig = plt.figure() ax = fig.add_subplot(121) cax = fig....
Run subprocess and print output to logging
21,953,835
8
2014-02-22T11:44:53Z
21,953,948
8
2014-02-22T11:53:28Z
[ "python", "logging", "subprocess" ]
I am looking for the way to call shell scripts from python and write their stdout and stderr to file using logging. Here is my code: ``` import logging import tempfile import shlex import os def run_shell_command(command_line): command_line_args = shlex.split(command_line) logging.info('Subprocess: \"' + com...
> I am sure that there is the way to do it without creating temporary > file to store process output You simply have to check for the documentation of [`Popen`](http://docs.python.org/2/library/subprocess.html#frequently-used-arguments), in particular about `stdout` and `stderr`: > `stdin`, `stdout` and `stderr` spec...
Which is the fastest way to extract day, month and year from a given date?
21,954,197
5
2014-02-22T12:18:16Z
21,954,923
16
2014-02-22T13:25:09Z
[ "python", "date", "datetime", "pandas" ]
I read a csv file containing 150,000 lines into a pandas dataframe. This dataframe has a field, 'Date', with the dates in *yyyy-mm-dd* format. I want to extract the month, day and year from it and copy into the dataframes' columns, 'Month', 'Day' and 'Year' respectively. For a few hundred records the below two methods ...
In 0.15.0 you will be able to use the new .dt accessor to do this nice syntactically. ``` In [36]: df = DataFrame(date_range('20000101',periods=150000,freq='H'),columns=['Date']) In [37]: df.head(5) Out[37]: Date 0 2000-01-01 00:00:00 1 2000-01-01 01:00:00 2 2000-01-01 02:00:00 3 2000-01-01 03:00:00...
CKAN Install: paster error
21,955,234
2
2014-02-22T13:53:50Z
21,967,384
7
2014-02-23T11:06:23Z
[ "python", "ckan", "paster" ]
Installing CKAN locally on OSX 10.9, based on <http://docs.ckan.org/en/latest/maintaining/installing/install-from-source.html>. I've created and activated the python virtualenv and now need to create a CKAN config file: ``` $ paster make-config ckan /etc/ckan/default/development.ini ``` The output is as follows (Imp...
`ImportError: No module named pylons.util` looks like Python cannot find the Pylons package, one of the Python packages that CKAN depends on. Two possibilities come to mind: 1. Did you activate your CKAN virtualenv, before running the paster command? `~/ckan/default/bin/activate`. 2. Have you installed the Python pack...
Curses returning AttributeError: 'module' object has no attribute 'initscr'
21,955,285
4
2014-02-22T13:57:30Z
21,955,290
25
2014-02-22T13:58:03Z
[ "python", "curses" ]
I am following the [Curses programming HowTo on the Python site](http://docs.python.org/3/howto/curses.html), but I am running into a rather bizarre issue. My code is currently very short, doesn't actually do anything **because** of this error, I haven't been able to move on. Here's my code: ``` import curses #from c...
You named your file `curses.py`, so Python thinks that file is the `curses` module. Name it something else.
Use Jinja2 template engine in external javascript file
21,956,500
11
2014-02-22T15:43:53Z
21,957,104
14
2014-02-22T16:35:49Z
[ "javascript", "python", "flask", "external", "jinja2" ]
I working on a web project using Python and Flask. I was just wondering if I can access parameters sent by python in my external javascript files? It's working well with html files or with js embedded in html files but not when javascript is extern. See below. The python code ``` @app.route('/index') def index(): ...
The index.js is probably not served by your flask instance, but it is most definitely not processed by your templateing engine and even if it would it would not have the same context as the html it is requested for. I think the cleanest solution would be to have an initiation function in your `index.js` and call it fr...
Python - Enable access control on simple http server
21,956,683
38
2014-02-22T16:00:26Z
21,957,017
66
2014-02-22T16:28:45Z
[ "python" ]
I have the following shell script for very simple http server ``` #!/bin/sh echo "Serving at http://localhost:3000" python -m SimpleHTTPServer 3000 ``` and I was wondering how I can enable /add [ Access-Control-Allow-Origin: \* ] on this server?
Unfortunately, [`SimpleHTTPServer`](https://docs.python.org/2/library/simplehttpserver.html) is really that simple that it does not allow any customization, especially not of the headers it sends. You can however create a simple HTTP server yourself, using most of `SimpleHTTPServerRequestHandler`, and just add that des...
Python - Enable access control on simple http server
21,956,683
38
2014-02-22T16:00:26Z
28,632,834
22
2015-02-20T15:43:28Z
[ "python" ]
I have the following shell script for very simple http server ``` #!/bin/sh echo "Serving at http://localhost:3000" python -m SimpleHTTPServer 3000 ``` and I was wondering how I can enable /add [ Access-Control-Allow-Origin: \* ] on this server?
You can try alternatives supporting cors: ``` # install (requires nodejs/npm) npm install http-server -g #run http-server -p 3000 --cors ```
Fresh deploy on Heroku fails with "use --allow-unverified PIL to allow"
21,958,382
5
2014-02-22T18:15:40Z
21,966,391
20
2014-02-23T09:21:42Z
[ "python", "django", "heroku", "pip" ]
Tried deploying a Django project to a fresh app on Heroku (The code is running on other instances for past two years) - and was hit with this: ``` Downloading/unpacking PIL==1.1.7 (from -r requirements.txt (line 7)) Could not find any downloads that satisfy the requirement PIL==1.1.7 (from -r requirements.txt (...
I asked the maintainer of pip, and he replied with a simple solution. I am detailing how to go about it as a response to my own question. Here is what you need to do for now - until the packages are hosted internally and verified. On local machine, create a new virtual environment and add one line on top of the `requi...
Setting the window to a fixed size with Tkinter
21,958,534
19
2014-02-22T18:28:10Z
21,958,849
11
2014-02-22T18:51:18Z
[ "python", "python-2.7", "tkinter" ]
This program will create a window where a message is displayed according to a check box. ``` from Tkinter import * class App: def __init__(self,master): self.var = IntVar() frame = Frame(master) frame.grid() f2 = Frame(master,width=200,height=100) f2.grid(row=0,column=1) ...
You can use the `minsize` and `maxsize` to set a minimum & maximum size, for example: ``` def __init__(self,master): master.minsize(width=666, height=666) master.maxsize(width=666, height=666) ``` Will give your window a fixed width & height of 666 pixels. Or, just using `minsize` ``` def __init__(self,mast...
Setting the window to a fixed size with Tkinter
21,958,534
19
2014-02-22T18:28:10Z
21,960,119
48
2014-02-22T20:29:57Z
[ "python", "python-2.7", "tkinter" ]
This program will create a window where a message is displayed according to a check box. ``` from Tkinter import * class App: def __init__(self,master): self.var = IntVar() frame = Frame(master) frame.grid() f2 = Frame(master,width=200,height=100) f2.grid(row=0,column=1) ...
This code makes a window with the conditions that the user cannot change the dimensions of the `Tk()` window, and also disables the maximise button. ``` import tkinter as tk root = tk.Tk() root.resizable(width=False, height=False) root.mainloop() ``` Within the program you can change the window dimensions with @Carp...
.pyw tk program closes instantly?
21,959,542
2
2014-02-22T19:44:47Z
21,959,597
7
2014-02-22T19:49:17Z
[ "python", "python-3.x", "tkinter", "tk" ]
I'm just beginning to learn tkinter and I'm missing something fundamental here. When I try to do nothing but create a blank window, I get mixed results. Here's the code: ``` from tkinter import * from tkinter import ttk root = Tk() ``` And what happens is that if I run it in the python shell it works perfectly (like...
The problem is not the file type, as you will be pleased to know. Saving as a `.pyw` just means that the console will not show up when the file is run (no strings attached, the code runs exactly the same)- and there are no exceptions whatever the code may be. What you need to do is add this to the end of your code (th...
Why can't Python increment variable in closure?
21,959,985
4
2014-02-22T20:19:09Z
21,960,034
16
2014-02-22T20:22:48Z
[ "python", "closures" ]
In this code snippet I can print the value of counter from inside the bar function ``` def foo(): counter = 1 def bar(): print("bar", counter) return bar bar = foo() bar() ``` But when I try to increment counter from inside the bar function I get an UnboundLocalError error. ``` UnboundLocalErro...
You can't mutate closure variables in Python 2. In Python 3, which you appear to be using due to your `print()`, you can declare them `nonlocal`: ``` def foo(): counter = 1 def bar(): nonlocal counter counter += 1 print("bar", counter) return bar ``` Otherwise, the assignment within `bar()` makes...
matplotlib plot datetime in pandas DataFrame
21,961,360
9
2014-02-22T22:18:19Z
21,961,491
7
2014-02-22T22:30:24Z
[ "python", "matplotlib", "pandas" ]
I have a pandas DataFrame that looks like this `training.head()` ![enter image description here](http://i.stack.imgur.com/G5PWJ.png) The DataFrame has been sorted by date. I'd like to make a scatterplot where the date of the campaign is on the x axis and the rate of success is on the y axis. I was able to get a line ...
If I remember correctly, the plotting code only considers numeric columns. Internally it selects just the numeric columns, so that's why you get the key error. What's the dtype of `date`? If it's a `datetime64`, you can recast it as an `np.int64`: ``` df['date_int'] = df.date.astype(np.int64) ``` And then you're plo...
How to print all variables values when debugging Python with pdb, without specifying each variable?
21,961,693
23
2014-02-22T22:48:56Z
21,961,813
24
2014-02-22T23:02:34Z
[ "python", "debugging", "pdb" ]
I'm debugging my Python scripts using *pdb* and the manual says I can use **p variables** command to print the values of the specified variables at a certain point. But what if I had lots of variables, like 20 variables, and I would like to track the value of all of them? How do I print all of them without specifying e...
pdb is a fully featured python shell, so you can execute arbitrary commands. `locals()` and `globals()` will display all the variables in scope with their values. You can use `dir()` if you're not interested in the values. When you declare a variable in Python, it's put into locals or globals as appropriate, and the...
Stuffing a pandas DataFrame.plot into a matplotlib subplot
21,962,508
8
2014-02-23T00:20:09Z
21,967,899
12
2014-02-23T12:00:05Z
[ "python", "matplotlib", "pandas" ]
My brain hurts I have some code that produces 33 graphics in one long column ``` #fig,axes = plt.subplots(nrows=11,ncols=3,figsize=(18,50)) accountList = list(set(training.account)) for i in range(1,len(accountList)): training[training.account == accountList[i]].plot(kind='scatter',x='date_int',y='rate',title=ac...
The axes handles that `subplots` returns vary according to the number of subplots requested: * for (1x1) you get a single handle, * for (n x 1 or 1 x n) you get a 1d array of handles, * for (m x n) you get a 2d array of handles. It appears that your problem arises from the change in interface from the 2nd to 3rd case...
Reading from sqlite3 remote databases
21,963,020
3
2014-02-23T01:31:46Z
21,963,088
7
2014-02-23T01:38:52Z
[ "python", "sqlite", "sqlite3" ]
In my server I'm trying to read from a bunch of sqlite3 databases (sent from web clients) and process their data. The db files are in an S3 bucket and I have their url and I can open them in memory. Now the problem is `sqlite3.connect` only takes an absolute path string and I can't pass to it a file in memory. ``` co...
SQLite *requires* database files to be stored on disk (it uses various locks and paging techniques). An in-memory file will not suffice. I'd create a temporary directory to hold the database file, write it to that directory, *then* connect to it. The directory gives SQLite the space to write commit logs as well. To h...
How to execute a python script and write output to txt file?
21,963,270
5
2014-02-23T02:09:09Z
21,963,346
8
2014-02-23T02:20:19Z
[ "python", "output" ]
I'm executing a .py file, which spits out a give string. This command works fine execfile ('file.py') But I want the output (in addition to it being shown in the shell) written into a text file. I tried this, but it's not working :( execfile ('file.py') > ('output.txt') All I get is this: tugsjs6555 False I gue...
what your doing is checking the output of `execfile('file.py')` against the string `'output.txt'` you can do what you want to do with subprocess ``` #!/usr/bin/env python import subprocess with open("output.txt", "w+") as output: subprocess.call(["python", "./script.py"], stdout=output); ```
Timeout for python requests.get entire response
21,965,484
29
2014-02-23T07:36:20Z
21,966,169
20
2014-02-23T08:58:04Z
[ "python", "timeout", "python-requests" ]
I'm gathering statistics on a list of websites and I'm using requests for it for simplicity. Here is my code: ``` data=[] websites=['http://google.com', 'http://bbc.co.uk'] for w in websites: r= requests.get(w, verify=False) data.append( (r.url, len(r.content), r.elapsed.total_seconds(), str([(l.status_code, l...
Set the [timeout parameter](http://docs.python-requests.org/en/latest/api/#requests.request): ``` r = requests.get(w, verify=False, timeout=10) ``` As long as you don't set `stream=True` on that request, this will cause the call to `requests.get()` to timeout if the connection takes more than ten seconds, or if the s...
Timeout for python requests.get entire response
21,965,484
29
2014-02-23T07:36:20Z
22,096,841
33
2014-02-28T13:43:58Z
[ "python", "timeout", "python-requests" ]
I'm gathering statistics on a list of websites and I'm using requests for it for simplicity. Here is my code: ``` data=[] websites=['http://google.com', 'http://bbc.co.uk'] for w in websites: r= requests.get(w, verify=False) data.append( (r.url, len(r.content), r.elapsed.total_seconds(), str([(l.status_code, l...
What about using eventlet? If you want to timeout the request after 10 seconds, even if data is being received, this snippet will work for you: ``` import requests import eventlet eventlet.monkey_patch() with eventlet.Timeout(10): requests.get("http://ipv4.download.thinkbroadband.com/1GB.zip", verify=False) ```
Timeout for python requests.get entire response
21,965,484
29
2014-02-23T07:36:20Z
22,156,618
10
2014-03-03T20:23:12Z
[ "python", "timeout", "python-requests" ]
I'm gathering statistics on a list of websites and I'm using requests for it for simplicity. Here is my code: ``` data=[] websites=['http://google.com', 'http://bbc.co.uk'] for w in websites: r= requests.get(w, verify=False) data.append( (r.url, len(r.content), r.elapsed.total_seconds(), str([(l.status_code, l...
To create a timeout you can use [signals](http://docs.python.org/3.3/library/signal). The best way to solve this case is probably to 1. Set an exception as the handler for the alarm signal 2. Call the alarm signal with a ten second delay 3. Call the function inside a `try-except-finally` block. 4. The except block is...
Python's int function performance
21,966,475
8
2014-02-23T09:30:32Z
21,966,720
10
2014-02-23T09:55:11Z
[ "python", "c", "python-3.x", "int", "python-internals" ]
Does Python's built-in function [int](https://docs.python.org/3/library/functions.html?highlight=int#int) still try to convert the submitted value even if the value is already an integer? More concisely: is there any performance difference between `int('42')` and `int(42)` caused by conversion algorithm?
This is handled in function [`long_long` in `Objects/longobject.c`](http://hg.python.org/cpython/file/d8f48717b74e/Objects/longobject.c#l4302), as explained in more detail by thefourtheye: ``` static PyObject * long_long(PyObject *v) { if (PyLong_CheckExact(v)) Py_INCREF(v); else v = _PyLong_Co...
Python based asynchronous workflow modules : What is difference between celery workflow and luigi workflow?
21,967,398
11
2014-02-23T11:08:42Z
25,704,688
8
2014-09-06T20:58:56Z
[ "python", "celery", "luigi" ]
I am using django as a web framework. I need a workflow engine that can do synchronous as well as asynchronous(batch tasks) chain of tasks. I found celery and luigi as batch processing workflow. My first question is what is the difference between these two modules. Luigi allows us to rerun failed chain of task and onl...
**Disclaimer:** I use Celery almost everyday & I've very little experience with Luigi. **Celery:** *What is Celery?* Celery is a simple, flexible and reliable distributed system to process vast amounts of messages, while providing operations with the tools required to maintain such a system. *Why use Celery?* * It...
Python based asynchronous workflow modules : What is difference between celery workflow and luigi workflow?
21,967,398
11
2014-02-23T11:08:42Z
34,112,320
11
2015-12-05T23:50:07Z
[ "python", "celery", "luigi" ]
I am using django as a web framework. I need a workflow engine that can do synchronous as well as asynchronous(batch tasks) chain of tasks. I found celery and luigi as batch processing workflow. My first question is what is the difference between these two modules. Luigi allows us to rerun failed chain of task and onl...
(I'm the author of Luigi) Luigi is not meant for synchronous low-latency framework. It's meant for large batch processes that run for hours or days. So I think for your use case, Celery might actually be slightly better
how to get user email with python social auth with facebook and save it
21,968,004
12
2014-02-23T12:09:17Z
21,968,367
13
2014-02-23T12:45:54Z
[ "python", "django", "facebook", "python-social-auth" ]
I'm trying to implement [python-social-auth](https://github.com/omab/python-social-auth) in django. I want users to authenticate through facebook and save their email. I'm able to authenticate users but the extended permission for email is not showing up in the facebook authentification box and it's not storing the e...
I think the problem is using FACEBOOK\_EXTENDED\_PERMISSIONS. According to <http://python-social-auth.readthedocs.org/en/latest/backends/facebook.html#oauth2> you should use: `SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']`
how to get user email with python social auth with facebook and save it
21,968,004
12
2014-02-23T12:09:17Z
34,651,518
18
2016-01-07T09:27:52Z
[ "python", "django", "facebook", "python-social-auth" ]
I'm trying to implement [python-social-auth](https://github.com/omab/python-social-auth) in django. I want users to authenticate through facebook and save their email. I'm able to authenticate users but the extended permission for email is not showing up in the facebook authentification box and it's not storing the e...
After some changes in Facebook Login API - Facebook's Graph API v2.4 You will have to add these lines to fetch email ``` SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id,name,email', } ```
What is a "scalar" in numpy?
21,968,643
19
2014-02-23T13:09:50Z
21,968,948
27
2014-02-23T13:40:13Z
[ "python", "numpy", "scipy" ]
[The documentation](http://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#arrays-scalars) states the purpose of scalars, such as the fact that conventional Python numbers like float and integer are too primitive therefore more complex data types are neccessary. It also states certain kinds of scalars(dat...
A NumPy scalar is any object which is an instance of [`np.generic`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.generic.html) or whose `type` is in `np.ScalarType`: ``` In [12]: np.ScalarType Out[13]: (int, float, complex, long, bool, str, unicode, buffer, numpy.int16, numpy.float16, numpy.int...
PyCharm include and modify External library in project
21,970,771
12
2014-02-23T16:12:12Z
21,993,881
19
2014-02-24T16:51:47Z
[ "python", "django", "python-2.7", "ide", "pycharm" ]
I have an issue where I am developing a Django project which includes other libraries we are also developing. My current structure is as follows: * Main Project * + App1 * + App2 --- * Libraries * + Library 1 * + Library 2 All libraries have their own setup scripts and are in separate git repositories, and we are ...
Well, you can add other directories as content roots: ![enter image description here](http://i.stack.imgur.com/Qe2Cv.png) Then simply mark the directory as a source root: ![enter image description here](http://i.stack.imgur.com/AIn5h.png) This should allow you to refactor, rename and do all the things you've wanted...
How do I increase the cell width of the ipython notebook in my browser?
21,971,449
58
2014-02-23T17:08:18Z
21,975,477
7
2014-02-23T22:22:36Z
[ "python", "ipython", "ipython-notebook", "jupyter" ]
I would like to increase the width of the ipython notebook in my browser. I have a high-resolution screen, and I would like to expand the cell width/size to make use of this extra space. Thanks!
You can set the CSS of a notebook by calling a stylesheet from any cell. As an example, take a look at the [12 Steps to Navier Stokes course](https://bitbucket.org/cfdpython/cfd-python-class/overview). In particular, creating a file containing ``` <style> div.cell{ width:100%; margin-left:1%; ...
How do I increase the cell width of the ipython notebook in my browser?
21,971,449
58
2014-02-23T17:08:18Z
24,207,353
88
2014-06-13T14:08:29Z
[ "python", "ipython", "ipython-notebook", "jupyter" ]
I would like to increase the width of the ipython notebook in my browser. I have a high-resolution screen, and I would like to expand the cell width/size to make use of this extra space. Thanks!
That `div.cell` solution didn't actually work on my IPython, however luckily someone suggested a working solution for new IPythons: Create a file `~/.ipython/profile_default/static/custom/custom.css` (iPython) or `~/.jupyter/custom/custom.css` (Jupyter) with content ``` .container { width:100% !important; } ``` Then...
How do I increase the cell width of the ipython notebook in my browser?
21,971,449
58
2014-02-23T17:08:18Z
34,058,270
54
2015-12-03T05:06:51Z
[ "python", "ipython", "ipython-notebook", "jupyter" ]
I would like to increase the width of the ipython notebook in my browser. I have a high-resolution screen, and I would like to expand the cell width/size to make use of this extra space. Thanks!
If you don't want to change your default settings, and you only want to change the width of the current notebook you're working on, you can enter the following into a cell: ``` from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) ```
How do I increase the cell width of the ipython notebook in my browser?
21,971,449
58
2014-02-23T17:08:18Z
35,342,269
16
2016-02-11T14:38:53Z
[ "python", "ipython", "ipython-notebook", "jupyter" ]
I would like to increase the width of the ipython notebook in my browser. I have a high-resolution screen, and I would like to expand the cell width/size to make use of this extra space. Thanks!
To get this to work with jupyter (version 4.0.6) I created `~/.jupyter/custom/custom.css` containing: ``` /* Make the notebook cells take almost all available width */ .container { width: 99% !important; } /* Prevent the edit cell highlight box from getting clipped; * important so that it also works when cell...
BeautifulSoup - scraping a forum page
21,972,690
4
2014-02-23T18:38:52Z
21,978,029
7
2014-02-24T02:46:38Z
[ "python", "beautifulsoup", "screen-scraping" ]
I'm trying to scrape a forum discussion and export it as a csv file, with rows such as "thread title", "user", and "post", where the latter is the actual forum post from each individual. I'm a complete beginner with Python and BeautifulSoup so I'm having a really hard time with this! My current problem is that all th...
Ok here we go. Not quite sure what I'm helping you do here, but hopefully you have a good reason to be analyzing silk road posts. You have a few issues here, the big one is that you aren't parsing the data at all. **What you're essentially doing with .get\_text() is going to the page, highlighting the whole thing, and...
How to disable query cache with mysql.connector
21,974,169
4
2014-02-23T20:35:43Z
21,974,489
8
2014-02-23T21:03:00Z
[ "python", "mysql", "mysql-python", "kivy" ]
I'm connecting mysql on my Kivy application. ``` import mysql.connector con = mysql.connector.Connect(host='XXX', port=XXX, user='XXX', password='XXX', database='XXX') cur = con.cursor() db = cur.execute("""select SELECT SQL_NO_CACHE * from abc""") data = cur.fetchall() print (data) ``` After inserting or deleting on...
I solved this with adding the code after fetchall() ``` con.commit() ``` Calling the same select query without doing a commit, won't update the results.
Active Django settings file from Celery worker
21,975,666
5
2014-02-23T22:41:16Z
26,106,063
13
2014-09-29T18:03:32Z
[ "python", "django", "celery", "django-celery" ]
So I already looked around a lot for this but couldn't find a good answer. I'm using Celery 3.1.7 and Django 1.5.1., without django-celery package since newer versions of Celery don't require it anymore. I managed to set up tasks and execute them using RabbitMQ. Everything is working as it should there. However, I am i...
When initializing the celery worker on the command line, just set the environment variable prior to the celery command. `DJANGO_SETTINGS_MODULE='proj.settings' celery -A proj worker -l info`
Peewee model to JSON
21,975,920
7
2014-02-23T23:06:38Z
21,979,166
16
2014-02-24T04:55:13Z
[ "python", "json", "peewee" ]
I'm creating an API using peewee as the ORM and I need the ability to convert a peewee model object into a JSON object to send to the user. Does anyone know of a good way to do this?
Peewee has a `model_to_dict` and `dict_to_model` helpers in the `playhouse.shortcuts` extension module. * <http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#model_to_dict> * <http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#dict_to_model> You could use these as follows: ``` from playhouse.shortcut...
Django Error: OperationalError: no such table: polls_poll
21,976,383
3
2014-02-23T23:49:06Z
23,184,956
9
2014-04-20T16:42:02Z
[ "python", "django", "shell", "sqlite3" ]
Going through Django tutorial 1 using Python 2.7 and can't seem to resolve this error: **OperationalError: no such table: polls\_poll** This happens the moment I enter `Poll.objects.all()` into the shell. Things I've already tried based on research through the net: 1) Ensured that `'polls'` is listed under `INSTALLE...
I meet the same problem today and fix it I think you miss some command in tutorial 1 just do follow: `./python manage.py makemigrations polls` `python manage.py sql polls` `./python manage.py syncdb` then fix it and gain the table polls and you can see the table created you should read the "manage.py makemigrations"...
how to convert list to dict of index and data in one line(for use in lambda)
21,976,556
2
2014-02-24T00:09:06Z
21,976,560
7
2014-02-24T00:09:46Z
[ "python", "dictionary" ]
I have a list ``` a = ['a','b','c','d'] ``` I want to convert to following format ``` {0:'a', 1:'b', 2:'c', 3:'d' } ``` Can somebody tell me how to do this ?
Use [`dict`](http://docs.python.org/3/library/functions.html#func-dict) and [`enumerate`](http://docs.python.org/3/library/functions.html#enumerate): ``` >>> a = ['a','b','c','d'] >>> dict(enumerate(a)) {0: 'a', 1: 'b', 2: 'c', 3: 'd'} >>> ```
Using grequests to make several thousand get requests to sourceforge, get "Max retries exceeded with url"
21,978,115
17
2014-02-24T02:55:33Z
22,839,550
16
2014-04-03T13:39:34Z
[ "python", "http-get", "grequests" ]
I am very new to all of this; I need to obtain data on several thousand sourceforge projects for a paper I am writing. The data is all freely available in json format at the url http://sourceforge.net/api/project/name/[project name]/json. I have a list of several thousand of these URL's and I am using the following cod...
So, I'm answering here, maybe it will help others. In my case, it was not rate limiting by the destination server, but something much simpler: I didn't explicitly close the responses, so they were keeping the socket open, and the python process ran out of file handles. My solution (don't know for sure which one fixed...
Improving Python NetworkX graph layout
21,978,487
11
2014-02-24T03:40:54Z
21,990,980
24
2014-02-24T14:44:38Z
[ "python", "networkx" ]
I am having some problems in visualizing the graphs created with python-networkx, I want to able to reduce clutter and regulate the distance between the nodes (I have also tried spring\_layout, it just lays out the nodes in an elliptical fashion). Please advise. ![enter image description here](http://i.stack.imgur.com/...
In networkx, it's worth checking out the graph drawing algorithms provided by [graphviz](http://www.graphviz.org/) via [`nx.graphviz_layout`](http://networkx.lanl.gov/reference/generated/networkx.drawing.nx_agraph.graphviz_layout.html). I've had good success with `neato` but the other possible inputs are * `dot` - "h...
Select integers from a given range
21,979,979
3
2014-02-24T05:59:12Z
21,980,041
7
2014-02-24T06:03:08Z
[ "python" ]
I need to select 6 integers from `range(1, 51)` such that no two consecutive integers are selected. `(1, 3, 6, 9, 13, 28)` is a valid selection but `(1, 3, 4, 9, 13, 28)` is not. I need to build a list of all such possible combinations, with each combination in a tuple. Instead of a list a generator will also do. I und...
You can use `all` with a generator expression: ``` >>> t = (1,3,4,9,13,28) >>> all( x-y > 1 for x, y in zip(t[1:], t)) False >>> t = (1,3,6,9,13,28) >>> all( x-y > 1 for x, y in zip(t[1:], t)) True ``` **Code:** ``` import itertools for t in itertools.combinations(range(1, 20), 6): if all( x-y > 1 for x, y in zi...
Calculate cosine similarity of two matrices - Python
21,980,644
2
2014-02-24T06:42:56Z
21,980,844
7
2014-02-24T06:55:07Z
[ "python", "numpy", "matrix", "cosine-similarity" ]
I have defined two **matrices** like following: ``` from scipy import linalg, mat, dot a = mat([-0.711,0.730]) b = mat([-1.099,0.124]) ``` Now, I want to calculate the cosine similarity of these two **matrices**. What is the wrong with following code. It gives me an error of `objects are not aligned` ``` c = dot(a,b...
You cannot multiply 1x2 matrix by 1x2 matrix. In order to calculate dot product between their rows the second one has to be transposed. ``` from scipy import linalg, mat, dot a = mat([-0.711,0.730]) b = mat([-1.099,0.124]) c = dot(a,b.T)/linalg.norm(a)/linalg.norm(b) ```
How to change size of bokeh figure
21,980,662
11
2014-02-24T06:43:48Z
22,005,949
12
2014-02-25T06:06:26Z
[ "python", "plot", "bokeh" ]
I have read most of the documentation on bokeh and many of the examples. All of them contain the default square window. The only example I have seen that is the slightly different is [here](http://bokeh.pydata.org/plot_gallery/iris_splom.html) which has subplots and sets height and width in the creation of a Plot objec...
If you've already created the plot, then you can use the `bokeh.plotting.curplot()` function to return the "current" plot, and then set its `height` and `width` attributes. If you are building up a `Plot` object using the lower-level interfaces (e.g. the examples in `bokeh/examples/glyph/`, then you can just set those ...
How to avoid defensive if conditions in python?
21,981,147
4
2014-02-24T07:13:01Z
21,981,196
9
2014-02-24T07:15:28Z
[ "python", "defensive-programming" ]
I am writing a code which tries to dig deep into the input object and find out a value lying inside that object. Here is a sample code: ``` def GetThatValue(inObj): if inObj: level1 = inObj.GetBelowObject() if level1: level2 = level1.GetBelowObject() if level2: le...
Using `for` loop: ``` def GetThatValue(inObj): for i in range(4): if not inObj: break # OR return None inObj = inObj.GetBelowObject() return inObj ``` **UPDATE** To avoid deeply nested if statements. Check the exceptional case, and return earlier. For example, following nested `i...
Is a generator the callable? Which is the generator?
21,982,118
8
2014-02-24T08:07:19Z
21,982,504
10
2014-02-24T08:30:11Z
[ "python", "generator", "callable" ]
> A generator is simply a function which returns an object on which you can call next, such that for every call it returns some value, until it raises a StopIteration exception, signaling that all values have been generated. Such an object is called an iterator. ``` >>> def myGen(n): ... yield n ... yield n + ...
The terminology is unfortunately confusing, as "generator" is so commonly used to refer to either the function or the returned iterator that it's hard to say one usage is more correct. The [documentation of the yield statement](http://docs.python.org/2/reference/simple_stmts.html#the-yield-statement) says > The yield ...
How to get the call count using Mock @patch?
21,982,964
5
2014-02-24T08:55:47Z
21,983,089
15
2014-02-24T09:02:15Z
[ "python", "unit-testing", "mocking" ]
I am writing a unit test for some library we are working on. This library makes use of `requests.post()` to perform POST HTTP requests to an external server. Inside my UT, I obviously don't want to contact the real server but to mock the response. To do that, I wrote a function that goes like: ``` def mocked_post(ur...
I'd not use `mocked_post` as the `new` argument here. I'd set up the [`side_effect` attribute](http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.side_effect) of a fresh `Mock` instead: ``` @patch('mylib.requests.post') class MyTest(TestCase): def test_foo(self, post_mock): post_mock.side_effect ...
How to pass dictionary items as function arguments in python?
21,986,194
15
2014-02-24T11:17:21Z
21,986,301
28
2014-02-24T11:22:17Z
[ "python", "function", "python-2.7", "dictionary" ]
My code 1st file: ``` data = {'school':'DAV', 'standard': '7', 'name': 'abc', 'city': 'delhi'} my_function(*data) ``` 2nd file: ``` my_function(*data): schoolname = school cityname = city standard = standard studentname = name ``` in the above code, only keys of "data" dictionary were get passed t...
If you want to use them like that, define the function with the variable names as normal (but use `klass` for `class`, you can't use reserved words): ``` def my_function(school, city, klass, name): schoolname = school cityname = city standard = klass studentname = name ``` Now (as long as you rename ...
How to pass dictionary items as function arguments in python?
21,986,194
15
2014-02-24T11:17:21Z
21,986,334
12
2014-02-24T11:23:31Z
[ "python", "function", "python-2.7", "dictionary" ]
My code 1st file: ``` data = {'school':'DAV', 'standard': '7', 'name': 'abc', 'city': 'delhi'} my_function(*data) ``` 2nd file: ``` my_function(*data): schoolname = school cityname = city standard = standard studentname = name ``` in the above code, only keys of "data" dictionary were get passed t...
\*data interprets arguments as tuples, instead you have to pass \*\*data which interprets the arguments as dictionary. ``` data = {'school':'DAV', 'class': '7', 'name': 'abc', 'city': 'pune'} def my_function(**data): schoolname = data['school'] cityname = data['city'] standard = data['class'] studen...
Legend only shows one label when plotting with pandas
21,988,196
12
2014-02-24T12:44:55Z
21,989,204
17
2014-02-24T13:28:19Z
[ "python", "matplotlib", "plot", "pandas" ]
I have two Pandas DataFrames that I'm hoping to plot in single figure. I'm using IPython notebook. I would like the legend to show the label for both of the DataFrames, but so far I've been able to get only the latter one to show. Also any suggestions as to how to go about writing the code in a more sensible way would...
This is indeed a bit confusing. I think it boils down to how Matplotlib handles the secondary axes. Pandas probably calls `ax.twinx()` somewhere which superimposes a secondary axes on the first one, but this is actually a separate axes. Therefore also with separate lines & labels and a separate legend. Calling `plt.leg...
Finding index of maximum value in array with NumPy
21,989,513
12
2014-02-24T13:41:26Z
21,991,653
16
2014-02-24T15:16:32Z
[ "python", "arrays", "numpy", "max" ]
I would like to find a maximum in a `float64` array, excluding `nan` values. I saw `np.nanmax` function but it doesn't give the index corresponding to the found value. it 's quite strange to scan after to the value specially the function necessarily use the index ??? Can't it be a mistake searching like that . isn't...
Numpy has an `argmax` function that returns just that, although you will have to deal with the `nan`s manually. `nan`s always get sorted to the end of an array, so with that in mind you can do: ``` a = np.random.rand(10000) a[np.random.randint(10000, size=(10,))] = np.nan a = a.reshape(100, 100) def nanargmax(a): ...
Python a, b = b, a +b
21,990,883
3
2014-02-24T14:40:59Z
21,990,952
12
2014-02-24T14:43:44Z
[ "python" ]
This is my first question and i started to learn Python so i will just ask. Is there difference between: ``` a, b = b, a + b and a = b b = a + b ``` when you write it in below example it shows different results. ``` def fib(n): a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a + b ...
The line: ``` a, b = b, a + b ``` is closer to: ``` temp_a = a a = b b = temp_a + b ``` where `b` is using the *old* value of `a` before `a` was reassigned to the value of `b`. Python first evaluates the right-hand expression and stores the results on the stack, then takes those two values and assigns them to `a` ...
Python a, b = b, a +b
21,990,883
3
2014-02-24T14:40:59Z
21,990,958
17
2014-02-24T14:43:55Z
[ "python" ]
This is my first question and i started to learn Python so i will just ask. Is there difference between: ``` a, b = b, a + b and a = b b = a + b ``` when you write it in below example it shows different results. ``` def fib(n): a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a + b ...
In `a, b = b, a + b`, the expressions on the right hand side are evaluated before being assigned to the left hand side. So it is equivalent to: ``` c = a + b a = b b = c ``` In the second example, the value of `a` has already been changed by the time `b = a + b` is run. Hence, the result is different.
Sort list of objects with Jinja2 and Flask depending the field pressed
21,990,914
4
2014-02-24T14:42:16Z
21,991,025
9
2014-02-24T14:46:32Z
[ "javascript", "python", "sorting", "flask", "jinja2" ]
I have a model in Flask called Dog, with the parameters Name, Breed and Age. Through Jinja2 I show them in a template as follow: ``` <table> <tr> <td>Name</td> <td>Breed</td> <td>Age</td> </tr> {% for dog in dogs_list %} <tr> <td>{{ dog.name }}</td> <td>{{ dog.breed }}</td> <td>{{ dog.age }}</td> </tr> {% endfor %} </...
The attribute does not need to be a fixed string, it can be a request parameter too: ``` {% set sort_on = request.args.sort_on|default('name') %} {% for dog in dogs_list|sort(attribute=sort_on) %} ``` This looks for a GET parameter `sort_on` (defaulting to `'name'`), then uses that value to sort the `dogs_list`.
How can I create several websocket chats in Tornado?
21,991,348
3
2014-02-24T15:01:30Z
22,047,070
8
2014-02-26T16:16:51Z
[ "python", "html5", "websocket", "tornado" ]
I am trying to create a Tornado application with several chats. The chats should be based on HTML5 websocket. The Websockets communicate nicely, but I always run into the problem that each message is posted twice. The application uses four classes to handle the chat: * `Chat` contains all written messages so far and ...
If you want to create a multi-chat application based on Tornado I recommend you use some kind of message queue to distribute new message. This way you will be able to launch multiple application process behind a load balancer like nginx. Otherwise you will be stuck to one process only and thus be severely limited in sc...
What is django.utils.datetime_safe and should I use it instead of standard datetime?
21,991,666
5
2014-02-24T15:16:55Z
21,991,735
8
2014-02-24T15:19:44Z
[ "python", "django", "datetime" ]
What are the differences? Is it safer to use `datetime_safe`? I can't find any documentation on this class.
The difference is noted in the source code for `datetime_safe`: ``` # Python's datetime strftime doesn't handle dates before 1900. # These classes override date and datetime to support the formatting of a date # through its full "proleptic Gregorian" date range. ``` Huh.
Binding a PyQT/PySide widget to a local variable in Python
21,992,849
7
2014-02-24T16:08:40Z
21,993,853
12
2014-02-24T16:50:45Z
[ "python", "pyqt", "dependency-properties", "pyside" ]
I'm pretty new to PySide/PyQt, I'm coming from C#/WPF. I've googled alot on this topic but it no good answer seems to show up. Ii want to ask is there a way where I can bind/connect a QWidget to a local variable, whereby each object update themselves on change. Example: If I have a `QLineEdit` and I have a local vari...
You're asking for two different things here. 1. You want to have a plain python object, `self.name` subscribe to changes on a `QLineEdit`. 2. You want to have your `QLineEdit` subscribe to changes on a plain python object `self.name`. Subscribing to changes on `QLineEdit` is easy because that's what the Qt signal/slo...
abs() vs fabs() speed difference and advantage of fabs()
21,994,052
16
2014-02-24T16:58:54Z
21,994,207
16
2014-02-24T17:06:43Z
[ "python", "function", "absolute-value" ]
I ran some simple tests on abs() and fabs() functions and I don't understand what are the advantages of using fabs(), if it is: 1) slower 2) works only on floats 3) will throw an exception if used on a different type ``` In [1]: %timeit abs(5) 10000000 loops, best of 3: 86.5 ns per loop In [3]: %timeit fabs(5) 100...
From [an email response](https://mail.python.org/pipermail/python-dev/2005-July/054993.html) from [Tim Peters](http://stackoverflow.com/users/2705542/tim-peters): > > Why does math have an fabs function? Both it and the abs builtin function > > wind up calling fabs() for floats. abs() is faster to boot. > > Nothing de...
Python Social Auth Django template example
21,995,917
16
2014-02-24T18:26:01Z
22,435,656
13
2014-03-16T10:24:27Z
[ "python", "django", "django-templates", "python-social-auth" ]
Does someone has an open example using [Python Social Auth](http://python-social-auth.readthedocs.org/) with Django in templates? I took a look in their Github repo, and in the django exmaple, there is nothing about how to deal with it in templates (e.g. doing login, logout, etc).
Inside the python-social-auth there is an example. You just need to install python-social-auth, configure your database and your facebook app or another social app and put your Secret and key in settings.py file and run the application. There is a template with template tags and much more. Click here: <https://github.c...
Python Social Auth Django template example
21,995,917
16
2014-02-24T18:26:01Z
24,415,355
7
2014-06-25T17:51:15Z
[ "python", "django", "django-templates", "python-social-auth" ]
Does someone has an open example using [Python Social Auth](http://python-social-auth.readthedocs.org/) with Django in templates? I took a look in their Github repo, and in the django exmaple, there is nothing about how to deal with it in templates (e.g. doing login, logout, etc).
I found this tutorial most helpful: <http://www.artandlogic.com/blog/2014/04/tutorial-adding-facebooktwittergoogle-authentication-to-a-django-application/> The example application in python-social-auth is comparatively terse and difficult to follow.
Python Social Auth Django template example
21,995,917
16
2014-02-24T18:26:01Z
24,452,183
30
2014-06-27T12:45:55Z
[ "python", "django", "django-templates", "python-social-auth" ]
Does someone has an open example using [Python Social Auth](http://python-social-auth.readthedocs.org/) with Django in templates? I took a look in their Github repo, and in the django exmaple, there is nothing about how to deal with it in templates (e.g. doing login, logout, etc).
Let’s say you followed Python Social Auth configuration guidelines at <http://psa.matiasaguirre.net/docs/configuration/django.html> and you want using facebook login. Your backend settings in settings.py should look: ``` AUTHENTICATION_BACKENDS = ( 'social.backends.facebook.FacebookOAuth2', 'django.contrib.auth.back...
Join multiple tables in SQLAlchemy/Flask
21,996,288
11
2014-02-24T18:45:24Z
22,005,769
12
2014-02-25T05:54:15Z
[ "python", "join", "sqlalchemy", "flask" ]
I am trying to figure out the correct join query setup within SQLAlchemy, but I can't seem to get my head around it. I have the following table setup (simplified, I left out the non-essential fields): ``` class Group(db.Model): id = db.Column(db.Integer, primary_key = True) number = db.Colum...
Following will give you the objects you need in one query: ``` q = (session.query(Group, Member, Item, Version) .join(Member) .join(Item) .join(Version) .filter(Version.name == my_version) .order_by(Group.number) .order_by(Member.number) ).all() print_tree(q) ```...
Combining logic statements AND in numpy array
21,996,661
4
2014-02-24T19:07:38Z
21,996,748
7
2014-02-24T19:11:35Z
[ "python", "arrays", "numpy" ]
What would be the way to select elements when two conditions are `True` in a matrix? In R, it is basically possible to combine vectors of booleans. So what I'm aiming for: ``` A = np.array([2,2,2,2,2]) A < 3 and A > 1 # A < 3 & A > 1 does not work either ``` Evals to: ValueError: The truth value of an array with mo...
you could just use `&`, eg: ``` x = np.arange(10) (x<8) & (x>2) ``` gives ``` array([False, False, False, True, True, True, True, True, False, False], dtype=bool) ``` A few details: * This works because `&` is shorthand for the numpy ufunc `bitwise_and`, which for the `bool` type is the same as `logical_and`....
Combining logic statements AND in numpy array
21,996,661
4
2014-02-24T19:07:38Z
21,996,749
8
2014-02-24T19:11:36Z
[ "python", "arrays", "numpy" ]
What would be the way to select elements when two conditions are `True` in a matrix? In R, it is basically possible to combine vectors of booleans. So what I'm aiming for: ``` A = np.array([2,2,2,2,2]) A < 3 and A > 1 # A < 3 & A > 1 does not work either ``` Evals to: ValueError: The truth value of an array with mo...
There's a function for that: ``` In [8]: np.logical_and(A < 3, A > 1) Out[8]: array([ True, True, True, True, True], dtype=bool) ``` Since you can't override the `and` operator in Python it always tries to cast its arguments to `bool`. That's why the code you have gives an error. Numpy has defined the `__and__` ...
Changing what the ends of whiskers represent in matplotlib's boxplot function
21,997,897
7
2014-02-24T20:07:34Z
21,998,600
10
2014-02-24T20:45:01Z
[ "python", "matplotlib" ]
I understand that the ends of whiskers in matplotlib's box plot function extend to max value below 75% + 1.5 IQR and minimum value above 25% - 1.5 IQR. I would like to change it to represent max and minimum values of the data or the 5th and 95th quartile of the data. Is is possible to do this?
To get the whiskers to appear at the min and max of the data, set the `whis` parameter to an arbitrarily large number. In other words: `boxplots = ax.boxplot(myData, whis=np.inf)`. The `whis` kwarg is a scaling factor of the interquartile range. Whiskers are drawn to the outermost data points within `whis * IQR` away ...
How to make an optional value for argument using argparse?
21,997,933
22
2014-02-24T20:09:17Z
21,998,252
26
2014-02-24T20:25:22Z
[ "python", "python-3.x", "argparse" ]
I am creating a python script where I want to have an argument that manipulates how many search results you get as output. I've currently named the argument `--head`. This is the functionality I'd like it to have: 1. When `--head` is not passed at the command line I'd like it to default to one value. In this case, a r...
After a little more reading in the documentation I found what I needed: `nargs='?'`. This is used with the `store` action, and does exactly what I want. Here is an example: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument('--head', dest='size', const=1...
How to show data labels when you mouse over data
21,998,663
3
2014-02-24T20:48:24Z
22,002,324
8
2014-02-25T00:42:49Z
[ "python", "pandas", "matplotlib" ]
I am plotting some data that looks like ``` 931,Oxfordshire,9314125,123255,Larkmead School,Abingdon,125,124,20,SUPP,8 931,Oxfordshire,9314126,123256,John Mason School,Abingdon,164,164,25,6,16 931,Oxfordshire,9314127,123257,Fitzharrys School,Abingdon,150,149,9,0,11 931,Oxfordshire,9316076,123298,Our Lady's Abingdon,Abi...
Just to plug my own project, have a look at `mpldatacursor`: <https://github.com/joferkington/mpldatacursor> As a basic example, just calling `datacursor(hover=True, point_labels=df['E'])` will get you 90% of the way to what you want. For example, taking your code snippet above: ``` from StringIO import StringIO impo...
beautiful soup just get the value inside the tag
22,003,302
2
2014-02-25T02:15:38Z
22,003,368
7
2014-02-25T02:22:47Z
[ "python", "beautifulsoup" ]
The following command: ``` volume = soup.findAll("span", {"id": "volume"})[0] ``` gives: ``` <span class="gr_text1" id="volume">16,103.3</span> ``` when I issue a print(volume). How do I get just the number?
Extract the string from the element: ``` volume = soup.findAll("span", {"id": "volume"})[0].string ```
Get virtualenv's bin folder path from script
22,003,769
12
2014-02-25T03:06:02Z
22,004,069
27
2014-02-25T03:38:13Z
[ "python", "django", "virtualenv", "virtualenvwrapper" ]
I'm using virtualenvwrapper with a django project that has a management task that automatically writes some config files, so the user just has to ``` ./manage.py generate_configuration > much_nice.conf ``` And then move the file elsewhere. One of the generated config files is a task for supervisord that launches a ce...
The path to the virtual env is in the environment variable VIRTUAL\_ENV ``` echo $VIRTUAL_ENV ```
webbrowser.open() in python
22,004,498
5
2014-02-25T04:20:39Z
22,004,572
8
2014-02-25T04:26:05Z
[ "python", "html" ]
I have a python file `html_gen.py` which write a new `html` file `index.html` in the same directory, and would like to open up the `index.html` when the writing is finished. So I wrote ``` import webbrowser webbrowser.open("index.html"); ``` But nothing happen after executing the .py file. If I instead put a code `...
Try specifying the "file://" at the start of the URL. Also, use the absolute path of the file: ``` webbrowser.open('file://' + os.path.realpath(filename)) ```
Convert Columns to String in Pandas
22,005,911
24
2014-02-25T06:03:30Z
22,006,514
42
2014-02-25T06:38:55Z
[ "python", "numpy", "pandas" ]
I have the following DataFrame from a SQL query: ``` (Pdb) pp total_rows ColumnID RespondentCount 0 -1 2 1 3030096843 1 2 3030096845 1 ``` and I want to pivot it like this: ``` total_data = total_rows.pivot_table(cols=['ColumnID']) (Pdb) pp total_data Co...
One way to convert to string is to use [astype](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html): ``` total_rows['ColumnID'] = total_rows['ColumnID'].astype(str) ``` However, perhaps you are looking for the [`to_json`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFr...
python get module variable by name
22,011,073
5
2014-02-25T10:17:45Z
22,011,250
10
2014-02-25T10:23:53Z
[ "python", "variables", "module" ]
I'm trying to find a way to access module variable by name, but haven't found anything yet. The thing I'm using now is: ``` var = eval('myModule.%s' % (variableName)) ``` but it's fuzzy and breaks IDE error checking (i.e. in eclipse/pydev import myModule is marked as unused, while it's needed for above line). Is ther...
``` import mymodule var = getattr(mymodule, variablename) ```
Get the parameters of a JavaScript function with Scrapy
22,011,481
6
2014-02-25T10:32:53Z
26,738,593
11
2014-11-04T15:13:27Z
[ "javascript", "python", "web-scraping", "scrapy" ]
I was wondering if it is possible to extract the parameters of a JavaScript function with Scrapy, from a code similar to this one: ``` <script type="text/javascript"> var map; function initialize() { var fenway = new google.maps.LatLng(43.2640611,2.9388228); }; } </script> ``` I would like to extract the ...
This is where [`re()`](http://doc.scrapy.org/en/latest/topics/selectors.html#scrapy.selector.Selector.re) method would help. The idea is to locate the `script` tag via `xpath()` and use `re()` to extract the `lat` and `lng` from the `script` tag's contents. Demo from the [`scrapy shell`](http://doc.scrapy.org/en/lates...