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
Extracting image src based on attribute with BeautifulSoup
18,304,532
5
2013-08-18T23:09:03Z
18,304,676
8
2013-08-18T23:35:47Z
[ "python", "html-parsing", "web-scraping", "beautifulsoup" ]
I'm using BeautifulSoup to get a HTML page from IMDb, and I would like to extract the poster image from the page. I've got the image based on one of the attributes, but I don't know how to extract the data inside it. Here's my code: ``` url = 'http://www.imdb.com/title/tt%s/' % (id) soup = BeautifulSoup(urllib2.urlop...
You're almost there - just a couple of mistakes. `soup.find()` gets the first element that matches, not a list, so you don't need to iterate over it. Once you have got the element, you can get its attributes (like `src`) using dictionary access. Here's a reworked version: ``` film_id = '0423409' url = 'http://www.imdb...
Python: find contour lines from matplotlib.pyplot.contour()
18,304,722
9
2013-08-18T23:26:19Z
18,309,914
15
2013-08-19T08:57:59Z
[ "python", "numpy", "matplotlib", "spatial", "contour" ]
I'm trying to find (but not draw!) contour lines for some data: ``` from pprint import pprint import matplotlib.pyplot z = [[0.350087, 0.0590954, 0.002165], [0.144522, 0.885409, 0.378515], [0.027956, 0.777996, 0.602663], [0.138367, 0.182499, 0.460879], [0.357434, 0.297271, 0.587715]] cn = matplotlib.pyp...
You can get the vertices back by looping over collections and paths and using the `iter_segments()` method of [`matplotlib.path.Path`](http://matplotlib.org/api/path_api.html#matplotlib.path.Path). Here's a function that returns the vertices as a set of nested lists of contour lines, contour sections and arrays of x,y...
How to compute the center of a polygon in 2D and 3D space
18,305,712
2
2013-08-19T02:43:05Z
18,307,215
7
2013-08-19T05:58:14Z
[ "c++", "python", "matlab", "geometry", "polygon" ]
Consider a **simple convex polygon** in 2D Cartesian space. If given a list of vertex coordinates sorted in a **counter-clockwise orientation** like this `[[x0, y0], ..., [xn, yn]]`. How could you compute the center of the polygon (the point inside the polygon that is **equidistant to all vertices**)? Also consider a ...
You definition of center doesn't make sense in general. To see this just draw three non-aligned points on a plane and compute the one an only circle that passes for all three points. Clearly your center of the triangle must be the center of this circle. Now draw a fourth point that doesn't lie on the circle and form ...
How to create HTTPS tornado server
18,307,131
11
2013-08-19T05:50:52Z
18,307,308
24
2013-08-19T06:05:39Z
[ "python", "python-3.x", "tornado" ]
Please help me to create HTTPS tornado server My current code Python3 doesn't work ``` import os, socket, ssl, pprint, tornado.ioloop, tornado.web, tornado.httpserver from tornado.tcpserver import TCPServer class getToken(tornado.web.RequestHandler): def get(self): self.write("hello") application = torna...
No need to use `TCPServer`. Try following: ``` import tornado.httpserver import tornado.ioloop import tornado.web class getToken(tornado.web.RequestHandler): def get(self): self.write("hello") application = tornado.web.Application([ (r'/', getToken), ]) if __name__ == '__main__': http_server = ...
Python Requests package: Handling xml response
18,308,529
35
2013-08-19T07:29:48Z
18,308,594
65
2013-08-19T07:33:55Z
[ "python", "xml", "httprequest", "python-requests" ]
I like very much the `requests` package and its comfortable way to handle JSON responses. Unfortunately, I did not understand if I can also process XML responses. Has anybody experience how to handle XML responses with the `requests` package? Is it necessary to include another package such as `urllib2` for the XML dec...
`requests` does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward. Python comes with built-in XML parsers. I recommend you use the [ElementTree API](http://docs.python.org/2/libra...
Is freeing handled differently for small/large numpy arrays?
18,310,668
10
2013-08-19T09:37:40Z
18,311,900
12
2013-08-19T10:44:44Z
[ "python", "memory", "memory-management", "numpy", "memory-leaks" ]
I am trying to debug a memory problem with my large Python application. Most of the memory is in `numpy` arrays managed by Python classes, so [Heapy](http://guppy-pe.sourceforge.net/) etc. are useless, since they do not account for the memory in the `numpy` arrays. So I tried to manually track the memory usage using th...
Reading from [Numpy's policy for releasing memory](http://numpy-discussion.10968.n7.nabble.com/Numpy-s-policy-for-releasing-memory-td1533.html) it seems like `numpy` does *not* have any special handling of memory allocation/deallocation. It simply calls `free()` when the reference count goes to zero. In fact it's prett...
Python 3, Converting a string storing binary data to Int
18,311,500
3
2013-08-19T10:25:06Z
18,311,529
7
2013-08-19T10:26:42Z
[ "python", "string", "binary" ]
I have the variable Number which is equal to "0b11001010" and I want it to be the type int like a normal binary is stored e.g. 0b11001010 ``` Number = "0b11001010" NewNumber = 0b11001010 ``` is there a really simple way and I am overlooking it? Thanks.
In python you can only create it as a binary value (as a syntactic sugar), it will be converted into an integer immediately. Try it for yourself: ``` >>> 0b11001010 202 ``` The same thing will happen with octal and hexadecimal values. So you can convert your binary string to an integer, with the `int()` function's `b...
How can I split a string into tokens?
18,312,447
6
2013-08-19T11:15:34Z
18,312,518
13
2013-08-19T11:18:42Z
[ "python", "token", "tokenize", "equation", "shlex" ]
If I have a string ``` 'x+13.5*10x-4e1' ``` how can I split it into the following list of tokens? ``` ['x', '+', '13', '.', '5', '*', '10', 'x', '-', '4', 'e', '1'] ``` Currently I'm using the shlex module: ``` str = 'x+13.5*10x-4e1' lexer = shlex.shlex(str) tokenList = [] for token in lexer: tokenList.append(...
Use the regular expression module's `split()` function, to split at * `'\d+'` -- digits (number characters) and * `'\W+'` -- non-word characters: **CODE:** ``` import re print([i for i in re.split(r'(\d+|\W+)', 'x+13.5*10x-4e1') if i]) ``` **OUTPUT:** ``` ['x', '+', '13', '.', '5', '*', '10', 'x', '-', '4', 'e', ...
Access index in pandas.Series.apply
18,316,211
27
2013-08-19T14:22:07Z
18,316,830
20
2013-08-19T14:52:38Z
[ "python", "pandas" ]
Lets say I have a MultiIndex Series `s`: ``` >>> s values a b 1 2 0.1 3 6 0.3 4 4 0.7 ``` and I want to apply a function which uses the index of the row: ``` def f(x): # conditions or computations using the indexes if x.index[0] and ...: other = sum(x.index) + ... return something ``` How can ...
I don't believe `apply` has access to the index; it treats each row as a numpy object, not a Series, as you can see: ``` In [27]: s.apply(lambda x: type(x)) Out[27]: a b 1 2 <type 'numpy.float64'> 3 6 <type 'numpy.float64'> 4 4 <type 'numpy.float64'> ``` To get around this limitation, promote the indexe...
Initialize all the classes in a module into nameless objects in a list
18,316,820
6
2013-08-19T14:51:49Z
18,317,154
7
2013-08-19T15:07:19Z
[ "python", "oop" ]
Is there a way to initialize all classes from a python module into a list of nameless objects? **Example** I have a module `rules` which contains all child classes from a class Rule. Because of that, I'm certain they will all implement a method `run()` and will have a attribute `name` which will be generated during th...
There are at least two approaches you can take. You can get all of the subclasses of a class by calling a class's `__subclasses__()` method. So if your parent class is called `Rule`, you could call: ``` rule_list = [cls() for cls in Rule.__subclasses__()] ``` This will give you all subclasses of `Rule`, and will not ...
How can I combine range() functions
18,317,913
4
2013-08-19T15:47:45Z
18,317,968
7
2013-08-19T15:50:33Z
[ "python", "python-2.x" ]
For some code I'm writing, I need to iterate from 1-30 skipping 6. What I tried naively is ``` a = range(1,6) b = range(7,31) for i in a+b: print i ``` Is there a way to do it more efficiently?
Use [`itertools.chain`](http://docs.python.org/2/library/itertools.html#itertools.chain): ``` import itertools a = range(1,6) b = range(7,31) for i in itertools.chain(a, b): print i ``` Or tricky flattening generator expressions: ``` a = range(1,6) b = range(7,31) for i in (x for y in (a, b) for x in y): p...
How can I combine range() functions
18,317,913
4
2013-08-19T15:47:45Z
18,317,975
7
2013-08-19T15:50:52Z
[ "python", "python-2.x" ]
For some code I'm writing, I need to iterate from 1-30 skipping 6. What I tried naively is ``` a = range(1,6) b = range(7,31) for i in a+b: print i ``` Is there a way to do it more efficiently?
In python 2 you are not combining "range functions"; these are just lists. Your example works just well. But range always creates a full list in memory, so a better way if only needed in for loop could be to to use a generator expression and xrange: ``` range_with_holes = (j for j in xrange(1, 31) if j != 6) for i in...
Reverse Z Axis on matplotlib 3D Plot
18,318,763
4
2013-08-19T16:33:54Z
18,318,831
8
2013-08-19T16:38:15Z
[ "python", "matplotlib", "mplot3d" ]
How would one reverse the order on the z axis of a 3D plot (i.e. negative is up, and positive is down)? The following code produces a cone with the base pointing downward; is there a command (like `ax.reverse_zlim3d(True)` or something?) that can be used to change the tick order? The following code plots a cone with t...
Use the [`invert_zaxis`](http://matplotlib.org/mpl_toolkits/mplot3d/api.html?highlight=invert_zaxis#mpl_toolkits.mplot3d.axes3d.Axes3D.invert_zaxis) method of the `Axes3D`: ``` from matplotlib import pyplot as p from mpl_toolkits.mplot3d import Axes3D # @UnusedImport import numpy as np from math import pi, cos, si...
What's the best way to generate random strings of a specific length in Python?
18,319,101
22
2013-08-19T16:55:53Z
18,319,156
58
2013-08-19T16:59:21Z
[ "python", "random" ]
For a project, I need a method of creating thousands of random strings while keeping collisions low. I'm looking for them to be only 12 characters long and uppercase only. Any suggestions?
**CODE:** ``` from random import choice from string import ascii_uppercase print(''.join(choice(ascii_uppercase) for i in range(12))) ``` **OUTPUT:** *5 examples:* ``` QPUPZVVHUNSN EFJACZEBYQEB QBQJJEEOYTZY EOJUSUEAJEEK QWRWLIWDTDBD ``` --- **EDIT:** If you need only digits, use the `digits` constant instead of...
What's the best way to generate random strings of a specific length in Python?
18,319,101
22
2013-08-19T16:55:53Z
28,490,542
9
2015-02-13T00:32:01Z
[ "python", "random" ]
For a project, I need a method of creating thousands of random strings while keeping collisions low. I'm looking for them to be only 12 characters long and uppercase only. Any suggestions?
By `Django`, you can use `get_random_string` function in `django.utils.crypto` module. ``` get_random_string(length=12, allowed_chars=u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') Returns a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set...
Python installing setuptools, ez_setup.py error
18,320,925
5
2013-08-19T18:48:36Z
18,387,915
11
2013-08-22T18:14:08Z
[ "python", "setuptools" ]
I am trying to install setuptools on Windows. The documentation says I should run ez\_setup.py. So I did and I get the following output: ``` Extracting in c:\users\ut601039\appdata\local\temp\tmpf6a2mb Now working in c:\users\ut601039\appdata\local\temp\tmpf6a2mb\setuptools-1.0 Installing Setuptools Something went...
how are you trying to run & install it? ideally.. run cmd then cd to extracted folder & run `python setup.py install` this should install it.. if you are on 64 bit windows with 64bit python then you need to get the appropriate version can be found here: (<http://www.lfd.uci.edu/~gohlke/pythonlibs/#setuptools>)
Django-Grappelli: Reverse for 'grp_related_lookup' with arguments '()' and keyword arguments '{}' not found
18,321,026
11
2013-08-19T18:54:38Z
23,156,851
20
2014-04-18T15:06:39Z
[ "python", "django", "django-grappelli" ]
I use django-grappelli to create orderable inlines on the admin site. Occasionally (not reproducibly - about 50% of the time, which is particularly weird), Django throws the following exception when I try to save the ordering from the inline: ``` Exception Type: NoReverseMatch Exception Value: Reverse for 'grp_relat...
You probably forgot to add grappelli urls into your urls.py (at least it was the case for me) ``` url(r'^grappelli/', include('grappelli.urls')), ```
Program for word reversal randomly skips out letters?
18,321,318
5
2013-08-19T19:11:59Z
18,321,356
7
2013-08-19T19:14:52Z
[ "python" ]
My program keeps randomly skipping out letters! For example, 'coolstory' becomes 'yrotsloc' and 'awesome' becomes 'mosewa' Here is the code: ``` def reverse(text): length = len(text) reversed_text = [] for i in range(0,length + 1): reversed_text += [''] original_list = [] for l in text: ...
This happens when you have duplicate letters because ``` original_list.index(l) ``` will always return the same value for the same `l`. So `new_place` will be the same for two of the same letters at different locations. One common way to reverse strings in Python is with slicing: ``` >>> s = "hello" >>> s[::-1] 'ol...
how to setup custom middleware in django
18,322,262
32
2013-08-19T20:10:55Z
32,242,074
51
2015-08-27T06:24:16Z
[ "python", "django", "django-views", "django-middleware" ]
I am trying to create middleware to optionally pass a kwarg to every view that meets a condition. The problem is that I cannot find an example of how to setup the middleware. I have seen classes that override the method I want to, process\_view: ``` Class CheckConditionMiddleware(object): def process_view(self,...
# First: The path structure If you don't have it you need to create the **middleware** folder within your app following the structure: ``` yourproject/yourapp/middleware ``` *The folder middleware should be placed in the same folder as settings.py, urls, templates...* **Important: Don't forget to create the \_\_ini...
PyTesser simple usage error
18,322,933
5
2013-08-19T20:54:17Z
18,324,406
10
2013-08-19T22:54:06Z
[ "python", "ocr" ]
I've downloaded [PyTesser](https://code.google.com/p/pytesser/) and extracted it. I was in the `pytesser_v0.0.1` folder and tried to run the [sample usage](https://code.google.com/p/pytesser/#Usage_Example) code in the python interpreter: ``` from pytesser import * print image_file_to_string('fnord.tif') ``` and the...
This isn't as well documented as it could be, but if you are not on Windows you need to install the `tesseract` binary for your platform. On Ubuntu and other Debian based Linux distributions, `apt-get install tesseract-ocr`. Then you can run: ``` python pytesser.py ``` which uses the test files `phototest.tif`, `fnor...
How can I check if a string has the same characters? Python
18,325,280
2
2013-08-20T00:48:49Z
18,325,300
8
2013-08-20T00:51:04Z
[ "python", "string", "python-2.7" ]
I need to be able to discern if a string of an arbitrary length, greater than 1 (and only lowercase), has the same set of characters within a base or template string. For example, take the string "aabc": "azbc" and "aaabc" would be false while "acba" would be true. Is there a fast way to do this in python without kee...
Sort the two strings and then compare them: ``` sorted(str1) == sorted(str2) ``` If the strings might not be the same length, you might want to make sure of that first to save time: ``` len(str1) == len(str2) and sorted(str1) == sorted(str2) ```
Python script that prints its source
18,326,002
4
2013-08-20T02:19:30Z
18,326,087
7
2013-08-20T02:30:34Z
[ "python" ]
Is it possible (not necessarly using python introspection) to print the source code of a script? I want to execute a short python script that also print its source (so I can see which commands are executed). The script is something like this: ``` command1() #command2() command3() print some_variable_that_contain_sr...
As long as you're not doing anything crazy with packages, put this at the top of your script ``` with open(__file__) as f: print f.read() ``` Which will read in the current file and print it out.
Python class variable name vs __name__
18,326,719
6
2013-08-20T03:56:23Z
18,326,791
7
2013-08-20T04:03:49Z
[ "python", "class" ]
I'm trying to understand the relationship between the variable a Python class object is assigned to and the `__name__` attribute for that class object. For example: ``` In [1]: class Foo(object): ...: pass ...: In [2]: Foo.__name__ = 'Bar' In [3]: Foo.__name__ Out[3]: 'Bar' In [4]: Foo Out[4]: __main__.B...
It's simple. There is no relationship at all. When you create a class a local variable is created with name you used, pointing at the class so you can use it. The class also gets an attribute `__name__` that contains the name of that variable, because that's handy in certain cases, like pickling. You can set the loc...
Find element's index in pandas Series
18,327,624
18
2013-08-20T05:33:54Z
18,327,852
25
2013-08-20T05:52:43Z
[ "python", "pandas" ]
I know this is a very basic question but for some reason I can't find an answer. How can I get the index of certain element of a Series in python pandas? (first occurrence would suffice) I.e., I'd like something like: ``` import pandas as pd myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4]) print myseries.find(7) ...
``` >>> myseries[myseries == 7] 3 7 dtype: int64 >>> myseries[myseries == 7].index[0] 3 ``` Though I admin that there should be a better way to do that, but this at least avoids iterating and looping through the object and moves it to the C level.
Find element's index in pandas Series
18,327,624
18
2013-08-20T05:33:54Z
18,334,025
11
2013-08-20T11:37:59Z
[ "python", "pandas" ]
I know this is a very basic question but for some reason I can't find an answer. How can I get the index of certain element of a Series in python pandas? (first occurrence would suffice) I.e., I'd like something like: ``` import pandas as pd myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4]) print myseries.find(7) ...
Converting to an Index, you can use `get_loc` ``` In [1]: myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4]) In [3]: Index(myseries).get_loc(7) Out[3]: 3 In [4]: Index(myseries).get_loc(10) KeyError: 10 ``` Duplicate handling ``` In [5]: Index([1,1,2,2,3,4]).get_loc(2) Out[5]: slice(2, 4, None) ``` Will return ...
How to get index of element in Set object
18,329,308
9
2013-08-20T07:29:54Z
18,329,412
20
2013-08-20T07:35:48Z
[ "python" ]
I have something like this: ``` numberList = {} for item in results: data = json.loads(item[0]) if data[key] in itemList: numberList[itemList.index(data[key])] += 1 print numberList ``` where itemList is 'set' object. How can I access index of single element in ...
A set is just an unordered collection of unique elements. So, an element is either in a set or it isn't. This means that no element in a set has an index. Consider the set `{1, 2, 3}`. The set contains 3 elements: 1, 2, and 3. There's no concept of indices or order here; the set just contains those 3 values. So, if `...
python value becomes zero, how to prevent
18,331,966
2
2013-08-20T09:48:33Z
18,332,194
7
2013-08-20T09:59:08Z
[ "python", "numpy", "floating-point", "statistics", "rounding" ]
I have a numerical problem while doing likelihood ratio tests in python. I'll not go into too much detail about what the statistics mean, my problems comes down to calculating this: ``` LR = LR_H0 / LR_h1 ``` where `LR` is the number of interest and `LR_H0` and `LR_H1` are numbers that can be *VERY* close to zero. Th...
Work with logarithms. Take the log of all your likelihoods, and add or subtract logarithms instead of multiplying and dividing. You'll be able to work with much greater ranges of values without losing precision.
How to read an array of integers from single line of input in python3
18,332,801
2
2013-08-20T10:32:36Z
18,332,884
7
2013-08-20T10:36:28Z
[ "python", "arrays", "list", "input", "python-3.2" ]
I want to read an array of integers from single line of input in python3. For example: Read this array to a variable/list ``` 1 3 5 7 9 ``` ### What I have tried 1. `arr = input.split(' ')` But this does not convert them to integers. It creates array of strings 2. `arr = input.split(' ')` `for i,val in enumerate...
Use `map`: ``` arr = list(map(int, input.split())) ``` Just adding, in Python 2.x you don't need the to call `list()`, since `map()` already returns a `list`, but in Python 3.x ["many processes that iterate over iterables return iterators themselves"](http://stackoverflow.com/a/1303354/832621).
out of memory issue in installing packages on Ubuntu server
18,334,366
26
2013-08-20T11:55:10Z
18,335,151
68
2013-08-20T12:32:38Z
[ "python", "gcc", "ubuntu", "memory-management", "lxml" ]
I am using a Ubuntu cloud server with limited 512MB RAM and 20 GB HDD. Its 450MB+ RAM is already used by processes. I need to install a new package called `lxml` which gets complied using `Cpython` while installation and its a very heavy process so it always exits with error `gcc: internal compiler error: Killed (prog...
Extend your RAM by adding a swap file: <http://www.cyberciti.biz/faq/linux-add-a-swap-file-howto/> > a swap file is a file stored on the computer hard drive that is used > as a temporary location to store information that is not currently > being used by the computer RAM. By using a swap file a computer has > the abil...
scikit-learn install failure / numpy not found / missing numpy headers
18,334,472
3
2013-08-20T11:59:30Z
18,358,965
7
2013-08-21T13:37:37Z
[ "python", "numpy", "install", "scikit-learn", "opensuse" ]
When i try to install scikit-learn on a Suse (openSuse 12.2 x86\_64) server via: ``` pip install -U scikit-learn ``` i get the following error: ``` (....) compile options: '-I/usr/lib64/python2.7/site-packages/numpy/core/include -Isklearn/svm/src/libsvm -I/usr/lib64/python2.7/site-packages/numpy/core/include -I/usr...
Ok when i installed numpy with pip or normally all the include header were missing. To fix this i **installed the package "python-numpy-devel"** (with zypper, stupid suse package names...) which contains the headers. After that the headers are there and the rest works.
How to upload a file using an ajax call in flask
18,334,717
10
2013-08-20T12:11:30Z
20,107,080
19
2013-11-20T21:09:49Z
[ "python", "ajax", "flask" ]
Hi I'm quite new to flask and I want to upload a file using an ajax call to the server. As mentioned in the documentation, I added a file upload to the html as folows: ``` <form action="" method=post enctype="multipart/form-data" id="testid"> <table> <tr> <td> <label>Upload</label> </td> <td> <in...
To answer your question... HTML: ``` <form id="upload-file" method="post" enctype="multipart/form-data"> <fieldset> <label for="file">Select a file</label> <input name="file" type="file"> </fieldset> <fieldset> <button id="upload-file-btn" type="button">Upload</button> </fields...
python using argparse.ArgumentParser method
18,335,687
9
2013-08-20T12:57:30Z
18,335,770
8
2013-08-20T13:01:49Z
[ "python", "command-line", "argparse" ]
I've tried to learn how `argparse.ArgumentParser` works and I've write a couple lines for that : ``` global firstProduct global secondProduct myparser=argparse.ArgumentParser(description='parser test') myparser.add_argument("product1",help="enter product1",dest='product_1') myparser.add_argument("product2",help="ente...
Omit the `dest` parameter when using a positional argument. The name supplied for the positional argument will be the name of the argument: ``` import argparse myparser = argparse.ArgumentParser(description='parser test') myparser.add_argument("product_1", help="enter product1") myparser.add_argument("product_2", help...
Saving utf-8 texts in json.dumps as UTF8, not as \u escape sequence
18,337,407
132
2013-08-20T14:18:18Z
18,337,754
190
2013-08-20T14:33:20Z
[ "python", "json", "unicode", "utf-8", "escaping" ]
sample code: ``` >>> import json >>> json_string = json.dumps("ברי צקלה") >>> print json_string "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4" ``` The problem: it's not human readable. My (smart) users want to verify or even edit text files with JSON dumps. (and i'd rather not use XML) Is there a way to serial...
Use the `ensure_ascii=False` switch to `json.dumps()`, then encode the value to UTF-8 manually: ``` >>> json_string = json.dumps(u"ברי צקלה", ensure_ascii=False).encode('utf8') >>> json_string '"\xd7\x91\xd7\xa8\xd7\x99 \xd7\xa6\xd7\xa7\xd7\x9c\xd7\x94"' >>> print json_string "ברי צקלה" ``` If you are w...
Saving utf-8 texts in json.dumps as UTF8, not as \u escape sequence
18,337,407
132
2013-08-20T14:18:18Z
26,078,471
16
2014-09-27T19:41:39Z
[ "python", "json", "unicode", "utf-8", "escaping" ]
sample code: ``` >>> import json >>> json_string = json.dumps("ברי צקלה") >>> print json_string "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4" ``` The problem: it's not human readable. My (smart) users want to verify or even edit text files with JSON dumps. (and i'd rather not use XML) Is there a way to serial...
UPDATE: This is wrong answer, but it's still useful to understand why it's wrong. See comments. How about `unicode-escape`? ``` >>> d = {1: "ברי צקלה", 2: u"ברי צקלה"} >>> json_str = json.dumps(d).decode('unicode-escape').encode('utf8') >>> print json_str {"1": "ברי צקלה", "2": "ברי צקלה"}...
Saving utf-8 texts in json.dumps as UTF8, not as \u escape sequence
18,337,407
132
2013-08-20T14:18:18Z
28,032,808
11
2015-01-19T20:14:42Z
[ "python", "json", "unicode", "utf-8", "escaping" ]
sample code: ``` >>> import json >>> json_string = json.dumps("ברי צקלה") >>> print json_string "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4" ``` The problem: it's not human readable. My (smart) users want to verify or even edit text files with JSON dumps. (and i'd rather not use XML) Is there a way to serial...
Peters' python 2 workaround fails on an edge case: ``` d = {u'keyword': u'bad credit \xe7redit cards'} with io.open('filename', 'w', encoding='utf8') as json_file: data = json.dumps(d, ensure_ascii=False).decode('utf8') try: json_file.write(data) except TypeError: # Decode data to Unicode ...
Django: DateField "This field cannot be blank."
18,339,384
4
2013-08-20T15:43:08Z
18,339,463
9
2013-08-20T15:46:39Z
[ "python", "django" ]
I'm posting a rest request like this: ``` {title:some title, recurring:true, day:Wednesday, time:12:30, description:some text} ``` I am not passing the date because the event is recurring and the value should be empty. The server response is: ``` {"date": ["This field cannot be blank."]} ``` Here is the relevant py...
Add the `blank=True` parameter to the definition of your `date` field if you want that field to be optional. From the [docs](https://docs.djangoproject.com/en/1.5/ref/models/fields/#blank): > Note that this is different than null. null is purely database-related, whereas blank is validation-related. If a field has bl...
Import directory into pycharm
18,343,433
4
2013-08-20T19:26:00Z
18,517,887
7
2013-08-29T17:56:51Z
[ "python", "pycharm" ]
I am trying to import a legacy project into pycharm for debugging. The directory structure looks like: top folder ---> folder one top folder ---> folder two The problem is that programs in the sub-folders use: ``` import top from top import module ``` Pycharm returns the error: "No module named top" How can I ...
First thing to make sure is to do what Games said, you need to make sure each folder that is representing a package is done by putting a `__init__.py` file which is a empty python file named exactly `__init__.py` that tells the interpreter that the folder is a python package. Second thing to look for is that pycharm l...
efficient way to count the element in a dictionary in Python using a loop
18,343,472
6
2013-08-20T19:28:16Z
18,346,544
10
2013-08-20T23:28:03Z
[ "python", "performance", "dictionary", "coding-style" ]
I have a list of values. I wish to count during a loop the number of element for each class (i.e. 1,2,3,4,5) ``` mylist = [1,1,1,1,1,1,2,3,2,2,2,2,3,3,4,5,5,5,5] mydict = dict() for index in mylist: mydict[index] = +1 mydict Out[344]: {1: 1, 2: 1, 3: 1, 4: 1, 5: 1} ``` I wish to get this result ``` Out[344]: {1:...
For your smaller example, with a limited diversity of elements, you can use a set and a dict comprehension: ``` >>> mylist = [1,1,1,1,1,1,2,3,2,2,2,2,3,3,4,5,5,5,5] >>> {k:mylist.count(k) for k in set(mylist)} {1: 6, 2: 5, 3: 3, 4: 1, 5: 4} ``` To break it down, `set(mylist)` uniquifies the list and makes it more com...
Format and print list of tuples as one line
18,343,950
3
2013-08-20T19:56:55Z
18,343,985
8
2013-08-20T19:59:36Z
[ "python", "list", "tuples" ]
I have a list containing tuples that is generated from a database query and it looks something like this. ``` [(item1, value1), (item2, value2), (item3, value3),...] ``` The tuple will be mixed length and when I print the output it will look like this. ``` item1=value1, item2=value2, item3=value3,... ``` I have loo...
You're after something like: ``` >>> a = [('val', 1), ('val2', 2), ('val3', 3)] >>> ', '.join('{}={}'.format(*el) for el in a) 'val=1, val2=2, val3=3' ``` This also doesn't care what type the tuple elements are... you'll get the `str` representation of them automatically.
Python: subprocess.call, stdout to file, stderr to file, display stderr on screen in real time
18,344,932
19
2013-08-20T21:03:22Z
18,345,099
45
2013-08-20T21:16:22Z
[ "python", "subprocess", "stderr" ]
I have a command line tool (actually, several) that I am writing a wrapper for in Python. The tool is generally used like this: ``` $ path_to_tool -option1 -option2 > file_out ``` The user gets the output written to file\_out, and is also able to see various status messages of the tool as it is running. I want to ...
You *can* do this with `subprocess`, but it's not trivial. If you look at the [Frequently Used Arguments](http://docs.python.org/2/library/subprocess.html#frequently-used-arguments) in the docs, you'll see that you can pass `PIPE` as the `stderr` argument, which creates a new pipe, passes one side of the pipe to the ch...
Animate a rotating 3D graph in matplotlib
18,344,934
8
2013-08-20T21:03:26Z
18,345,457
10
2013-08-20T21:42:41Z
[ "python", "animation", "matplotlib" ]
I have a scatter plot set up and plotted the way I want it, and I want to create an .mp4 video of the figure rotating in space, as if I had used `plt.show()` and dragged the viewpoint around. [This answer](http://stackoverflow.com/a/12905458/326402) is almost exactly what I want, except to save a movie I would have to...
If you want to learn more about `matplotlib` animations you should really follow [this tutorial](http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/). It explains in great length how to create animated plots. **Note:** Creating animated plots require `ffmpeg` or `mencoder` to be installed. Here is...
installing request module in python 2.7 windows
18,345,763
7
2013-08-20T22:08:39Z
35,190,243
10
2016-02-04T00:10:54Z
[ "python", "python-2.7", "module", "request", "install" ]
I am facing issues while installing request module (python 2.7) on windows. Tries the below steps as per docuemntation: **1** `pip install requests` error `'pip' is not recognized as an internal or external command, operable program or batch file.` **2** `easy_install requests` error `'easy_install' is not rec...
If you want to install requests directly you can use the "-m" (module) option available to python. `python.exe -m pip install requests` You can do this directly in PowerShell, though you may need to use the full python path (eg. C:\Python27\python.exe) instead of just python.exe
TypeError: 'int' object does not support indexing
18,345,825
15
2013-08-20T22:14:51Z
18,345,835
14
2013-08-20T22:15:21Z
[ "python", "sql", "postgresql" ]
I have this query: ``` some_id = 1 cursor.execute(' SELECT "Indicator"."indicator" FROM "Indicator" WHERE "Indicator"."some_id" = %s;', some_id) ``` I get the following error: ``` TypeError: 'int' object does not support indexing ``` some\_id is an int but I'd like to select indicators that have so...
You should pass query parameters to [`execute()`](http://www.python.org/dev/peps/pep-0249/#id15) as a tuple (an iterable, strictly speaking), `(some_id,)` instead of `some_id`: ``` cursor.execute(' SELECT "Indicator"."indicator" FROM "Indicator" WHERE "Indicator"."some_id" = %s;', (some_id,)) ```
TypeError: 'int' object does not support indexing
18,345,825
15
2013-08-20T22:14:51Z
18,345,864
18
2013-08-20T22:17:06Z
[ "python", "sql", "postgresql" ]
I have this query: ``` some_id = 1 cursor.execute(' SELECT "Indicator"."indicator" FROM "Indicator" WHERE "Indicator"."some_id" = %s;', some_id) ``` I get the following error: ``` TypeError: 'int' object does not support indexing ``` some\_id is an int but I'd like to select indicators that have so...
``` cursor.execute(' SELECT "Indicator"."indicator" FROM "Indicator" WHERE "Indicator"."some_id" = %s;', [some_id]) ``` This turns the `some_id` parameter into a list, which is indexable. Assuming your method works like i think it does, this should work. The error is happening because somewhere in tha...
Python Tkinter - How to insert text at the beginning of the text box?
18,346,206
2
2013-08-20T22:51:11Z
18,346,296
11
2013-08-20T23:02:05Z
[ "python", "textbox", "tkinter" ]
I am using Python 2.7.5 and Tkinter. I am writing status messages into a text widget. To insert I am using: ``` text_widget.insert(INSERT, 'my status here.\n') ``` This works fine. However, each status is added after the previous status. How do I insert new lines at the top of the `Text` widget so that the most recen...
``` text_widget.insert('1.0', 'my status here.\n') ``` In short, the text widget can be indexed using a string notation of the form `"lineNum.columnNum"`, as well as using the special indices like `Tkinter.INSERT`. I would recommend reading [effbot's documentation for the Tkinter text widget](http://effbot.org/tkinte...
Resolving a vim plugin mapping conflict - mapping already exists for \t
18,346,350
10
2013-08-20T23:07:45Z
18,346,601
9
2013-08-20T23:33:56Z
[ "python", "vim", "plugins", "conflict" ]
I followed <http://sontek.net/blog/detail/turning-vim-into-a-modern-python-ide#intro> to install a bunch of plugins for Python programming in gvim (installed on a Windows 8 machine). It appears that there is a mapping conflict between the 'command-t' and 'tasklist' plugins, as I get the following error message: ``` >E...
tasklist will not map to `<leader>t` if a mapping to `<Plug>TaskList` is found. So you just need to create a mapping to `<Plug>TaskList` in your vimrc. The example I found in the source code was ``` nnoremap <leader>v <Plug>TaskList ```
how to use concatenate a fixed string and a variable in Python
18,348,717
7
2013-08-21T04:09:12Z
18,348,727
10
2013-08-21T04:10:47Z
[ "python", "string-concatenation" ]
I want to include file name 'main.txt' in the subject for that I am passing file name from command line. but getting error in doing so ``` python sample.py main.txt #running python with argument msg['Subject'] = "Auto Hella Restart Report "sys.argv[1] #line where i am using that passed argument ```
I'm guessing that you meant to do this: ``` msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1] # To concatenate strings in python, use ^ ```
Python - Get Class from lxml xpath
18,348,777
3
2013-08-21T04:17:42Z
18,348,794
7
2013-08-21T04:19:46Z
[ "python", "python-2.7", "xpath", "lxml" ]
Using Twitter as simply for example only and ignoring the fact they have a perfectly usable API, the following script gets the current 5th tweet from the users page. ``` import urllib2 from lxml import etree xpathselector = "/html/body/div/div[2]/div/div[5]/div[2]/div/ol/li[5]/div/div/p" url = "https://twitter.com/b...
Use `get` method of [Element](http://lxml.de/api/lxml.etree._Element-class.html#get): ``` print result[0].get('class') ``` prints ``` js-tweet-text tweet-text ```
Fastest way to sort multiple lists - Python
18,349,028
6
2013-08-21T04:46:26Z
18,349,149
7
2013-08-21T04:58:03Z
[ "python", "performance", "list", "sorting", "zip" ]
I have two lists, x and y, and I want to sort x and permute y by the permutation of x-sorting. For example, given ``` x = [4, 2, 1, 3] y = [40, 200, 1, 30] ``` I want to get ``` x_sorted = [1,2,3,4] y_sorted = [1, 200, 30, 40] ``` As discussed in past questions, a simple way to solve this is ``` x_sorted, y_sorted...
Using [numpy.argsort](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html): ``` >>> import numpy as np >>> x = np.array([4,2,1,3]) >>> y = np.array([40,200,1,30]) >>> order = np.argsort(x) >>> x_sorted = x[order] >>> y_sorted = y[order] >>> x_sorted array([1, 2, 3, 4]) >>> y_sorted array([ 1, 200, ...
How to handle both GET and POST requests in TornadoWeb framework?
18,349,959
2
2013-08-21T06:06:09Z
18,350,128
7
2013-08-21T06:17:12Z
[ "python", "flask", "tornado" ]
I'm really new to Python community, it's been a while that I'm trying to learn Flask and Tornado frameworks. As you know we can handle GET and POST requests together in Flask very easily, For example a simple URL routing in Flask is something like this: ``` @app.route('/index', methods=['GET', 'POST']) def index(): ...
You can go with using [prepare()](http://www.tornadoweb.org/en/stable/web.html?highlight=requesthandler#tornado.web.RequestHandler.prepare) method: > Called at the beginning of a request before get/post/etc. > Override this method to perform common initialization regardless of > the request method. ``` class MainHand...
Check if string ends with one of the strings from a list
18,351,951
75
2013-08-21T08:02:18Z
18,351,973
18
2013-08-21T08:03:36Z
[ "python", "string", "list" ]
What is the pythonic way of writing the following code? ``` extensions = ['.mp3','.avi'] file_name = 'test.mp3' for extension in extensions: if file_name.endswith(extension): #do stuff ``` I have a vague memory that the explicit declaration of the `for` loop can be avoided and be written in the `if` cond...
Just use: ``` if file.endswith(tuple(extensions)): ```
Check if string ends with one of the strings from a list
18,351,951
75
2013-08-21T08:02:18Z
18,351,977
151
2013-08-21T08:03:46Z
[ "python", "string", "list" ]
What is the pythonic way of writing the following code? ``` extensions = ['.mp3','.avi'] file_name = 'test.mp3' for extension in extensions: if file_name.endswith(extension): #do stuff ``` I have a vague memory that the explicit declaration of the `for` loop can be avoided and be written in the `if` cond...
Though not widely known, [str.endswith](http://docs.python.org/2/library/stdtypes.html#str.endswith) also accepts a tuple. You don't need to loop. ``` >>> 'test.mp3'.endswith(('.mp3', '.avi')) True ```
Mask a circular sector in a numpy array
18,352,973
8
2013-08-21T08:54:01Z
18,354,475
15
2013-08-21T10:03:35Z
[ "python", "numpy", "matrix", "angle" ]
I have a code that slices a numpy array into a circle. I wish to recover only the values included in a certain range of angles from the circle and mask the array. For example: mask the original array with the (x,y) positions comprised between 0 and 45 degrees of the circle. Is there a pythonic way for doing so? Here'...
I would do this by converting from cartesian to polar coordinates and constructing boolean masks for the circle and for the range of angles you want: ``` import numpy as np def sector_mask(shape,centre,radius,angle_range): """ Return a boolean mask for a circular sector. The start/stop angles in `angle_...
List of index values in Pandas DataFrame
18,358,938
11
2013-08-21T13:36:05Z
18,360,223
20
2013-08-21T14:29:34Z
[ "python", "pandas" ]
I'm probably using poor search terms when trying to find this answer. Right now, before indexing a DataFrame, I'm getting a list of values in a column this way... ``` list = list(df['column']) ``` ...then I'll `set_index` on the column. This seems like a wasted step. When trying the above on an index, I get a key er...
To get the `index` values as a `list`/`list` of `tuple`s for `Index`/`MultiIndex` do: ``` df.index.values.tolist() # an ndarray method, you probably shouldn't depend on this ``` or ``` list(df.index.values) # this will always work in pandas ```
python/c++ - Compiling shared library with cmake and installing with distutils
18,360,245
8
2013-08-21T14:30:54Z
18,362,479
7
2013-08-21T16:06:50Z
[ "c++", "python", "cmake", "boost-python", "distutils" ]
I have a boost.python project that I compile using cmake and make. It's part of a python module, and I want to be able to install that module using distutils. I have followed the instructions [here](http://bloerg.net/2012/11/10/cmake-and-distutils.html) to create a CMakeLists.txt file that first compiles the shared lib...
In the end I followed the answer [here](http://stackoverflow.com/questions/2444701/distribute-pre-compiled-python-extension-module-with-distutils) and overrode the build\_ext command. As I want the build to be cross platform, and since the shared library lies inside the module source tree, I import the module shared li...
How to get IP address of hostname inside jinja template
18,360,528
7
2013-08-21T14:42:15Z
18,376,629
9
2013-08-22T09:32:03Z
[ "python", "jinja2", "salt-stack" ]
Our saltstack is based on hostnames (webN.*, dbN.*, etc.). But for various things I need IPs of those servers. For now I had them stored in pillars, but the number of places I need to sync grows. I tried to use publish + network.ip\_addrs, but that kinda sucks, because it needs to do the whole salt-roundtrip just to r...
You could use a custom grain. Create file \_grains/fqdn\_ip.py in the state tree directory: ``` import socket def fqdn_ip(): return { 'fqdn_ip': socket.gethostbyname(socket.getfqdn()) } ``` In template: ``` {{ grains.fqdn_ip }} ``` Another way is use dnsutil module (requires dig command on minion):...
Using flask_login session with jinja2 templates
18,361,151
13
2013-08-21T15:09:35Z
18,361,227
28
2013-08-21T15:12:38Z
[ "python", "python-2.7", "flask", "jinja2", "flask-login" ]
I have simple jinja2 template with registration/login links, I should hide them when user logged in, I also use flask\_login module for this stuff. Question is: **How should I identify is user logged in in jinja2 templates?**
Flask-Login adds the `current_user` variable to your templates: ``` {% if current_user.is_authenticated %} ... {% else %} ... {% endif %} ``` They mention this briefly in [the documentation](http://flask-login.readthedocs.org/en/latest/#login-example).
PyLint 1.0.0 with PyDev + Eclipse: "include-ids" option no longer allowed, breaks Eclipse integration
18,362,779
6
2013-08-21T16:22:06Z
18,362,912
7
2013-08-21T16:29:20Z
[ "python", "eclipse", "pydev", "pylint" ]
As noted in this question: [How do I get Pylint message IDs to show up after pylint-1.0.0?](http://stackoverflow.com/questions/18133264/how-do-i-get-pylint-message-ids-to-show-up-after-pylint-1-0-0) pylint 1.0.0 no longer accepts "include-ids" option. (It returns "lint.py: error: no such option: --include-ids"). Unfor...
This should be already fixed in the latest nightly build. Please grab it there. See: <http://pydev.org/download.html> for details on how to get it.
Finding components of very large graph
18,363,348
4
2013-08-21T16:52:49Z
18,364,211
9
2013-08-21T17:42:42Z
[ "python", "algorithm" ]
I have a very large graph represented in a text file of size about 1TB with each edge as follows. ``` From-node to-node ``` I would like to split it into its weakly connected components. If it was smaller I could load it into networkx and run their component finding algorithms. For example <http://networkx.github.io/...
If you have few enough nodes (e.g. a few hundred million), then you could compute the connected components with a single pass through the text file by using a [disjoint set forest](http://en.wikipedia.org/wiki/Disjoint-set_data_structure#Disjoint-set_forests) stored in memory. This data structure only stores the rank ...
The State of Optional Static Typing in Python?
18,364,372
19
2013-08-21T17:50:57Z
18,364,928
14
2013-08-21T18:21:49Z
[ "python", "python-3.x", "static-typing" ]
I've been playing with Typscript for a while now, and I gotta say, bundled with the fact that nodejs is faster than the current implementation for CPython for my web development needs, I've been more inclined to make more things with it. In fact, I've made a couple of basic apps with it, even for desktop. What I love ...
> Or do we need to invent something like Typescript but for Python 3? That's **mypy** !!! :-) Personally, I think they either they are going to merge, or Python is going to come with its own solution. Hope this happens very soon!!!
Why is numpy's einsum faster than numpy's built in functions?
18,365,073
56
2013-08-21T18:31:42Z
18,365,665
15
2013-08-21T19:07:13Z
[ "python", "arrays", "performance", "numpy", "multidimensional-array" ]
Lets start with three arrays of `dtype=np.double`. Timings are performed on a intel CPU using numpy 1.7.1 compiled with `icc` and linked to intel's `mkl`. A AMD cpu with numpy 1.6.1 compiled with `gcc` without `mkl` was also used to verify the timings. Please note the timings scale nearly linearly with system size and ...
I think these timings explain what's going on: ``` a = np.arange(1000, dtype=np.double) %timeit np.einsum('i->', a) 100000 loops, best of 3: 3.32 us per loop %timeit np.sum(a) 100000 loops, best of 3: 6.84 us per loop a = np.arange(10000, dtype=np.double) %timeit np.einsum('i->', a) 100000 loops, best of 3: 12.6 us p...
Why is numpy's einsum faster than numpy's built in functions?
18,365,073
56
2013-08-21T18:31:42Z
18,366,008
26
2013-08-21T19:27:56Z
[ "python", "arrays", "performance", "numpy", "multidimensional-array" ]
Lets start with three arrays of `dtype=np.double`. Timings are performed on a intel CPU using numpy 1.7.1 compiled with `icc` and linked to intel's `mkl`. A AMD cpu with numpy 1.6.1 compiled with `gcc` without `mkl` was also used to verify the timings. Please note the timings scale nearly linearly with system size and ...
First off, there's been a lot of past discussion about this on the numpy list. For example, see: <http://numpy-discussion.10968.n7.nabble.com/poor-performance-of-sum-with-sub-machine-word-integer-types-td41.html> <http://numpy-discussion.10968.n7.nabble.com/odd-performance-of-sum-td3332.html> Some of boils down to the...
Why is numpy's einsum faster than numpy's built in functions?
18,365,073
56
2013-08-21T18:31:42Z
19,612,080
15
2013-10-26T21:28:35Z
[ "python", "arrays", "performance", "numpy", "multidimensional-array" ]
Lets start with three arrays of `dtype=np.double`. Timings are performed on a intel CPU using numpy 1.7.1 compiled with `icc` and linked to intel's `mkl`. A AMD cpu with numpy 1.6.1 compiled with `gcc` without `mkl` was also used to verify the timings. Please note the timings scale nearly linearly with system size and ...
Now that numpy 1.8 is released, where according to the docs all ufuncs should use SSE2, I wanted to double check that Seberg's comment about SSE2 was valid. To perform the test a new python 2.7 install was created- numpy 1.7 and 1.8 were compiled with `icc` using standard options on a AMD opteron core running Ubuntu. ...
Explanation of 'or' in exception syntax, why is it valid syntax and how does it work?
18,365,441
8
2013-08-21T18:53:56Z
18,365,488
12
2013-08-21T18:55:42Z
[ "python", "exception" ]
A colleague of mine mistakenly typed this (simplified) code, and was wondering why his exception wasn't getting caught: ``` >>> try: ... raise ValueError ... except IndexError or ValueError: ... print 'Caught!' ... Traceback (most recent call last): File "<stdin>", line 2, in <module> ValueError ``` Now I ...
That's because `IndexError or ValueError` is evaluated to `IndexError`. ``` >>> IndexError or ValueError <type 'exceptions.IndexError'> ``` The `or` operator returns the first expression that evaluates to `True` (In this case `IndexError`), or the last expression, if none of them are `True`. So, your except stateme...
Python how to write to a binary file?
18,367,007
38
2013-08-21T20:25:50Z
18,367,059
10
2013-08-21T20:28:58Z
[ "python" ]
I have a list of bytes as integers, which is something like ``` [120, 3, 255, 0, 100] ``` How can I write this list to a file as binary? Would this work? ``` newFileBytes = [123, 3, 255, 0, 100] # make file newFile = open (directoryPath + newFileCounter + ".txt", "wb") # write to file newFile.write(newFileBytes) ``...
Use [`struct.pack`](https://docs.python.org/3.5/library/struct.html#struct.pack) to convert the integer values into binary bytes, then write the bytes. E.g. ``` newFile.write(struct.pack('5B', *newFileBytes)) ``` However I would never give a binary file a `.txt` extension. The benefit of this method is that it works...
Python how to write to a binary file?
18,367,007
38
2013-08-21T20:25:50Z
18,367,068
42
2013-08-21T20:29:09Z
[ "python" ]
I have a list of bytes as integers, which is something like ``` [120, 3, 255, 0, 100] ``` How can I write this list to a file as binary? Would this work? ``` newFileBytes = [123, 3, 255, 0, 100] # make file newFile = open (directoryPath + newFileCounter + ".txt", "wb") # write to file newFile.write(newFileBytes) ``...
This is exactly what [`bytearray`](http://docs.python.org/3.3/library/functions.html#bytearray) is for: ``` newFileByteArray = bytearray(newFileBytes) newFile.write(newFileByteArray) ``` If you're using Python 3.x, you can use `bytes` instead (and probably ought to, as it signals your intention better). But in Python...
PySide Import Error on Ubuntu 13.04
18,369,516
11
2013-08-21T23:53:41Z
18,381,196
17
2013-08-22T12:59:32Z
[ "python", "qt", "ubuntu", "pyqt", "pyside" ]
while trying just to import ``` from PySide import QtGui ``` I'm getting the following error: **ImportError: libpyside-python2.7.so.1.2: cannot open shared object file: No such file or directory** > ls > /usr/local/lib/python2.7/dist-packages/PySide/libpyside-python2.7.so.1.2 > > /usr/local/lib/python2.7/dist-packa...
The output of `ldd` suggests that `libshiboken-python2.7.so.1.2` can't be found. `/usr/local/lib/python2.7/dist-packages/PySide`, where it is found, is not typically a directory where the dynamic linker would look for it. There are several options in this case: * add the directory to the directories checked by the d...
Compile vim7.4 source code with python support failed
18,370,234
3
2013-08-22T01:25:58Z
18,370,296
11
2013-08-22T01:35:22Z
[ "python", "vim" ]
I have download the source code of vim7.4 and decide to upgrade the vim to 7.4. However, I can not add python support to it: ``` ./configure --enable-pythoninterp --enable-rubyinterp --enable-gui=no --without-x --enable-cscope --enable-multibyte --prefix=/usr ``` While checking src/auto/config.log, I found: ``` co...
Make sure you have the python development packages installed (python-devel or python-dev I think). You can specify the python config directory by passing, to `./configure`, something like: ``` --with-python-config-dir=/usr/lib64/python2.7/config ``` To find the config directory (you may need to do `updatedb` first): ...
Compile vim7.4 source code with python support failed
18,370,234
3
2013-08-22T01:25:58Z
18,370,434
8
2013-08-22T01:50:48Z
[ "python", "vim" ]
I have download the source code of vim7.4 and decide to upgrade the vim to 7.4. However, I can not add python support to it: ``` ./configure --enable-pythoninterp --enable-rubyinterp --enable-gui=no --without-x --enable-cscope --enable-multibyte --prefix=/usr ``` While checking src/auto/config.log, I found: ``` co...
From your error messages you don't have `python-dev` installed ``` sudo apt-get install python-dev ``` this should fix your problem
Python - Pymongo Insert and Update Documents
18,371,351
7
2013-08-22T03:48:45Z
18,372,494
9
2013-08-22T05:43:53Z
[ "python", "mongodb", "pymongo" ]
Using PyMongo, I have a set of dict's in a list that I'd like to submit to my MongoDB. Some of the items in the list are new entries, and some are to update. Example: **On Server Database:** ``` [{"_id" : 1, "foo" : "bar}] ``` **To send to database:** ``` [{"_id" : 1, "foo" : "HELLO"}, {"_id" : 2, "Blah" : "Bloh"}...
Use `upsert` option: ``` from pymongo import MongoClient cl = MongoClient() coll = cl["local"]["test2"] data = [{"_id" : 1, "foo" : "HELLO"}, {"_id" : 2, "Blah" : "Bloh"}] for d in data: coll.update({'_id':d['_id']}, d, True) ```
python copy files by wildcards
18,371,768
20
2013-08-22T04:34:24Z
18,371,774
7
2013-08-22T04:35:23Z
[ "python", "file", "copy", "glob", "shutil" ]
I am learning python (python 3) and I can copy 1 file to a new directory by doing this ``` import shutil shutil.copyfile('C:/test/test.txt', 'C:/lol/test.txt') ``` What I am now trying to do is to copy all \*.txt files from C:/ to C:/test \*.txt is a wildcard to search for all the text files on my hard drive
Use [`glob.glob()`](http://docs.python.org/2/library/glob.html#glob.glob) to get a list of the matching filenames and then iterate over the list.
python copy files by wildcards
18,371,768
20
2013-08-22T04:34:24Z
18,372,078
25
2013-08-22T05:08:52Z
[ "python", "file", "copy", "glob", "shutil" ]
I am learning python (python 3) and I can copy 1 file to a new directory by doing this ``` import shutil shutil.copyfile('C:/test/test.txt', 'C:/lol/test.txt') ``` What I am now trying to do is to copy all \*.txt files from C:/ to C:/test \*.txt is a wildcard to search for all the text files on my hard drive
``` import glob import shutil dest_dir = "C:/test" for file in glob.glob(r'C:/*.txt'): print file shutil.copy(file, dest_dir) ```
Python, split tuple items to single stuff
18,372,952
3
2013-08-22T06:15:43Z
18,372,987
8
2013-08-22T06:18:15Z
[ "python", "split", "tuples" ]
I have tuple in Python that looks like this: ``` tuple = ('sparkbrowser.com', 0, 'http://facebook.com/sparkbrowser', 'Facebook') ``` and I wanna split it out so I could get every item from tuple independent so I could do something like this: ``` domain = "sparkbrowser.com" level = 0 url = "http://facebook.com/sparkb...
Python can unpack sequences naturally. ``` domain, level, url, text = ('sparkbrowser.com', 0, 'http://facebook.com/sparkbrowser', 'Facebook') ```
How to call method by string in Python?
18,374,447
4
2013-08-22T07:42:36Z
18,374,510
8
2013-08-22T07:46:38Z
[ "python" ]
Can I call a method to process data by combining strings? For example, it is ok to type "data.image.truecolor()" in code, ``` data.image.truecolor() # This line is successful to call method ``` My problem is : if I have a data object named data (not a string), how to combine ".image.truecolor" sting to call method t...
``` methods=["fog","ir108","dnb","overview"] dataImage = data.image for method in methods: result = getattr(dataImage ,method) # to call method to process the data result() # to get the data processed ``` Why not like this when you know you will be invoking methods of `data.image`? Otherwise, if you didn't kn...
Sorting a list of tuples with 3 elements in python
18,374,585
2
2013-08-22T07:50:58Z
18,374,632
9
2013-08-22T07:53:22Z
[ "python", "list", "sorting", "tuples" ]
I have a list of some tuples. Each tuple has three elements. I need to sort the list. To break tie between two tuples, first element of tuple is looked then if still tied then the second element. List is like below. ``` L = [(1, 14, 0), (14, 1, 1), (1, 14, 2), (14, 2, 3), (2, 4, 4), (4, 11, 5), (11, -1000, 6)] ``` In...
Just sort the list; the default sort does just what you want. When comparing two tuples, they are ordered according to their contents; sorted on the first element first, then if they are equal, sorted on the second element, etc. Demo: ``` >>> L = [(14, 2, 3), (1, 14, 0), (14, 1, 1), (1, 14, 2), (2, 4, 4), (4, 11, 5)...
AttributeError: Assignment not allowed to composite field "task" in protocol message object
18,376,190
10
2013-08-22T09:14:12Z
18,376,567
7
2013-08-22T09:28:49Z
[ "python", "protocol-buffers" ]
I'm using protocol-buffers python lib to send data,but it's have some problems, so ``` Traceback (most recent call last): File "test_message.py", line 17, in <module> ptask.task = task File "build\bdist.win32\egg\google\protobuf\internal\python_message.py", line 513, in setter AttributeError: Assignment not al...
I don't know *protocol-buffers* but I took a look at [the docs](https://developers.google.com/protocol-buffers/docs/reference/python-generated) and it says: > You cannot assign a value to an embedded message field. Instead, > assigning a value to any field within the child message implies > setting the message field i...
AttributeError: Assignment not allowed to composite field "task" in protocol message object
18,376,190
10
2013-08-22T09:14:12Z
20,808,391
8
2013-12-27T21:59:25Z
[ "python", "protocol-buffers" ]
I'm using protocol-buffers python lib to send data,but it's have some problems, so ``` Traceback (most recent call last): File "test_message.py", line 17, in <module> ptask.task = task File "build\bdist.win32\egg\google\protobuf\internal\python_message.py", line 513, in setter AttributeError: Assignment not al...
I'm new to protocol-buffers too and faced with the same problem. I've found [this method](https://developers.google.com/protocol-buffers/docs/reference/python/google.protobuf.message.Message-class#MergeFrom) helpful. I think it should work: ``` task = yacc.task() task.id = 1000 task.msg = u"test" ptask = yacc.task_in...
AttributeError: Assignment not allowed to composite field "task" in protocol message object
18,376,190
10
2013-08-22T09:14:12Z
22,771,612
7
2014-03-31T20:33:04Z
[ "python", "protocol-buffers" ]
I'm using protocol-buffers python lib to send data,but it's have some problems, so ``` Traceback (most recent call last): File "test_message.py", line 17, in <module> ptask.task = task File "build\bdist.win32\egg\google\protobuf\internal\python_message.py", line 513, in setter AttributeError: Assignment not al...
Try [CopyFrom](https://developers.google.com/protocol-buffers/docs/reference/python/google.protobuf.message.Message-class#CopyFrom): ``` ptask.task.CopyFrom(task) ```
Python argparse: name parameters
18,376,983
6
2013-08-22T09:47:05Z
18,377,151
11
2013-08-22T09:54:29Z
[ "python", "argparse" ]
I'm writing a program that use argparse, for parsing some arguments that I need. for now I have this: `parser.add_argument('--rename', type=str, nargs=2, help='some help')` when I run this script I see this: ``` optional arguments: -h, --help show this help message and exit --rename RENAME RENAME ...
If you set `metavar=('OLDFILE', 'NEWFILE')`: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument('--rename', type=str, nargs=2, help='some help', metavar=('OLDFILE', 'NEWFILE')) args = parser.parse_args() print(args) ``` Then `test.py -h` yields ``` usage: test.py [-h] [--r...
Django bulk_create function example
18,383,471
9
2013-08-22T14:35:16Z
18,383,565
12
2013-08-22T14:39:20Z
[ "python", "django", "django-models" ]
I'm trying to understand bulk\_create in Django This was my original query I'm trying to convert: ``` for e in q: msg = Message.objects.create( recipient_number=e.mobile, content=batch.content, sender=e.contact_owner, billee=batch.user, sender_name=batch.sender_name ) `...
The second code in the question create a single object, because it pass a set with a Message object. To create multiple objects, pass multiple Message objects to bulk\_create. For example: ``` objs = [ Message( recipient_number=e.mobile, content=batch.content, sender=e.contact_owner, ...
How can I convert HH:MM:SS string to UNIX epoch time?
18,383,528
6
2013-08-22T14:37:53Z
18,383,731
7
2013-08-22T14:45:45Z
[ "python", "datetime", "time" ]
I have a program ([sar command line utility](http://linux.die.net/man/1/sar)) which outputs it's lines with time column. I parse this file with my python script and I would like to convert sar's `02:31:33 PM` into epochs e.g. `1377181906` (current year, month and day with hours, minutes and seconds from abovementioned ...
Here's one way to do it: * read the string into datetime using `strptime` * set year, month, day of the datetime object to current date's year, month and day via `replace` * convert datetime into unix timestamp via `calendar.timegm` --- ``` >>> from datetime import datetime >>> import calendar >>> dt = datetime.strp...
python s3 boto connection.close causes an error
18,383,839
3
2013-08-22T14:50:31Z
24,958,783
11
2014-07-25T15:04:03Z
[ "python", "amazon-s3", "boto" ]
I have code that writes files to s3. The code was working fine ``` conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.get_bucket(BUCKET, validate=False) k = Key(bucket) k.key = self.filekey k.set_metadata('Content-Type', 'text/javascript') k.set_contents_from_string(js...
I can't find that error message in the latest boto source code, so unfortunately I can't tell you what caused it. Recently, we had problems when we were NOT calling `conn.close()`, so there definitely is at least one case where you must close the connection. Here's my understanding of what's going on: S3Connection (we...
matplotlib hatched fill_between without edges?
18,386,106
11
2013-08-22T16:28:55Z
18,386,311
16
2013-08-22T16:40:26Z
[ "python", "matplotlib" ]
I have a region I'd like to hatch which borders on an existing plot line (of the same colour) that is dashed. However, when I use `fill_between` the region to be hatched has a border drawn around it also. This border seems share properties with the lines that create the hatching so I cannot set edgecolour to "none" or...
This seems to do the trick! ``` import matplotlib.pyplot as plt plt.plot([0,1],[0,1],ls="--",c="b") plt.fill_between([0,1],[0,1], color="none", hatch="X", edgecolor="b", linewidth=0.0) plt.show() ``` ![import matplotlib.pyplot as plt](http://i.stack.imgur.com/RtaJI.png)
Why use else in try/except construct in Python?
18,387,582
7
2013-08-22T17:56:45Z
18,387,639
11
2013-08-22T17:59:19Z
[ "python", "exception-handling", "try-catch" ]
I am learning Python and have stumbled upon a concept I can't readily digest: the optional `else` block within the `try` construct. According to [the documentation](http://docs.python.org/2/tutorial/errors.html#handling-exceptions): > The try ... except statement has an optional else clause, which, when > present, mu...
The `else` block is only executed if the code in the `try` doesn't raise an exception; if you put the code outside of the `else` block, it'd happen regardless of exceptions. Also, it happens before the `finally`, which is generally important. This is generally useful when you have a brief setup or verification section...
How do Python comparison operators < and > work with a function name as an operand?
18,387,938
14
2013-08-22T18:15:39Z
18,388,016
12
2013-08-22T18:19:12Z
[ "python" ]
Ran into this problem (in Python 2.7.5) with a little typo: ``` def foo(): return 3 if foo > 8: launch_the_nukes() ``` Dang it, I accidentally exploded the Moon. My understanding is that `E > F` is equivalent to `(E).__gt__(F)` and for well behaved classes (such as builtins) equivalent to `(F).__lt__(E)`. If th...
> But, none of these methods work with function objects while the < and > operators do work. What goes on under the hood that makes this happen? In default of any other sensible comparison, CPython in the 2.x series compares based on type name. (This is [documented as an implementation detail](http://docs.python.org/2...
Map method in python
18,388,187
6
2013-08-22T18:29:29Z
18,388,272
7
2013-08-22T18:33:06Z
[ "python", "list", "functional-programming" ]
``` class FoodExpert: def init(self): self.goodFood = [] def addGoodFood(self, food): self.goodFood.append(food) def likes(self, x): return x in self.goodFood def prefers(self, x, y): x_rating = self.goodFood.index(x) y_rating = self.goodFood.index(y) if x...
`map` applies a function on an iterable and returns a new list where the function was applied on each item. In your case, it shows `None` because `f.addGoodFood` function returns nothing. For testing purposes change `addGoodFood` this way: ``` def addGoodFood(self, food): self.goodFood.append(food) return "t...
ipython pandas plot does not show
18,388,870
14
2013-08-22T19:05:19Z
22,677,264
21
2014-03-27T02:40:58Z
[ "python", "matplotlib", "pandas", "ipython", "anaconda" ]
I am using the anaconda distribution of ipython/Qt console. I want to plot things inline so I type the following from the ipython console: ``` %pylab inline ``` Next I type the tutorial at (<http://pandas.pydata.org/pandas-docs/dev/visualization.html>) into ipython... ``` import matplotlib.pyplot as plt import panda...
Plots are not displayed until you run > plt.show()
Open file in different directory python
18,389,946
8
2013-08-22T20:11:47Z
18,389,980
10
2013-08-22T20:13:55Z
[ "python", "python-3.x" ]
I need to open a file from a different directory without using it's path while staying in the current directory. When I execute the below code: ``` for file in os.listdir(sub_dir): f = open(file, "r") lines = f.readlines() for line in lines: line.replace("dst=", ", ") line.replace("proto="...
`os.listdir()` lists *only* the filename without a path. Prepend these with `sub_dir` again: ``` for filename in os.listdir(sub_dir): f = open(os.path.join(sub_dir, filename), "r") ``` If all you are doing is loop over the lines from the file, just loop over the file itself; using `with` makes sure that the file ...
Open file in different directory python
18,389,946
8
2013-08-22T20:11:47Z
18,389,986
9
2013-08-22T20:14:15Z
[ "python", "python-3.x" ]
I need to open a file from a different directory without using it's path while staying in the current directory. When I execute the below code: ``` for file in os.listdir(sub_dir): f = open(file, "r") lines = f.readlines() for line in lines: line.replace("dst=", ", ") line.replace("proto="...
You must give the full path if those files are not in the current directory: ``` f = open( os.path.join(sub_dir, file) ) ``` I would not use `file` as a variable name, maybe `filename`, since this is used to create a file object in Python.
Scroll backwards and forwards through matplotlib plots
18,390,461
5
2013-08-22T20:43:38Z
18,391,039
7
2013-08-22T21:20:34Z
[ "python", "matplotlib" ]
My code produces a number of plots from data using matplotib and I would like to be able to scroll forwards and backwards through them in a live demonstration (maybe by pressing the forwards and backwards keys or using the mouse). Currently I have to save each one as an image separately and then use a separate image vi...
An easy way to achieve that is storing in a list a tuple of the x and y arrays and then use a handler event that picks the next (x,y) pair to be plotted: ``` import numpy as np import matplotlib.pyplot as plt # define your x and y arrays to be plotted t = np.linspace(start=0, stop=2*np.pi, num=100) y1 = np.cos(t) y2 ...
coffeescript dictionary set default
18,391,040
4
2013-08-22T21:20:36Z
18,410,063
8
2013-08-23T19:02:03Z
[ "python", "dictionary", "coffeescript" ]
In Python if you have a dictionary that consists of lists like ``` mydict = {'foo': [], 'bar':[3, 4]} ``` and if you want to add something into that lists you can do ``` mydict.setdefault('baz', []).append(5) ``` not to write ``` key, list_element = 'baz', 5 if key in mylist: mydict[key].append(list_elem...
i recommend against using `||`/ `or` to test for membership—it's basically a clever trick that will silently fail against falsy values. i prefer to write ``` ( mydict[ name ]?= [] ).push value ``` which i find clearer; it assumes that in case `mydict` does not have an entry for `name` or that value is `null` or `un...
python - How to format variable number of arguments into a string?
18,391,059
3
2013-08-22T21:22:12Z
18,391,092
9
2013-08-22T21:24:04Z
[ "python", "string", "string-formatting" ]
We know that formatting **one** argument can be done using **one** `%s` in a string: ``` >>> "Hello %s" % "world" 'Hello world' ``` for two arguments, we can use two `%s` (duh!): ``` >>> "Hello %s, %s" % ("John", "Joe") 'Hello John, Joe' ``` So, how can I format a variable number of arguments *without having to exp...
You'd use `str.join()` on the list *without* string formatting, then interpolate the *result*: ``` "Hello %s" % ', '.join(my_args) ``` Demo: ``` >>> my_args = ["foo", "bar", "baz"] >>> "Hello %s" % ', '.join(my_args) 'Hello foo, bar, baz' ``` If some of your arguments are not yet strings, use a list comprehension: ...
Celery flower's Broker tab is blank
18,391,563
6
2013-08-22T22:02:22Z
18,391,872
11
2013-08-22T22:33:31Z
[ "python", "redis", "celery" ]
I'm running celery and celery flower with redis as a broker. Everything boots up correctly, the worker can find jobs from redis, and the celery worker completes the jobs successfully. The issue I'm having is the Broker tab in the celery flower web UI doesn't show any of the information from Redis. I know the Redis url...
Turns out I needed to start Celery Flower with both the `broker` and `broker_api` command line arguments: ``` celery flower --broker=redis://localhost:6379/0 --broker_api=redis://localhost:6379/0 ``` Hope this helps someone else.
Viewing a list of all python operators via the interpreter
18,392,074
5
2013-08-22T22:53:54Z
18,392,248
7
2013-08-22T23:11:45Z
[ "python", "operator-overloading", "naming" ]
Say I've just implemented some class in Python and want to overload say the '-' operator, but can't remember if I need to use `__subtract__`, `__minus__`, or in fact the correct answer `__sub__`. Is there a quick way to find this out via the interpreter? I tried simple things like `help(-)` but no success. There's ple...
### All standard operators ``` >>> help('SPECIALMETHODS') ``` ### Only basic ones ``` >>> help('BASICMETHODS') ``` ### Only numeric ones ``` >>> help('NUMBERMETHODS') ``` ### Other help subsections ``` >>> help('ATTRIBUTEMETHODS') >>> help('CALLABLEMETHODS') >>> help('MAPPINGMETHODS') >>> help('SEQUENCEMETHODS1'...
Issue trying to change language from Django template
18,392,405
4
2013-08-22T23:33:35Z
18,393,243
10
2013-08-23T01:21:02Z
[ "python", "django", "internationalization", "django-i18n" ]
I need to include two buttons or links to allow users change language between English and Spanish. I've read [the docs](https://docs.djangoproject.com/en/1.5/topics/i18n/translation/#the-set-language-redirect-view) and tried this: ``` <form action="/i18n/setlang/" method="post">{% csrf_token %} <input name="langua...
After more testing and thanks to the [related question](http://stackoverflow.com/questions/5489601/django-i18n-change-language) linked by @AronYsidoro I've finally found the issue and a very simple solution that actually solves this. First, let me explain the problem: When working with `i18_patterns` in your `urls.py`...
Google App Engine (Python) - Uploading a file (image)
18,392,779
6
2013-08-23T00:19:45Z
23,902,282
7
2014-05-28T03:21:13Z
[ "python", "image", "google-app-engine", "upload", "app-engine-ndb" ]
I want the user to be able to upload images to Google App Engine. I have the following (Python): ``` class ImageData(ndb.Model): name = ndb.StringProperty(indexed=False) image = ndb.BlobProperty() ``` Information is submitted by the user using a form (HTML): ``` <form name = "input" action = "/register" me...
Had the same prob. just replace ``` imagedata.image = self.request.get('image') ``` with: ``` imagedata.image = str(self.request.get('image')) ``` also your form needs to have enctype="multipart/form-data ``` <form name = "input" action = "/register" method = "post" enctype="multipart/form-data"> ```
Python logging - determine level number from name
18,392,804
5
2013-08-23T00:21:39Z
18,392,839
11
2013-08-23T00:25:57Z
[ "python" ]
Python logging levels can be registered using `logging.addLevelName`. Is there a method to obtain the Python logging number from a level name?
After you call `addLevelName`, the resulting level is treated exactly the same as all of the standard ones: ``` >>> import logging >>> logging.getLevelName(10) 'DEBUG' >>> logging.getLevelName('DEBUG') 10 >>> logging.addLevelName(15, 'DEBUGGISH') >>> logging.getLevelName(15) 'DEBUGGISH' >>> logging.getLevelName('DEBUG...
Avoid counter increment in Python loop
18,394,033
3
2013-08-23T03:06:46Z
18,394,044
8
2013-08-23T03:07:44Z
[ "python" ]
How can I avoid having to increment the `sequence` counter manually in the following Python code: ``` sequence = 0 for value in random.sample(range(1000), 7): # do something with value and sequence sequence += 1 ```
Enumerate! You can refer to the Python [docs](http://docs.python.org/2/library/functions.html#enumerate). ``` for sequence, value in enumerate(random.sample(range(1000), 7)): # do something with value and sequence ```
Recursive sub folder search and return files in a list python
18,394,147
22
2013-08-23T03:18:56Z
18,394,205
45
2013-08-23T03:24:48Z
[ "python", "list", "recursion", "os.walk" ]
I am working on a script to recursively go through subfolders in a mainfolder and build a list off a certain file type. I am having an issue with the script. Its currently set as follows ``` for root, subFolder, files in os.walk(PATH): for item in files: if item.endswith(".txt") : fileNamePath ...
You should be using the `dirpath` which you call `root`. The `dirnames` are supplied so you can prune it if there are folders that you don't wish `os.walk` to recurse into. ``` import os result = [os.path.join(dp, f) for dp, dn, filenames in os.walk(PATH) for f in filenames if os.path.splitext(f)[1] == '.txt'] ``` Ed...
Test if numpy array contains only zeros
18,395,725
24
2013-08-23T05:55:33Z
18,395,906
14
2013-08-23T06:08:53Z
[ "python", "numpy" ]
We initialize a numpy array with zeros as bellow: ``` np.zeros((N,N+1)) ``` But how do we check whether all elements in a given n\*n numpy array matrix is zero. The method just need to return a True if all the values are indeed zero.
Check out [numpy.count\_nonzero](http://docs.scipy.org/doc/numpy/reference/generated/numpy.count_nonzero.html#numpy.count_nonzero). ``` >>> np.count_nonzero(np.eye(4)) 4 >>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]]) 5 ```