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
saving images in python at a very high quality
16,183,462
21
2013-04-24T04:38:27Z
26,402,197
11
2014-10-16T10:33:30Z
[ "python", "graphics", "matplotlib", "save" ]
How can I save python plots at very high quality? That is, when I keep zooming in on the object saved in a pdf file, there is no blurring? Also, what would be the best mode to save it in? `png`, `eps`? Or some other? I can't do `pdf` because there is a hidden number that happens that mess with `Latexmk` compilation.
Just to add my results, also using matplotlib. .eps made all my text bold and removed transparency. .svg gave me high-res pictures that actually looked like my graph. ``` import matplotlib.pyplot as plt fig, ax = plt.subplots() # Do the plot code fig.savefig('myimage.svg', format='svg', dpi=1200) ``` I used 1200 dpi...
Use IPython magic functions in ipdb shell
16,184,487
15
2013-04-24T06:04:14Z
18,808,166
9
2013-09-15T01:47:53Z
[ "python", "debugging", "ipython" ]
When debugging Python script using `ipdb my_script.py`, I want to use IPython magic functions like `%paste`, `%cd` in `ipdb` debug session shell. Is is possible and how?
You can open a IPython shell inside a stack, just like pdb does. Do the following: * Import embed() from IPython, and put it inside your code. * Run the script Example: ``` from IPython import embed def some_func(): i = 0 embed() return 0 ``` **In Python shell**: ``` >>> te.func() IPython 1.0.0 -- An...
Use IPython magic functions in ipdb shell
16,184,487
15
2013-04-24T06:04:14Z
27,972,406
8
2015-01-15T20:29:14Z
[ "python", "debugging", "ipython" ]
When debugging Python script using `ipdb my_script.py`, I want to use IPython magic functions like `%paste`, `%cd` in `ipdb` debug session shell. Is is possible and how?
According to the [ipdb Github repo](https://github.com/gotcha/ipdb/issues/33) magic IPython functions are not available. Fortunately, the [IPython debugger](https://github.com/ipython/ipython/blob/master/IPython/core/debugger.py#L521) provides a couple of clues of how to get this functionality without launching a separ...
Python Tkinter scrollbar for frame
16,188,420
14
2013-04-24T09:32:05Z
16,198,198
21
2013-04-24T17:13:09Z
[ "python", "tkinter", "scrollbar", "frame" ]
My objective is to add a vertical scroll bar to a frame which has several labels in it. The scroll bar should automatically enabled as soon as the labels inside the frame exceed the height of the frame. After searching through, I found [this](http://stackoverflow.com/questions/3085696/adding-a-scrollbar-to-a-grid-of-wi...
Here is an example: ``` from Tkinter import * # from x import * is bad practice from ttk import * # http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame class VerticalScrolledFrame(Frame): """A pure Tkinter scrollable frame that actually works! * Use the 'interior' attribute to place widgets inside the...
Python Tkinter scrollbar for frame
16,188,420
14
2013-04-24T09:32:05Z
16,841,928
7
2013-05-30T16:59:34Z
[ "python", "tkinter", "scrollbar", "frame" ]
My objective is to add a vertical scroll bar to a frame which has several labels in it. The scroll bar should automatically enabled as soon as the labels inside the frame exceed the height of the frame. After searching through, I found [this](http://stackoverflow.com/questions/3085696/adding-a-scrollbar-to-a-grid-of-wi...
**Am i doing it right?Is there better/smarter way to achieve the output this code gave me?** Generally speaking, yes, you're doing it right. Tkinter has no native scrollable container other than the canvas. As you can see, it's really not that difficult to set up. As your example shows, it only takes 5 or 6 lines of c...
Conditional definition of a function in a module
16,192,448
12
2013-04-24T12:48:22Z
16,192,948
7
2013-04-24T13:11:48Z
[ "python", "design-patterns", "cross-platform" ]
My question is about finding the "good way" of defining a function whose implementation differs according to a given criterion. This function will be called from several scripts, therefore I must place it in a module. For the sake of example, my criterion concerns which platform the script is run on, but be clear that...
If you have a look at the Python standard lib, you see that all three of them are used: * `subprocess` uses solutions 1 and 2; there are several places where the test happens. * `os` uses a variant of solution 3 (`import ... as path`). So use the one which seems the most appropriate and the simplest. > [Solution 1] ...
pycurl https error: unable to get local issuer certificate
16,192,832
4
2013-04-24T13:06:25Z
16,196,263
8
2013-04-24T15:38:10Z
[ "python", "windows", "ssl", "ssl-certificate", "pycurl" ]
![Screenshot of the error](http://i.stack.imgur.com/0bKFY.png) ``` >>> import pycurl >>> c = pycurl.Curl() >>> c.setopt(c.URL, 'https://quora.com') >>> c.perform() Traceback (most recent call last): File "<stdin>", line 1, in <module> pycurl.error: (60, 'SSL certificate problem: unable to get local issuer certificat...
The problem is that `pycurl` needs an up-to-date certificate chain to verify the ssl certificates. A good solution would be to use [certifi](https://pypi.python.org/pypi/certifi). It's basically an up-to-date copy of mozilla's built in certificate chain wrapped in a python package which can be kept up to date using p...
Python nicest way to take boolean expression string apart
16,192,874
4
2013-04-24T13:08:30Z
16,193,036
8
2013-04-24T13:15:46Z
[ "python" ]
I have a boolean expression string, that I would like to take apart: ``` condition = "a and (b or (c and d))" ``` Or let's say: I want to be able to access the string contents between two parenthesis. I want following outcome: ``` "(b or (c and d))" "(c and d)" ``` I've tried the following with regular expressi...
This is the sort of thing you can't do with a simple regex. You need to actually parse the text. [pyparsing](http://pyparsing.wikispaces.com/) is apparently excellent for doing that.
Get smallest N values from numpy array ignoring inf and nan
16,193,202
6
2013-04-24T13:23:36Z
16,193,445
8
2013-04-24T13:35:24Z
[ "python", "arrays", "math", "numpy" ]
I need a good, quick method for finding the 10 smallest real values from a numpy array that could have arbitrarily many `nan` and/or `inf` values. I need to identify the indices of these smallest real values, not the values themselves. I have found the `argmin` and `nanargmin` functions from numpy. They aren't really...
The only values that should be throwing this out are the negative infinite ones. So try: ``` import numpy as np a = np.random.rand(20) a[4] = -np.inf k = 10 a[np.isneginf(a)] = inf result = a[np.argsort(a)[:k]] ```
TypeError: expected string or buffer
16,193,521
17
2013-04-24T13:39:36Z
16,193,573
16
2013-04-24T13:41:31Z
[ "python", "regex" ]
I have this simple code: ``` import re, sys f = open('findallEX.txt', 'r') lines = f.readlines() match = re.findall('[A-Z]+', lines) print match ``` I keep getting the 'expected string or buffer' error and i don't know why. Can anybody help? Thanks!
`lines` is a list. `re.findall()` doesn't take lists. ``` >>> import re >>> f = open('README.md', 'r') >>> lines = f.readlines() >>> match = re.findall('[A-Z]+', lines) Traceback (most recent call last): File "<input>", line 1, in <module> File "/usr/lib/python2.7/re.py", line 177, in findall return _compile(p...
How do I perform secondary sorting in python?
16,193,578
4
2013-04-24T13:41:42Z
16,193,637
20
2013-04-24T13:44:18Z
[ "python" ]
If i have a list of numbers `[4,2,5,1,3]` I want to sort it first by some function `f` and then for numbers with the same value of `f` i want it to be sorted by the magnitude of the number. This code does not seem to be working. ``` list5 = sorted(list5) list5 = sorted(list5, key = lambda vertex: degree(vertex)) ``` ...
Sort it by a (firstkey, secondkey) tuple: ``` sorted(list5, key=lambda vertex: (degree(vertex), vertex)) ```
Where should I put my own python module so that it can be imported
16,196,268
13
2013-04-24T15:38:18Z
16,196,400
7
2013-04-24T15:44:21Z
[ "python", "python-2.7" ]
I have my own package in python and I am using it very often. what is the most elegant or conventional directory where i should put my package so it is going to be imported without playing with PYTHONPATH or sys.path? What about site-packages for example? `/usr/lib/python2.7/site-packages`. Is it common in python to...
I usually put the stuff i want to have ready to import in the user site directory: ``` ~/.local/lib/pythonX.X/site-packages ``` To show the right directory for your platform, you can use `python -m site --user-site` --- edit: it will show up in `sys.path` once you create it: ``` mkdir -p "`python -m site --user-si...
Images from ImageField in Django don't load in template
16,196,603
7
2013-04-24T15:52:15Z
16,198,963
22
2013-04-24T17:54:57Z
[ "python", "django", "image", "django-templates", "django-models" ]
I'm building a gallery using Django(1.5.1) on my local machine. In my Album model I have a `ImageField`. There is a view to show all images of an album. It works well, but at the end images don't show up. There's border of images as you can see but images don't load. ### screenshot ![enter image description here](htt...
I have a clue on what's the problem. `MEDIA_URL` should be like this: ``` MEDIA_ROOT='<the full path to your media folder>' (i.e: '/home/ike/project/media/') MEDIA_URL='/media/' ``` Note the slash character at the beginning. That is because media is a folder in your root server folder and not relative to whatever oth...
Get exit code and stderr from subprocess call
16,198,546
18
2013-04-24T17:32:04Z
16,198,668
26
2013-04-24T17:38:26Z
[ "python", "python-3.x" ]
I read up on the functions provided by subprocess - call, check\_call, check\_output, and understand how each works and differs in functionality from one another. I am currently using check\_output, so I can have access to the stdout, and used "try block" to catch the exception, as follows: ``` # "cmnd" is a string th...
Try this version: ``` try: cmnd_output = check_output(cmnd, stderr=STDOUT, shell=True, timeout=3, universal_newlines=True); except CalledProcessError as exc: print("Status : FAIL", exc.re...
Get exit code and stderr from subprocess call
16,198,546
18
2013-04-24T17:32:04Z
27,661,481
18
2014-12-26T20:09:57Z
[ "python", "python-3.x" ]
I read up on the functions provided by subprocess - call, check\_call, check\_output, and understand how each works and differs in functionality from one another. I am currently using check\_output, so I can have access to the stdout, and used "try block" to catch the exception, as follows: ``` # "cmnd" is a string th...
The accepted solution covers the case in which you are ok mixing `stdout` and `stderr`, but in cases in which the child process (for whatever reason) decides to use `stderr` IN ADDITION to `stdout` for a non failed output (i.e. to output a non-critical warning), then the given solution may not desirable. For example, ...
python 2.7 presence in a dictionary
16,200,067
8
2013-04-24T18:59:07Z
16,200,446
11
2013-04-24T19:20:44Z
[ "python", "python-2.7" ]
I want to test a presence of a key in a dictionary as 'if key is not in dictionary: do something' I have already done this already multiple times, but this time it behaves strangely. particularly: ``` termCircuit = termCircuitMap[term] ``` returns KeyError when I debugged this code in Eclipse PyDev, i got the follo...
You might see this behavior if your key's `__hash__` function is not properly defined. E.g., the following gives roughly the same behavior as you describe: ``` import random class Evil(int): def __hash__(self): return random.randint(0, 10000) evil_vals = [Evil(n) for n in range(10)] dict_with_evil_keys ...
deleting multiple elements without updating till the end
16,200,363
3
2013-04-24T19:16:03Z
16,200,413
9
2013-04-24T19:18:59Z
[ "python", "list" ]
I have two lists: ``` list_a = [1,5,8] list_b = [12,4,2,5,7,5,3,6,8] ``` The elements in `list_a` correspond to the indices of elements in `list_b`. Both lists are of size greater than 100. How can I delete the elements of `list_b` whose indices are in `list_a`, so if you take the lists above the resulting list is `...
Two options: * Create a new list with a list comprehension: ``` newlist = [el for i, el in enumerate(oldlist) if i not in indices_to_delete] ``` This will be all the faster if `indices_to_delete` was a `set`: ``` indices_to_delete = set(indices_to_delete) newlist = [el for i, el in enumerate(oldlist) ...
Running multiple instances of celery on the same server
16,200,532
4
2013-04-24T19:26:01Z
16,285,519
8
2013-04-29T18:16:40Z
[ "python", "celery" ]
I want to run to instances of celery on the same machine. One is for an 'A' version of my application, the other is for the 'B' version. I have two instances, which I start like this: ``` (env1)/home/me/firstapp$ celery -A app.tasks worker --config celeryconfig (env2)/home/me/secondapp$ celery -A app.tasks worker -n ...
I solved this by using a virtual host for celery. Once the rabbitmq server is running I issue these commands: ``` rabbitmqctl add_user user password rabbitmqctl add_vhost app2 rabbitmqctl set_permissions -p app2 user ".*" ".*" ".*" ``` Then I start celery with: ``` celery -A tasks worker --broker=amqp://user:passwo...
Why doesn't #include <Python.h> work?
16,200,997
8
2013-04-24T19:56:01Z
32,425,901
13
2015-09-06T16:44:04Z
[ "c++", "python", "visual-studio-2010", "wrapper" ]
I'm trying to run Python modules in C++ using `"#include <Python.h>"`, however, after setting the "Additional Include Dependencies" of the project to "\include" I get the following error when debuging, ``` LINK : fatal error LNK1104: cannot open file 'python27_d.lib' ``` I read that I should download the development ...
I normally circumvent this by using the non-debug Python lib in debug builds. Typically, this leads to code like: ``` #ifdef _DEBUG #undef _DEBUG #include <Python.h> #define _DEBUG #else #include <Python.h> #endif ``` where you hide the definition of \_DEBUG during the inclusion of Python.h.
In which order is an if statement evaluated in Python
16,201,362
6
2013-04-24T20:16:23Z
16,201,394
10
2013-04-24T20:18:19Z
[ "python" ]
If you have an if statement where several variables or functions are evaluated, in which order are they evaluated? ``` if foo > 5 or bar > 6: print 'foobar' ``` In this specific case, will foo be evaluated against the five and then bar against the 6 (left to right) or will it be evaluated right to left? I am assu...
The left clause will be evaluated first, and then the right one only if the first one is `False`. This is why you can do stuff like: ``` if not person or person.name == 'Bob': print "You have to select a person and it can't be Bob" ``` Without it breaking. Conversely, with an `and` clause, the right clause will...
numpy divide row by row sum
16,202,348
16
2013-04-24T21:16:31Z
16,202,486
30
2013-04-24T21:25:06Z
[ "python", "multidimensional-array", "numpy" ]
How can I divide a numpy array row by the sum of all values in this row? This is one example. But I'm pretty sure there is a fancy and much more efficient way of doing this: ``` import numpy as np e = np.array([[0., 1.],[2., 4.],[1., 5.]]) for row in xrange(e.shape[0]): e[row] /= np.sum(e[row]) ``` Result: ``` ...
Method #1: use `None` (or `np.newaxis`) to add an extra dimension so that broadcasting will behave: ``` >>> e array([[ 0., 1.], [ 2., 4.], [ 1., 5.]]) >>> e/e.sum(axis=1)[:,None] array([[ 0. , 1. ], [ 0.33333333, 0.66666667], [ 0.16666667, 0.83333333]]) ``` Method #2: g...
Adding two pandas.series objects
16,202,711
9
2013-04-24T21:41:04Z
16,202,796
13
2013-04-24T21:47:26Z
[ "python", "pandas" ]
I'm working through the "Python For Data Analysis" and I don't understand a particular functionality. Adding two pandas series objects will automatically align the indexed data but if one object does not contain that index it is returned as NaN. For example from book: ``` a = Series([35000,71000,16000,5000],index=...
Pandas does not assume that 500+NaN=500, but it is easy to ask it to do that: `a.add(b, fill_value=0)`
Trouble with assigning (or re-overloading) the assignment operator in Python
16,203,185
5
2013-04-24T22:17:19Z
16,203,259
8
2013-04-24T22:23:16Z
[ "python" ]
I'm having trouble assigning the assignment operator. I have successfully overloaded `__setattr__`. But after the object is initialized, I want `__setattr__` to do something else, so I try assigning it to be another function, `__setattr2__`. Code: ``` class C(object): def __init__(self): self.x = 0 ...
[From the docs](http://docs.python.org/2/reference/datamodel.html#new-style-special-lookup): > ## Special method lookup for new-style classes > > For new-style classes, implicit invocations of special methods are > only guaranteed to work correctly if defined on an object’s type, not > in the object’s instance dic...
How to input variables in logger formatter?
16,203,908
5
2013-04-24T23:23:30Z
16,204,656
8
2013-04-25T00:49:39Z
[ "python", "logging" ]
I currently have: ``` FORMAT = '%(asctime)s - %(levelname)s - %(message)s' logging.basicConfig(format=FORMAT, datefmt='%d/%m/%Y %H:%M:%S', filename=LOGFILE, level=getattr(logging, options.loglevel.upper())) ``` ... which works great, however I'm trying to do: ``` FORMAT = '%(MYVAR)s %(asctime)s - %(levelname)s - %(m...
You could use a [custom filter](http://docs.python.org/2/howto/logging-cookbook.html#using-filters-to-impart-contextual-information): ``` import logging MYVAR = 'Jabberwocky' class ContextFilter(logging.Filter): """ This is a filter which injects contextual information into the log. """ def filter(s...
TypeError: object of type 'Cursor' has no len()
16,204,077
8
2013-04-24T23:41:40Z
16,204,173
11
2013-04-24T23:52:53Z
[ "python", "mongodb", "cursor", "pymongo" ]
TypeError: object of type 'Cursor' has no len() I get the above error when i try to execute ``` reply = db['test'].find({"date":{"$gt":date_query}} ,{"date":1,"route_id":1,"loc":1,"_id":0}) length = len(reply) ``` Please help
EDIT: Just noticed you referenced mongodb in your tags. I was confused because the body of your question didn't specify which database you are using. The cursor has a method 'count()' which will return what you're looking for. [PyMongo Cursor Docs](http://api.mongodb.org/python/current/api/pymongo/cursor.html)
For Base64 encode, prefer str.encode('base64_codec') or base64.b64encode(str)?
16,205,713
4
2013-04-25T03:08:14Z
16,205,776
8
2013-04-25T03:16:12Z
[ "python", "codec" ]
In Python library, there is base64 module for working on Base64. At the same time, if you want to encode a string, there is codec for base64, i.e. `str.encode('base64_encode')`. Which approach is preferred?
While it may work for Python 2: ``` >>> 'foo'.encode('base64') 'Zm9v\n' ``` Python 3 doesn't support it: ``` >>> 'foo'.encode('base64') Traceback (most recent call last): File "<stdin>", line 1, in <module> LookupError: unknown encoding: base64 ``` And in terms of speed (in Python 2), the `b64encode` method is ab...
requests.HTTPError uncaught after a requests.get() 404 response
16,206,062
2
2013-04-25T03:48:41Z
16,206,247
10
2013-04-25T04:13:13Z
[ "python", "error-handling", "try-catch", "python-requests" ]
I'm having a slight problem with the requests library. Say for example I have a statement like this in Python: ``` try: request = requests.get('google.com/admin') #Should return 404 except requests.HTTPError, e: print 'HTTP ERROR %s occured' % e.code ``` For some reason the exception is not being caught. I've...
Interpreter is your friend: ``` import requests requests.get('google.com/admin') # MissingSchema: Invalid URL u'google.com/admin': No schema supplied ``` Also, `requests` exceptions: ``` import requests.exceptions dir(requests.exceptions) ``` Also notice that by default `requests` doesn't raise exception if status ...
Python/BeautifulSoup - how to remove all tags from an element?
16,206,380
17
2013-04-25T04:26:49Z
23,353,571
10
2014-04-29T00:40:34Z
[ "python", "beautifulsoup" ]
How can I simply strip all tags from an element I find in BeautifulSoup?
why has no answer I've seen mentioned anything about the `unwrap` method? Or, even easier, the `get_text` method <http://www.crummy.com/software/BeautifulSoup/bs4/doc/#unwrap> <http://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text>
Python/BeautifulSoup - how to remove all tags from an element?
16,206,380
17
2013-04-25T04:26:49Z
28,162,403
16
2015-01-27T02:47:02Z
[ "python", "beautifulsoup" ]
How can I simply strip all tags from an element I find in BeautifulSoup?
With `BeautifulStoneSoup` gone in `bs4`, it's even simpler in Python3 ``` from bs4 import BeautifulSoup soup = BeautifulSoup(html) text = soup.get_text() print(text) ```
Confused by python file mode "w+"
16,208,206
54
2013-04-25T06:51:34Z
16,208,298
37
2013-04-25T06:57:27Z
[ "python", "file", "io" ]
From the [doc](http://docs.python.org/2/library/functions.html#open), > Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distin...
Let's say you're opening the file with a `with` statement like you should be. Then you'd do something like this to read from your file: ``` with open('somefile.txt', 'w+') as f: # Note that f has now been truncated to 0 bytes, so you'll only # be able to read data that you wrote earlier... f.write('somedat...
Confused by python file mode "w+"
16,208,206
54
2013-04-25T06:51:34Z
16,212,401
83
2013-04-25T10:30:37Z
[ "python", "file", "io" ]
From the [doc](http://docs.python.org/2/library/functions.html#open), > Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distin...
All file modes in Python * `r` for reading * `w` for writing * `r+` opens for reading and writing (cannot truncate a file) * `w+` for writing and reading (can truncate a file) * `rb+` reading or writing a binary file * `wb+` writing a binary file * `a+` opens for appending
Confused by python file mode "w+"
16,208,206
54
2013-04-25T06:51:34Z
23,566,951
77
2014-05-09T14:19:17Z
[ "python", "file", "io" ]
From the [doc](http://docs.python.org/2/library/functions.html#open), > Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distin...
## ***Here is a list of the different modes of opening a file:*** * # r > Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. * # rb > Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the...
django logging set context globally per request?
16,210,101
19
2013-04-25T08:38:38Z
16,210,572
8
2013-04-25T09:01:07Z
[ "python", "django", "logging" ]
Lets say I want to log like this formatting string : ``` %(levelname)s %(asctime)s %(module)s %(funcName)s %(message)s %(user_id) ``` It can be done using this type of logging command : `logging.error('Error fetching information', extra = { 'user_id': 22 } )` This will add the current userid to logging messages for...
There exists a ThreadLocal middleware on <https://github.com/jedie/django-tools/blob/master/django_tools/middlewares/ThreadLocal.py> which helps you with your issue in making the current request available everywhere. So what you need to do is add the middleware to your MIDDLEWARE\_CLASSES setting, and create a functio...
Communication between two python scripts
16,213,235
3
2013-04-25T11:13:20Z
16,213,366
8
2013-04-25T11:19:18Z
[ "python", "inter-process-communicat" ]
a methodology question: I have a "main" python script which runs on an infinite loop on my system, and I want to send information to it (a json data string for example) occasionally with some other python scripts that will be started later by myself or another program and will end just after sending the string. I can...
zeromq: <http://www.zeromq.org/> - is best solution for interprocess communications imho and have a excelent binding for python: <http://www.zeromq.org/bindings:python>
Updating h5py Datasets
16,213,525
8
2013-04-25T11:26:48Z
16,215,898
11
2013-04-25T13:19:59Z
[ "python", "hdf5", "h5py" ]
Does any one have an idea for updating hdf5 datasets from h5py? Assuming we create a dataset like: ``` import h5py import numpy f = h5py.File('myfile.hdf5') dset = f.create_dataset('mydataset', data=numpy.ones((2,2),"=i4")) new_dset_value=numpy.zeros((3,3),"=i4") ``` Is it possible to extend the dset to a 3x3 numpy a...
You need to create the dataset with the "extendable" property. It's not possible to change this after the initial creation of the dataset. To do this, [you need to use the "maxshape" keyword](https://code.google.com/p/h5py/wiki/HowTo#Appending_to_a_dataset_%28HDF5_1.8_only%29). A value of `None` in the `maxshape` tuple...
How to convert base64 string to image?
16,214,190
6
2013-04-25T12:02:09Z
16,214,280
19
2013-04-25T12:06:31Z
[ "python", "base64" ]
I'm converting an image to **base64** string and sending it from android device to the server. Now, I need to change that string back to an image and save it in the database. Any help?
Try this: ``` import base64 imgdata = base64.b64decode(imgstring) filename = 'some_image.jpg' # I assume you have a way of picking unique filenames with open(filename, 'wb') as f: f.write(imgdata) # f gets closed when you exit the with statement # Now save the value of filename to your database ```
Write data to disk in Python as a background process
16,214,736
5
2013-04-25T12:25:33Z
16,214,889
7
2013-04-25T12:33:06Z
[ "python", "file", "multiprocessing" ]
I have a program in Python that basically does the following: ``` for j in xrange(200): # 1) Compute a bunch of data # 2) Write data to disk ``` 1) takes about 2-5 minutes 2) takes about ~1 minute Note that there is too much data to keep in memory. Ideally what I would like to do is write the data to disk...
You could try [using multiple processes](http://docs.python.org/2/library/multiprocessing.html) like this: ``` import multiprocessing as mp def compute(j): # compute a bunch of data return data def write(data): # write data to disk if __name__ == '__main__': pool = mp.Pool() for j in xrange(200)...
Test if ValidationError was raised
16,214,846
8
2013-04-25T12:31:00Z
16,214,886
11
2013-04-25T12:33:02Z
[ "python", "django", "unit-testing" ]
I want to test if an exception was raised how can I do that? in my models.py I have this function, the one I want to test: ``` def validate_percent(value): if not (value >= 0 and value <= 100): raise ValidationError('error') ``` in my tests.py I tried this: ``` def test_validate_percent(self): self....
`assertRaises` is used as a context manager: ``` def test_validate_percent(self): with self.assertRaises(ValidationError): validate_percent(1000) ``` or with a callable: ``` def test_validate_percent(self): self.assertRaises(ValidationError, validate_percent, 1000) ``` * <http://docs.python.org/2/li...
TypeError: <lambda>() takes no arguments (1 given)
16,215,045
8
2013-04-25T12:40:28Z
16,215,075
20
2013-04-25T12:41:54Z
[ "python", "lambda", "tkinter" ]
I am a newbie to python programming and am still trying to figure out the use of lambda. Was worrking on some gui program after much googling i figured that i need to use this for buttons to work as i need it to **THIS WORKS** ``` mtrf = Button(root, text = "OFF",state=DISABLED,command = lambda:b_clicked("mtrf")) ```...
`Scale` calls the function passed as `command` with one argument, so you have to use it (although throw it away immediately). Change: ``` command=lambda: scale_changed('LED') ``` to ``` command=lambda x: scale_changed('LED') ```
test for membership in a 2d numpy array
16,216,078
9
2013-04-25T13:28:46Z
16,216,866
8
2013-04-25T14:03:09Z
[ "python", "numpy" ]
I have two 2D arrays of the same size ``` a = array([[1,2],[3,4],[5,6]]) b = array([[1,2],[3,4],[7,8]]) ``` I want to know the rows of b that are in a. So the output should be : ``` array([ True, True, False], dtype=bool) ``` without making : ``` array([any(i == a) for i in b]) ``` cause a and b are huge. Ther...
What we'd really like to do is use `np.in1d`... except that `np.in1d` only works with 1-dimensional arrays. Our arrays are multi-dimensional. However, we can *view* the arrays as a 1-dimensional array of *strings*: ``` a = a.ravel().view((np.str, a.itemsize*a.shape[1])) ``` For example, ``` In [15]: a = np.array([[1...
Python: Getting text of a Regex match
16,217,910
7
2013-04-25T14:45:59Z
16,217,967
8
2013-04-25T14:48:31Z
[ "python", "regex" ]
I have a regex match object in Python. I want to get the text it matched. Say if the pattern is `'1.3'`, and the search string is `'abc123xyz'`, I want to get `'123'`. How can I do that? I know I can use `match.string[match.start():match.end()]`, but I find that to be quite cumbersome (and in some cases wasteful) for ...
You can simply use the match object's `group` function, like: ``` match = re.search(r"1.3", "abc123xyz") if match: doSomethingWith(match.group(0)) ``` to get the entire match. **EDIT:** as thg435 points out, you can also omit the `0` and just call `match.group()`. Addtional note: if your pattern contains parenth...
Fast interpolation of regularly sampled 3D data with different intervals in x,y, and z
16,217,995
14
2013-04-25T14:49:43Z
16,220,527
12
2013-04-25T16:54:07Z
[ "python", "numpy", "scipy", "interpolation", "volume-rendering" ]
I have some volumetric imaging data consisting of values sampled on a regular grid in x,y,z, but with a non-cubic voxel shape (the space between adjacent points in z is greater than in x,y). I would eventually like to be able to be able to interpolate the values on some arbitrary 2D plane that passes through the volume...
You can use `map_coordinates` with a little bit of algebra. Lets say the spacings of your grid are `dx`, `dy` and `dz`. We need to map these **real world** coordinates to **array index** coordinates, so lets define three new variables: ``` xx = x / dx yy = y / dy zz = z / dz ``` The **array index** input to `map_coor...
Fast interpolation of regularly sampled 3D data with different intervals in x,y, and z
16,217,995
14
2013-04-25T14:49:43Z
16,221,098
7
2013-04-25T17:30:30Z
[ "python", "numpy", "scipy", "interpolation", "volume-rendering" ]
I have some volumetric imaging data consisting of values sampled on a regular grid in x,y,z, but with a non-cubic voxel shape (the space between adjacent points in z is greater than in x,y). I would eventually like to be able to be able to interpolate the values on some arbitrary 2D plane that passes through the volume...
Here's a simple class `Intergrid` that maps / scales non-uniform to uniform grids, then does `map_coordinates`. On a [4d test case](http://stackoverflow.com/questions/14119892/python-4d-linear-interpolation-on-a-rectangular-grid) it runs at about 1 μsec per query point. HTML doc is [here](https://denis-bz.github.com/...
How to instantiate a template method of a template class with swig?
16,218,929
9
2013-04-25T15:32:37Z
16,269,493
9
2013-04-29T00:12:42Z
[ "c++", "python", "swig" ]
I have a class in C++ which is a template class, and one method on this class is templated on another placeholder ``` template <class T> class Whatever { public: template <class V> void foo(std::vector<V> values); } ``` When I transport this class to the swig file, I did ``` %template(Whatever_MyT) Whatever<...
Declare instances of the member templates first, then declare instances of the class templates. ### Example ``` %module x %inline %{ #include<iostream> template<class T> class Whatever { T m; public: Whatever(T a) : m(a) {} template<class V> void foo(V a) { std::cout << m << " " << a << std::endl; } }; %...
Get a subarray from a numpy array based on index
16,222,621
2
2013-04-25T18:57:40Z
16,222,673
7
2013-04-25T19:00:22Z
[ "python", "numpy" ]
I have a numpy array vector, and I want to get a subset based on the indexes: ``` import numpy as np input=np.array([1,2,3,4,5,6,7,8,9,10]) index=np.array([0,1,0,0,0,0,1,0,0,1]) ``` what is a pythonic way to get out output=[2,7,10]?
``` output = input[index.astype(np.bool)] ``` or ``` output = input[np.where(index)[0]] ```
forced conversion of non-numeric numpy arrays with NAN replacement
16,223,483
4
2013-04-25T19:47:52Z
16,223,595
8
2013-04-25T19:54:37Z
[ "python", "numpy", "type-conversion", null, "coercion" ]
Consider the array `x = np.array(['1', '2', 'a'])` Tying to convert to a float array raises an exception ``` x.astype(np.float) ValueError: could not convert string to float: a ``` Does numpy provide any efficient way to coerce this into a numeric array, replacing non-numeric values with something like NAN? Altern...
You can convert an array of strings into an array of floats (with NaNs) using `np.genfromtxt`: ``` In [83]: np.set_printoptions(precision=3, suppress=True) In [84]: np.genfromtxt(np.array(['1','2','3.14','1e-3','b','nan','inf','-inf'])) Out[84]: array([ 1. , 2. , 3.14 , 0.001, nan, nan, inf, -inf]) ...
Python dictionary key/value with prefixes - what's the prefix for?
16,224,115
2
2013-04-25T20:26:42Z
16,224,153
7
2013-04-25T20:29:17Z
[ "python", "unicode", "python-unicode" ]
I've seen a Python dict looks like this lately: ``` test1 = {u'user':u'user1', u'user_name':u'alice'} ``` This confuses me a bit, what is the `u` before the key/value pair for? Is it some sort of prefix? How is this different: ``` test2 = {'user':'user1', 'user_name':'alice'} ``` I've tried to play with both test1 ...
In Python 2, you have to force Unicode character to remain in Unicode. So, `u` prevents the text to translate to ASCII. (remaining as unicode) For example, this won't work in Python 2: ``` 'ô SO'.upper() == 'Ô SO'' ``` Unless you do this: ``` u'ô SO'.upper() == 'Ô SO' ``` You can read more on this: [**DOCS**]...
Using print() inside recursive functions in Python3
16,224,200
7
2013-04-25T20:32:29Z
16,224,253
7
2013-04-25T20:36:01Z
[ "python", "recursion", "python-3.x" ]
I am following the book Introduction to Computing Using Python, by Ljubomir Perkovic, and I am having trouble with one of the examples in recursion section of the book. The code is as follows: ``` def pattern(n): 'prints the nth pattern' if n == 0: # base case print(0, end=' ') else: #recursi...
The `print` function doesn't always flush the output. You should flush it explicitly: ``` import sys def pattern(n): 'prints the nth pattern' if n == 0: # base case print(0, end=' ') else: #recursive step: n > 0 pattern(n-1) # print n-1st pattern print(n, end=' ') ...
Get the second largest number in a list in linear time
16,225,677
18
2013-04-25T22:16:23Z
16,225,722
8
2013-04-25T22:21:54Z
[ "python", "performance" ]
I'm learning Python and the simple ways to handle lists is presented as an advantage. Sometimes it is, but look at this: ``` >>> numbers = [20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7] >>> numbers.remove(max(numbers)) >>> max(numbers) 74 ``` A very easy, quick way of obtaining the second largest number from a list. Exce...
You could always use [`sorted`](http://docs.python.org/2/library/functions.html#sorted) ``` >>> sorted(numbers)[-2] 74 ```
Get the second largest number in a list in linear time
16,225,677
18
2013-04-25T22:16:23Z
16,225,736
28
2013-04-25T22:23:22Z
[ "python", "performance" ]
I'm learning Python and the simple ways to handle lists is presented as an advantage. Sometimes it is, but look at this: ``` >>> numbers = [20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7] >>> numbers.remove(max(numbers)) >>> max(numbers) 74 ``` A very easy, quick way of obtaining the second largest number from a list. Exce...
You could use the `heapq` module: ``` >>> el = [20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7] >>> import heapq >>> heapq.nlargest(2, el) [90.8, 74] ``` And go from there...
Get the second largest number in a list in linear time
16,225,677
18
2013-04-25T22:16:23Z
16,226,255
12
2013-04-25T23:15:50Z
[ "python", "performance" ]
I'm learning Python and the simple ways to handle lists is presented as an advantage. Sometimes it is, but look at this: ``` >>> numbers = [20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7] >>> numbers.remove(max(numbers)) >>> max(numbers) 74 ``` A very easy, quick way of obtaining the second largest number from a list. Exce...
Since @OscarLopez and I have different opinions on what the second largest means, I'll post the code according to my vision and in line with the first algorithm provided by the asker. ``` def second_largest(numbers): count = 0 m1 = m2 = float('-inf') for x in numbers: count += 1 if x > m2: ...
Python: Function Documentation
16,225,782
2
2013-04-25T22:27:40Z
16,225,792
10
2013-04-25T22:28:30Z
[ "python", "documentation" ]
Is there a way to check what a function or a method does inside of python itself similar to the help function in Matlab. I want to get the definition of the function without having to Google it.
Yes, you can call `help(whatever)` inside python interactive interpreter. ``` >>> help Type help() for interactive help, or help(object) for help about object. >>> help(zip) Help on built-in function zip in module __builtin__: zip(...) zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)] Return a lis...
How to get Python division by -0.0 and 0.0 to result in -Inf and Inf, respectively?
16,226,633
8
2013-04-25T23:58:52Z
16,226,757
12
2013-04-26T00:13:50Z
[ "python", "python-2.7", "ieee-754", "divide-by-zero" ]
I have a situation where it is reasonable to have a division by 0.0 or by -0.0 where I would expect to see +Inf and -Inf, respectively, as results. It seems that Python enjoys throwing a ``` ZeroDivisionError: float division by zero ``` in either case. Obviously, I figured that I could simply wrap this with a test fo...
``` from math import copysign def divide(numerator, denominator): if denominator == 0.0: return copysign(float('inf'), denominator) return numerator / denominator >>> divide(1, -0.0) -inf >>> divide(1, 0) inf ```
How to get Python division by -0.0 and 0.0 to result in -Inf and Inf, respectively?
16,226,633
8
2013-04-25T23:58:52Z
16,226,779
8
2013-04-26T00:16:55Z
[ "python", "python-2.7", "ieee-754", "divide-by-zero" ]
I have a situation where it is reasonable to have a division by 0.0 or by -0.0 where I would expect to see +Inf and -Inf, respectively, as results. It seems that Python enjoys throwing a ``` ZeroDivisionError: float division by zero ``` in either case. Obviously, I figured that I could simply wrap this with a test fo...
I completely agree with @Mark Ransom, except that I would use `try` instead: ``` def f(a, b): try: return a / b except ZeroDivisionError: return copysign(float('inf'), denominator) ``` The reason I recommend this is that if you are performing this function many times, you don't have to waste t...
A Python "catch all" method for undefined/unimplemented attributes in classes
16,227,657
10
2013-04-26T02:09:02Z
16,227,679
9
2013-04-26T02:13:05Z
[ "python" ]
I *love* Python's `@property` decorate system. I love that you can run custom code when you call `aClassObect.attribute`. Especially for validating data when you're setting an attribute. However, one thing that I want, but I can't find, is a way to run custom code when trying to set an attribute that doesn't exist. For...
override `__getattr__` and `__setattr__`.
A Python "catch all" method for undefined/unimplemented attributes in classes
16,227,657
10
2013-04-26T02:09:02Z
16,228,010
8
2013-04-26T02:56:25Z
[ "python" ]
I *love* Python's `@property` decorate system. I love that you can run custom code when you call `aClassObect.attribute`. Especially for validating data when you're setting an attribute. However, one thing that I want, but I can't find, is a way to run custom code when trying to set an attribute that doesn't exist. For...
To elaborate a bit on [Elazar](http://stackoverflow.com/users/2289509/elazar)'s answer, you'll want to override the [`__setattr__`](http://docs.python.org/2/reference/datamodel.html#customizing-attribute-access) magic method and do a check in it to see if the attribute already exists. If not, raise an exception. Here's...
Python: simplest way to get list of values from dict?
16,228,248
48
2013-04-26T03:25:57Z
16,228,268
70
2013-04-26T03:27:37Z
[ "python", "list", "dictionary" ]
What is the simplest way to get a list of the values in a dict in Python? In Java, getting the values of a Map as a List is as easy as doing `list = map.values();`. I'm wondering if there is a similarly simple way in Python to get a list of values from a dict.
Yes it's the exact same thing in [Python 2](https://docs.python.org/2/library/stdtypes.html#dict.values): ``` d.values() ``` In [Python 3](https://docs.python.org/3/library/stdtypes.html#dict.values) (where `dict.values` returns a [*view*](https://docs.python.org/3/library/stdtypes.html#dict-views) of the dictionaryâ...
What is the difference between json.dumps/loads and tornado.escape.json_encode/json_decode?
16,228,427
7
2013-04-26T03:46:45Z
16,228,559
11
2013-04-26T04:03:53Z
[ "python", "tornado" ]
It seems they are behaving exactly the same way. ``` >>> data [('a', 'b'), {'a': 1, 'b': 2}, ['a', 'b'], 'a', 'b'] >>> json.dumps(data) '[["a", "b"], {"a": 1, "b": 2}, ["a", "b"], "a", "b"]' >>> tornado.escape.json_encode(data) '[["a", "b"], {"a": 1, "b": 2}, ["a", "b"], "a", "b"]' >>> json.loads(json.dumps(data)) [[u...
Sometimes it's useful to read [the source code](https://github.com/facebook/tornado/blob/master/tornado/escape.py): ``` def json_encode(value): return json.dumps(value).replace("</", "<\\/") def json_decode(value): return json.loads(to_basestring(value)) def to_basestring(value): if isinstance(value, _BA...
How to multiply numpy 2D array with numpy 1D array?
16,229,823
6
2013-04-26T06:09:59Z
16,229,848
8
2013-04-26T06:12:09Z
[ "python", "numpy" ]
The two arrays: ``` a = numpy.array([[2,3,2],[5,6,1]]) b = numpy.array([3,5]) c = a * b ``` What I want is: ``` c = [[6,9,6], [25,30,5]] ``` But, I am getting this error: ``` ValueError: operands could not be broadcast together with shapes (2,3) (2) ``` How to **multiply** a nD array with 1D array, where `le...
You need to convert array b to a (2, 1) shape array, use None or `numpy.newaxis` in the index tuple: ``` import numpy a = numpy.array([[2,3,2],[5,6,1]]) b = numpy.array([3,5]) c = a * b[:, None] ``` Here is the [document](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing).
How to expose raw byte buffers with Boost::Python?
16,232,520
6
2013-04-26T09:01:14Z
17,759,608
8
2013-07-20T06:57:14Z
[ "python", "boost", "boost-python", "bytebuffer" ]
I've got third party C++ library in which some class methods use raw byte buffers. I'm not quite sure how to deal in Boost::Python with it. C++ library header is something like: ``` class CSomeClass { public: int load( unsigned char *& pInBufferData, int & iInBufferSize ); int save( unsigned char *& pOu...
You have to write, yourself, functions on your bindings that will return a [Py\_buffer](http://docs.python.org/2/c-api/buffer.html?highlight=buffer#buffers-and-memoryview-objects) object from that data, allowing your to either read-only (use `PyBuffer_FromMemory`) or read-write (use `PyBuffer_FromReadWriteMemory`) your...
Distributed task queues (Ex. Celery) vs crontab scripts
16,232,572
59
2013-04-26T09:04:04Z
16,234,656
84
2013-04-26T10:50:13Z
[ "python", "django", "celery" ]
I'm having trouble understanding the purpose of 'distributed task queues'. For example, python's [celery library](http://www.celeryproject.org/). I know that in celery, the python framework, you can set timed windows for functions to get executed. However, that can also be easily done in a linux crontab directed at a ...
It depends what you want your tasks to be doing, if you need to distribute them, and how you want to manage them. A crontab is capable of executing a script every N intervals. It runs, and then returns. Essentially you get a single execution each interval. You could just direct a crontab to execute a django management...
How to strip comma in Python string
16,233,593
16
2013-04-26T09:53:49Z
16,233,599
38
2013-04-26T09:54:27Z
[ "python", "string", "strip" ]
How can I strip the comma from a Python string such as `Foo, bar`? I tried `'Foo, bar'.strip(',')`, but it didn't work.
You want to [`replace`](http://docs.python.org/2/library/stdtypes.html#str.replace) it, not [`strip`](http://docs.python.org/2/library/stdtypes.html#str.strip) it: ``` s = s.replace(',', '') ```
Convert 1D array into numpy matrix
16,235,564
8
2013-04-26T11:40:47Z
16,235,630
13
2013-04-26T11:44:16Z
[ "python", "numpy" ]
I have a simple, one dimensional Python array with random numbers. What I want to do is convert it into a numpy Matrix of a specific shape. My current attempt looks like this: ``` randomWeights = [] for i in range(80): randomWeights.append(random.uniform(-1, 1)) W = np.mat(randomWeights) W.reshape(8,10) ``` Unfor...
`reshape()` doesn't reshape in place, you need to assign the result: ``` >>> W = W.reshape(8,10) >>> W.shape (8,10) ```
create a multichannel zeros mat in python with cv2
16,235,955
5
2013-04-26T12:01:57Z
16,236,373
9
2013-04-26T12:23:06Z
[ "python", "opencv", "numpy" ]
i want to create a multichannel mat object in python with cv2 opencv wrapper. i've found examples on the net where the c++ Mat::zeros is replaced with numpy.zeros, that seems good. but no multichannel type seems to fit.. look at the code: ``` import cv2 import numpy as np size = 200, 200 m = np.zeros(size, dtype=np...
Try this as `size`: ``` size = 200, 200, 3 m = np.zeros(size, dtype=np.uint8) ``` Basically what I did to find what arguments I need for the matrix is: ``` img = cv2.imread('/tmp/1.jpg') print img.shape, img.dtype # (398, 454, 3), uint8 ``` But one could probably find it in OpenCV documentation as well.
os.path.join() takes exactly one argument (2 given)
16,236,435
2
2013-04-26T12:26:12Z
16,236,476
14
2013-04-26T12:28:19Z
[ "python", "os.path" ]
i'm getting python error: **TypeError: join() takes exactly one argument (2 given)** in line 139, of set\_Xpress method, which looks like this: ``` from os import path from json import load ... def set_Xpress(Xpress_number, special_ts, disk, platform, testcase): ... with open("{0}:\\BBT2\\Configura...
`path` is not the `os.path` module, it's a string. You redefined it somewhere. ``` from os import path # path is a module, path.join takes many arguments ... path = '/some/path' # path is now a string, path.join is a totally # different method, takes a single iterable ... report = path.join(o...
UserWarning: converting a masked element to nan
16,236,644
9
2013-04-26T12:36:47Z
16,237,927
8
2013-04-26T13:39:16Z
[ "python", "numpy" ]
Executing a python script (way to long to include here) I wrote leads to a warning message. I don't know at which line in my code this gets raised. How can I get this information? Furthermore, what does this mean exactly? In fact, I didn't know I was using a masked array of some sort? ``` /usr/lib/pymodules/python2.7...
You can use the [`warnings`](http://docs.python.org/2/library/warnings.html) module to convert warnings to exceptions. The simplest method is called `simplefilter`. Here's an example; the code that generates the warning is in func2b(), so there is a nontrival traceback. ``` import warnings def func1(): print "fu...
What is termios.TIOCGWINSZ
16,237,137
6
2013-04-26T13:01:35Z
16,237,327
12
2013-04-26T13:10:54Z
[ "python" ]
I want to get the size of the terminal. I am using this functionality: ``` import sys, struct, fcntl, termios s = struct.pack('HHHH', 0, 0, 0, 0) t = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, s) print(struct.unpack('HHHH', t)) ``` But what on earth is `termios.TIOCGWINSZ`?
It is a magic constant determined by the system you are running on resp. by the terminal driver. In combination with `ioctl()`, it serves to tell exectly what you want, in your case call IOCtl to Get the Window Size. Thus the name `TIOCGWINSZ`, `IOC`tl to `G`et the `WIN`dow `S`i`Z`e. [This bit of documentation](http:...
I screwed up the system version of Python Pip on Ubuntu 12.10
16,237,490
21
2013-04-26T13:18:46Z
18,956,081
27
2013-09-23T09:40:07Z
[ "python", "pip", "ubuntu-12.10" ]
I wanted to update pip on my main install of Python, specifically to get the list command. Which also includes the list- updates capability. So I ran: ``` sudo pip install --upgrade pip ``` All looked good on the install but then I went to run pip and got this: (end of install included if it helps) ``` Installing p...
I had the same message on linux. ``` /usr/bin/pip: No such file or directory ``` but then checked which pip was being called. ``` $ which pip /usr/local/bin/pip ``` On my debian wheezy machine I fixed it doing following... ``` /usr/local/bin/pip uninstall pip apt-get remove python-pip apt-get install python-pi...
I screwed up the system version of Python Pip on Ubuntu 12.10
16,237,490
21
2013-04-26T13:18:46Z
22,543,353
55
2014-03-20T19:36:05Z
[ "python", "pip", "ubuntu-12.10" ]
I wanted to update pip on my main install of Python, specifically to get the list command. Which also includes the list- updates capability. So I ran: ``` sudo pip install --upgrade pip ``` All looked good on the install but then I went to run pip and got this: (end of install included if it helps) ``` Installing p...
Before getting happy with apt-get removes and installs. It's worthwhle to reset your bash cache. ``` hash -r ``` Bash will cache the path to pip using the distrubtion install (apt-get) which is /usr/bin/pip. If you're still in the same shell session, due to the cache, after updating pip from pip your shell will still...
Python: how to implement __getattr__()?
16,237,659
15
2013-04-26T13:26:51Z
16,237,698
27
2013-04-26T13:28:31Z
[ "python" ]
My class has a dict, for example: ``` class MyClass(object): def __init__(self): self.data = {'a': 'v1', 'b': 'v2'} ``` Then I want to use the dict's key with MyClass instance to access the dict, for example: ``` ob = MyClass() v = ob.a # Here I expect ob.a returns 'v1' ``` I know this should be imple...
``` class MyClass(object): def __init__(self): self.data = {'a': 'v1', 'b': 'v2'} def __getattr__(self, attr): return self.data[attr] ``` --- ``` >>> ob = MyClass() >>> v = ob.a >>> v 'v1' ``` Be careful when implementing `__setattr__` though, you will need to make a few modifications: ```...
python total_ordering : why __lt__ and __eq__ instead of __le__?
16,238,322
7
2013-04-26T13:57:39Z
16,238,370
9
2013-04-26T13:59:58Z
[ "python", "python-3.x", "comparison-operators" ]
In Python3, the [functools.total\_ordering decorator](http://docs.python.org/3.3/library/functools.html#functools.total_ordering) allows one to only overload `__lt__` and `__eq__` to get all 6 comparison operators. I don't get why one has to write two operators when one would be enough, namely `__le__` or `__ge__`, an...
The documentation states you **must** define one of `__lt__()`, `__le__()`, `__gt__()`, or `__ge__()`, but only **should** supply an `__eq__()` method. In other words, the `__eq__` method is *optional*. The [`total_ordering` implementation](http://hg.python.org/cpython/file/3.3/Lib/functools.py#l82) does not require ...
flask unit test: how to test request from logged in user
16,238,462
8
2013-04-26T14:04:17Z
16,238,537
13
2013-04-26T14:08:02Z
[ "python", "unit-testing", "flask", "flask-login" ]
I'm writing some unit tests for my Flask web application and I'm trying to test the differences in the response between a request made by an anonymous user and a logged in user. I'm using the `Flask-Login` extension to implement the user login/logout. Obviously I'm able to perform an anonymous request, but how do I s...
Flask-Login looks for `user_id` in the session, you can set this in the tests using [`session_transaction`](http://flask.pocoo.org/docs/testing/#accessing-and-modifying-sessions): ``` with app.test_client() as c: with c.session_transaction() as sess: sess['user_id'] = 'myuserid' sess['_fresh'] = Tr...
Download file, parse it and serve in Flask
16,238,818
6
2013-04-26T14:22:58Z
16,247,035
7
2013-04-27T00:25:27Z
[ "python", "flask" ]
I'm taking my first steps with Flask. I can successfuly download a file from a client and give it back with the code from here: <http://flask.pocoo.org/docs/patterns/fileuploads/> But how to change it (eg. line after line) and then serve it to the client? I can get the string with `read()` after: ``` if file and all...
You can use [`make_response`](http://flask.pocoo.org/docs/api/#flask.make_response) to create the response for your string and add `Content-Disposition: attachment; filename=anyNameHere.txt` to it before returning it: ``` @app.route("/transform-file", methods=["POST"]) def transform(): # Check for valid file and a...
Sending messages from other languages to an IPython kernel
16,240,747
10
2013-04-26T16:07:49Z
16,260,274
13
2013-04-28T06:30:07Z
[ "python", "protocols", "messaging", "ipython", "zeromq" ]
Does anyone have any experience of communicating with IPython kernels from outside of Python? If I were trying to send messages from a Python app to an IPython kernel, I'd use the [`zmq.kernelmanager`](https://github.com/ipython/ipython/blob/0.13.x/IPython/zmq/kernelmanager.py) API. As it is, I'll obviously need to wr...
This is a document that desparately needs to exist, but the implementation of the wire protocol is implemented in a [single object](https://github.com/ipython/ipython/blob/master/IPython/kernel/zmq/session.py), so it shouldn't be too hard to grok from there. The [message spec doc](http://ipython.org/ipython-doc/dev/dev...
How to signal from a running QThread back to the PyQt Gui that started it?
16,241,297
6
2013-04-26T16:41:29Z
16,242,210
7
2013-04-26T17:40:03Z
[ "python", "multithreading", "pyqt", "qthread" ]
I am trying to understand how to use signaling from a Qthread back to the Gui interface that started. Setup: I have a process (a simulation) that needs to run almost indefinitely (or at least for very long stretches of time)., While it runs, it carries out various computations, amd some of the results must be sent bac...
The problem here is simple: your `SimulRunner` never gets sent a signal that causes it to start its work. One way of doing that would be to connect it to the `started` signal of the Thread. Also, in python you should use the new-style way of connecting signals: ``` ... self.simulRunner = SimulRunner() self.simulThrea...
How to resolve "iterator should return strings, not bytes"
16,243,023
8
2013-04-26T18:32:29Z
16,243,182
18
2013-04-26T18:42:41Z
[ "python", "django", "python-3.x", "iterator" ]
I am trying to import a CSV file, using a form to upload the file from the client system. After I have the file, I'll take parts of it and populate a model in my app. However, I'm getting an "iterator should return strings, not bytes" error when I go to iterate over the lines in the uploaded file. I've spent hours tryi...
`request.FILES` gives you *binary* files, but the `csv` module wants to have text-mode files instead. You need to wrap the file in a [`io.TextIOWrapper()` instance](http://docs.python.org/3/library/io.html#io.TextIOWrapper), and you need to figure out the encoding: ``` from io import TextIOWrapper f = TextIOWrapper(...
django DetailView - how to use 'request' in get_context_data
16,243,560
25
2013-04-26T19:07:43Z
16,243,717
39
2013-04-26T19:20:18Z
[ "python", "django" ]
I am trying to modify context data, so I overrided get\_context\_data. I need 'request' variable for modify this context. So, how can i get 'request' variable in get\_context-data ?
You have access to the request in `self.request` - the third paragraph [here](https://docs.djangoproject.com/en/dev/topics/class-based-views/generic-display/#dynamic-filtering) explains a little more. *EDIT: The text referred to, in case it changes:* > > The key part to making this work is that when class-based views...
Numpy first occurence of value greater than existing value
16,243,955
37
2013-04-26T19:35:50Z
16,244,044
44
2013-04-26T19:42:17Z
[ "python", "numpy" ]
I have a 1D array in numpy and I want to find the position of the index where a value exceeds the value in numpy array. E.g. ``` aa = range(-10,10) ``` Find position in `aa` where, the value `5` gets exceeded.
This is a little faster (and looks nicer) ``` np.argmax(aa>5) ``` Since [`argmax`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html) will stop at the first `True` ("In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.") and doesn't...
Numpy first occurence of value greater than existing value
16,243,955
37
2013-04-26T19:35:50Z
16,244,056
7
2013-04-26T19:42:53Z
[ "python", "numpy" ]
I have a 1D array in numpy and I want to find the position of the index where a value exceeds the value in numpy array. E.g. ``` aa = range(-10,10) ``` Find position in `aa` where, the value `5` gets exceeded.
``` In [34]: a=np.arange(-10,10) In [35]: a Out[35]: array([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) In [36]: np.where(a>5) Out[36]: (array([16, 17, 18, 19]),) In [37]: np.where(a>5)[0][0] Out[37]: 16 ```
Numpy first occurence of value greater than existing value
16,243,955
37
2013-04-26T19:35:50Z
25,032,853
25
2014-07-30T09:09:54Z
[ "python", "numpy" ]
I have a 1D array in numpy and I want to find the position of the index where a value exceeds the value in numpy array. E.g. ``` aa = range(-10,10) ``` Find position in `aa` where, the value `5` gets exceeded.
given the sorted content of your array, there is an even faster method: [searchsorted](http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html). ``` import time N = 10000 aa = np.arange(-N,N) %timeit np.searchsorted(aa, N/2)+1 %timeit np.argmax(aa>N/2) %timeit np.where(aa>N/2)[0][0] %timeit np.nonz...
handling zeros in pandas DataFrames column divisions in Python
16,244,180
5
2013-04-26T19:52:27Z
16,244,367
12
2013-04-26T20:05:19Z
[ "python", "numpy", "pandas", "dataframe" ]
What's the best way to handle zero denominators when dividing pandas DataFrame columns by each other in Python? for example: ``` df = pandas.DataFrame({"a": [1, 2, 0, 1, 5], "b": [0, 10, 20, 30, 50]}) df.a / df.b # yields error ``` I'd like the ratios where the denominator is zero to be registered as NA (`numpy.nan`...
You need to work in floats, otherwise you will have integer division, prob not what you want ``` In [12]: df = pandas.DataFrame({"a": [1, 2, 0, 1, 5], "b": [0, 10, 20, 30, 50]}).astype('float64') In [13]: df Out[13]: a b 0 1 0 1 2 10 2 0 20 3 1 30 4 5 50 In [14]: df....
Preventing exceptions from terminating Python iterator
16,244,200
4
2013-04-26T19:53:45Z
16,244,272
8
2013-04-26T19:58:27Z
[ "python" ]
How do you prevent exceptions from prematurely terminating a Python generator/iterator? For example, consider the following: ``` #!/usr/bin/env python def MyIter(): yield 1 yield 2 yield 3 raise Exception, 'blarg!' yield 4 # this never happens my_iter = MyIter() while 1: try: value =...
The generator needs to handle the exception within itself; it is terminated if it raises an unhandled exception, just like any other function.
Adding records to a numpy record array
16,246,643
8
2013-04-26T23:31:12Z
16,246,964
16
2013-04-27T00:13:49Z
[ "python", "numpy", "concatenation", "record" ]
Let's say I define a record array ``` >>> y=np.zeros(4,dtype=('a4,int32,float64')) ``` and then I proceed to fill up the 4 records available. Now I get more data, something like ``` >>> c=('a',7,'24.5') ``` and I want to add this record to `y`. I can't figure out a clean way to do it. The best I have seen in `np.co...
You can use `numpy.append()`, but as you need to convert the new data into a record array also: ``` import numpy as np y = np.zeros(4,dtype=('a4,int32,float64')) y = np.append(y, np.array([("0",7,24.5)], dtype=y.dtype)) ``` Since ndarray can't dynamic change it's size, you need to copy all the data when you want to a...
Why Decimal(2**0.5) doesn't give the number in the predefined accuracy?
16,247,924
3
2013-04-27T03:07:56Z
16,247,936
9
2013-04-27T03:09:55Z
[ "python", "python-2.7" ]
I am doing the following inspired by this [thread](http://stackoverflow.com/questions/16247776/program-displaying-to-few-digits): ``` >>> from decimal import * >>> import math >>> getcontext().prec = 1000 >>> Decimal(2**0.5) Decimal('1.4142135623730951454746218587388284504413604736328125') >>> Decimal(math.sqrt(2)) De...
The `2 ** 0.5` is being calculated as a `float` and then converted to a `Decimal`. Instead, use two `Decimal`s from the start: ``` >>> from decimal import Decimal, getcontext >>> getcontext().prec = 100 >>> Decimal(2) ** Decimal('0.5') Decimal('1.414213562373095048801688724209698078569671875376948073176679737990732478...
Writing a Custom Matrix Class in Python, __setitem__ issues
16,248,012
3
2013-04-27T03:25:42Z
16,248,029
9
2013-04-27T03:30:00Z
[ "python", "python-3.x" ]
I'm working on a custom class to handle matrices using Python. I'm running into a problem where my test program is, apparently, not passing enough arguments to my **setitem** method. Here's the code: ``` def __setitem__(self, rowIndex, colIndex, newVal): self.values[rowIndex][colIndex] = newVal ``` and the test c...
The error message says it all: ``` TypeError: __setitem__() takes exactly 4 arguments (3 given) ``` Your `__setitem__` takes 4 (self being passed automatically, like always): ``` def __setitem__(self, rowIndex, colIndex, newVal): ``` but this line: ``` M[0, 0] = 5.0 ``` doesn't pass 0, 0, and 5.0 to `__setitem__`...
Confidence intervals for model prediction
16,248,013
5
2013-04-27T03:25:51Z
16,248,779
9
2013-04-27T05:42:44Z
[ "python", "statsmodels" ]
I am following along with a [statsmodels tutorial](http://github.com/jseabold/tutorial) An OLS model is fitted with ``` formula = 'S ~ C(E) + C(M) + X' lm = ols(formula, salary_table).fit() print lm.summary() ``` Predicted values are provided through: `lm.predict({'X' : [12], 'M' : [1], 'E' : [2]})` The result is...
We've been meaning to make this easier to get to. You should be able to use ``` from statsmodels.sandbox.regression.predstd import wls_prediction_std prstd, iv_l, iv_u = wls_prediction_std(results) ``` If you have any problems, please file an issue on github.
how python count list length
16,249,418
7
2013-04-27T07:14:39Z
16,249,474
13
2013-04-27T07:21:07Z
[ "python", "python-2.7" ]
I'm learning python. Want to know how len() works. Does it count from beginning to end of a list every time I call len(), or, since list is also an class, len() just returns a variable in the list object which record the list's length. Also, I hope someone can tell me where I can find the source code of those built-in...
Download Python 2.7 source code here: <http://www.python.org/getit/releases/2.7.4/> `list` is implemented in `./Include/listobject.h` and `./Objects/listobject.c`. ``` typedef struct { PyObject_VAR_HEAD /* Vector of pointers to list elements. list[0] is ob_item[0], etc. */ PyObject **ob_item; /* ob_...
Changing file permission in python
16,249,440
10
2013-04-27T07:17:12Z
16,249,475
12
2013-04-27T07:21:07Z
[ "python", "file-permissions" ]
I am trying to change permission of a file access ``` os.chmod(path, mode) ``` I want to make it read only ``` os.chmod(path, 0444) ``` is there any other way make a file read only?
`os.chmod(path, 0444)` *is* the Python command for changing file permissions in Python 2.x. For a combined Python 2 and Python 3 solution, change `0444` to `0o444`. You could always use Python to call the chmod command using [`subprocess`](http://docs.python.org/2/library/subprocess.html). I think this will only work ...
Changing file permission in python
16,249,440
10
2013-04-27T07:17:12Z
16,249,655
21
2013-04-27T07:45:45Z
[ "python", "file-permissions" ]
I am trying to change permission of a file access ``` os.chmod(path, mode) ``` I want to make it read only ``` os.chmod(path, 0444) ``` is there any other way make a file read only?
``` os.chmod(path, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) ``` [stat](http://docs.python.org/2/library/stat.html) > The following flags can also be used in the mode argument of > os.chmod(): > > `stat.S_ISUID` Set UID bit. > > `stat.S_ISGID` Set-group-ID bit. This bit has several special uses. For > a directory i...
Dynamically updating a bar plot in matplotlib
16,249,466
6
2013-04-27T07:20:23Z
16,252,695
10
2013-04-27T13:28:38Z
[ "python", "matplotlib" ]
I have a number of sensors attached to my Raspberry Pi; I'm sending their data to my PC twice a second using TCP. I would like to continuously graph these values using matplotlib. The method I'm currently using seems inefficient (I'm clearing the subplot and redrawing it every time) and has some undesirable drawbacks ...
You could use [`animation.FuncAnimation`](http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/). Plot the bar plot once and save the return value, which is a collection of Rects: ``` rects = plt.bar(range(N), x, align='center') ``` Then, to change the height of a bar, call `rect.set_height`: ``` ...
How to import data from mongodb to pandas?
16,249,736
30
2013-04-27T07:59:07Z
16,255,680
38
2013-04-27T18:45:56Z
[ "python", "mongodb", "pandas" ]
I have a large amount of data in a collection in mongodb which I need to analyze. How do i import that data to pandas? I am new to pandas and numpy. EDIT: The mongodb collection contains sensor values tagged with date and time. The sensor values are of float datatype. Sample Data: ``` { "_cls" : "SensorReport", "_i...
`pymongo` might give you a hand, followings are some codes I'm using: ``` import pandas as pd from pymongo import MongoClient def _connect_mongo(host, port, username, password, db): """ A util for making a connection to mongo """ if username and password: mongo_uri = 'mongodb://%s:%s@%s:%s/%s' % (us...
How to import data from mongodb to pandas?
16,249,736
30
2013-04-27T07:59:07Z
20,693,013
15
2013-12-19T22:33:39Z
[ "python", "mongodb", "pandas" ]
I have a large amount of data in a collection in mongodb which I need to analyze. How do i import that data to pandas? I am new to pandas and numpy. EDIT: The mongodb collection contains sensor values tagged with date and time. The sensor values are of float datatype. Sample Data: ``` { "_cls" : "SensorReport", "_i...
[`Monary`](https://bitbucket.org/djcbeach/monary/wiki/Home) does exactly that, and it's *super fast*. ([another link](http://djcinnovations.com/index.php/archives/164)) See [this cool post](http://alexgaudio.com/2012/07/07/monarymongopandas.html) which includes a quick tutorial and some timings.
How to import data from mongodb to pandas?
16,249,736
30
2013-04-27T07:59:07Z
27,617,290
8
2014-12-23T09:15:23Z
[ "python", "mongodb", "pandas" ]
I have a large amount of data in a collection in mongodb which I need to analyze. How do i import that data to pandas? I am new to pandas and numpy. EDIT: The mongodb collection contains sensor values tagged with date and time. The sensor values are of float datatype. Sample Data: ``` { "_cls" : "SensorReport", "_i...
You can load your mongodb data to pandas DataFrame using this code. It works for me. Hopefully for you too. ``` import pymongo import pandas as pd from pymongo import MongoClient client = MongoClient() db = client.database_name collection = db.collection_name data = pd.DataFrame(list(collection.find())) ```
Draw a terrain with python?
16,251,490
5
2013-04-27T11:19:48Z
16,252,461
8
2013-04-27T13:04:43Z
[ "python", "numpy", "3d", "plot", "rendering" ]
I have a numpy 2d-array representing the geometrical height of a specific area where a street will be build. I can visualize this using `scipy.misc.toimage`. However I would like to get a simple 3D view of the area. Is there a simple way to plot or render this data as an 3d-image?
Perhaps use matplotlib's [plot\_surface](http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#surface-plots) or [plot\_wireframe](http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#wireframe-plots): ``` import matplotlib.pyplot as plt import numpy as np import mpl_toolkits.mplot3d.axes3d as axes3d np.random...
Symmetric streamplot with matplotlib
16,252,231
11
2013-04-27T12:44:03Z
16,322,093
8
2013-05-01T16:21:15Z
[ "python", "matplotlib" ]
I'm trying to plot the streamlines of a magnetic field around a sphere using matplotlib, and it does work quite nicely. However, the resulting image is not symmetric, but it should be (I think). ![enter image description here](http://i.stack.imgur.com/0QbrB.png) This is the code used to generate the image. Excuse the ...
Quoting from the documentation: > ``` > density : float or 2-tuple > Controls the closeness of streamlines. When density = 1, > the domain is divided into > a 25x25 grid—density linearly scales this grid. > Each cell in the grid can have, at most, one traversing streamline. > For different dens...
How to convert country names to ISO 3166-1 alpha-2 values, using python
16,253,060
11
2013-04-27T14:09:59Z
16,253,157
11
2013-04-27T14:19:50Z
[ "python", "list", "iso" ]
I have a list of countries like: ``` countries=['American Samoa', 'Canada', 'France'...] ``` I want to convert them like this: ``` countries=['AS', 'CA', 'FR'...] ``` Is there any module or any way to convert them?
There is a module called [`pycountry`](https://pypi.python.org/pypi/pycountry). Here's an example code: ``` import pycountry input_countries = ['American Samoa', 'Canada', 'France'] countries = {} for country in pycountry.countries: countries[country.name] = country.alpha2 codes = [countries.get(country, 'Unk...
Can we use a self made corpus for training for LDA using gensim?
16,254,207
3
2013-04-27T16:05:52Z
16,260,043
10
2013-04-28T05:48:43Z
[ "python", "lda", "gensim" ]
I have to apply LDA (Latent Dirichlet Allocation) to get the possible topics from a data base of 20,000 documents that I collected. How can I use these documents rather than the other corpus available like the Brown Corpus or English Wikipedia as training corpus ? You can refer [this](http://radimrehurek.com/gensim/m...
After going through the documentation of the Gensim package, I found out that there are total 4 ways of transforming a text repository into a corpus. There are total 4 formats for the corpus: 1. Market Matrix (.mm) 2. SVM Light (.svmlight) 3. Blie Format (.lad-c) 4. Low Format (.low) In this problem, as mentioned ab...
Python giving same result when I call a function multiple times, despite random component
16,255,113
3
2013-04-27T17:43:52Z
16,255,224
9
2013-04-27T17:54:48Z
[ "python", "memory", "random", "simulation" ]
I am writing a baseball game simulation. I would like to be able to run multiple games to see how different batting averages affect outcomes. Each game is made up of "at-bats", the result of which comes from a random number. The issue is that when I go to run multiple games, I get the same result for every game. I im...
The problem lies in your use of global variables. After your game() has run for the first time, outs is 27. When you call game again, it still has the same value, so your while loop exits immediately.
Format negative integers in two's complement representation
16,255,496
2
2013-04-27T18:26:16Z
16,255,550
9
2013-04-27T18:33:20Z
[ "python", "bit-manipulation" ]
I would like to represent an negative integer in bits, using two's complement representation. Using standard Python bit representation utilities doesn't help much: ``` >>> bin(-5) '-0b101' >>> format(-5, 'b') '-101' ``` `-5` in two's complement is represented as `1011`. How do I do this?
Python's integers already use two's complement, but since they have arbitrary precision, the binary representation of negative numbers would have an infinite string of 1s at the start, much like positive numbers have an infinite string of 0s. Since this obviously can't be shown, it is represented with a minus sign inst...
Python Assignment Order
16,256,051
2
2013-04-27T19:27:59Z
16,256,066
11
2013-04-27T19:30:34Z
[ "python" ]
I am new to python. Can someone explain why the following two python example does not output the same thing? Example 1 ``` a, b = 0, 1 while b < 50: print(b) a, b = b, a + b ``` Example 2 ``` a, b = 0, 1 while b < 50: print(b) a = b b = a + b ``` Thanks
In the first version, when you write ``` a, b = b, a + b ``` the expression ``` b, a + b ``` is evaluated first. After it has been evaluated, it is subsequently assigned to `a, b` with tuple unpacking. The key point is that the entire right hand side of an assignment statement is evaluated in its entirety before pe...