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
Remove char at specific index - python
14,198,497
8
2013-01-07T15:03:48Z
14,198,515
16
2013-01-07T15:04:39Z
[ "python" ]
I have a string that has two "0" (str) in it and I want to remove only the "0" (str) at index 4 I have tried calling .replace but obviously that removes all "0", and I cannot find a function that will remove the char at position 4 for me. Anyone have a hint for me?
Use slicing, rebuilding the string minus the index you want to remove: ``` newstr = oldstr[:4] + oldst[5:] ```
Remove char at specific index - python
14,198,497
8
2013-01-07T15:03:48Z
14,198,572
9
2013-01-07T15:08:12Z
[ "python" ]
I have a string that has two "0" (str) in it and I want to remove only the "0" (str) at index 4 I have tried calling .replace but obviously that removes all "0", and I cannot find a function that will remove the char at position 4 for me. Anyone have a hint for me?
as a sidenote, `replace` doesn't have to move all zeros. If you just want to remove the first specify `count` to 1: ``` 'asd0asd0'.replace('0','',1) ``` Out: `'asdasd0'`
Python error when tryint to access list by index - "List indices must be integers, not str"
14,198,821
6
2013-01-07T15:24:46Z
14,198,883
18
2013-01-07T15:28:07Z
[ "python" ]
I have the following Python code : ``` currentPlayers = query.getPlayers() for player in currentPlayers: return str(player['name'])+" "+str(player['score']) ``` And I'm getting the following error: > TypeError: list indices must be integers, not str I've been looking for an error close to mine, but not ...
Were you expecting `player` to be a `dict` rather than a `list`? ``` >>> player=[1,2,3] >>> player["score"] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list indices must be integers, not str >>> player={'score':1, 'age': 2, "foo":3} >>> player['score'] 1 ```
How to choose the graphic toolkit for PyQt
14,200,167
4
2013-01-07T16:40:03Z
14,201,027
9
2013-01-07T17:31:20Z
[ "python", "user-interface", "pyqt", "gnome", "kde" ]
I'm developing an PyQt application for my clients. The problem is that my default graphical is Gnome and my client KDE. So there is some difference I can not contrôle. How can I force the pyQt to choose the good graphical system (Gnome) instead of the default system (KDE)?
Use [`QApplication::setStyle ( QStyle * style )`](http://doc.qt.digia.com/4.7-snapshot/qapplication.html#setStyle) with one of these values as parameter: * plastique * cde * motif * sgi * windows * cleanlooks * mac
How to create a menu and submenus in Python curses?
14,200,721
11
2013-01-07T17:12:51Z
14,205,494
28
2013-01-07T22:50:11Z
[ "python", "python-2.7", "curses" ]
AFAIK, there is no curses menu extension available in Python yet so you have to roll your own solution. I know about this patch <http://bugs.python.org/issue1723038> but I don't what's the current state of it. I found a nice class for Python that wraps what I want called 'cmenu' here <http://www.promisc.org/blog/?p=33>...
I really recommend you look into using [panels](http://docs.python.org/2/library/curses.panel.html#module-curses.panel). Anytime you will have widgets that could possibly overlap, it makes life alot easier. This is a simple example that should get you started. (Neither curses.beep() or curses.flash() seem to work on my...
Impossible to initialize Elixir
14,201,210
10
2013-01-07T17:44:07Z
14,291,297
15
2013-01-12T07:29:15Z
[ "python", "mysql", "sqlalchemy", "python-elixir" ]
I'm starting with Elixir and SQL Alchemy. I've created a python file connecting with a Mysql database to but as soon as I execute with python I get the error bellow: ``` root@raspberrypi:/Python/mainFlask/yonkiPOPS# python yonki.py Traceback (most recent call last): File "yonki.py", line 1, in <module> from elix...
Elixir 0.7.1 seems to be incompatible with the latest version of SQLalchemy, 0.8. You can solve that problem with ``` sudo pip install SQLAlchemy==0.7.8 ```
Impossible to initialize Elixir
14,201,210
10
2013-01-07T17:44:07Z
17,915,596
7
2013-07-29T03:25:42Z
[ "python", "mysql", "sqlalchemy", "python-elixir" ]
I'm starting with Elixir and SQL Alchemy. I've created a python file connecting with a Mysql database to but as soon as I execute with python I get the error bellow: ``` root@raspberrypi:/Python/mainFlask/yonkiPOPS# python yonki.py Traceback (most recent call last): File "yonki.py", line 1, in <module> from elix...
Just open the ./elixir/entity.py, find the import line like this: ``` from sqlalchemy.orm import ScopedSession, \ ``` then adjust it to: ``` from sqlalchemy.orm import scoped_session as ScopedSession, \ ```
Does pypy support cython extension?
14,201,555
4
2013-01-07T18:09:32Z
14,202,251
7
2013-01-07T18:57:04Z
[ "python", "cython", "pypy" ]
I have a project which runs is run in pypy (and already achieves a nice speedup over its python counterpart). However, I do have a Cython implementation of one function which is way faster than the pypy version. So I would like to include this function. The problem is that pypy does not seem to find this module (even ...
If you want to make Cython extension available under PyPy, you have to recompile it and reinstall it under PyPy. I suggest using a virtualenv for that, to start with. However, if this is purely for speedups, I would really really discourage you from doing so. The CPyext (CPython C API emulation) is really slow and you'...
Don't convert newline when reading a file
14,202,438
3
2013-01-07T19:09:32Z
14,202,499
13
2013-01-07T19:13:30Z
[ "python" ]
I'm reading a text file: ``` f = open('data.txt') data = f.read() ``` However newline in `data` variable is normalized to LF ('\n') while the file contains CRLF ('\r\n'). How can I instruct Python to read the file as is?
In Python 2.x: ``` f = open('data.txt', 'rb') ``` As [the docs](http://docs.python.org/2/library/functions.html#open) say: > The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append `'b...
Does selenium write and read the webelement values
14,202,609
4
2013-01-07T19:21:35Z
14,203,237
7
2013-01-07T20:07:39Z
[ "python", "selenium" ]
I am doing automation using Python2.7 and selenium first time. Now can I write and read as well the below HTML contents? ***Radio Buttons*** ``` <form name="myWebForm" action="mailto:youremail@email.com" method="post"> <h4>Please select your favorite food category.</h4> <input type="radio" name="food" /> : Italian<br...
Yes, check into xpath ``` x = brower.select_element_by_xpath('//option[contains(text(), "CO"]') x.text (print the div text) x.click() clicks the div ``` or just ``` brower.select_element_by_xpath('//option[contains(text(), "CO"]').click() ``` to read the list, this should work; ``` for i in browers.select_element...
How to copy a dictionary of lists?
14,204,326
4
2013-01-07T21:27:32Z
14,204,440
7
2013-01-07T21:35:30Z
[ "python", "dictionary", "deep-copy" ]
How can i copy a dictionary of lists and what is its complexity? The dictionary I'm tryint to copy is something like this: ``` myDict = { 'k1': ['a', 'b', 'c'], 'k2': ['d', 'e', 'f'], 'k3': ['g', 'h', 'i'] } ```
``` from copy import deepcopy myCopy = deepcopy(myDict) ``` `deepcopy` is always **the** way.
scipy.sparse dot extremely slow in Python
14,204,406
4
2013-01-07T21:32:56Z
14,204,859
7
2013-01-07T22:04:54Z
[ "python", "numpy", "scipy", "sparse-matrix" ]
The following code will not even finish on my system: ``` import numpy as np from scipy import sparse p = 100 n = 50 X = np.random.randn(p,n) L = sparse.eye(p,p, format='csc') X.T.dot(L).dot(X) ``` Is there any explanation why this matrix multiplication is hanging?
`X.T.dot(L)` is not, as you may think, a 50x100 matrix, but an array of 50x100 sparse matrices of 100x100 ``` >>> X.T.dot(L).shape (50, 100) >>> X.T.dot(L)[0,0] <100x100 sparse matrix of type '<type 'numpy.float64'>' with 100 stored elements in Compressed Sparse Column format> ``` It seems that the problem is tha...
c++11 regex slower than python
14,205,096
50
2013-01-07T22:20:33Z
14,229,152
61
2013-01-09T06:02:38Z
[ "c++", "python", "regex", "performance", "c++11" ]
hi i would like to understand why the following code which does a split string split using regex ``` #include<regex> #include<vector> #include<string> std::vector<std::string> split(const std::string &s){ static const std::regex rsplit(" +"); auto rit = std::sregex_token_iterator(s.begin(), s.end(), rsplit, -...
## Notice See also this answer: <http://stackoverflow.com/a/21708215> which was the base for the **EDIT 2** at the bottom here. --- I've augmented the loop to 1000000 to get a better timing measure. This is my Python timing: ``` real 0m2.038s user 0m2.009s sys 0m0.024s ``` Here's an equivalent of your c...
Python's Multiple Inheritance: Picking which super() to call
14,206,015
21
2013-01-07T23:40:02Z
14,206,070
32
2013-01-07T23:45:16Z
[ "python", "multiple-inheritance", "super" ]
In Python, how do I pick which Parent's method to call? Say I want to call the parent ASDF2's `__init__` method. Seems like I have to specify **ASDF1** in the super()..? And if I want to call ASDF3's `__init__`, then I must specify **ASDF2**?! ``` >>> class ASDF(ASDF1, ASDF2, ASDF3): def __init__(self): su...
That's not what [`super()`](https://docs.python.org/3.4/library/functions.html#super) is for. Super basically picks one (or all) of its parents in a specific order. If you only want to call a single parent's method, do this ``` class ASDF(ASDF1, ASDF2, ASDF3): def __init__(self): ASDF2.__init__(self) ```
Python's Multiple Inheritance: Picking which super() to call
14,206,015
21
2013-01-07T23:40:02Z
14,206,085
8
2013-01-07T23:46:40Z
[ "python", "multiple-inheritance", "super" ]
In Python, how do I pick which Parent's method to call? Say I want to call the parent ASDF2's `__init__` method. Seems like I have to specify **ASDF1** in the super()..? And if I want to call ASDF3's `__init__`, then I must specify **ASDF2**?! ``` >>> class ASDF(ASDF1, ASDF2, ASDF3): def __init__(self): su...
`super` calls the next method in the method resolution order. In a linear inheritance tree, that will be method from the immediately parent class. Here, you have three parents, and the next `__init__` method from `ASDF1`'s perspective is that of `ASDF2`. In general, the safe thing to do is to pass the first class in t...
How to set an environment variable in Amazon Elastic Beanstalk (Python)
14,206,760
7
2013-01-08T01:04:49Z
15,961,468
10
2013-04-12T01:08:31Z
[ "python", "amazon-web-services", "environment-variables", "elastic-beanstalk" ]
I have been working on a Django application lately, trying to get it to work with Amazon Elastic Beanstalk. In my `.ebextensions/python.config` file, I have set the following: ``` option_settings: - namespace: aws:elasticbeanstalk:application:environment option_name: ProductionBucket value: s3-bucket-name ...
I was having the same problem. Believe it or not, you have to commit the .ebextensions directory and all \*.config files to version control before you deploy in order for them to show up as environmental variables on the server. In order to keep your sensitive information out of version control you can use a config f...
Trouble understanding output from scikit random forest
14,207,410
4
2013-01-08T02:39:16Z
14,212,533
9
2013-01-08T10:07:22Z
[ "python", "machine-learning", "scikit-learn", "random-forest" ]
Say I have a dataset like this: ``` 5.9;0.645;0.12;2;0.075;32;44;0.99547;3.57;0.71;10.2;5 6;0.31;0.47;3.6;0.067;18;42;0.99549;3.39;0.66;11;6 ``` where the 1st 11 columns indicate features (acidity, chlorides, etc) and the last column indicates the rating given to the item (eg. 5 or 6) The dataset is trained thus: `...
In addition to Diego's answer: `RandomForestClassifier` is a classifier to predict class assignment for a discrete number of classes without ordering between the class labels. If you want to output continuous, floating point rating, you should try to use a regression model such as `RandomForestRegressor` instead. Yo...
IOError: [Errno 32] Broken pipe: Python
14,207,708
37
2013-01-08T03:18:28Z
14,208,261
16
2013-01-08T04:33:42Z
[ "python", "python-3.x", "sigpipe" ]
I have a very simple Python 3 script: ``` f1 = open('a.txt', 'r') print(f1.readlines()) f2 = open('b.txt', 'r') print(f2.readlines()) f3 = open('c.txt', 'r') print(f3.readlines()) f4 = open('d.txt', 'r') print(f4.readlines()) f1.close() f2.close() f3.close() f4.close() ``` But it always says: ``` IOError: [Errno 32]...
I haven't reproduced the issue, but perhaps this method would solve it: (writing line by line to `stdout` rather than using `print`) ``` import sys with open('a.txt', 'r') as f1: for line in f1: sys.stdout.write(line) ``` --- You could catch the broken pipe? This writes the file to `stdout` line by line ...
IOError: [Errno 32] Broken pipe: Python
14,207,708
37
2013-01-08T03:18:28Z
14,213,673
21
2013-01-08T11:10:14Z
[ "python", "python-3.x", "sigpipe" ]
I have a very simple Python 3 script: ``` f1 = open('a.txt', 'r') print(f1.readlines()) f2 = open('b.txt', 'r') print(f2.readlines()) f3 = open('c.txt', 'r') print(f3.readlines()) f4 = open('d.txt', 'r') print(f4.readlines()) f1.close() f2.close() f3.close() f4.close() ``` But it always says: ``` IOError: [Errno 32]...
A "Broken Pipe" error occurs when you try to write to a pipe that has been closed on the other end. Since the code you've shown doesn't involve any pipes directly, I suspect you're doing something outside of Python to redirect the standard output of the Python interpreter to somewhere else. This could happen if you're ...
IOError: [Errno 32] Broken pipe: Python
14,207,708
37
2013-01-08T03:18:28Z
16,865,106
69
2013-05-31T20:05:58Z
[ "python", "python-3.x", "sigpipe" ]
I have a very simple Python 3 script: ``` f1 = open('a.txt', 'r') print(f1.readlines()) f2 = open('b.txt', 'r') print(f2.readlines()) f3 = open('c.txt', 'r') print(f3.readlines()) f4 = open('d.txt', 'r') print(f4.readlines()) f1.close() f2.close() f3.close() f4.close() ``` But it always says: ``` IOError: [Errno 32]...
The problem is due to SIGPIPE handling. You can solve this problem using the following code: ``` from signal import signal, SIGPIPE, SIG_DFL signal(SIGPIPE,SIG_DFL) ``` [See here](http://newbebweb.blogspot.com/2012/02/python-head-ioerror-errno-32-broken.html) for background on this solution.
IOError: [Errno 32] Broken pipe: Python
14,207,708
37
2013-01-08T03:18:28Z
30,091,579
18
2015-05-07T03:50:10Z
[ "python", "python-3.x", "sigpipe" ]
I have a very simple Python 3 script: ``` f1 = open('a.txt', 'r') print(f1.readlines()) f2 = open('b.txt', 'r') print(f2.readlines()) f3 = open('c.txt', 'r') print(f3.readlines()) f4 = open('d.txt', 'r') print(f4.readlines()) f1.close() f2.close() f3.close() f4.close() ``` But it always says: ``` IOError: [Errno 32]...
To bring [Alex L.'s helpful answer](http://stackoverflow.com/a/14208261/45375), [akhan's helpful answer](http://stackoverflow.com/a/16865106/45375), and [Blckknght's helpful answer](http://stackoverflow.com/a/14213673/45375) together with some additional information: * **[Standard Unix signal `SIGPIPE`](https://www.gn...
IOError: [Errno 32] Broken pipe: Python
14,207,708
37
2013-01-08T03:18:28Z
35,761,190
7
2016-03-03T00:59:34Z
[ "python", "python-3.x", "sigpipe" ]
I have a very simple Python 3 script: ``` f1 = open('a.txt', 'r') print(f1.readlines()) f2 = open('b.txt', 'r') print(f2.readlines()) f3 = open('c.txt', 'r') print(f3.readlines()) f4 = open('d.txt', 'r') print(f4.readlines()) f1.close() f2.close() f3.close() f4.close() ``` But it always says: ``` IOError: [Errno 32]...
I feel obliged to point out that the method using ``` signal(SIGPIPE, SIG_DFL) ``` is indeed **dangerous** (as already suggested by David Bennet in the comments) and in my case led to platform-dependent funny business when combined with `multiprocessing.Manager` (because the standard library relies on BrokenPipeError...
How to put result of JavaScript function into python variable. PyQt
14,208,166
5
2013-01-08T04:22:18Z
14,213,401
7
2013-01-08T10:54:40Z
[ "javascript", "python", "qt", "pyqt" ]
I want to make a function in PyQt evaluateJavaScript() (or may be similar one) and than display a result of evaluated function. Real function will be much bigger, and it might not be a string. I'm only interesting in how to create a function inside PyQt code and than get the result into python variable. To be more cl...
In this example first I create a `myWindow` javascript object by passing `self` to the main frame, then call `evaluateJavaScript` when `loadFinished`: ``` #!/usr/bin/env python #-*- coding:utf-8 -*- from PyQt4 import QtCore, QtGui, QtWebKit getJsValue = """ w = document.getElementsByTagName('p')[0]; myWindow.show...
Sort a list with a custom order in Python
14,208,256
5
2013-01-08T04:32:43Z
14,208,276
15
2013-01-08T04:35:31Z
[ "python", "list", "sorting", "python-2.7" ]
I have a list `mylist = [['123', 'BOOL', '234'], ['345', 'INT', '456'], ['567', 'DINT', '678']]` I want to sort it with the order of 1. `DINT` 2. `INT` 3. `BOOL` Result: `[['567', 'DINT', '678'], ['345', 'INT', '456'], ['123', 'BOOL', '234']]` I've seen other similar questions in stackoverflow but nothing similar ...
``` SORT_ORDER = {"DINT": 0, "INT": 1, "BOOL": 2} mylist.sort(key=lambda val: SORT_ORDER[val[1]]) ``` All we are doing here is providing a new element to sort on by returning an integer for each element in the list rather than the whole list. We *could* use inline ternary expressions, but that would get a bit unwield...
Reading the pdf properties/metadata in python
14,209,214
14
2013-01-08T06:13:15Z
14,209,316
17
2013-01-08T06:22:11Z
[ "python", "pdf", "metadata" ]
How can I read the properties/metadata like Title, Author, Subject and Keywords stored on a pdf file using python?
Try [pdfminer](https://github.com/euske/pdfminer/): ``` from pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument fp = open('diveintopython.pdf', 'rb') parser = PDFParser(fp) doc = PDFDocument(parser) print doc.info # The "Info" metadata ``` Here's the output: ``` >>> [{'CreationDate':...
Python call constructor of its own instance
14,209,657
5
2013-01-08T06:51:10Z
14,209,708
16
2013-01-08T06:54:45Z
[ "python" ]
``` class Foo(): def __init__(self): pass def create_another(self): return Foo() # is not working as intended, because it will make y below becomes Foo class Bar(Foo): pass x = Bar() y = x.create_another() ``` y should be of class Bar not Foo. Is there something like: `self.const...
For new-style classes, use `type(self)` to get the 'current' class: ``` def create_another(self): return type(self)() ``` You could also use `self.__class__` as that is the value `type()` will use, but using the API method is always recommended. For old-style classes (python 2, not inheriting from `object`), `ty...
Automatically cropping an image with python/PIL
14,211,340
7
2013-01-08T08:57:17Z
14,211,727
10
2013-01-08T09:21:59Z
[ "python", "image", "image-processing", "python-imaging-library", "crop" ]
Can anyone help me figure out what's happening in my image auto-cropping script? I have a png image with a large transparent area/space. I would like to be able to automatically crop that space out and leave the essentials. Original image has a squared canvas, optimally it would be rectangular, encapsulating just the m...
You can use numpy, convert the image to array, find all non-empty columns and rows and then create an image from these: ``` import Image import numpy as np image=Image.open('L_2d.png') image.load() image_data = np.asarray(image) image_data_bw = image_data.max(axis=2) non_empty_columns = np.where(image_data_bw.max(ax...
Automatically cropping an image with python/PIL
14,211,340
7
2013-01-08T08:57:17Z
14,211,878
17
2013-01-08T09:30:26Z
[ "python", "image", "image-processing", "python-imaging-library", "crop" ]
Can anyone help me figure out what's happening in my image auto-cropping script? I have a png image with a large transparent area/space. I would like to be able to automatically crop that space out and leave the essentials. Original image has a squared canvas, optimally it would be rectangular, encapsulating just the m...
For me it works as: ``` import Image import sys image=Image.open('L_2d.png') image.load() imageSize = image.size imageBox = image.getbbox() cropped=image.crop(imageBox) cropped.save('L_2d_cropped.png') ``` When you search for boundaries by `mask=imageComponents[3]`, you search only by blue channel.
Python in Windows Store apps
14,211,949
8
2013-01-08T09:34:14Z
14,299,990
14
2013-01-13T02:12:37Z
[ "python", "windows-runtime", "windows-store-apps", "microsoft-metro", "winjs" ]
The Windows Store app [Python 3 For Metro](http://apps.microsoft.com/windows/en-us/app/python-3-for-metro/82f0c953-93d4-461c-893f-c298b0d919d2) claims that it allows users to edit and run Python files (I can't get it to work). How is this possible from within the sandbox? Can I run a file (say `test.py` on the desktop)...
> How is this possible from within the sandbox? I have ported the Python interpreter to WinRT to achieve that. Instead of using Win32 API, it now uses WinRT API (in particular for reading files from the user's Documents folder). > Can I run a file (say test.py on the desktop) from my JavaScript app? In principle, ye...
Python jinja2 shorthand conditional
14,214,942
71
2013-01-08T12:27:33Z
14,215,034
140
2013-01-08T12:32:08Z
[ "python", "jinja2" ]
Say I have this: ``` {% if files %} Update {% else %} Continue {% endif %} ``` In PHP, say, I can write a shorthand conditional, like: ``` <?php echo $foo ? 'yes' : 'no'; ?> ``` Is there then a way I can translate this to work in a jinja2 template: ``` 'yes' if foo else 'no' ```
Yes, it's possible to use [inline if-expressions](http://jinja.pocoo.org/docs/templates/#if-expression): ``` {{ 'Update' if files else 'Continue' }} ```
scipy with py2exe
14,215,303
15
2013-01-08T12:48:41Z
14,216,383
13
2013-01-08T13:49:20Z
[ "python", "scipy", "py2exe" ]
I get the following error message using python v2.7.3 and scipy v0.11.0 with py2exe v0.6.10 on a 64 bit machine using 64 bit versions of the packages from [Christoph Gohlke](http://www.lfd.uci.edu/~gohlke/pythonlibs). If anyone can provide relevant and useful suggestions I would greatly appreciate it. Here is the error...
This seems to be a problem common to py2exe and pyinstaller with scipy 0.11.0 as discussed [here](http://www.pyinstaller.org/ticket/596). The temporal solution given in that thread is to import the file manually: > adding the following codes into your program > > ``` > def dependencies_for_myprogram(): > from sci...
scipy with py2exe
14,215,303
15
2013-01-08T12:48:41Z
14,217,239
10
2013-01-08T14:33:07Z
[ "python", "scipy", "py2exe" ]
I get the following error message using python v2.7.3 and scipy v0.11.0 with py2exe v0.6.10 on a 64 bit machine using 64 bit versions of the packages from [Christoph Gohlke](http://www.lfd.uci.edu/~gohlke/pythonlibs). If anyone can provide relevant and useful suggestions I would greatly appreciate it. Here is the error...
Problem solved! Thank you VERY much joaquin. In searching for two days I had not come across that pyinstaller link. For future readers, in the options for py2exe I added ``` scipy.sparse.csgraph._validation ``` to the includes.
Python: remove multiple character in list of string
14,215,338
2
2013-01-08T12:50:27Z
14,215,379
8
2013-01-08T12:52:27Z
[ "python", "string", "list" ]
Having such list: ``` x = ['+5556', '-1539', '-99','+1500'] ``` How can I remove + and - in nice way? This works but I'm looking for more pythonic way. ``` x = ['+5556', '-1539', '-99', '+1500'] n = 0 for i in x: x[n] = i.replace('-','') n += 1 n = 0 for i in x: x[n] = i.replace('+','') n += 1 print...
``` x = [i.replace('-', "").replace('+', '') for i in x] ```
Python: remove multiple character in list of string
14,215,338
2
2013-01-08T12:50:27Z
14,215,384
9
2013-01-08T12:52:41Z
[ "python", "string", "list" ]
Having such list: ``` x = ['+5556', '-1539', '-99','+1500'] ``` How can I remove + and - in nice way? This works but I'm looking for more pythonic way. ``` x = ['+5556', '-1539', '-99', '+1500'] n = 0 for i in x: x[n] = i.replace('-','') n += 1 n = 0 for i in x: x[n] = i.replace('+','') n += 1 print...
Use [`str.strip()`](http://docs.python.org/2/library/stdtypes.html#str.strip) or preferably [`str.lstrip()`](http://docs.python.org/2/library/stdtypes.html#str.lstrip): ``` In [1]: x = ['+5556', '-1539', '-99','+1500'] ``` using `list comprehension`: ``` In [3]: [y.strip('+-') for y in x] Out[3]: ['5556', '1539', '9...
Python: remove multiple character in list of string
14,215,338
2
2013-01-08T12:50:27Z
14,216,120
10
2013-01-08T13:35:11Z
[ "python", "string", "list" ]
Having such list: ``` x = ['+5556', '-1539', '-99','+1500'] ``` How can I remove + and - in nice way? This works but I'm looking for more pythonic way. ``` x = ['+5556', '-1539', '-99', '+1500'] n = 0 for i in x: x[n] = i.replace('-','') n += 1 n = 0 for i in x: x[n] = i.replace('+','') n += 1 print...
Use `string.translate()`, or for Python 3.x `str.translate`: Python 2.x: ``` >>> import string >>> identity = string.maketrans("", "") >>> "+5+3-2".translate(identity, "+-") '532' >>> x = ['+5556', '-1539', '-99', '+1500'] >>> x = [s.translate(identity, "+-") for s in x] >>> x ['5556', '1539', '99', '1500'] ``` Pyth...
Django/Python: Update the relation to point at settings.AUTH_USER_MODEL
14,215,976
6
2013-01-08T13:26:26Z
14,240,038
8
2013-01-09T15:48:36Z
[ "python", "django", "postgresql" ]
I'm completely new to Python and Django, but I need to install testbedserver-software (for which I follow this [tutorial](http://wiki.confine-project.eu/soft%3aserver-installation)) on my server. Now I'm running into trouble when running following command: ``` python manage.py syncdb ``` The following error is shown:...
in `settings_example.py` you have `AUTH_USER_MODEL = 'users.User'`. However you are using an app - `menu.bookmark` - that has a relation to `django.contrib.auth.User` - you can't have both. Setting `AUTH_USER_MODEL` means that you are replacing the built-in Django user model with your own. See <http://procrastinatingde...
Can I use open cv with python on Google app engine?
14,217,858
4
2013-01-08T15:03:16Z
14,217,913
8
2013-01-08T15:06:05Z
[ "python", "google-app-engine", "opencv", "python-2.7" ]
HI actually I was working on a project which i intended to deploy on the google appengine. However I found that google app engine is supported by python. Can I run openCV with python scripts on Google app engine?
No. GAE only supports either pure python extensions or extensions that they are supplying themselves. OpenCV uses C, so it is not suitable. > The interpreter can run any Python code, including Python modules you include with your application, as well as the Python standard library. The interpreter cannot load Python ...
Swap position of entities in the list
14,218,638
3
2013-01-08T15:41:16Z
14,218,688
7
2013-01-08T15:43:07Z
[ "python" ]
I have a following example list ``` x= [['True_304', 'false_2'], ['True_702', 'false_2_1'], ['True_204', 'false_222_2']] ``` I would like to swap the positions of entities so that the second entity is first and first one is second. Basically, something like: ``` x= [['false_2', 'True_304'], ['false_2_1', 'True...
You can use list comprehensions: ``` >>> x = [['True_304', 'false_2'], ['True_702', 'false_2_1'], ['True_204', 'false_222_2']] >>> [[b, a] for [a, b] in x] [['false_2', 'True_304'], ['false_2_1', 'True_702'], ['false_222_2', 'True_204']] ```
Sorted function in python
14,218,933
5
2013-01-08T15:55:15Z
14,218,971
9
2013-01-08T15:56:49Z
[ "python", "sorting" ]
I have written a program which must sort the following: ``` unsorted_list=[['le', 5], ['aab', 4], ['aaa', 5]] ``` to: ``` [['aaa', 5], ['le', 5], ['aab', 4]] ``` It should be sorted by number. If the numbers are the same then it should sort alphabetical. I have the following code: ``` def sortItem(lista): ''' ...
Since `x[1]` is an integer, you can sort it from maximum to minimum simply by negating it: ``` sorted(unsorted_list, key=lambda x: (-x[1], x[0])) ``` The tuples created in `key` will be sorted according to the first element (`-x[1]`), then by second element (`x[0]`). This corresponds exactly to your logic: *"So, it ...
shlex.split still not supporting unicode?
14,218,992
8
2013-01-08T15:57:53Z
14,219,159
8
2013-01-08T16:07:20Z
[ "python", "unicode", "python-unicode", "shlex" ]
According to the documentation, in Python 2.7.3, shlex should support UNICODE. However, when running the code below, I get: `UnicodeEncodeError: 'ascii' codec can't encode characters in position 184-189: ordinal not in range(128)` Am I doing something wrong? ``` import shlex command_full = u'software.py -fileA="sequ...
The `shlex.split()` code wraps both `unicode()` and `str()` instances in a `StringIO()` object, which can only handle Latin-1 bytes (so not the full unicode codepoint range). You'll have to encode (to UTF-8 should work) if you still want to use `shlex.split()`; the maintainers of the module meant that `unicode()` obje...
Python multiprocessing: TypeError: expected string or Unicode object, NoneType found
14,219,038
12
2013-01-08T16:00:27Z
16,751,395
18
2013-05-25T16:05:14Z
[ "python", "python-2.7", "python-multithreading" ]
I am attempting to download a whole ftp directory in parallel. ``` #!/usr/bin/python import sys import datetime import os from multiprocessing import Process, Pool from ftplib import FTP curYear="" remotePath ="" localPath = "" def downloadFiles (remotePath,localPath): splitted = remotePath.split('/'); ...
**Update, May 9, 2014:** I have determined the precise limitation. It is possible to send objects across process boundaries to worker processes as long as the objects can be pickled by [Python's pickle facility](https://docs.python.org/2/library/pickle.html). The problem which I described in my original answer occurre...
Update a PostgreSQL array using SQLAlchemy
14,219,775
3
2013-01-08T16:38:48Z
14,221,733
8
2013-01-08T18:33:19Z
[ "python", "postgresql", "sqlalchemy" ]
I'm trying to update an integer array on a PostgreSQL table using a SQL statement in SQLAlchemy Core. I first tried using the query generator, but couldn't figure out how to do that either. I believe that Psycopg2, which is the dialect that I'm using, can automatically form the array into a format that PostgreSQL can a...
If your table is defined like this: ``` from datetime import datetime from sqlalchemy import * from sqlalchemy.dialects.postgresql import ARRAY meta = MetaData() surveys_table = Table('surveys', meta, Column('surveys_id', Integer, primary_key=True), Column('questions_ids_ordered', ARRAY(Integer)), Column(...
How to add Headers to Scrapy CrawlSpider Requests?
14,220,174
3
2013-01-08T16:58:44Z
14,232,936
7
2013-01-09T10:18:31Z
[ "python", "scrapy" ]
I'm working with the CrawlSpider class to crawl a website and I would like to modify the headers that are sent in each request. Specifically, I would like to add the referer to the request. As per [this question](http://stackoverflow.com/questions/12054958/scrapyhow-to-print-request-referrer/12055059#12055059), I chec...
You can pass `REFERER` manually to each [request](http://doc.scrapy.org/en/latest/topics/request-response.html#scrapy.http.Request) using `headers` argument: ``` yield Request(parse=..., headers={'referer':...}) ``` RefererMiddleware [does the same](https://github.com/scrapy/scrapy/blob/master/scrapy/contrib/spidermi...
Equality in Pandas DataFrames - Column Order Matters?
14,224,172
17
2013-01-08T21:16:05Z
14,224,489
7
2013-01-08T21:38:58Z
[ "python", "pandas" ]
As part of a unit test, I need to test two DataFrames for equality. The order of the columns in the DataFrames is not important to me. However, it seems to matter to Pandas: ``` import pandas df1 = pandas.DataFrame(index = [1,2,3,4]) df2 = pandas.DataFrame(index = [1,2,3,4]) df1['A'] = [1,2,3,4] df1['B'] = [2,3,4,5] d...
You could sort the columns using [`sort`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.sort.html): ``` df1.sort(axis=1) == df2.sort(axis=1) ``` This will evaluate to a dataframe of all `True` values. --- As @osa comments this fails for NaN's and isn't particularly robust either, in practise u...
Equality in Pandas DataFrames - Column Order Matters?
14,224,172
17
2013-01-08T21:16:05Z
21,000,675
23
2014-01-08T16:04:29Z
[ "python", "pandas" ]
As part of a unit test, I need to test two DataFrames for equality. The order of the columns in the DataFrames is not important to me. However, it seems to matter to Pandas: ``` import pandas df1 = pandas.DataFrame(index = [1,2,3,4]) df2 = pandas.DataFrame(index = [1,2,3,4]) df1['A'] = [1,2,3,4] df1['B'] = [2,3,4,5] d...
The most common intent is handled like this: ``` def assertFrameEqual(df1, df2, **kwds ): """ Assert that two dataframes are equal, ignoring ordering of columns""" from pandas.util.testing import assert_frame_equal return assert_frame_equal(df1.sort(axis=1), df2.sort(axis=1), check_names=True, **kwds ) ```...
How to create two mutually dependent objects in SQLAlchemy?
14,225,356
2
2013-01-08T22:45:38Z
14,242,000
7
2013-01-09T16:40:48Z
[ "python", "session", "transactions", "sqlalchemy", "flask-sqlalchemy" ]
I have two Python classes `Note` and `Link` mapping to PostgresQL tables. `Note` has a foreign-key reference to `Link`, while `Link` points back to the node through a piece of JSON text. Links point to other things besides `Note`s but that doesn't matter here. ``` Note +------+------------------+-------...
I'd advise against using Elixir's methods such as "save()" which mis-uses SQLAlchemy's API. Here is the aforementioned approach using standard SQLAlchemy events. Everything is achieved in one flush as well. ``` from sqlalchemy import * from sqlalchemy.orm import * from sqlalchemy.ext.declarative import declarative_bas...
Python: How to use RegEx in an if statement?
14,225,608
12
2013-01-08T23:06:11Z
14,225,664
26
2013-01-08T23:11:31Z
[ "python", "regex" ]
I have the following code which looks through the files in one directory and copies files that contain a certain string into another directory, but I am trying to use Regular Expressions as the string could be upper and lowercase or a mix of both. Here is the code that works, before I tried to use RegEx's ``` import ...
``` if re.match(regex, content) is not None: blah.. ``` You could also use `re.search` depending on how you want it to match.
Save list of DataFrames to multisheet Excel spreadsheet
14,225,676
27
2013-01-08T23:12:25Z
14,225,838
42
2013-01-08T23:27:40Z
[ "python", "pandas", "openpyxl" ]
How can I export a list of DataFrames into one Excel spreadsheet? The docs for [`to_excel`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html) state: > Notes > If passing an existing ExcelWriter object, then the sheet will be added > to the existing workbook. This can be used to ...
You should be using pandas own `ExcelWriter` class: ``` from pandas import ExcelWriter # from pandas.io.parsers import ExcelWriter ``` Then the `save_xls` function works as expected: ``` def save_xls(list_dfs, xls_path): writer = ExcelWriter(xls_path) for n, df in enumerate(list_dfs): df.to_excel(wri...
flask sqlalchemy column constraint for positive integer
14,225,998
2
2013-01-08T23:42:53Z
14,226,374
9
2013-01-09T00:19:11Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
how can i define a column as a positive integer using flask sqlalchemy? i am hoping the answer would look something like this: ``` class City(db.Model): id = db.Column(db.Integer, primary_key=True) population = db.Column(db.Integer, positive=True) def __init__(self,population): self.population = p...
unfortunately, on the python side, sqlalchemy does its best to stay out of the way; there's no 'special sqlalchemy' way to express that the instance attribute must satisfy some constraint: ``` >>> class Foo(Base): ... __tablename__ = 'foo' ... id = Column(Integer, primary_key=True) ... bar = Column(Integer...
Find a value within nested json dictionary in python
14,227,561
6
2013-01-09T02:49:23Z
14,227,627
11
2013-01-09T02:57:09Z
[ "python", "dictionary", "python-2.7", "nested" ]
From the following json, in python, I'd like to extract the value "TEXT". All the keys are constant except for unknown. Unknown could be any string like "a6784t66" or "hobvp\*nfe". **The value of unknown is not known**, only that it will be in that position in each json response. ``` { "A": { "B": { "unkno...
It is a bit lenghty, but in that example above: ``` In [1]: import json In [2]: s = """\ ...: { ...: "A": { ...: "B": { ...: "unknown": { ...: "1": "F", ...: "maindata": [ ...: { ...: "Info": "TEXT" ...: } ...: ] ...:...
Formatting PyYAML dump() output
14,228,915
12
2013-01-09T05:40:51Z
16,561,170
9
2013-05-15T09:16:54Z
[ "python", "yaml", "pyyaml" ]
I have a list of dictionaries, which I want to serialize: ``` list_of_dicts = [ { key_1: value_a, key_2: value_b}, { key_1: value_c, key_2: value_d}, ... { key_1: value_x, key_2: value_y} ] yaml.dump(list_of_dicts, file, default_flow_style = False) ``` produces ...
There's no easy way to do this with the library (Node objects in yaml dumper syntax tree are passive and can't emit this info), so I ended up with ``` stream = yaml.dump(list_of_dicts, default_flow_style = False) file.write(stream.replace('\n- ', '\n\n- ')) ```
What does `key_prefix` do for flask-cache?
14,228,985
3
2013-01-09T05:47:33Z
14,234,456
10
2013-01-09T11:43:20Z
[ "python", "caching", "flask", "flask-extensions" ]
For example like this, is it necessary to use `key_prefix`? ``` @cache.cached(timeout=50, key_prefix='all_comments') def get_all_comments(): comments = do_serious_dbio() return [x.author for x in comments] cached_comments = get_all_comments() ``` In the [document](http://packages.python.org/Flask-Cache/#cach...
First the [`request.path`](http://flask.pocoo.org/docs/api/#flask.Request.path) is everything (except params) after your `script_root`. For example: 1. For a url like, `http://127.0.0.1:5000/users/login/`, request data is: ``` request.path is: /users/login/ ``` 2. For a url like in the example from the link ...
Native Python function to remove NoneType elements from list?
14,229,433
7
2013-01-09T06:25:40Z
14,229,471
11
2013-01-09T06:28:30Z
[ "python", "list", "nonetype" ]
I'm using Beautiful Soup in Python to scrape some data from HTML files. In some cases, Beautiful Soup returns lists that contain both `string` and `NoneType` objects. I'd like to filter out all the `NoneType` objects. In Python, lists with containing `NoneType` objects are not iterable, so list comprehension isn't an ...
You can do this using list comprehension: ``` clean = [x for x in lis if x != None] ``` As pointed in the comments you could also use `is not`, even if it essentially compiles to the same bytecode: ``` clean = [x for x in lis if x is not None] ``` You could also used `filter` (note: this will also filter empty stri...
Native Python function to remove NoneType elements from list?
14,229,433
7
2013-01-09T06:25:40Z
14,230,402
20
2013-01-09T07:40:54Z
[ "python", "list", "nonetype" ]
I'm using Beautiful Soup in Python to scrape some data from HTML files. In some cases, Beautiful Soup returns lists that contain both `string` and `NoneType` objects. I'd like to filter out all the `NoneType` objects. In Python, lists with containing `NoneType` objects are not iterable, so list comprehension isn't an ...
I think the cleanest way to do this would be: ``` #lis = some list with NoneType's filter(None, lis) ```
python reading a tab separated file using delimiter
14,229,643
3
2013-01-09T06:40:40Z
14,230,532
8
2013-01-09T07:51:16Z
[ "python" ]
I am using the following to read a tab separated file .There are three columns in the file but the first column is being ignored when i print the column header only.how can i include the first column too ``` f = open("/tmp/data.txt") for l in f.readlines(): print l.strip().split("\t") break f.close() ``` Output...
I would also suggest to use the csv module. It is easy to use and fits best if you want to read in table like structures stored in a CSV like format (tab/space/something else delimited). The [module documentation](http://docs.python.org/2/library/csv.html) gives good examples where the simplest usage is stated to be: ...
Named tuples in a list
14,230,908
5
2013-01-09T08:19:00Z
14,230,915
9
2013-01-09T08:19:27Z
[ "python" ]
I have the following list ``` a = [[a1, b1, c1, [d1, e1, f1], [a2, b2, c2, [d2, e2, f2], [a3, b3, c3, [d3, e3, f3]] ``` How can I make this into a list of named tuples such that ``` a[0].val1 >>> a1 a[1].val2 >>> b2 a[0].box >>> [d1, e1, f1] ```
Use the [`collections.namedtuple` class factory](http://docs.python.org/2/library/collections.html#collections.namedtuple) to create a named tuple class: ``` mynamedtuple = collections.namedtuple('mynamedtuple', ('val1', 'val2', 'val3', 'box')) somenamedtuple = mynamedtuple('a1', 'a2', 'a3', ['d1', 'e1', 'f1']) somen...
Why required and default are mutally exclusive in ndb?
14,231,068
7
2013-01-09T08:30:36Z
14,263,920
9
2013-01-10T17:36:56Z
[ "python", "google-app-engine", "gae-datastore", "app-engine-ndb" ]
In old google appengine datastore API "required" and "default" could be used together for property definitions. Using ndb I get a ``` ValueError: repeated, required and default are mutally exclusive. ``` Sample code: ``` from google.appengine.ext import ndb from google.appengine.ext import db class NdbCounter(ndb.M...
I think you are right. Perhaps I was confused when I write that part of the code. It makes sense that "required=True" means "do not allow writing the value None" so it should be possible to combine this with a default value. Please file a feature request in the NDB tracker: <http://code.google.com/p/appengine-ndb-exper...
LLDB Python scripting in Xcode
14,232,208
3
2013-01-09T09:41:37Z
14,249,379
11
2013-01-10T01:24:43Z
[ "python", "xcode", "scripting", "lldb" ]
I've just discovered [this](http://lldb.llvm.org/scripting.html) handy feature of LLDB that allows me to write Python scripts that have access to variables in the frame when I'm on a breakpoint in LLDB. However I'm having a few issues when using it in Xcode (v4.5.2). Firstly, I can't find anywhere that says where I sho...
Between Xcode, lldb, and the Python interpreter there are some problems with the interactive console, unfortunately. Please do file a bug report at <http://bugreport.apple.com/> - I don't know if there is a bug report about this specific issue already, although problems in general here are known. You may want to use th...
How to check for the existence of a get parameter in flask
14,234,063
7
2013-01-09T11:18:52Z
14,234,100
12
2013-01-09T11:21:13Z
[ "python", "flask" ]
I'm new to python and flask. I know that I can fetch a GET parameter with request.args.get(varname);. I wanted to check whether a GET request to my server is specifying and optional parameter or not. Flask documentation didn't helped much.
You can actually use the default value, ``` opt_param = request.args.get("something") if opt_param is None: print "Argument not provided" ```
python split by number of times specified
14,235,638
2
2013-01-09T12:52:50Z
14,235,682
9
2013-01-09T12:55:02Z
[ "python" ]
In the following string how can i split the string in the following manner ``` str1="hi\thello\thow\tare\tyou" str1.split("\t") n=1 Output=["hi"] n=2 output:["hi","hello"] ```
``` str1.split('\t', n)[:-1] ``` [`str.split`](http://docs.python.org/2/library/stdtypes.html#str.split) has an optional second argument which is how many times to split. We remove the last item in the list (the leftover) with the slice. For example: ``` a = 'foo,bar,baz,hello,world' print(a.split(',', 2)) # ['foo',...
How to pickle a scipy.stats distribution (can't pickle instancemethod objects)
14,235,693
4
2013-01-09T12:55:34Z
14,235,957
7
2013-01-09T13:11:07Z
[ "python", "scipy", "pickle" ]
How can I save a scipy.stats distribution? For example: ``` a = [scipy.stats.norm(0,1), scipy.stats.norm(0,2)] with open("distro.pickle", 'w') as f: pickle.dump(a, f) ``` Doing this I get a `TypeError: can't pickle instancemethod objects`
They do not support pickling. The easier way to "solve" your problem is to pickle the arguments and, when unpickling, create a new object: ``` >>> from collections import namedtuple >>> Norm = namedtuple('Norm', 'mu variance') >>> def pickle_norm(n): ... return pickle.dumps(Norm(*n.args)) ... >>> def unpickle_nor...
Export many small DataFrames to a single Excel worksheet
14,235,984
3
2013-01-09T13:12:41Z
21,836,138
8
2014-02-17T17:59:31Z
[ "python", "excel", "export", "pandas" ]
With [this code](http://stackoverflow.com/questions/14225676/save-list-of-dataframes-to-multisheet-excel-spreadsheet/14225838#14225838), it is possible to export every data frame in a new worksheet iterating data frames list: ``` def save_xls(list_dfs, xls_path): writer = ExcelWriter(xls_path) for n, df in enu...
Something like this: ? ``` from pandas import ExcelWriter def dfs2xlsx(list_dfs,xls_path = None): #save_xls([df1,df2],'output1.xlsx') if xls_path == None : xls_path = '~tmp.xlsx' writer = ExcelWriter(xls_path) i=0 for n, df in enumerate(list_dfs): df.to_excel(writer,'Sheet1',startco...
Elegant way to test SSH availability
14,236,346
10
2013-01-09T13:30:18Z
14,237,026
10
2013-01-09T14:05:32Z
[ "python", "ssh", "paramiko" ]
I need a Python program I'm using to poll a remote server for SSH connectivity and notify when it is available. I am currently doing this using paramiko; attempt to connect, if failure, wait and retry until success or max retries. This works, but it's a bit clunky. Also paramiko seems to either connect or throw an erro...
As mentioned in the comment by frb, a `try ... except` block is a good approach to test availability of a specific service. You shouldn't use a "catch-all" `except` block though, but limit it to the specific exceptions that occur if the service is unavailable. According to documentation, [`paramiko.SSHClient.connect`]...
Wrong syntax when nesting 3 classes in Python?
14,238,214
3
2013-01-09T15:05:59Z
14,238,291
8
2013-01-09T15:09:38Z
[ "python", "syntax", "nested-class" ]
Would there be a simple way to fix this error while keeping all 3 levels? Deriving ClassA from object does not help. Thanks in advance! ``` >>> class classA: ... class classB(object): ... def __init__(self): ... self.b = 3 ... class classC(classA.classB): ... def __init__(...
No. At the time you define `classC`, `classA` does not exist yet. It is only created after its body is fully executed. (The dict created from the body's execution is one parameter for the class creation call `class = type('classname', (superclass_1, superclass_2, superclass_3), said_dict})`.) The easiest way would be...
Cannot Insert Unicode Using cx-Oracle
14,238,824
12
2013-01-09T15:35:55Z
15,803,435
10
2013-04-04T05:49:34Z
[ "python", "oracle", "unicode", "cx-oracle" ]
I am having an issue inserting unicode into an Oracle schema, I think the database is an Oracle 11g instance but am not certain at this point. I'm using python 2.6.1 on OS X 10.6.8 (this is the system verison of python) and am using the cx-Oracle driver module version 5.1 downloaded from sourceforge.net, built and inst...
Setting environment variable is the right way, but "AL32UTF8" is not the right value for NLS\_LANG. To get the right value of the NLS\_LANG used in your instance of Oracle, execute ``` SELECT USERENV ('language') FROM DUAL ```
How can I create lists from a list of strings?
14,241,133
4
2013-01-09T15:55:12Z
14,241,195
25
2013-01-09T15:58:41Z
[ "python" ]
I have a list of strings such as: ``` names = ['apple','orange','banana'] ``` And I would like to create a list for each element in the list, that would be named exactly as the string: ``` apple = [] orange = [] banana = [] ``` How can I do that in Python?
You would do this by creating a `dict`: ``` fruits = {k:[] for k in names} ``` Then access each by (for eg:) `fruits['apple']` - you do not want to go down the road of separate variables!
Interleave different length lists, elimating duplicates and preserve order in Python
14,241,320
19
2013-01-09T16:05:13Z
14,242,169
14
2013-01-09T16:48:22Z
[ "python", "list", "iterator", "order" ]
I have two lists, lets say: ``` keys1 = ['A', 'B', 'C', 'D', 'E', 'H', 'I'] keys2 = ['A', 'B', 'E', 'F', 'G', 'H', 'J', 'K'] ``` How do I create a merged list without duplicates that preserve the order of both lists, inserting the missing elements where they belong? Like so: ``` merged = ['A...
What you need is basically what any merge utility does: It tries to merge two sequences, while keeping the relative order of each sequence. You can use Python's [`difflib`](http://docs.python.org/2/library/difflib.html) module to diff the two sequences, and merge them: ``` from difflib import SequenceMatcher def merg...
Using super() in classes
14,242,033
3
2013-01-09T16:42:04Z
14,242,058
7
2013-01-09T16:43:24Z
[ "python", "oop" ]
I'm trying to use super() for a simple class hierarchy in this manner: ``` class Employee(object): def __init__(self, name): self.name = name class FullTime(Employee): def __init__(self, name, satOff, freeDays=[], alDays=[], programDays=[]): global satsOffDict global dayDict su...
You use the *current* class in `super()`: ``` super(FullTime, self).__init__(name) ``` `super()` looks for requested methods relative to the first argument; you started the search from `Employee` instead, looking for the parent classes; `object.__init__()` is the next parent method that matches in that case. You nee...
Build a dependency graph in python
14,242,295
7
2013-01-09T16:54:24Z
14,244,306
8
2013-01-09T18:47:12Z
[ "python", "graph", "dependencies" ]
I was wondering if python has some built-in library (or any library on the net..) That will create for for me a graph of dependencies ? I have a file formatted like that ``` A::Requires = "" B::Requires = A C::Requires = B H::Requires = A AA::Requires = "" BB::Requires = AA C::Requ...
Assuming your input from above is given as a string in `raw`: ``` import networkx as nx import re regex = re.compile(r'^([A-Z]+)::Requires\s+=\s([A-Z"]+)$') G = nx.DiGraph() roots = set() for l in raw.splitlines(): if len(l): target, prereq = regex.match(l).groups() if prereq == '""': ...
How can I start the python shell and automatically initialize it with some commands?
14,244,253
5
2013-01-09T18:44:44Z
14,244,310
8
2013-01-09T18:47:30Z
[ "python" ]
I find that when I start the python shell I have a bunch of commands I always type to get into the state I want. It is tiresome to keep re-typing these commands, so I have bundled them into a script. Now I just type: ``` execfile('script.py') ``` as soon as I enter the shell, and it goes through all the steps to get ...
I think you're looking for the [PYTHONSTARTUP](http://docs.python.org/2/using/cmdline.html#envvar-PYTHONSTARTUP) environment variable
How can I start the python shell and automatically initialize it with some commands?
14,244,253
5
2013-01-09T18:44:44Z
14,244,342
12
2013-01-09T18:49:40Z
[ "python" ]
I find that when I start the python shell I have a bunch of commands I always type to get into the state I want. It is tiresome to keep re-typing these commands, so I have bundled them into a script. Now I just type: ``` execfile('script.py') ``` as soon as I enter the shell, and it goes through all the steps to get ...
Here's a way without having to mess with environment variables: For example, if I had a script with the following in it called `script.py`: ``` #!/usr/bin/env python print("example") ``` I could tell `python` to run this before bringing me to the interpreter with the `-i` flag. ``` $ python -i script.py example >>>...
scipy: Interpolating trajectory
14,244,289
8
2013-01-09T18:46:34Z
14,245,293
10
2013-01-09T19:51:01Z
[ "python", "interpolation", "spline" ]
I have a trajectory formed by a sequence of *(x,y)* pairs. I would like to interpolate points on this trajectory using splines. How do I do this? Using `scipy.interpolate.UnivariateSpline` doesn't work because neither *x* nor *y* are monotonic. I could introduce a parametrization (e.g. length *d* along the trajectory)...
Using splprep you can interpolate over curves of any geometry. ``` from scipy import interpolate tck,u=interpolate.splprep([x,y],s=0.0) x_i,y_i= interpolate.splev(np.linspace(0,1,100),tck) ``` Which produces a plot like the one given, but only using the x and y points and not the alpha and r paramters. ![Same as your...
MySQLdb install error - _mysql.c:44:23: error: my_config.h: No such file or directory
14,244,866
6
2013-01-09T19:25:23Z
27,058,112
17
2014-11-21T09:32:09Z
[ "python", "django", "mysql-python" ]
I'm trying to install MySQLdb extension, but I get this error any idea what may be the cause? Could be something with permissions? I'm using Mac OX Lion.... This is a part of the error a got. Django is installed fine, but I need to install this extension. Thanks for any help. ``` ppp-071ca:MySQL-python-1.2.4b4 miguel...
If ubuntu : `apt-get install mysql-devel` If centos/rhel : `yum install mysql-devel` Then install MySQL-python
Parsing a date that can be in several formats in python
14,245,029
10
2013-01-09T19:36:07Z
14,245,134
10
2013-01-09T19:42:16Z
[ "python", "ruby", "parsing", "datetime" ]
I would like to parse a date that can come in several formats, that I know beforehand. If I could not parse, I return nil. In ruby, I do like this: ``` DATE_FORMATS = ['%m/%d/%Y %I:%M:%S %p', '%Y/%m/%d %H:%M:%S', '%d/%m/%Y %H:%M', '%m/%d/%Y', '%Y/%m/%d'] def parse_or_nil(date_str) parsed_date = nil DATE_FORMA...
You can use `try/except` to catch the `ValueError` that would occur when trying to use a non-matching format. As @Bakuriu mentions, you can stop the iteration when you find a match to avoid the unnecessary parsing, and then define your behavior when `my_date` doesn't get defined because not matching formats are found: ...
Parsing a date that can be in several formats in python
14,245,029
10
2013-01-09T19:36:07Z
14,245,142
11
2013-01-09T19:42:40Z
[ "python", "ruby", "parsing", "datetime" ]
I would like to parse a date that can come in several formats, that I know beforehand. If I could not parse, I return nil. In ruby, I do like this: ``` DATE_FORMATS = ['%m/%d/%Y %I:%M:%S %p', '%Y/%m/%d %H:%M:%S', '%d/%m/%Y %H:%M', '%m/%d/%Y', '%Y/%m/%d'] def parse_or_nil(date_str) parsed_date = nil DATE_FORMA...
I would just try [dateutil](http://labix.org/python-dateutil). It can recognize most of the formats: ``` from dateutil import parser parser.parse(string) ``` if you end up using datetime.strptime as suggested @RocketDonkey: ``` from datetime import datetime def func(s,flist): for f in flist: try: ...
How to read part of binary file with numpy?
14,245,094
7
2013-01-09T19:39:30Z
14,245,580
11
2013-01-09T20:09:26Z
[ "python", "numpy", "scipy" ]
I'm converting a matlab script to numpy, but have some problems with reading data from a binary file. Is there an equivelent to `fseek` when using `fromfile` to skip the beginning of the file? This is the type of extractions I need to do: ``` fid = fopen(fname); fseek(fid, 8, 'bof'); second = fread(fid, 1, 'schar'); f...
You can use seek with a file object in the normal way, and then use this file object in `fromfile`. Here's a full example: ``` import numpy as np import os data = np.arange(100, dtype=np.int) data.tofile("temp") # save the data f = open("temp", "rb") # reopen the file f.seek(256, os.SEEK_SET) # seek x = np.fromf...
Python - reset stdout to normal, after previously redirecting it to a file
14,245,227
12
2013-01-09T19:47:04Z
14,245,252
17
2013-01-09T19:48:06Z
[ "python", "stdout" ]
At the beginning of my python program I have the following line: ``` sys.stdout = open('stdout_file', 'w') ``` Halfway through my program I would like to set stdout back to the normal stdout. How do I do this?
The original `stdout` can be accessed as `sys.__stdout__`. This [is documented](http://docs.python.org/2/library/sys.html#sys.__stdin__).
Python virtualenv --system-site-packages iPython
14,245,376
2
2013-01-09T19:56:37Z
14,246,495
7
2013-01-09T21:07:18Z
[ "python", "virtualenv", "ipython" ]
I am using EPD on OS X and have ipython installed. In my 'general' environment everything is functioning as expected. I installed virtualenv and virtualenvwrapper to generate a dev environment. I only want to install a small subset of 'new' modules (different versions), so I used: `mkvirtualenv development --python=ep...
Sure, just tell pip to ignore the installed IPython: ``` pip install --ignore-installed ipython ```
Using a WHERE ___ IN ___ statement
14,245,396
3
2013-01-09T19:57:36Z
14,245,421
9
2013-01-09T19:59:21Z
[ "python", "sql", "sqlite" ]
I'm trying to figure out how to properly use a WHERE **\_ IN \_** statement Definition: ``` c.execute('''CREATE TABLE IF NOT EXISTS tab ( _id integer PRIMARY KEY AUTOINCREMENT, obj text NOT NULL ) ;''') ``` I'm trying to do something like this: ``` list_of_vars=['foo','bar'] statement="SELECT * FROM tab...
You need to create enough parameters to match your list of vars: ``` statement = "SELECT * FROM tab WHERE obj IN ({0})".format(', '.join(['?'] * len(list_of_vars))) c.execute(statement, list_of_vars) ``` Note that you pass in `list_of_vars` as the parameter values list. Using the `', '.join()` we generate a string of...
python unittest - Using 'buffer' option to suppress stdout - how do I do it?
14,245,499
6
2013-01-09T20:04:06Z
14,245,739
7
2013-01-09T20:20:15Z
[ "python", "unit-testing" ]
In the unittest docs [ <http://docs.python.org/2/library/unittest.html#unittest.main> ], I see the following method signature described: ``` unittest.main([module[, defaultTest[, argv[, testRunner[, testLoader[, exit[, verbosity[, failfast[, catchbreak[, buffer]]]]]]]]]]) ``` The last option is "buffer". The docs exp...
The point is that [*buffer* option](http://docs.python.org/2/library/unittest.html#cmdoption-unittest-b) affects stdout writing inside your tests, ignoring that of unittest2 behaviour. That is to say, you will see the difference, if you add string like ``` print "Suppress me!" ``` to any test method, this expression ...
'RuntimeError: maximum recursion depth exceeded in cmp' when working with lists
14,246,081
4
2013-01-09T20:42:24Z
14,246,529
9
2013-01-09T21:09:22Z
[ "python", "list" ]
I've encountered the error `RuntimeError: maximum recursion depth exceeded in cmp` when working with lists. More precisely, `p0 in points`, the `points.index(p0)` method call as well as the `points.remove(p0)` method call on the `points` list have been raising the error for a specific dictionary `p0` at a specific inde...
Probably you have a circular structure where one of your dicts refers to itself through a chain of `'next'`s, like this: ``` >>> a = {} >>> b = {} >>> a['next'] = b >>> b['next'] = a >>> a == b Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: maximum recursion depth exceeded in cm...
Compare (assert equality of) two complex data structures containing numpy arrays in unittest
14,246,983
16
2013-01-09T21:38:40Z
14,249,723
12
2013-01-10T02:02:22Z
[ "python", "unit-testing", "numpy" ]
I use Python's `unittest` module and want to check if two complex data structures are equal. The objects can be lists of dicts with all sorts of values: numbers, strings, Python containers (lists/tuples/dicts) and `numpy` arrays. The latter are the reason for asking the question, because I cannot just do ``` self.asse...
Would have commented, but it gets too long... Fun fact, you cannot use `==` to test if arrays are the same I would suggest you use [`np.testing.assert_array_equal`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.testing.assert_array_equal.html) instead. 1. that checks dtype, shape, etc., 2. that doesn't fa...
Python None comparison: should I use "is" or ==?
14,247,373
74
2013-01-09T22:06:58Z
14,247,383
106
2013-01-09T22:08:04Z
[ "python", "comparison", "nonetype" ]
> **Possible Duplicate:** > [When is the `==` operator not equivalent to the `is` operator? (Python)](http://stackoverflow.com/questions/3647692/when-is-the-operator-not-equivalent-to-the-is-operator-python) I am using Python 2.x. My editor gives me a 'warning' underline when I compare `my_var == None`, but no warn...
### Summary: Use `is` when you want to check against an object's *identity* (e.g. checking to see if `var` is `None`). Use `==` when you want to check *equality* (e.g. Is `var` equal to `3`?). ### Explanation: You can have custom classes where `my_var == None` will return `True` e.g: ``` class Negator(object): ...
Python None comparison: should I use "is" or ==?
14,247,373
74
2013-01-09T22:06:58Z
14,247,419
49
2013-01-09T22:10:46Z
[ "python", "comparison", "nonetype" ]
> **Possible Duplicate:** > [When is the `==` operator not equivalent to the `is` operator? (Python)](http://stackoverflow.com/questions/3647692/when-is-the-operator-not-equivalent-to-the-is-operator-python) I am using Python 2.x. My editor gives me a 'warning' underline when I compare `my_var == None`, but no warn...
`is` is generally preferred when comparing arbitrary objects to singletons like `None` because it is faster and more predictable. `is` always compares by object identity, whereas what `==` will do depends on the exact type of the operands and even on their ordering. This recommendation is supported by PEP 8, which exp...
Python None comparison: should I use "is" or ==?
14,247,373
74
2013-01-09T22:06:58Z
14,247,424
9
2013-01-09T22:11:07Z
[ "python", "comparison", "nonetype" ]
> **Possible Duplicate:** > [When is the `==` operator not equivalent to the `is` operator? (Python)](http://stackoverflow.com/questions/3647692/when-is-the-operator-not-equivalent-to-the-is-operator-python) I am using Python 2.x. My editor gives me a 'warning' underline when I compare `my_var == None`, but no warn...
PEP 8 defines that it is better to use the is operator when comparing singletons.
Python Pandas How to select rows with one or more nulls from a DataFrame without listing columns explicitly?
14,247,586
36
2013-01-09T22:22:05Z
14,247,708
63
2013-01-09T22:33:07Z
[ "python", null, "pandas" ]
I have a dataframe with ~300K rows and ~40 columns. I want to find out if any rows contain null values - and put these 'null'-rows into a separate dataframe so that I could explore them easily. I can create a mask explicitly: ``` mask=False for col in df.columns: mask = mask | df[col].isnull() dfnulls = df[mask] ``` ...
[Updated to adapt to modern `pandas`, which has `isnull` as a method of `DataFrame`s..] You can use `isnull` and `any` to build a boolean Series and use that to index into your frame: ``` >>> df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)]) >>> df.isnull() 0 1 2 0 Fa...
How do I change button size in Python?
14,247,709
5
2013-01-09T22:33:08Z
14,247,813
10
2013-01-09T22:41:10Z
[ "python", "tkinter" ]
I am doing a simple project in school and I need to make six different buttons to click on. The buttons must have different sizes, but I can't find how do do it. I have made the button by using: ``` def __init__(self, master): super().__init__(master) self.grid() self.button1 = Button(self, text = "Send", ...
Configuring a button (or any widget) in Tkinter is done by calling a configure method ["config"](http://effbot.org/tkinterbook/button.htm#reference) To change the size of a button called button1 you simple call ``` button1.config( height = WHATEVER, width = WHATEVER2 ) ``` If you know what size you want at initiliza...
Python: SyntaxError: non-keyword after keyword arg
14,247,732
25
2013-01-09T22:35:18Z
14,247,754
46
2013-01-09T22:36:57Z
[ "python" ]
When I run the following code ``` def regEx1(): os.chdir("C:/Users/Luke/Desktop/myFiles") files = os.listdir(".") os.mkdir("C:/Users/Luke/Desktop/FilesWithRegEx") regex_txt = input("Please enter the website your are looking for:") for x in (files): inputFile = open((x), encoding = "utf8", "r") conten...
It's just what it says: ``` inputFile = open((x), encoding = "utf8", "r") ``` You have specified `encoding` as a keyword argument, but `"r"` as a positional argument. You can't have positional arguments after keyword arguments. Perhaps you wanted to do: ``` inputFile = open((x), "r", encoding = "utf8") ```
Finding properties of sloppy hand-drawn rectangles
14,248,571
23
2013-01-09T23:52:17Z
14,249,961
16
2013-01-10T02:34:51Z
[ "python", "algorithm", "image-processing", "opencv", "graphics" ]
Image I'm working with: ![https://dl.dropbox.com/u/454490/1%20%28Small%29.JPG](https://dl.dropbox.com/u/454490/1%20%28Small%29.JPG) I'm trying to find each of the boxes in this image. The results don't have to be 100% accurate, just as long as the boxes found are approximately correct in position/size. From playing w...
I suggest a simpler approach as a starting point. For instance, morphological gradient can serve as a good local detector of strong edges, and threshold on it tends to be simple. Then, you can remove too small components, which is relatively easy for your problem too. In your example, each remaining connected component...
Finding properties of sloppy hand-drawn rectangles
14,248,571
23
2013-01-09T23:52:17Z
14,279,746
12
2013-01-11T14:03:50Z
[ "python", "algorithm", "image-processing", "opencv", "graphics" ]
Image I'm working with: ![https://dl.dropbox.com/u/454490/1%20%28Small%29.JPG](https://dl.dropbox.com/u/454490/1%20%28Small%29.JPG) I'm trying to find each of the boxes in this image. The results don't have to be 100% accurate, just as long as the boxes found are approximately correct in position/size. From playing w...
I see you have already got the answer. But I think there is a much more simpler,shorter and better method available in OpenCV to resolve this problem. While finding contours, you are also finding the hierarchy of the contours. Hierarchy of the contours is the relation between different contours. So the flag you used ...
Serializing output to JSON - ValueError: Circular reference detected
14,249,115
14
2013-01-10T00:53:13Z
14,251,249
10
2013-01-10T05:18:00Z
[ "python", "json", "python-2.7" ]
I'm trying to output results of my mysql query to JSON. I have problem with serializing datetime.datetime field, so I wrote small function to do that: ``` def date_handler(obj): if hasattr(obj, 'isoformat'): return obj.isoformat() else: return obj ``` and then in main code I'm just running: `...
The function you pass as the `default` argument will only be called for objects that are not natively serializable by the `json` module. It must return a serializable object, or raise a TypeError. Your version returns the same object you were passed if it's not of the one type you're fixing (dates). That is causing th...
Serializing output to JSON - ValueError: Circular reference detected
14,249,115
14
2013-01-10T00:53:13Z
17,923,104
7
2013-07-29T11:42:21Z
[ "python", "json", "python-2.7" ]
I'm trying to output results of my mysql query to JSON. I have problem with serializing datetime.datetime field, so I wrote small function to do that: ``` def date_handler(obj): if hasattr(obj, 'isoformat'): return obj.isoformat() else: return obj ``` and then in main code I'm just running: `...
In stead of raising the TypeError yourself, you should relay the call to JSONEncoder's default-method: ``` def date_handler(obj): if hasattr(obj, 'isoformat'): return obj.isoformat() else: json.JSONEncoder.default(self,obj) ``` This will also raise TypeError and is a better practice, it allows...
Change "Quoted-printable" encoding to "utf-8"
14,249,288
4
2013-01-10T01:12:53Z
14,249,341
9
2013-01-10T01:19:41Z
[ "python", "encoding", "python-3.x" ]
I am trying to read email with imaplib. I get this mail body: ``` =C4=EE=E1=F0=FB=E9 =E4=E5=ED=FC! ``` That is `Quoted-printable` encoding. I need to get `utf-8` from this. It should be `Добрый день!` I googled it, but it is too messy with Python's versions. It is already unicode in Python 3, I cann't us...
The [`quopri` module](http://docs.python.org/2/library/quopri.html) can convert those bytes to an unencoded byte stream. You need to then decode those from whatever character set they're in, then encode back to `utf-8`. ``` >>> b = quopri.decodestring('=C4=EE=E1=F0=FB=E9 =E4=E5=ED=FC') >>> print(b.decode('windows-1251...
Why is python round so strange?
14,249,971
5
2013-01-10T02:35:41Z
14,250,080
7
2013-01-10T02:48:46Z
[ "python" ]
My code: ``` #!/usr/bin/python # -*- coding: utf-8 -*- print (round(1.555,1)) #It seems normal print (round(1.555,2)) #Why it is not output 1.56? print (round(1.556,2)) #It seems normal ``` Output: ``` sam@sam:~/code/python$ ./t2.py 1.6 1.55 1.56 sam@sam:~/code/python$ ``` `round(1.555,1)` o...
Take a look at [the documentation](http://docs.python.org/2/library/functions.html#round): > **Note** The behavior of `round()` for floats can be surprising: for example, `round(2.675, 2)` gives `2.67` instead of the expected > `2.68`. This is not a bug: it’s a result of the fact that most decimal > fractions can’...
python import module from parent package
14,250,058
5
2013-01-10T02:45:38Z
14,250,136
11
2013-01-10T02:54:50Z
[ "python", "import", "module", "package", "parent" ]
I have the following directory structure ``` foo/ __init__.py settings.py bar/ __init__.py myfile.py ``` In myfile.py I have: import settings I get the following error: `ImportError: No module named settings`, why? How can I efectively import the `settings` file from `myfile.py`
From <http://docs.python.org/2/tutorial/modules.html#intra-package-references> : ``` from .. import settings ``` Hope it helps
Default value for next element in Python iterator if iterator is empty?
14,250,184
7
2013-01-10T03:03:35Z
14,250,244
16
2013-01-10T03:10:39Z
[ "python", "iterator" ]
I have a list of objects, and I would like to find the first one for which a given method returns true for some input value. This is relatively easy to do in Python: ``` pattern = next(p for p in pattern_list if p.method(input)) ``` However, in my application it is common that there is no such `p` for which `p.method...
`next` accepts a default value: ``` next(...) next(iterator[, default]) ``` Returns the next item from the iterator. If the default argument is given and the iterator is exhausted, it is returned instead of raising StopIteration. and so ``` >>> print next(i for i in range(10) if i**2 == 9) 3 >>> print next(i fo...
Is there any vim plugin written in python?
14,253,997
4
2013-01-10T08:56:21Z
14,254,151
13
2013-01-10T09:05:13Z
[ "python", "vim", "vim-plugin" ]
Just like Command-T . Command-T requires Vim compiled with Ruby support. Is there any vim plugin written in python ?
Many: * <https://github.com/klen/rope-vim> * <https://github.com/SirVer/ultisnips> You can find 90+ more on Github by querying the `username:vim-scripts` for `language:python` (meaning Python is the primary language): * <https://github.com/search?q=language%3Apython+username%3Avim-scripts>
Mixing categorial and continuous data in Naive Bayes classifier using scikit-learn
14,254,203
17
2013-01-10T09:08:22Z
14,255,284
17
2013-01-10T10:07:55Z
[ "python", "machine-learning", "data-mining", "classification", "scikit-learn" ]
I'm using scikit-learn in Python to develop a classification algorithm to predict gender of a certain customers. Amongst others I want to use the Naive Bayes classifier but my problem is that I have a mix of categorial data (ex: "Registered online", "Accepts email notifications" etc) and continuous data (ex: "Age", "Le...
You have at least two options: * Transform all your data into a categorical representation by computing percentiles for each continuous variables and then binning the continuous variables using the percentiles as bin boundaries. For instance for the height of a person create the following bins: "very small", "small", ...
Is there a way to pass variables into Jinja2 parents?
14,254,308
6
2013-01-10T09:15:12Z
22,582,736
9
2014-03-22T19:52:01Z
[ "python", "html", "google-app-engine", "jinja2" ]
I'm trying to pass some variables from the child page to the template. This is my python code: ``` if self.request.url.find("&try") == 1: isTrying = False else: isTrying = True page_values = { "trying": isTrying } page = jinja_environment.get_template("p/index.html") s...
The example on the Jinja2 Tips and Tricks page explains this perfectly, <http://jinja.pocoo.org/docs/templates/#base-template>. Essentially, if you have a base template ``` **base.html** <html> <head> <title> MegaCorp -{% block title %}{% endblock %}</title> </head> <body> <div id="content"...
How can I attach a pyplot function to a figure instance?
14,254,379
10
2013-01-10T09:19:06Z
14,254,791
10
2013-01-10T09:43:30Z
[ "python", "numpy", "matplotlib" ]
Previously, I had a problem with the [interference between multiple Matplotlib figures](http://stackoverflow.com/questions/7673444/avoid-interference-between-multiple-matplotlib-figures-on-the-web). Finally i got tracked that to an issue that some pyplot functions do not attach to their figure instance but can be rende...
You can create a subplot and than call the `contour` method of the subplot: ``` fig1 = figure(figsize=(4, 4), facecolor='white') ax = fig1.add_subplot(111) ax.contour(X, Y, Z) ``` [`plt.subplots`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplots) makes it convenient to create a figure and subplots...