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
Why do python instances have no __name__ attribute?
14,514,838
8
2013-01-25T03:24:26Z
14,514,930
12
2013-01-25T03:37:35Z
[ "python" ]
``` >>> class Foo: ... 'it is a example' ... print 'i am here' ... i am here >>> Foo.__name__ 'Foo' >>> Foo().__name__ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: Foo instance has no attribute '__name__' >>> Foo.__doc__ 'it is a example' >>> Foo().__doc__ 'it is a examp...
You're seeing an artifact of the implementation of classes and instances. The `__name__` attribute isn't stored in the class dictionary; therefore, it can't be seen from a direct instance lookup. Look at `vars(Foo)` to see that only `__module__` and `__doc__` are in the class dictionary and are visible to the instance...
Confused by lexical closure in list comprehension
14,514,922
4
2013-01-25T03:35:32Z
14,514,938
8
2013-01-25T03:38:13Z
[ "python" ]
``` l = [1, 2, 3] a,b,c = [lambda: n*n for n in l] a() #=> 9 b() #=> 9 c() #=> 9 ``` Why is this? I expected a(), b(), c(), to be 1, 4, and 9.
`n` isn't in a local closure of the functions. try ``` a, b, c = [lambda n=n: n*n for n in l] ``` This "abuse" of the default parameter causes a local variable called `n` to be created for each function Here is another way to create a closure in Python2 ``` >>> L=[1, 2, 3] >>> def fgen(): ... local_n = global_...
Python Opencv SolvePnP yields wrong translation vector
14,515,200
11
2013-01-25T04:11:00Z
14,543,277
16
2013-01-27T00:51:03Z
[ "python", "opencv", "camera-calibration" ]
I am attempting to calibrate and find the location and rotation of a single virtual camera in Blender 3d using homography. I am using Blender so that I can double check my results before I move on to the real world where that is more difficult. I rendered ten pictures of a chess board in various locations and rotations...
I think you may be thinking of `tvecs_new` as the camera position. Slightly confusingly that is not the case! In fact its the position of the world origin in camera co-ords. To get the camera pose in the object/world co-ords, I believe you need to do: ``` `-np.matrix(rotation_matrix).T * np.matrix(tvecs_new)` ``` And...
How to save "complete webpage" not just basic html using Python
14,516,590
15
2013-01-25T06:34:28Z
14,517,464
13
2013-01-25T07:43:01Z
[ "python", "html", "python-2.7", "urllib2", "urllib" ]
I am using following code to save webpage using Python: ``` import urllib import sys from bs4 import BeautifulSoup url = 'http://www.vodafone.de/privat/tarife/red-smartphone-tarife.html' f = urllib.urlretrieve(url,'test.html') ``` **Problem**: This code saves html as basic html without javascripts, images etc. I wan...
Try emulating your browser with [selenium](http://pypi.python.org/pypi/selenium). This script will pop up the `save as` dialog for the webpage. You will still have to figure out how to emulate pressing enter for download to start as the file dialog is out of selenium's reach (how you do it is also OS dependent). ``` f...
How do I test for exceptions in if-statements in python?
14,516,873
2
2013-01-25T06:56:47Z
14,516,917
9
2013-01-25T06:59:36Z
[ "python", "function", "exception", "if-statement" ]
i want to write a function to report the different results from another function there are some exceptions among these results but I cannot convert them into if statement example : > if f(x) raise a ValueError, then my function has to return a string > 'Value' if f(x) raise a TypeError, then my function has to return...
You have [`try-except`](http://docs.python.org/2/tutorial/errors.html#handling-exceptions) to handle exceptions in Python: - ``` def reporter(f,x): try: if f(x): # f(x) is not None and not throw any exception. Your last case return "Generic" # f(x) is `None` retur...
Correct way to use scipy.signal.spectral.lombscargle
14,518,970
6
2013-01-25T09:34:38Z
14,527,096
9
2013-01-25T17:23:48Z
[ "python", "numpy", "scipy", "signal-processing", "scientific-computing" ]
I'm refering to the following post : [Using scipy.signal.spectral.lombscargle for period discovery](http://stackoverflow.com/questions/13349181/using-scipy-signal-spectral-lombscargle-for-period-discovery) I realize the answer given correct for certain case. ## Frequency for sin(x), which is 1/(2\* pi) ``` # imports...
You are rightfully expecting the peak to show up at `1 / pi`, but the highest frequency you are testing is `1 / 2 / pi`... Try the following single change : ``` freqs = linspace(0.01, 3, 3000) ``` and now the output is the expected: ``` 1/pi = 0.318309886184 Frequency = 0.318311478264 ``` Note, though, that if you ...
Python exception handling - line number
14,519,177
19
2013-01-25T09:47:56Z
14,519,268
13
2013-01-25T09:53:29Z
[ "python", "exception", "indexing" ]
I'm using python to evaluate some measured data. Because of many possible results it is difficult to handle or possible combinations. Sometimes an error happens during the evaluation. It is usually an index error because I get out of range from measured data. It is very difficult to find out on which place in code the...
To simply get the line number you can use `sys`, if you would like to have more, try the [traceback](http://docs.python.org/2/library/traceback.html) module. ``` import sys try: [][2] except IndexError: print 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) ``` *prints*: ``` Error on line 3 ``` -...
Python exception handling - line number
14,519,177
19
2013-01-25T09:47:56Z
20,264,059
30
2013-11-28T10:50:36Z
[ "python", "exception", "indexing" ]
I'm using python to evaluate some measured data. Because of many possible results it is difficult to handle or possible combinations. Sometimes an error happens during the evaluation. It is usually an index error because I get out of range from measured data. It is very difficult to find out on which place in code the...
Solution, printing filename, linenumber, line itself and exception descrition: ``` import linecache import sys def PrintException(): exc_type, exc_obj, tb = sys.exc_info() f = tb.tb_frame lineno = tb.tb_lineno filename = f.f_code.co_filename linecache.checkcache(filename) line = linecache.getl...
Algorithm for generating a 3D Hilbert space-filling curve in Python
14,519,267
7
2013-01-25T09:53:26Z
14,519,455
8
2013-01-25T10:03:21Z
[ "python", "algorithm", "3d", "hilbert-curve" ]
I'd like to map points in a RGB color cube to a one-dimensional list in Python, in a way that makes the list of colors look nice and continuous. I believe using a 3D Hilbert space-filling curve would be a good way to do this, but I've searched and haven't found very helpful resources for this problem. Wikipedia in par...
This paper seems to have quite a discussion: [An inventory of three-dimensional Hilbert space-filling curves](http://arxiv.org/abs/1109.2323). Quoting from the abstract: > Hilbert's two-dimensional space-filling curve is appreciated for its > good locality properties for many applications. However, it is not > clear ...
Python 2.7 or 3.3 for learning Django
14,519,625
8
2013-01-25T10:13:43Z
14,519,663
7
2013-01-25T10:16:13Z
[ "python", "django", "python-3.x", "python-2.7" ]
I am interested in learning Python but I don't know which version I should chose. When I Googled, I got answers posted over a year ago. If I want to learn Django, which version will be useful and will get support? Note that I know C, C++, Java and C#.
Django only has experimental support for Python 3, so you'll have to go with Python 2.7 for now.
In python, is there a static equivalent to isinstance?
14,523,167
2
2013-01-25T13:54:19Z
14,523,193
8
2013-01-25T13:55:31Z
[ "python", "inheritance", "static", "isinstance" ]
I want to scan a module (using `dir()`) and extract all class names (`type` objects) of classes that extend a certain parent class. Is there any way to do this without first creating instances that I can check with `isinstance()`?
I think you might be looking for [`issubclass`](http://docs.python.org/2/library/functions.html#issubclass)
Display a ‘loading’ message while a time consuming function is executed in Flask
14,525,029
15
2013-01-25T15:39:44Z
29,146,550
8
2015-03-19T13:56:51Z
[ "python", "html", "flask", "loading" ]
I’m still relatively new to Flask, and a bit of a web noob in general, but I’ve had some good results so far. Right now I’ve got a form in which users enter a query, which is given to a function that can take anywhere between 5 and 30 seconds to return a result (looking up data with the Freebase API). The proble...
Add this to your index.html or js file (I'm assuming you have jQuery here, you could use standard javascript of course.): ``` <script type="text/javascript">// <![CDATA[ function loading(){ $("#loading").show(); $("#content").hide(); } // ]]></script> ``` Add this to you...
Celery Worker Database Connection Pooling
14,526,249
15
2013-01-25T16:38:26Z
26,853,948
11
2014-11-10T22:11:06Z
[ "python", "postgresql", "connection-pooling", "celery" ]
I am using Celery standalone (not within Django). I am planning to have one worker task type running on multiple physical machines. The task does the following 1. Accept an XML document. 2. Transform it. 3. Make **multiple** database reads and writes. I'm using PostgreSQL, but this would apply equally to other store ...
I like tigeronk2's idea of one connection per worker. As he says, Celery maintains its own pool of workers so there really isn't a need for a separate database connection pool. The [Celery Signal docs](http://docs.celeryproject.org/en/latest/userguide/signals.html#worker-signals) explain how to do custom initialization...
Why am getting a MultipleObjectsReturned error inside a try block?
14,526,355
3
2013-01-25T16:43:53Z
14,526,597
9
2013-01-25T16:55:55Z
[ "python", "django", "exception" ]
Any help on this one would great. I'm using python 2.7 and django 1.2 Here's my code: ``` for save in saved: #list to iterate try: sect = obj.get(name=save) #obj is a RelatedManager except: #if two sections have the same name sect = obj.filter(name=save) else: #finish my code ``` I...
Two objects have the `name` values equal to the value of `save` When using `get` and there are more than 1 row returned it raises [`MultipleObjectsReturned`](https://docs.djangoproject.com/en/dev/ref/exceptions/#multipleobjectsreturned) I think you should catch this explicitly because your except as it stands will al...
What does the ^ (XOR) operator do?
14,526,584
15
2013-01-25T16:55:36Z
14,526,622
7
2013-01-25T16:56:52Z
[ "python", "math" ]
What mathematical operation does XOR perform?
`^` *is* the [Python bitwise XOR operator](http://docs.python.org/2/reference/expressions.html#binary-bitwise-operations). It is how you spell `XOR` in python: ``` >>> 0 ^ 0 0 >>> 0 ^ 1 1 >>> 1 ^ 0 1 >>> 1 ^ 1 0 ``` XOR stands for [exclusive OR](http://en.wikipedia.org/wiki/Exclusive_or). It is used in cryptography b...
What does the ^ (XOR) operator do?
14,526,584
15
2013-01-25T16:55:36Z
14,526,640
26
2013-01-25T16:58:00Z
[ "python", "math" ]
What mathematical operation does XOR perform?
XOR is a binary operation, it stands for "exclusive or", that is to say the resulting bit evaluates to one if only exactly *one* of the bits is set. This is its function table: ``` a | b | a ^ b --|---|------ 0 | 0 | 0 0 | 1 | 1 1 | 0 | 1 1 | 1 | 0 ``` This operation is performed between every two corresponding bits...
vim as a python ide
14,527,902
4
2013-01-25T18:15:06Z
14,528,068
9
2013-01-25T18:25:43Z
[ "python", "vim" ]
Python support is integrated in the latest versions of emacs. For example `C-c C-z` provides me an interpreter and `C-c C-c` automatically interprets the file I'm working on without moving to the other buffer. (Although there are some downsides to emacs's approach) Is this possible in vim, or as easy done as in emacs ...
To execute the current file in python, you can use the command `:!python %`. You can bind this to a keyboard shortcut by editing your vimrc. For example, adding `nnoremap \ll :!python %<cr>` to your vimrc will execute the current file in python when you type `\ll` in normal mode. (\* see footnote for more details). Th...
The specific behavior of the iteration faux pas
14,527,966
2
2013-01-25T18:19:34Z
14,528,039
7
2013-01-25T18:23:43Z
[ "python" ]
I had someone recently ask me recently about the faux pas of changing a list while iterating over it. They presented the following scenario (which I have now updated with a better example) as a possible use case when the behavior might be desirable: ``` >>> jersey_numbers = [4, 2, 3, 5, 1] # list of places in a race ...
When you remove an item from a list, everything in the list shifts over ... ``` [1, 2, 3, 4, 5] #remove ^ [1, 2, 3, 5] ``` If you do this while iterating over the object, and if you have items that you want to remove adjacent to each other, then when you remove the first, the second will shift over to take it's pla...
Python split for lists
14,529,523
12
2013-01-25T20:05:19Z
14,529,615
12
2013-01-25T20:11:21Z
[ "python", "list", "functional-programming" ]
If we have a `list` of `strings` in python and want to create sublists based on some special `string` how should we do? For instance: ``` l = ["data","more data","","data 2","more data 2","danger","","date3","lll"] p = split_special(l,"") ``` would generate: ``` p = [["data","more data"],["data 2","more data 2","da...
[itertools.groupby](http://docs.python.org/2/library/itertools.html#itertools.groupby) is one approach (as it often is): ``` >>> l = ["data","more data","","data 2","more data 2","danger","","date3","lll"] >>> from itertools import groupby >>> groupby(l, lambda x: x == "") <itertools.groupby object at 0x9ce06bc> >>> [...
Apply multiple functions to multiple groupby columns
14,529,838
27
2013-01-25T20:26:45Z
14,530,027
34
2013-01-25T20:40:24Z
[ "python", "group-by", "aggregate-functions", "pandas" ]
The [docs](http://pandas.pydata.org/pandas-docs/dev/groupby.html#applying-multiple-functions-at-once) show how to apply multiple functions on a groupby object at a time using a dict with the output column names as the keys: ``` In [563]: grouped['D'].agg({'result1' : np.sum, .....: 'result2' : np....
For the first part you can pass a dict of column names for keys and a list of functions for the values: ``` In [28]: df Out[28]: A B C D E GRP 0 0.395670 0.219560 0.600644 0.613445 0.242893 0 1 0.323911 0.464584 0.107215 0.204072 0.927325 0 2 0.321358 0.0760...
CapWords conventions: get_MyClass or get_my_class
14,530,524
3
2013-01-25T21:16:49Z
14,530,561
7
2013-01-25T21:19:31Z
[ "python", "coding-style" ]
This is a style conventions question. PEP8 convention for a class definition would be something like ``` class MyClass(object): def __init__(self, attri): self.attri = attri ``` So say I want to write a module-scoped function which takes some data, processes it, and then creates an instance of MyClass. ...
Depending on the usage of the function, it might be more appropriate to turn it into a [`classmethod`](http://docs.python.org/2/library/functions.html#classmethod) or `staticmethod`. Then it's association with the `class` is clear, but you don't violate any naming conventions. e.g.: ``` class MyClass(object): de...
How to Count bugs in an image?
14,531,072
11
2013-01-25T22:05:11Z
14,533,052
13
2013-01-26T02:00:01Z
[ "python", "image-processing", "computer-vision" ]
I have a picture like the below and I would like to count the number of bugs (continuous blobs of color/grey) that show up on it with Python. How could I do this best? ![Bugs on a noisy background](http://i.stack.imgur.com/JzNMK.jpg) I've so far looked at ImageChops, SciPy and PIL but I'm unsure what I can/should use...
Your gaussian filtering is mostly fine already, but you are considering a radius way bigger than needed for the task. For instance, let us consider a kernel of radius 15 as an example. Here is a representation of what we get: ![enter image description here](http://i.stack.imgur.com/muLStm.png) There are two clear val...
How can I delete a Riak bucket in Python?
14,531,708
6
2013-01-25T23:03:06Z
14,531,820
11
2013-01-25T23:15:13Z
[ "python", "riak" ]
I want to delete a Riak bucket in order to purge old data from my system. I understand that there is no single Riak API to do this, but instead one [deletes all the keys in the bucket](http://docs.basho.com/riak/latest/references/apis/http/#Bucket-Operations), which effectively deletes it. Riak does provide an API to f...
Like I said in the question, I figured this was pretty simple, especially with the [requests](http://docs.python-requests.org/en/latest/) library, so I developed a script to do this. I started with the Riak `keys=true` (i.e. non-chunked) [mode](http://docs.basho.com/riak/latest/references/apis/http/HTTP-List-Keys/#Requ...
Constructing the largest number possible by rearranging a list
14,532,105
18
2013-01-25T23:44:24Z
14,533,924
10
2013-01-26T04:39:58Z
[ "python", "algorithm", "list", "python-2.7", "integer" ]
Say I have an array of positive whole integers; I'd like to manipulate the order so that the concatenation of the resultant array is the largest number possible. For example `[97, 9, 13]` results in `99713`; `[9,1,95,17,5]` results in `9955171`. I'm not sure of an answer.
`sorted(x, cmp=lambda a, b: -1 if str(b)+str(a) < str(a)+str(b) else 1)`
Constructing the largest number possible by rearranging a list
14,532,105
18
2013-01-25T23:44:24Z
14,539,943
8
2013-01-26T18:10:03Z
[ "python", "algorithm", "list", "python-2.7", "integer" ]
Say I have an array of positive whole integers; I'd like to manipulate the order so that the concatenation of the resultant array is the largest number possible. For example `[97, 9, 13]` results in `99713`; `[9,1,95,17,5]` results in `9955171`. I'm not sure of an answer.
Intuitively, we can see that a reverse sort of single digit numbers would lead to the higest number: ``` >>> ''.join(sorted(['1', '5', '2', '9'], reverse=True)) '9521' ``` so reverse sorting should work. The problem arises when there are multi-digit snippets in the input. Here, intuition again lets us order `9` befor...
BOM in server response screws up json parsing
14,532,149
7
2013-01-25T23:49:20Z
14,532,226
11
2013-01-25T23:59:07Z
[ "python", "json", "urllib2", "urllib" ]
I'm trying to write a Python script that posts some JSON to a web server and gets some JSON back. I patched together a few different examples on StackOverflow, and I think I have something that's mostly working. ``` import urllib2 import json url = "http://foo.com/API.svc/SomeMethod" payload = json.dumps( {'inputs': ...
You should probably yell at whoever's running this service, because a BOM on UTF-8 text makes no sense. The BOM exists to disambiguate byte order, and UTF-8 is defined as being little-endian. That said, ideally you should decode bytes before doing anything else with them. Luckily, Python has a codec that recognizes an...
Hash value for directed acyclic graph
14,532,164
23
2013-01-25T23:52:01Z
14,568,407
8
2013-01-28T18:13:22Z
[ "python", "algorithm", "hash", "directed-acyclic-graphs" ]
How do I transform a directed acyclic graph into a hash value such that any two isomorphic graphs hash to the same value? It is acceptable, but undesirable for two isomorphic graphs to hash to different values, which is what I have done in the code below. We can assume that the number of vertices in the graph is at mos...
[Graph isomorphism for directed acyclic graphs is still GI-complete.](http://en.wikipedia.org/wiki/Graph_isomorphism_problem#GI-complete_classes_of_graphs) Therefore there is currently no known (worst case sub-exponential) solution to guarantee that two isomorphic directed acyclic graphs will yield the same hash. Only ...
Hash value for directed acyclic graph
14,532,164
23
2013-01-25T23:52:01Z
14,574,330
8
2013-01-29T01:42:01Z
[ "python", "algorithm", "hash", "directed-acyclic-graphs" ]
How do I transform a directed acyclic graph into a hash value such that any two isomorphic graphs hash to the same value? It is acceptable, but undesirable for two isomorphic graphs to hash to different values, which is what I have done in the code below. We can assume that the number of vertices in the graph is at mos...
To effectively test for graph isomorphism you will want to use [nauty](http://cs.anu.edu.au/people/bdm/nauty/). Specifically for Python there is the wrapper [pynauty](http://web.cs.dal.ca/~peter/software/), but I can't attest its quality (to compile it correctly I had to do some simple patching on its `setup.py`). If t...
creating for loop list.length
14,532,875
5
2013-01-26T01:28:17Z
14,532,900
13
2013-01-26T01:31:31Z
[ "python", "list", "for-loop" ]
I'm reading about for loops right now, and I am curious if you could do a for loop in Python like in Java is it even possible to do something like ``` for (int i = 1; i < list.length; i++) ``` and can you do another for loop inside this for loop ? thanks
In Python you can iterate over the `list` itself: ``` for item in my_list: #do something with item ``` or to use indices you can use [`xrange()`](http://docs.python.org/2.7/library/functions.html#xrange): ``` for i in xrange(1,len(my_list)): #as indexes start at zero so you ...
Can you suggest a good minhash implementation?
14,533,420
10
2013-01-26T03:01:43Z
16,490,847
10
2013-05-10T21:07:13Z
[ "python", "hash", "minhash" ]
I am trying to look for a minhash open source implementation which I can leverage for my work. The functionality I need is very simple, given a set as input, the implementation should return its minhash. A python or C implementation would be preferred, just in case I need to hack it to work for me. Any pointers woul...
You should have a look at the following open source libraries, in order. All of them are in Python, and show how you can calculate document similarity using LSH/MinHash: [lsh](https://github.com/embr/lsh) [LSHHDC : Locality-Sensitive Hashing based High Dimensional Clustering](https://github.com/go2starr/lshhdc) [M...
Python threading multiple bash subprocesses?
14,533,458
18
2013-01-26T03:09:25Z
14,533,902
30
2013-01-26T04:35:17Z
[ "python", "multithreading", "subprocess" ]
How does one use the threading and subprocess modules to spawn parallel bash processes? When I start threads ala the first answer here: [python multithreading for dummies](http://stackoverflow.com/questions/2846653/python-multithreading-for-dummies), the bash processes run sequentially instead of in parallel.
You don't need threads to run subprocesses in parallel: ``` from subprocess import Popen commands = [ 'date; ls -l; sleep 1; date', 'date; sleep 5; date', 'date; df -h; sleep 3; date', 'date; hostname; sleep 2; date', 'date; uname -a; date', ] # run in parallel processes = [Popen(cmd, shell=True) ...
Basic Python Programming to convert month number to month name using dictionary
14,533,709
3
2013-01-26T03:57:08Z
14,534,067
7
2013-01-26T05:08:42Z
[ "python", "python-2.7" ]
I am new to python and only know the most basic level. I am supposed to allow input of a date in the form of dd/mm/yyyy and convert it to something like 26 Aug, 1986. I am stuck as to how to convert my month(mm) from numbers to words. Below is my current code, hope you can help me. \*\* please do not suggest using cale...
Use Python's datetime.datetime! Read using `my_date = strptime(the_string, "%d/%m/%Y")`. Print it using `my_date.strftime("%d %b, %Y")`. Visit: <http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior> Example: ``` import datetime input = '23/12/2011' my_date = datetime.datetime.strptime(input,...
Legend not showing up in Matplotlib stacked area plot
14,534,130
17
2013-01-26T05:20:10Z
14,534,830
30
2013-01-26T07:23:00Z
[ "python", "numpy", "matplotlib" ]
I am creating a stacked line/area plot using [plt.fill\_between()](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.fill_between) method of the pyplot, and after trying so many things I am still not able to figure why it is not displaying any legend or labels (even when I provide them in the code). Here is ...
The `fill_between()` command creates a PolyCollection that is not supported by the `legend()` command. Therefore you will have to use another matplotlib artist (compatible with `legend()`) as a proxy, without adding it to the axes (so the proxy artist will not be drawn in the main axes) and feed it to the legend funct...
Legend not showing up in Matplotlib stacked area plot
14,534,130
17
2013-01-26T05:20:10Z
18,449,695
16
2013-08-26T17:33:38Z
[ "python", "numpy", "matplotlib" ]
I am creating a stacked line/area plot using [plt.fill\_between()](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.fill_between) method of the pyplot, and after trying so many things I am still not able to figure why it is not displaying any legend or labels (even when I provide them in the code). Here is ...
gcalmettes's answer was a helpful start, but I wanted my legend to pick up the colors that the stackplot had automatically assigned. Here's how I did it: ``` polys = pyplot.stackplot(x, y) legendProxies = [] for poly in polys: legendProxies.append(pyplot.Rectangle((0, 0), 1, 1, fc=poly.get_facecolor()[0])) ```
Legend not showing up in Matplotlib stacked area plot
14,534,130
17
2013-01-26T05:20:10Z
24,196,785
16
2014-06-13T02:26:57Z
[ "python", "numpy", "matplotlib" ]
I am creating a stacked line/area plot using [plt.fill\_between()](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.fill_between) method of the pyplot, and after trying so many things I am still not able to figure why it is not displaying any legend or labels (even when I provide them in the code). Here is ...
Another, arguably easier, technique is to plot an empty data set, and use it's legend entry: ``` plt.plot([], [], color='green', linewidth=10) plt.plot([], [], color='red', linewidth=10) ``` This works well if you have other data labels for the legend, too: ![enter image description here](http://i.stack.imgur.com/VB...
What do you mean by hashable in Python?
14,535,730
39
2013-01-26T09:48:07Z
14,535,739
39
2013-01-26T09:49:08Z
[ "python" ]
I tried searching internet but could not find the meaning of hashable. When they say objects are `hashable` or `hashable objects` what does it mean?
From the [Python glossary](http://docs.python.org/2/glossary.html): > An object is hashable if it has a hash value which never changes during its lifetime (it needs a `__hash__()` method), and can be compared to other objects (it needs an `__eq__()` or `__cmp__()` method). Hashable objects which compare equal must hav...
My FB HackerCup code too slow of large inputs
14,536,384
17
2013-01-26T11:14:56Z
14,537,023
14
2013-01-26T12:42:21Z
[ "python", "performance", "optimization" ]
I was solving the [`Find the min`](https://www.facebook.com/hackercup/problems.php?pid=494433657264959&round=185564241586420) problem on facebook hackercup using python, my code works fine for sample inputs but for large inputs(10^9) it is taking hours to complete. So, is it possible that the solution of that problem ...
After at most `k+1` steps, the last `k+1` numbers in the array will be `0...k` (in some order). Subsequently, the sequence is predictable: `m[i] = m[i-k-1]`. So the way to solve this problem is run your naive implementation for `k+1` steps. Then you've got an array with `2k+1` elements (the first `k` were generated fro...
My FB HackerCup code too slow of large inputs
14,536,384
17
2013-01-26T11:14:56Z
14,540,162
12
2013-01-26T18:33:30Z
[ "python", "performance", "optimization" ]
I was solving the [`Find the min`](https://www.facebook.com/hackercup/problems.php?pid=494433657264959&round=185564241586420) problem on facebook hackercup using python, my code works fine for sample inputs but for large inputs(10^9) it is taking hours to complete. So, is it possible that the solution of that problem ...
Here is my O(k) solution, which is based on the same idea as above, but runs much faster. ``` import os, sys f = open(sys.argv[1], 'r') T = int(f.readline()) def next(ary, start): j = start l = len(ary) ret = start - 1 while j < l and ary[j]: ret = j j += 1 return ret for t in r...
How do I receive Github Webhooks in Python
14,536,992
10
2013-01-26T12:36:24Z
14,550,657
11
2013-01-27T18:27:02Z
[ "python", "post", "web", "github", "webhooks" ]
Github offers to send [Post-receive hooks](https://help.github.com/articles/post-receive-hooks) to an URL of your choice when there's activity on your repo. I want to write a **small** Python command-line/background (i.e. no GUI or webapp) application running on my computer (later on a NAS), which continually **listens...
Here's a basic web.py example for receiving data via POST and doing something with it (in this case, just printing it to stdout): ``` import web urls = ('/.*', 'hooks') app = web.application(urls, globals()) class hooks: def POST(self): data = web.data() print print 'DATA RECEIVED:' ...
How do I receive Github Webhooks in Python
14,536,992
10
2013-01-26T12:36:24Z
14,550,821
18
2013-01-27T18:43:26Z
[ "python", "post", "web", "github", "webhooks" ]
Github offers to send [Post-receive hooks](https://help.github.com/articles/post-receive-hooks) to an URL of your choice when there's activity on your repo. I want to write a **small** Python command-line/background (i.e. no GUI or webapp) application running on my computer (later on a NAS), which continually **listens...
First thing is, web is request-response based. So something will request your link, and you will respond accordingly. Your server application will be continuously listening on a port; that you don't have to worry about. Here is the similar version in [`Flask`](https://flask.readthedocs.org/en/latest/) (my micro framew...
Why would anyone check 'x in list'?
14,537,220
4
2013-01-26T13:05:03Z
14,537,258
17
2013-01-26T13:10:11Z
[ "python", "list", "set" ]
In Python one can very easily check if a value is contained in a container by using the `in`-operator. I was wondering why anyone would ever use the `in`-operator on a list, though, when it's much more efficient to first transform the list to a set as such: ``` if x in [1,2,3]: ``` as opposed to ``` if x in set([1,2...
``` if x in set([1,2,3]): ``` is *not* faster than ``` if x in [1,2,3]: ``` Converting a list to a set requires iterating over the list, and is thus at least `O(n)` time.\* In practice it takes a lot longer than searching for an item, since it involves hashing and then inserting every item. Using a set is efficient...
Copy list and append an element in one line
14,537,369
2
2013-01-26T13:26:18Z
14,537,383
12
2013-01-26T13:27:58Z
[ "python" ]
Can this be reduced to a single line (after assigning `a`)? ``` a = [1,2,3] b = a[:] b.append(4) ```
The following is probably the simplest: ``` b = a + [4] ``` Here, you don't need `a[:]` since we're no longer copying the reference (`+` creates and returns a new list anyway).
a list of tuples into two lists
14,537,724
5
2013-01-26T14:14:55Z
14,537,750
14
2013-01-26T14:17:44Z
[ "python" ]
I have a list of tuples as follows: `[(12,1),(123,4),(33,4)]` and I want it to turn into `[12,123,33]` and `[1,4,4]` I was just wondering how I would go about this? Cheers in advance
You could use [zip()](http://docs.python.org/2/library/functions.html#zip): ``` zipped = [(12, 1), (123, 4), (33, 4)] >>> b, c = zip(*zipped) >>> b (12, 123, 33) >>> c (1, 4, 4) ``` Or you could achieve something similar using [list comprehensions](http://docs.python.org/2/tutorial/datastructures.html#list-comprehen...
a list of tuples into two lists
14,537,724
5
2013-01-26T14:14:55Z
14,537,754
7
2013-01-26T14:18:11Z
[ "python" ]
I have a list of tuples as follows: `[(12,1),(123,4),(33,4)]` and I want it to turn into `[12,123,33]` and `[1,4,4]` I was just wondering how I would go about this? Cheers in advance
This is a perfect use case for [`zip()`](http://docs.python.org/2/library/functions.html#zip): ``` In [41]: l = [(12,1), (123,4), (33,4)] In [42]: a, b = map(list, zip(*l)) In [43]: a Out[43]: [12, 123, 33] In [44]: b Out[44]: [1, 4, 4] ``` If you don't mind `a` and `b` being tuples rather than lists, you can remo...
How to install python subversion bindings needed by hg convert on Mac OS X 10.8?
14,538,468
5
2013-01-26T15:40:06Z
16,950,786
15
2013-06-05T22:12:03Z
[ "python", "osx", "svn", "mercurial" ]
I am looking for a solution, preferably clean and simple, to enable `hg convert` to work on OS X 10.8 with SVN repositories. Currently, if you try to convert a SVN repository you will get a `could not load Subversion python bindings` error. Note: Alex Martelli recommended in another answer to install CollabNet subver...
## Using homebrew The easiest way to get this working is to install `subversion` from source using [`homebrew`](http://brew.sh) and the `--with-python` flag. First, make sure you have your command-line tools installed. With Mavericks and Xcode 5, most commands like `cc` just work even though the command-line tools ar...
How to get the index with the key in Python dictionary?
14,538,885
3
2013-01-26T16:23:39Z
14,539,017
10
2013-01-26T16:36:07Z
[ "python", "python-2.7", "dictionary", "indexing", "key" ]
I have the key of a python dictionary and I want to get the corresponding index in the dictionary. Suppose I have the following dictionary, ``` d = { 'a': 10, 'b': 20, 'c': 30} ``` Is there a combination of python functions so that I can get the index value of 1, given the key value 'b'? ``` d.??('b') ``` I know it...
Use OrderedDicts: <http://docs.python.org/2/library/collections.html#collections.OrderedDict> ``` >>> x = OrderedDict((("a", "1"), ("c", '3'), ("b", "2"))) >>> x["d"] = 4 >>> x.keys().index("d") 3 >>> x.keys().index("c") 1 ``` For those using Python 3 ``` >>> list(x.keys()).index("c") 1 ```
4 lists into a list of tuples
14,539,422
2
2013-01-26T17:18:08Z
14,539,457
7
2013-01-26T17:20:17Z
[ "python", "list", "tuples" ]
I have 4 lists; ``` [1,3,6][1,5,9][1,2,4]['A','B','C'] ``` I want to create one list of tuples like so ``` [(1,1,1,'A'),(3,5,2,'B'),(6,9,4,'C')] ```
Use the built-in zip function: ``` >>> zip([1,3,6],[1,5,9],[1,2,4],['A','B','C']) [(1, 1, 1, 'A'), (3, 5, 2, 'B'), (6, 9, 4, 'C')] ``` It works with other iterables too.
Convert unicode with utf-8 string as content to str
14,539,807
5
2013-01-26T17:55:50Z
14,540,022
14
2013-01-26T18:18:30Z
[ "python", "unicode", "utf-8", "python-2.x", "pyquery" ]
I'm using pyquery to parse a page: ``` dom = PyQuery('http://zh.wikipedia.org/w/index.php', {'title': 'CSS', 'printable': 'yes', 'variant': 'zh-cn'}) content = dom('#mw-content-text > p').eq(0).text() ``` but what I get in `content` is a unicode string with utf-8 encoded content: ``` u'\xe5\xb1\x82\xe5\x8f\xa0\xe6\x...
If you have a `unicode` value with UTF-8 bytes, encode to Latin-1 to preserve the 'bytes': ``` content = content.encode('latin1') ``` because the Unicode codepoints U+0000 to U+00FF all map one-on-one with the latin-1 encoding; this encoding thus interprets your data as literal bytes. For your example this gives me:...
Pandas Drop Rows Outside of Time Range
14,539,992
10
2013-01-26T18:15:35Z
14,540,509
13
2013-01-26T19:08:54Z
[ "python", "pandas" ]
I am trying to go through every row in a DataFrame index and remove all rows that are not between a certain time. I have been looking for solutions but none of them separate the Date from the Time, and all I want to do is drop the rows that are outside of a Time range.
You can use the `indexer_between_time` `Index` method. For example, to *include* those times between 9am and 6pm (*inclusive*): ``` ts.ix[ts.index.indexer_between_time(datetime.time(9), datetime.time(18))] ``` to do the opposite and *exclude* those times between 6pm and 9am (*exclusive*): ``` ts.ix[ts.index.indexer...
Python 3 Float Decimal Points/Precision
14,540,143
4
2013-01-26T18:31:29Z
14,540,172
7
2013-01-26T18:34:18Z
[ "python", "python-3.x", "floating-point" ]
I am reading a text file with floating point numbers, all with either 1 or 2 decimal points. I am using `float()` to convert a line into a float, and raising a `ValueError` if that fails. I am storing all floats in a list. When printing it out, I'd like to print it out as a 2 decimal places floating point. Assume I ha...
In a word, you can't. `3.65` cannot be represented exactly as a `float`. The number that you're getting is the nearest number to `3.65` that has an exact `float` representation. The difference between (older?) Python 2 and 3 is purely due to the default formatting. I am seeing the following both in Python 2.7.3 and ...
script prints out of order
14,540,256
2
2013-01-26T18:42:32Z
14,540,284
8
2013-01-26T18:45:10Z
[ "python", "printing", "python-2.7" ]
I am using Python 2.7.3 and trying to understand why this script executes print statements out of order. i.e. the "-" prints AFTER the 2nd for loop. My script: ``` def cheeseshop(kind, *arguments, **keywords): print "-- Do you have any", kind, "?" print "-- I'm sorry, we're all out of", kind for arg in ar...
You didn't pass in the dictionary as keywords. Use the `**` syntax to do so: ``` cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", **{'shopkeeper':'Michael Palin', 'client':"John Cleese", 'sketch':"Cheese Shop Sketch"}) ``` or don't use ...
Python's function readlines(n) behavior
14,541,010
6
2013-01-26T19:58:51Z
14,541,029
7
2013-01-26T20:00:54Z
[ "python", "python-2.7" ]
I've read [**the documentation**](http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects), but what does readlines(n) do? By readlines(n), I mean readlines(3) or any other number. When I run readlines(3), it returns same thing as readlines().
The optional argument should mean how many (approximately) bytes are read from the file. The file will be read further, until the current line ends: ``` readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read. The optional size argument, if gi...
How do I know if ndb.Model.get_or_insert created a new entity or got an existing one?
14,542,175
10
2013-01-26T22:21:43Z
14,549,493
24
2013-01-27T16:34:43Z
[ "python", "google-app-engine", "app-engine-ndb" ]
For the following (broken) function, I want to return `True` if the entity was created or updated, and `False` otherwise. The problem is that I do not know whether `get_or_insert()` got an existing entity, or inserted one. Is there an easy way to determine this? ``` class MyModel(ndb.Model): def create_or_update(k...
`get_or_insert()` is a trivial function (although its implementation looks complex, because it tries to deal with unusual property names). You can easily write it yourself: ``` @ndb.transactional def my_get_or_insert(cls, id, **kwds): key = ndb.Key(cls, id) ent = key.get() if ent is not None: return (ent, Fa...
Annotate several points with one text in matplotlib
14,542,232
6
2013-01-26T22:29:32Z
14,545,981
13
2013-01-27T09:11:42Z
[ "python", "matplotlib", "annotate" ]
I want to use single annotation text to annotate several data points with several arrows. I made a simple workaround: ``` ax = plt.gca() ax.plot([1,2,3,4],[1,4,2,6]) an1 = ax.annotate('Test', xy=(2,4), xycoords='data', xytext=(30,-80), textcoords='offset points', arrowprops=dict(arrowstyle="-|>", ...
I guess the proper solution will require too much effort - subclassing \_AnnotateBase and adding support for multiple arrows all by yourself. But I managed to eliminate that issue with second annotate affecting visual appearance simply by adding `alpha=0.0`. So the updated solution here if no one will provide anything ...
Trying to run simple PIL python example, can't convert jpeg to float
14,543,015
4
2013-01-27T00:11:54Z
16,586,141
10
2013-05-16T11:22:51Z
[ "python", "image", "image-processing", "python-imaging-library" ]
so I wrote a simple python script ``` from PIL import Image from pylab import * im = array(Image.open('sample.jpg')) imshow(im) ``` and i get this error from IDLE ``` Traceback (most recent call last): File "/home/michael/Dropbox/OpenCV/greyscale.py", line 5, in <module> imshow(im) File "/usr/local/lib/pytho...
I know this is coming very later but I thought I should answer just in case anyone else had the same problem. I ran into the same problem and the issue was the image I loaded did not exist in the project folder.so you need to check that `sample.jpg` exist and that it loads properly before using it. ``` if os.path.isfi...
How to print a variable with Requests and JSON
14,543,570
9
2013-01-27T01:37:27Z
14,543,758
19
2013-01-27T02:10:36Z
[ "python", "json", "object", "python-requests", "nonetype" ]
I've been programming an application that pulls information from an online API, and I need some help with it. I'm using requests, and my current code is as follows ``` myData = requests.get('theapiwebsitehere.com/thispartisworking') myRealData = myData.json() x = myRealData['data']['playerStatSummaries']['playerStatS...
Two things, first, make sure you are using the latest version of `requests` (its 1.1.0); in previous versions `json` is not a method but a property. ``` >>> r = requests.get('https://api.github.com/users/burhankhalid') >>> r.json['name'] u'Burhan Khalid' >>> requests.__version__ '0.12.1' ``` In the latest version: `...
Why the following python code does not print to file
14,544,893
7
2013-01-27T06:01:49Z
14,544,949
8
2013-01-27T06:12:46Z
[ "python" ]
``` from sys import stdout stdout = open('file', 'w') print 'test' stdout.close() ``` does create the file, but it contains nothing. I had to use ``` import sys sys.stdout = open('file', 'w') print 'test' sys.stdout.close() ``` But wouldn't the `from ... import...` automatically make the name available? Why do I st...
The problem is this: `print` is equivalent to `sys.stdout.write()`. So when you do `from sys import stdout`, the variable `stdout` won't be used by `print`. But when you do ``` import sys print 'test' ``` it actually writes to `sys.stdout` which is pointing to the `file` you opened. **Analysis** ``` from sys impo...
python - putting list items in a queue
14,545,237
4
2013-01-27T07:05:59Z
14,545,263
9
2013-01-27T07:10:18Z
[ "python" ]
I have following code: ``` self.queryQ = Queue.Queue() queries = self.getQueries() # returns list for query in queries: self.queryQ.put(query) ``` Is there a better way for following code? Please provide pointers.
Well, you could use `map` ([docs](http://docs.python.org/2/library/functions.html#map)): ``` map(self.queryQ.put, self.getQueries()) ```
Does Python have a stack/heap and how is memory managed?
14,546,178
28
2013-01-27T09:47:36Z
14,546,231
44
2013-01-27T09:55:17Z
[ "python", "memory", "memory-management" ]
How are variables and memory managed in Python? Does it have a stack and a heap and what algorithm is used to manage memory? Given this knowledge are there any recommendations on memory management for large number/data crunching?
> How are variables and memory managed in Python. Automagically! No, really, you just create an object and the Python Virtual Machine handles the memory needed and where it shall be placed in the memory layout. > Does it have a stack and a heap and what algorithm is used to manage > memory? When we are talking about...
Does Python have a stack/heap and how is memory managed?
14,546,178
28
2013-01-27T09:47:36Z
14,546,714
17
2013-01-27T11:06:03Z
[ "python", "memory", "memory-management" ]
How are variables and memory managed in Python? Does it have a stack and a heap and what algorithm is used to manage memory? Given this knowledge are there any recommendations on memory management for large number/data crunching?
Python doesn't have ***any*** such thing. Python is the *language* and does not specify how exactly *implementations* must achieve the semantics defined by Python the language. Every implementation (CPython, PyPy, IronPython, *Stackless*, Jython...) is free to do its own thing! In **C**Python, *all* objects live on ...
Networkx in Python - draw node attributes as labels outside the node
14,547,388
7
2013-01-27T12:38:19Z
14,576,319
7
2013-01-29T05:35:39Z
[ "python", "networkx" ]
I have a graph of nodes with specific attributes and I want to draw the graph by networkx in Python with several attributes as labels of nodes outside the node. Can someone help me how can I write my code to achieve this aim? There is a loop in my code which generate "interface\_?" attribute for each input from firew...
You have access to the node positions in the 'pos' dictionary. So you can use matplotlib to put text wherever you like. e.g. ``` In [1]: import networkx as nx In [2]: G=nx.path_graph(3) In [3]: pos=nx.spring_layout(G) In [4]: nx.draw(G,pos) In [5]: x,y=pos[1] In [6]: import matplotlib.pyplot as plt In [7]: plt.t...
Python locale error: unsupported locale setting
14,547,631
67
2013-01-27T13:04:11Z
14,548,156
117
2013-01-27T14:06:07Z
[ "python", "locale", "ubuntu-11.04" ]
Why do I get the following error when doing this in python: ``` >>> import locale >>> print str( locale.getlocale() ) (None, None) >>> locale.setlocale(locale.LC_ALL, 'de_DE') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/locale.py", line 531, in setlocale retu...
You probably do not have any `de_DE` locale available. You can view a list of available locales with the `locale -a` command. For example, on my machine: ``` $ locale -a C C.UTF-8 en_AG en_AG.utf8 en_AU.utf8 en_BW.utf8 en_CA.utf8 en_DK.utf8 en_GB.utf8 en_HK.utf8 en_IE.utf8 en_IN en_IN.utf8 en_NG en_NG.utf8 en_NZ.utf8...
Python locale error: unsupported locale setting
14,547,631
67
2013-01-27T13:04:11Z
36,257,050
71
2016-03-28T06:20:33Z
[ "python", "locale", "ubuntu-11.04" ]
Why do I get the following error when doing this in python: ``` >>> import locale >>> print str( locale.getlocale() ) (None, None) >>> locale.setlocale(locale.LC_ALL, 'de_DE') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/locale.py", line 531, in setlocale retu...
Run following commands ``` export LC_ALL="en_US.UTF-8" export LC_CTYPE="en_US.UTF-8" sudo dpkg-reconfigure locales ``` It will solve this. (I was not able to solve my problem with other solutions. This one works for me)
Python locale error: unsupported locale setting
14,547,631
67
2013-01-27T13:04:11Z
37,112,094
13
2016-05-09T09:26:00Z
[ "python", "locale", "ubuntu-11.04" ]
Why do I get the following error when doing this in python: ``` >>> import locale >>> print str( locale.getlocale() ) (None, None) >>> locale.setlocale(locale.LC_ALL, 'de_DE') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/locale.py", line 531, in setlocale retu...
Due to [this link](https://bugs.launchpad.net/devstack/+bug/1249131), it is solving by entering this command: > export LC\_ALL=C
Jira-Python - jira.client import error
14,547,660
2
2013-01-27T13:07:44Z
15,534,399
14
2013-03-20T20:47:25Z
[ "python", "python-2.7", "jira" ]
I was installing jira-python like written in the docs $ pip install jira-python but after installation I try to run the example: ``` from jira.client import JIRA options = { 'server': 'https://jira.atlassian.com' } jira = JIRA(options) projects = jira.projects() keys = sorted([project.key for project in projec...
seems like the reason was that my test file was named jira.py :) thanks for your help Inbar!
How can I loop over entries in JSON?
14,547,916
10
2013-01-27T13:35:56Z
14,548,320
26
2013-01-27T14:25:24Z
[ "python", "json" ]
I want to loop over the content of a JSON file and print it to the console. I think I did mix up something with lists. This is what I tried to get all the `team_name` elements ``` from urllib2 import urlopen import json url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_sh...
Actually, to query the `team_name`, just add it in brackets to the last line. Apart from that, it seems to work on Python 2.7.3 on command line. ``` from urllib2 import urlopen import json url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1' response = urlopen(ur...
Python check instances of classes
14,549,405
20
2013-01-27T16:23:54Z
14,549,424
9
2013-01-27T16:27:58Z
[ "python", "object", "instance" ]
Is there any way to check if object is instance of class, not instance of concrete class, but instance of any class, i can check that object is not class, not module, not traceback etc., but i am interesting in a simple solution
Have you tried [`isinstance()`](http://docs.python.org/2/library/functions.html#isinstance) built in function? You could also look at `hasattr(obj, '__class__')` to see if the object was instantiated from some class type.
Python check instances of classes
14,549,405
20
2013-01-27T16:23:54Z
14,551,806
14
2013-01-27T20:21:32Z
[ "python", "object", "instance" ]
Is there any way to check if object is instance of class, not instance of concrete class, but instance of any class, i can check that object is not class, not module, not traceback etc., but i am interesting in a simple solution
`isinstance()` is your friend here. It returns a boolean and can be used in the following ways to check types. ``` if isinstance(obj, (int, long, float, complex)): print obj, "is a built-in number type" if isinstance(obj, MyClass): print obj, "is of type MyClass" ``` Hope this helps.
Sum of digits in a string
14,550,034
5
2013-01-27T17:27:14Z
14,550,070
9
2013-01-27T17:32:00Z
[ "python", "string", "sum", "digits" ]
if i just read my `sum_digits` function here, it makes sense in my head but it seems to be producing wrong results. Any tip? ``` def is_a_digit(s): ''' (str) -> bool Precondition: len(s) == 1 Return True iff s is a string containing a single digit character (between '0' and '9' inclusive). >>> is_a_digit('7') True ...
You're resetting the value of `b` on each iteration, if `a` is a digit. Perhaps you want: ``` b += int(a) ``` Instead of: ``` b = int(a) b += 1 ```
Sum of digits in a string
14,550,034
5
2013-01-27T17:27:14Z
14,550,071
14
2013-01-27T17:32:16Z
[ "python", "string", "sum", "digits" ]
if i just read my `sum_digits` function here, it makes sense in my head but it seems to be producing wrong results. Any tip? ``` def is_a_digit(s): ''' (str) -> bool Precondition: len(s) == 1 Return True iff s is a string containing a single digit character (between '0' and '9' inclusive). >>> is_a_digit('7') True ...
Notice that you can easily solve this problem using built-in functions. This is a more idiomatic and efficient solution: ``` def sum_digits(digit): return sum(int(x) for x in digit if x.isdigit()) sum_digits('hihello153john') => 9 ``` In particular, be aware that the `is_a_digit()` method already exists for stri...
Compare list in python to detect an equality
14,550,370
6
2013-01-27T18:00:32Z
14,550,447
8
2013-01-27T18:09:16Z
[ "python", "list", "compare" ]
First, I am a novice at python programming and attempted much research within other questions but none that I could find that relate to something like this (all others were a bit more advanced) --- That said moving on. **The solution needed:** Go through two two integer lists and compare for equality. Ideally I want i...
There are several possible interpretations of your question. 1) Loop over the lists pairwise, stopping when a pair is equal: ``` >>> s = [10, 14, 18, 20, 25] >>> t = [55, 42, 18, 12, 4] >>> for x, y in zip(s, t): if x == y: print 'Equal element found:', x break Equal element found: 1...
celery vs pyro : is Pyro an alternative to Celery?
14,551,178
10
2013-01-27T19:17:00Z
14,551,602
13
2013-01-27T20:01:03Z
[ "python", "celery", "pyro" ]
I am trying to learn about Celery and was wondering if Celery and Pyro are trying to achieve the same thing ? Could somebody please tell me if there is something which Celery can do which Pyro can not, or vice versa?
As I see in the official websites, [Celery](http://celeryproject.org/) and [Pyro](http://pypi.python.org/pypi/Pyro4), are intent to do different jobs but the confusion is pretty natural. The objective in both of the packages is help you with distributed computing but with different approaches: **Celery** is intent to ...
Processing a very very big data set in python - memory error
14,551,451
6
2013-01-27T19:45:42Z
14,551,692
12
2013-01-27T20:10:30Z
[ "python", "numpy", "python-2.7", "data-analysis" ]
I'm trying to process data obtained from a csv file using csv module in python. there are about 50 columns & 401125 rows in this. I used the following code chunk to put that data into a list ``` csv_file_object = csv.reader(open(r'some_path\Train.csv','rb')) header = csv_file_object.next() data = [] for row in csv_fil...
As noted by @DSM in the comments, the reason you're getting a memory error is that calling `np.size` on a list will copy the data into an array first and then get the size. If you don't need to work with it as a numpy array, just don't call `np.size`. If you do want numpy-like indexing options and so on, you have a fe...
Embed R code in python
14,551,472
8
2013-01-27T19:48:15Z
14,551,561
7
2013-01-27T19:57:35Z
[ "python" ]
I need to make computations in a python program, and I would prefer to make some of them in R. Is it possible to embed R code in python ?
[RPy](http://rpy.sourceforge.net/) is your friend for this type of thing. The scipy, numpy and matplotlib packages all do simular things to R and are very complete, but if you want to mix the languages RPy is the way to go! ``` from rpy2.robjects import * def main(): degrees = 4 grid = r.seq(0, 10, length=...
Running flask + gevent + requests not serving 'concurrently'
14,551,823
5
2013-01-27T20:23:08Z
14,552,642
15
2013-01-27T21:42:32Z
[ "python", "io", "flask", "gevent" ]
I kick off my flask app like this: ``` #!flask/bin/python from app import app_instance from gevent.pywsgi import WSGIServer #returns and instance of the application - using function to wrap configuration app = app_instance() http_server = WSGIServer(('',5000), app) http_server.serve_forever() ``` And then when I try...
I believe the issue is likely that you forgot to monkey patch. This makes it so that all of the normally blocking calls become non-blocking calls that utilize greenlets. To do this just put this code *before* you call anything else. ``` from gevent import monkey; monkey.patch_all() ``` Go to <http://www.gevent.org/in...
Encoding ☺ as IBM-437 fails while other valid characters like é succeed
14,553,178
3
2013-01-27T22:41:22Z
14,553,297
7
2013-01-27T22:56:07Z
[ "python", "encoding", "python-3.x", "codepages" ]
☺: ``` >>> bytes('☺','ibm437') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.3/encodings/cp437.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character '\u263a' in position 0: c...
IBM-437 is somewhat special in that it is not only a codepage (i.e. defines what should happen for byte values 128-255), but also redefines some of the ASCII control characters, [but only in some contexts](http://en.wikipedia.org/wiki/Code_page_437#Interpretation_of_code_points_1.E2.80.9331_and_127). Python maps those ...
Numpy __getitem__ delayed evaluation and a[-1:] not the same as a[slice(-1, None, none)]
14,553,485
7
2013-01-27T23:22:48Z
14,555,197
7
2013-01-28T03:49:59Z
[ "python", "numpy", "magic-methods" ]
So this is two questions about what I'm assuming is the same basic underlying confusion on my part. I hope that's ok. Here some code: ``` import numpy as np class new_array(np.ndarray): def __new__(cls, array, foo): obj = array.view(cls) obj.foo = foo return obj def __array_finalize...
You've been bit by a nasty bug indeed. It's kind of a relief to know I am not the only one! Fortunately it is easy to solve. Just add something like the following to your class. This is actually a copy-paste from some code I wrote a few months back, the docstring sort of tells what is going on, but you may want to read...
python setup.py sdist only including .py source from top level module
14,553,787
4
2013-01-28T00:09:11Z
14,553,799
7
2013-01-28T00:12:13Z
[ "python", "setup.py", "sdist" ]
I have a setup.py: ``` from setuptools import setup setup( ... packages=['mypackage'], test_suite='mypackage.tests', ... ) ``` `python setup.py sdist` creates a file that includes only the source modules from top-level mypackage and not mypackage.tests nor any other submodules. What am I...
Use the [`find_packages()` function](https://pythonhosted.org/setuptools/setuptools.html#using-find-packages): ``` from setuptools import setup, find_packages setup( # ... packages=find_packages(), ) ``` The function will search for python packages (directories with a `__init__.py` file) and return these as ...
RuntimeError: maximum recursion depth exceeded with Python 3.2 pickle.dump
14,556,350
2
2013-01-28T06:08:52Z
16,942,981
7
2013-06-05T14:46:56Z
[ "python" ]
I'm getting the above error with the code below. The error occurs at the last line. Please excuse the subject matter, I'm just practicing my python skills. =) ``` from urllib.request import urlopen from bs4 import BeautifulSoup from pprint import pprint from pickle import dump moves = dict() moves0 = set() url = 'htt...
Just want to contribute an answer for anyone else who may have this issue. Specifically, I was having it with caching BeautifulSoup objects in a Django session from a remote API. The short answer is the pickling BeautifulSoup nodes is not supported. I instead opted to store the original string data in my object and ha...
Is there a random number distribution that obeys Benford's Law?
14,556,451
9
2013-01-28T06:17:11Z
14,556,655
19
2013-01-28T06:34:50Z
[ "python", "random", "benfords-law" ]
Python has a number of ways to generate different distributions of random numbers, see the [documentation for the `random` module](http://docs.python.org/2/library/random.html). Unfortunately they aren't terribly understandable without the appropriate math background, especially considering the required parameters. I'...
Benford's law describes the distribution of the first digits of a set of numbers if the numbers are chosen from a wide range on the logarithmic scale. If you prepare a log-uniform distribution over one decade, it will respect the law as well. `10^[0,1)` will produce that distribution. This will produce the desired dis...
Why matplotlib does not plot?
14,558,843
11
2013-01-28T09:19:15Z
14,559,772
34
2013-01-28T10:15:22Z
[ "python", "matplotlib" ]
I started to learn MatPlotLib using [this](http://www.loria.fr/~rougier/teaching/matplotlib/) tutorial for beginners. Here is the first example. ``` from pylab import * X = np.linspace(-np.pi, np.pi, 256,endpoint=True) C,S = np.cos(X), np.sin(X) ``` If I write these 3 lines into my python file and execute it in the c...
It could be a problem with the backend. What is the output of `python -c 'import matplotlib; import matplotlib.pyplot; print(matplotlib.backends.backend)'`? If it is the 'agg' backend, what you see is the expected behaviour as it is a non-interactive backend that does not show anything to the screen, but work with plt...
Django 1.4 - Redirect to Non-HTTP urls
14,558,876
8
2013-01-28T09:21:55Z
14,558,985
13
2013-01-28T09:28:35Z
[ "python", "django", "url", "redirect", "django-1.4" ]
We have a view which redirects to a Non-HTTP url scheme. Its used in an iOS app. But since we have upgraded to Django1.4 we are getting a crash when this redirect code is executed. It crashes with > SuspeciousOperation at /myyrlscheme/ > > Unsafe redirect to URL with scheme appdev: Following is the code: ``` if acod...
I believe you'll need to have a custom Response object, consider following: ``` response = HttpResponse("", status=302) response['Location'] = "appdev://..." return response ```
Scipy Fast 1-D interpolation without any loop
14,559,687
6
2013-01-28T10:09:13Z
14,572,907
11
2013-01-28T23:05:22Z
[ "python", "numpy", "matplotlib", "scipy" ]
I have two 2D array, x(ni, nj) and y(ni,nj), that I need to interpolate over one axis. I want to interpolate along last axis for every ni. I wrote ``` import numpy as np from scipy.interpolate import interp1d z = np.asarray([200,300,400,500,600]) out = [] for i in range(ni): f = interp1d(x[i,:], y[i,:], kind='li...
The method you propose does have a python loop, so for large values of `ni` it is going to get slow. That said, unless you are going to have large `ni` you shouldn't worry much. I have created sample input data with the following code: ``` def sample_data(n_i, n_j, z_shape) : x = np.random.rand(n_i, n_j) * 1000 ...
Python - Join with newline
14,560,863
16
2013-01-28T11:18:20Z
14,560,881
10
2013-01-28T11:19:24Z
[ "python", "string" ]
In the Python console, when I type: ``` >>> "\n".join(['I', 'would', 'expect', 'multiple', 'lines']) ``` Gives: ``` 'I\nwould\nexpect\nmultiple\nlines' ``` Though I'd expect to see such an output: ``` I would expect multiple lines ``` What am I missing here?
You forgot to `print` the result. What you get is the `P` in [`RE(P)L`](http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) and not the actual printed result. In Py2.x you should so something like ``` >>> print "\n".join(['I', 'would', 'expect', 'multiple', 'lines']) I would expect multiple lines ``` ...
Python - Join with newline
14,560,863
16
2013-01-28T11:18:20Z
14,560,887
23
2013-01-28T11:20:06Z
[ "python", "string" ]
In the Python console, when I type: ``` >>> "\n".join(['I', 'would', 'expect', 'multiple', 'lines']) ``` Gives: ``` 'I\nwould\nexpect\nmultiple\nlines' ``` Though I'd expect to see such an output: ``` I would expect multiple lines ``` What am I missing here?
The console is printing the representation, not the string itself. If you prefix with `print`, you'll get what you expect. See [this question](http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python) for details about the difference between a string and the string's representation. Super-...
How to forecast in python using machine learning , from a given set of geographical data?
14,562,625
8
2013-01-28T13:00:35Z
14,563,092
17
2013-01-28T13:27:59Z
[ "python", "numpy", "machine-learning", "scikit-learn", "forecasting" ]
I was analyzing some geographical data and attempting to predict/forecast next occurrence of event with respect to time and it geographical position. The data was in following order (with sample data) ``` Timestamp Latitude Longitude Event 13307266 102.86400972 70.64039541 "Event A" 13311695 102.8082912 70.4...
Without example data or existing code I can't offer you anything concrete. However, often it's helpful to re-phrase your problem in the nomenclature of the field you want to explore. In ML terms: * Your problem's **features**: How your inputs are specified. Timestamp is continuous, geographic zone is discrete. * Your...
Python equivalent of sum() using xor()
14,562,991
5
2013-01-28T13:23:00Z
14,563,018
16
2013-01-28T13:24:46Z
[ "python", "sum", "xor" ]
I like the Python sum function : ``` >>> z = [1] * 11 >>> zsum = sum(z) >>> zsum == 11 True ``` I want the same functionality with using xor (^) not add (+). I want to use map. But I can not work out how to do this. Any hints? I am not satisfied with this : ``` def xor(l): r = 0 for v in l: r ^= v retur...
``` zxor = reduce(lambda a, b: a ^ b, z, 0) import operator zxor = reduce(operator.xor, z, 0) ```
Python py2exe window showing (tkinter)
14,566,531
4
2013-01-28T16:27:43Z
14,566,647
7
2013-01-28T16:34:26Z
[ "python", "tkinter", "py2exe" ]
I'm trying to make an exe by py2exe. The program is showing a popup-like window using Tkinter. The problem is, everything works fine when I run the setup like this: ``` setup(windows = [{'script': "msg.py"}], zipfile = None) ``` but it fails when I try to make an one-file exe: ``` setup(windows = [{'script': "msg.py...
I ended up encountering this same issue, my solution involved doing the following: Add `"dll_excludes": ["tcl85.dll", "tk85.dll"],` in your `options = {...}` and then manually copy those two DLLs from `PYTHON_PATH\DLLs\` (in my case `C:\Python27\DLLs`) to the location of your exe and try running it.
numpy.sum may be slower than Python for-loop
14,566,564
6
2013-01-28T16:30:03Z
14,573,065
8
2013-01-28T23:18:46Z
[ "python", "performance", "numpy", "vectorization" ]
When summing an array over a specific axis, the dedicated array method `array.sum(ax)` may actually be slower than a for-loop : ``` v = np.random.rand(3,1e4) timeit v.sum(0) # vectorized method 1000 loops, best of 3: 183 us per loop timeit for row in v[1:]: v[0] += row # python loo...
No you can't. As your interesting example points out `numpy.sum` can be suboptimal, and a better layout of the operations via explicit for loops can be more efficient. Let me show another example: ``` >>> N, M = 10**4, 10**4 >>> v = np.random.randn(N,M) >>> r = np.empty(M) >>> timeit.timeit('v.sum(axis=0, out=r)', 'f...
How to use Flask-Script and Gunicorn
14,566,570
12
2013-01-28T16:30:17Z
14,569,881
11
2013-01-28T19:43:45Z
[ "python", "flask", "gunicorn" ]
I'm working on on a Flask app using Flask's built in dev server. I start it using Flask-Script. I want to switch to using Gunicorn as the web server. To do so, do I need to write some sort of integration code between Flask-Script and Gunicorn? Or is Flask-Script irrelevant to running the app using Gunicorn? Thanks in ...
As Dhaivat said, you can just use your Flask app directly with Gunicorn. If you still want to use Flask-Script, you will need to create a custom `Command`. I don't have any experience with Gunicorn, but I found a similar [solution](https://bitbucket.org/youngking/flask-actions/src/381d6eea3e78/flaskext/actions/server_...
Django: why i can't get the tracebacks (in case of error) when i run LiveServerTestCase tests?
14,566,757
11
2013-01-28T16:40:41Z
14,586,614
17
2013-01-29T15:39:23Z
[ "python", "django", "debugging", "selenium", "traceback" ]
I'm writing some tests with Selenium. When i run my selenium tests (`LiveServerTestCase` type) and i have some error in my code (not in the test, i mean in the code executed, like the homepage view i reach with selenium) i get the 500 template (that usually i get when i have DEBUG = False) even if i have: ``` DEBUG =...
from the django docs <https://docs.djangoproject.com/en/1.4/topics/testing/#other-test-conditions> Seems not possible to override this at this moment, even with <https://docs.djangoproject.com/en/1.4/topics/testing/#django.test.utils.override_settings> the only way to see the debug information when it's returned a 50...
Pandas installation on Mac OS X: ImportError (cannot import name hashtable)
14,568,070
13
2013-01-28T17:51:55Z
14,568,392
30
2013-01-28T18:12:24Z
[ "python", "hashtable", "pandas", "cython", "importerror" ]
I would like to build pandas from source rather than use a package manager because I am interested in contributing. **The first time** I tried to build pandas, these were the steps I took: 1) created the virtualenv `mkvirtualenv --no-site-packages pandas` 2) activated the virtualenv 3) installed Anaconda CE. However...
I've received the same error (`ImportError: cannot import name hashtable`) when trying to import pandas from the source code directory. Try starting the python interpreter from a different directory and import pandas again.
Convert matplotlib data units to normalized units
14,568,545
3
2013-01-28T18:21:37Z
14,570,619
8
2013-01-28T20:27:59Z
[ "python", "matplotlib", "plot" ]
Does anyone know how to convert matplotlib data units into normalized units? The reason that I need it is that I need to create a subplot on top of another plot. And the default syntax: ``` plt.axes([0.1,0.1,0.3,0.3]) ``` requires normalized coordinates, but I want to use the data coordinates: For example this code...
Here's one way to do it: inner `axes` printed at `0.5, 2.5, 1.0, 0.3` (in outer `axes` coords) ![inner axes printed at 0.5, 2.5, 1.0, 0.3 (in outer axes coords)](http://i.stack.imgur.com/irWEa.png) You basically need two transformations -- one from src-coords to display, and one from display to dest-coord. From the ...
Create .zip in Python?
14,568,647
23
2013-01-28T18:27:40Z
14,569,017
42
2013-01-28T18:50:17Z
[ "python", "zip", "zipfile" ]
I'm trying to create a function in my script that zips the contents of a given source directory (`src`) to a zip file (`dst`). For example, `zip('/path/to/dir', '/path/to/file.zip')`, where `/path/to/dir` is a directory, and `/path/to/file.zip` doesn't exist yet. I **do not** want to zip the directory itself, this make...
The [`zipfile.write()`](http://docs.python.org/2/library/zipfile#zipfile.ZipFile.write) method takes an optional `arcname` argument that specifies what the name of the file should be inside the zipfile. You can use this to strip off the path to `src` at the beginning. Here I use [`os.path.abspath()`](http://docs.pytho...
Which is faster, numpy transpose or flip indices?
14,570,513
6
2013-01-28T20:21:02Z
14,570,676
8
2013-01-28T20:31:35Z
[ "python", "performance", "numpy", "transpose" ]
I have a dynamic programming algorithm (modified Needleman-Wunsch) which requires the same basic calculation twice, but the calculation is done in the orthogonal direction the second time. For instance, from a given cell *(i,j)* in matrix *scoreMatrix*, I want to both calculate a value from values "up" from *(i,j)*, as...
In NumPy, transpose returns a view with a different shape and [strides](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.strides.html). It does not touch the data. Therefore, you will likely find that the two approaches have identical performance, since in essence they are exactly the same. However, ...
k-means in python: Determine which data are associated with each centroid
14,570,610
4
2013-01-28T20:27:24Z
14,570,732
8
2013-01-28T20:34:52Z
[ "python", "scipy", "cluster-analysis", "k-means" ]
I've been using `scipy.cluster.vq.kmeans` for doing some k-means clustering, but was wondering if there's a way to determine which centroid each of your data points is (putativly) associated with. Clearly you could do this manually, but as far as I can tell the kmeans function doesn't return this?
There is a function `kmeans2` in `scipy.cluster.vq` that returns the labels, too. ``` In [8]: X = scipy.randn(100, 2) In [9]: centroids, labels = kmeans2(X, 3) In [10]: labels Out[10]: array([2, 1, 2, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 2, 2, 1, 2, 1, 2, 1, 2, 0, 1, 0, 2, 0, 1, 2, 0, 1, 0, 1, 1, 2, 2, 2, 2, 1, ...
IPython: redirecting output of a Python script to a file (like bash >)
14,571,090
19
2013-01-28T20:56:45Z
14,573,397
23
2013-01-28T23:53:11Z
[ "python", "io", "ipython" ]
I have a Python script that I want to run in IPython. I want to redirect (write) the output to a file, similar to: ``` python my_script.py > my_output.txt ``` How do I do this when I run the script in IPython, i.e. like `execfile('my_script.py')` There is an [older page](http://rcjp.wordpress.com/2009/03/24/redirect...
IPython has its own context manager for [capturing stdout/err](https://github.com/ipython/ipython/blob/rel-0.13.1/IPython/utils/io.py#L359), but it doesn't redirect to files, it redirects to an object: ``` from IPython.utils import io with io.capture_output() as captured: %run my_script.py print captured.stdout #...
Check if all numbers in a list are same sign in Python?
14,571,099
3
2013-01-28T20:57:28Z
14,571,124
15
2013-01-28T20:58:52Z
[ "python", "list", "python-2.7", "sign" ]
How can I tell if a list (or iterable) of numbers all have the same sign? Here's my first (naive) draft: ``` def all_same_sign(list): negative_count = 0 for x in list: if x < 0: negative_count += 1 return negative_count == 0 or negative_count == len(list) ``` Is there a more python...
You can make use of `all` function: - ``` >>> x = [1, 2, 3, 4, 5] >>> all(item >= 0 for item in x) or all(item < 0 for item in x) True ``` Don't know whether it's the most pythonic way.
Check if all numbers in a list are same sign in Python?
14,571,099
3
2013-01-28T20:57:28Z
14,571,132
13
2013-01-28T20:59:15Z
[ "python", "list", "python-2.7", "sign" ]
How can I tell if a list (or iterable) of numbers all have the same sign? Here's my first (naive) draft: ``` def all_same_sign(list): negative_count = 0 for x in list: if x < 0: negative_count += 1 return negative_count == 0 or negative_count == len(list) ``` Is there a more python...
How about: ``` same_sign = not min(l) < 0 < max(l) ``` Basically, this checks whether the smallest element of `l` and the largest element straddle zero. This doesn't short-circuit, but does avoid Python loops. Only benchmarking can tell whether this is a good tradeoff for your data (and whether the performance of th...
How to delete a subwindow in the python curses module
14,571,860
4
2013-01-28T21:48:41Z
14,733,235
7
2013-02-06T15:56:43Z
[ "python", "curses" ]
I've got a curses application that uses subwindows, but I can't seem to be able to delete them. For example, this code doesn't work: ``` import curses def fill(window, ch): y, x = window.getmaxyx() s = ch * (x - 1) for line in range(y): window.addstr(line, 0, s) def main(stdscr): fill(stdscr,...
Is there a good reason why you're using a subwindow? If you create a new top-level window then the code works correctly - simply change `stdscr.subwin` to `curses.newwin` and it works as you'd expect. I'm not a curses expert, but I believe a subwindow shares the character buffer with its parent such that changes to ei...