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
is Python list comprehension with access to the index/enumerate possible?
14,864,922
29
2013-02-13T22:59:56Z
14,864,942
15
2013-02-13T23:02:19Z
[ "python", "list", "indexing", "list-comprehension" ]
consider the following Python code with which I add in a new list2 all the items with indices from 1 to 3 of list1: ``` for ind, obj in enumerate(list1): if 4> ind > 0: list2.append(obj) ``` how would you write this using python list comprehension, if I have no access to the indices through enumerate? something ...
If you use `enumerate`, you *do* have access to the index: ``` list2 = [x for ind, x in enumerate(list1) if 4>ind>0] ```
Python module won't install
14,865,990
11
2013-02-14T00:46:34Z
14,867,310
12
2013-02-14T03:26:26Z
[ "python", "setuptools", "distutils" ]
This is my `setup.py` file ``` #!/usr/bin/env python from setuptools import setup from sys import path setup(name= 'conundrum', version= '0.1.0', author= 'elssar', author_email= 'elssar@altrawcode.com', py_modules= ['conundrum'], url= 'https://github.com/elssar/conundrum', license= 'MIT', ...
I cannot run `setup.py` from a different directory. It needs to be run from the directory it is in. That was the problem here. Fixed.
Combining Grid search and cross validation in scikit learn
14,866,228
9
2013-02-14T01:11:00Z
14,872,267
12
2013-02-14T10:06:26Z
[ "python", "svm", "scikit-learn", "cross-validation" ]
For improving Support Vector Machine outcomes i have to use grid search for searching better parameters and cross validation. I'm not sure how combining them in scikit-learn. Grid search search best parameters (<http://scikit-learn.org/stable/modules/grid_search.html>) and cross validation avoid overfitting (<http://sc...
You should do a development / evaluation split first, run the grid search on the development part and measure a unique final score on the evaluation part at the end: There is [an example](http://scikit-learn.org/stable/auto_examples/model_selection/grid_search_digits.html) in [the documentation](http://scikit-learn.or...
Update and create a multi-dimensional dictionary in Python
14,867,496
6
2013-02-14T03:49:45Z
14,867,580
10
2013-02-14T03:59:25Z
[ "python", "dictionary", "multidimensional-array" ]
I am parsing JSON that stores various code snippets and I am first building a dictionary of languages used by these snippets: ``` snippets = {'python': {}, 'text': {}, 'php': {}, 'js': {}} ``` Then when looping through the JSON I'm wanting add the information about the snippet into its own dictionary to the dictionar...
This is called [autovivification](http://en.wikipedia.org/wiki/Autovivification): You can do it with `defaultdict` ``` def tree(): return collections.defaultdict(tree) d = tree() d['js']['title'] = 'Script1' ``` If the idea is to have lists, you can do: ``` d = collections.defaultdict(list) d['js'].append({'fo...
unittest for none type in python?
14,868,170
6
2013-02-14T05:09:20Z
21,715,451
11
2014-02-11T23:29:35Z
[ "python", "unit-testing", "assertion", "nonetype" ]
I was just wondering how I would go about testing for a function that does not return anything. for example, say I have this function: ``` def is_in(char): my_list = [] my_list.append(char) ``` and then if I were to test it: ``` class TestIsIn(unittest.TestCase): def test_one(self): ''' Test if one ...
All Python functions return something. If you don't specify a return value, `None` is returned. So if your goal really is to make sure that something doesn't return a value, you can just say ``` self.assertIsNone(self.is_in('a')) ``` (However, this can't distinguish between a function without an explicit return value...
Is there a way to convert pyplot.imshow() object to numpy array?
14,869,321
2
2013-02-14T06:52:36Z
14,877,059
7
2013-02-14T14:30:24Z
[ "python", "opencv", "numpy", "matplotlib" ]
I need to visualize a 2D numpy array. I am using pyplot for this. Here's the code: ``` import cv2 as cv import numpy as np from matplotlib import pyplot img = pyplot.imshow( radiance_val ) #radiance_val is a 2D numpy array of size = ( 512, 512 ) #filled with np.float32 values pyplot.show() ``` I am getting the out...
Unless you really need the marker ticks and such, ``` im._rgba_cache ``` gives you direct access to the MxNx4 `numpy` array that is the color mapped data. If you just want the color mapped data, you can by pass `imshow` entirely and directly color-map the data your self (see [guide](http://matplotlib.org/users/color...
Logical OR operation with -1
14,870,421
3
2013-02-14T08:14:18Z
14,870,446
8
2013-02-14T08:16:00Z
[ "python", "python-2.7", "logical-operators" ]
Why is the output different for the following logical operations that I tried in python? ``` -1 or 1 1 or -1 ``` First returns `-1` and second returns `1`
`and` and `or` are both *lazy*; they evaluate operands until they can decide the result (`and` stops at the first `False` operand; `or` stops at the first `True` operand). They return the last operand evaluated, as noted in [the documentation](http://docs.python.org/2/reference/expressions.html#boolean-operations): > ...
Logical OR operation with -1
14,870,421
3
2013-02-14T08:14:18Z
14,870,451
7
2013-02-14T08:16:05Z
[ "python", "python-2.7", "logical-operators" ]
Why is the output different for the following logical operations that I tried in python? ``` -1 or 1 1 or -1 ``` First returns `-1` and second returns `1`
Read [the documentation](http://docs.python.org/3/reference/expressions.html#boolean-operations): > The expression `x or y` first evaluates `x`; if `x` is true, its value is returned; otherwise, `y` is evaluated and the resulting value is returned.
py2exe: error: libzmq.pyd: No such file or directory
14,870,825
4
2013-02-14T08:43:57Z
23,179,471
8
2014-04-20T07:07:23Z
[ "python", "py2exe", "pyzmq" ]
During py2exe build I get the following error: ``` creating python loader for extension 'win32clipboard' (C:\Python27\lib\site-packages\win32\win32clipboard.pyd -> win32clipboard.pyd) creating python loader for extension '_rl_accel' (C:\Python27\lib\site-packages\_rl_accel.pyd -> _rl_accel.pyd) *** finding dlls needed...
Three steps are necessary to make it work: * Exclude `libzmq.pyd` from dlls with `dll_excludes` option. This avoids "missing pyzmq.pyd" errors. * Exclude `zmq.libzmq` (same thing) from modules with `excludes`. This skips the usual .pyd renamind and proxying that py2exe does. * Add `zmq.backend.cython` explicitly with ...
Deleting variables in Python standard libraries
14,871,275
6
2013-02-14T09:12:53Z
14,871,298
8
2013-02-14T09:14:03Z
[ "python", "reference", "try-catch" ]
I've been reading some of the code in a standard *threading* library ( Python 2.6 ) and there was a piece of code which made me wonder. It can be shorten to the following structure ( compare to \_\_bootstrap\_inner method in *threading.py* ): ``` def foo(): exc_type, exc_value, exc_tb = sys.exc_info() try: ...
Yes, at the very least for `exc_tb`; traceback objects hold a reference to the current frame, and that makes this a circular reference. By deleting the local reference you break that circle, so you don't have to hope and trust that the garbage collector will be able to. From the [`sys.exc_info()` function docs](http:...
Find element in list
14,872,046
2
2013-02-14T09:54:43Z
14,872,113
9
2013-02-14T09:58:19Z
[ "python", "list" ]
I have a list like ``` list_a = [(1, 2), (2, 3), (4, 5)] ``` and now using this list i wanted to find a element which has last value 3 any short method to achieve this? it should return `(2,3)`
For example: ``` In [1]: list_a = [(1, 2), (2, 3), (4, 5)] In [2]: next(x for x in list_a if x[1] == 3) Out[2]: (2, 3) ``` Note that it returns a single element, not a list of them (seems to be what you are asking). If there are multiple tuples, the first one is returned.
Get IP Address when testing flask application through nosetests
14,872,829
11
2013-02-14T10:35:25Z
14,873,034
16
2013-02-14T10:46:21Z
[ "python", "testing", "flask", "nosetests", "werkzeug" ]
My application depends on `request.remote_addr` which is `None` when i run tests through nosetests which uses `app.test_client().post('/users/login', ....)`. **How can I emulate an IP (127.0.0.1 works fine) when I run tests?** I've tried setting environment variables, sent in headers with the post() method and I've di...
You can set options for the underlying Werkzeug environment using [environ\_base](http://werkzeug.pocoo.org/docs/test/#testing-api): ``` from flask import Flask, request import unittest app = Flask(__name__) app.debug = True app.testing = True @app.route('/') def index(): return str(request.remote_addr) class T...
Plotting of 1-dimensional Gaussian distribution function
14,873,203
6
2013-02-14T10:56:01Z
14,880,001
11
2013-02-14T16:54:43Z
[ "python", "plot", "gaussian" ]
How do I make plots of a 1-dimensional Gaussian distribution function using the mean and standard deviation parameter values (μ, σ) = (−1, 1), (0, 2), and (2, 3)? I'm new to programming, using Python. Thank you in advance!
With the excellent `matplotlib` and `numpy` packages ``` from matplotlib import pyplot as mp import numpy as np def gaussian(x, mu, sig): return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.))) for mu, sig in [(-1, 1), (0, 2), (2, 3)]: mp.plot(gaussian(np.linspace(-3, 3, 120), mu, sig)) mp.show() ```...
Plotting of 1-dimensional Gaussian distribution function
14,873,203
6
2013-02-14T10:56:01Z
17,331,318
8
2013-06-26T22:07:21Z
[ "python", "plot", "gaussian" ]
How do I make plots of a 1-dimensional Gaussian distribution function using the mean and standard deviation parameter values (μ, σ) = (−1, 1), (0, 2), and (2, 3)? I'm new to programming, using Python. Thank you in advance!
You are missing a parantheses in the denominator of your gaussian() function. As it is right now you divide by 2 and multiply with the variance (sig^2). But that is not true and as you can see of your plots the greater variance the more narrow the gaussian is - which is wrong, it should be opposit. So just change the ...
apscheduler in Flask executes twice
14,874,782
20
2013-02-14T12:22:32Z
15,491,587
20
2013-03-19T04:38:34Z
[ "python", "flask", "apscheduler" ]
I have problem when i am using apscheduler in my flask application. In my view.py file i am writing like this ``` import time from apscheduler.scheduler import Scheduler def test_scheduler(): print "TEST" print time.time() sched = Scheduler() sched.add_interval_job(test_scheduler, seconds=5) sched.start(...
In debug mode, Flask's reloader will load the flask app twice ([How to stop flask from initialising twice in Debug Mode?](http://stackoverflow.com/questions/9449101/how-to-stop-flask-from-initialising-twice-in-debug-mode)). I'm not sure why this is, but it causes apscheduler's jobs to be scheduled twice. A quick `print...
Readonly text field in Flask-Admin ModelView
14,874,846
5
2013-02-14T12:25:57Z
18,839,552
11
2013-09-17T00:40:42Z
[ "python", "flask", "flask-sqlalchemy", "flask-admin" ]
How can I make a field on a `ModelView` readonly? ``` class MyModelView(BaseModelView): column_list = ('name', 'last_name', 'email') ```
If you're talking about Flask-Admin with SQLAlchemy Models, and you're declaring a view by inheriting from sqlamodel.ModelView, you can just add this to your class definition: ``` class MyModelView(BaseModelView): column_list = ('name', 'last_name', 'email') form_widget_args = { 'email':{ '...
Python, numpy sort array
14,875,248
3
2013-02-14T12:50:36Z
14,875,366
20
2013-02-14T12:57:06Z
[ "python", "numpy" ]
I'am using numpy and have an array (ndarray type) which contain some values. Shape of this array 1000x1500. I reshaped it ``` brr = np.reshape(arr, arr.shape[0]*arr.shape[1]) ``` when I trying ``` brr.reverse() AttributeError: ‘numpy.ndarray’ object has no attribute ‘reverse’ ``` get error. How I can sort t...
If you just want to reverse it: ``` brr[:] = brr[::-1] ``` Actually, this reverses along axis 0. You could also revert on any other axis, if the array has more than one. To sort in reverse order: ``` >>> arr = np.random.random((1000,1500)) >>> brr = np.reshape(arr, arr.shape[0]*arr.shape[1]) >>> brr.sort() >>> brr ...
Duplicate element in python list
14,878,538
9
2013-02-14T15:42:16Z
14,878,621
15
2013-02-14T15:46:00Z
[ "python", "list", "list-comprehension" ]
I have a `list` in Python: ``` l = ['a', 'c', 'e', 'b'] ``` I want to duplicate each element immediately next to the original. ``` ll = ['a', 'a', 'c', 'c', 'e', 'e', 'b', 'b'] ``` The order of the elements should be preserved.
``` >>> l = ['a', 'c', 'e', 'b'] >>> [x for pair in zip(l,l) for x in pair] ['a', 'a', 'c', 'c', 'e', 'e', 'b', 'b'] ``` Or ``` >>> from itertools import repeat >>> [x for item in l for x in repeat(item, 2)] ['a', 'a', 'c', 'c', 'e', 'e', 'b', 'b'] ```
Merge xml files with nested elements without external libraries
14,878,706
11
2013-02-14T15:51:02Z
14,879,370
16
2013-02-14T16:23:46Z
[ "python", "xml", "python-2.7", "elementtree" ]
I am trying to merge multiple XML files together using Python and no external libraries. The XML files have nested elements. **Sample File 1:** ``` <root> <element1>textA</element1> <elements> <nested1>text now</nested1> </elements> </root> ``` **Sample File 2:** ``` <root> <element2>textB</element2> ...
What the code you posted is doing is combining all the elements regardless of whether or not an element with the same tag already exists. So you need to iterate over the elements and manually check and combine them the way you see fit, because it is not a standard way of handling XML files. I can't explain it better th...
Iterate a list of tuples
14,880,192
9
2013-02-14T17:05:31Z
14,880,267
22
2013-02-14T17:09:59Z
[ "python", "list", "iteration", "tuples" ]
I'm looking for a clean way to iterate over a list of tuples where each is a pair like so `[(a, b), (c,d) ...]`. On top of that I would like to alter the tuples in the list. Standard practice is to avoid changing a list while also iterating through it, so what should I do? Here's what I kind of want: ``` for i in ran...
Just replace the tuples in the list; you *can* alter a list while looping over it, as long as you avoid adding or removing elements: ``` for i, (a, b) in enumerate(tuple_list): new_b = some_process(b) tuple_list[i] = (a, new_b) ``` or, if you can summarize the changes to `b` into a function as I did above, us...
Why do some Python functions have an extra set of parenthesis around the argument list?
14,880,406
9
2013-02-14T17:17:48Z
14,880,436
10
2013-02-14T17:18:50Z
[ "python", "arguments", "parentheses" ]
I've seen some Python functions written like this: ``` def get_year((year,prefix,index,suffix)): return year ``` How does that differ (if at all) from other functions without the extra parentheses like this: ``` def do_format(yr,pfx,id,sfx): return "%s %s %s/%s"%(yr, id, pfx, sfx) ``` Or is it just a matter of ...
The first function takes a single tuple argument, whereas the second function takes 4 arguments. You can pass those parameters individually, or as a tuple with `splat` operator, that will unpack the tuple into individual parameters. E.g: ``` # Valid Invocations print do_format(*('2001', '234', '12', '123')) # Tuple ...
Encoding on PostgreSQL, Python, Jinja2
14,881,467
4
2013-02-14T18:21:16Z
14,887,474
7
2013-02-15T02:25:24Z
[ "python", "encoding", "utf-8", "flask", "jinja2" ]
I'm having a problem with encoding in my application and didn't find the solution anywhere on web. Here is the scenario: * PostgreSQL with UTF-8 encoding (`CREATE DATABASE xxxx WITH ENCODING 'UTF8'`) * Python logic also with UTF-8 encoding (`# -*- coding: utf-8 -*-`) * Jinja2 to show my HTML pages. Python and Jinja2 ...
The issue is that [psycopg2 returns *byte strings* by default in Python 2](http://initd.org/psycopg/docs/usage.html#unicode-handling): > When reading data from the database, in Python 2 the strings returned are usually 8 bit `str` objects encoded in the database client encoding So you can either: * Manually decode a...
rpy2 install on windows 7
14,882,477
13
2013-02-14T19:24:15Z
25,630,406
10
2014-09-02T18:57:49Z
[ "python", "windows", "install", "rpy2" ]
I'm trying to install rpy2 on my computer, but I wasn't able to do it. I downloaded the source package and I tryed to install Rpy2 (rpy2-2.3.2) using the command `python setup.py install`. This is the result: ``` running install running build running build_py running build_ext "C:\PROGRA~1\R\R-215~1.2\bin\R" CMD conf...
I just successfully installed rpy2 on Windows 8.1 64bit with the binary installer from <http://www.lfd.uci.edu/~gohlke/pythonlibs/#rpy2>. It is usually much easier to just download a binary instead of trying to compile a package in Windows. Also, you should set `R_HOME` environmental variable (in my case, to `C:\Progr...
How should I establish and manage database connections in a multi-module Python app?
14,883,346
8
2013-02-14T20:20:55Z
14,883,590
7
2013-02-14T20:37:55Z
[ "python", "mysql" ]
We have a Python application with over twenty modules, most of which are shared by several web and console applications. I've never had a clear understanding of the best practice for establishing and managing database connection in multi module Python apps. Consider this example: I have a module defining an object cl...
The best method is to open a connection when you need to do some operations (like getting and/or updating data); manipulate the data; write it back to the database in **one query** (very important for performance), and then close the connection. Opening a connection is a fairly light process. Some pitfalls for perform...
How to calculate moving average in Python 3?
14,884,017
4
2013-02-14T21:05:19Z
14,884,062
13
2013-02-14T21:07:58Z
[ "python", "python-3.x" ]
Let's say I have a list: ``` y = ['1', '2', '3', '4','5','6','7','8','9','10'] ``` I want to create a function that calculates the moving n-day average. So if `n` was 5, I would want my code to calculate the first 1-5, add it and find the average, which would be 3.0, then go on to 2-6, calculate the average, which wo...
There is a great sliding window generator in an old version of the Python docs with [`itertools` examples](http://docs.python.org/release/2.3.5/lib/itertools-example.html): ``` from itertools import islice def window(seq, n=2): "Returns a sliding window (of width n) over data from the iterable" " s -> (s0,s...
Incorrect string value warning when calling stored procedure in python
14,884,358
4
2013-02-14T21:28:16Z
14,884,915
8
2013-02-14T22:04:41Z
[ "python", "mysql", "stored-procedures", "utf-8", "mysql-python" ]
I have a database that has a stored procedure that I call it in my python script. until yesterday there were no problem with it. but yesterday my database server had a problem and restored the database. now I'm getting this warning from the same code: ``` Warning: Incorrect string value: '\xD9\x88\xD8\xB2\xDB\x8...
Problem solved! I added `CHARACTER SET utf8` to my stored procedure's VARCHAR arguments and problem solved: ``` ..., IN `title` VARCHAR(255) CHARSET utf8,... ``` But yet I wonder why before restoring DB there was no problem !!!???
Max/Min value of Dictionary of List
14,884,376
3
2013-02-14T21:29:04Z
14,884,421
8
2013-02-14T21:32:21Z
[ "python" ]
I have a dictionary mapping an id\_ to a list of data values like so: `dic = {id_ : [v1, v2, v3, v4]}`. I'm trying to iterate through every value in the dictionary and retrieve the max/min of a certain index of the list mappings. What I want to do is something like this: ``` maximum = max([data[0], ??) for id_, data ...
You need to use it something like this: ``` maximum = max(data[0] for data in dic.values()) ``` since you are not using your `keys`, simply use `dict.values()` to get just the values.
Django 1.4 Unknown command: 'runserver'
14,885,299
10
2013-02-14T22:31:47Z
14,900,746
18
2013-02-15T18:08:39Z
[ "python", "django", "python-2.7" ]
Something in my python path must have changed because now I cannot run the. ``` python app/manage.py runserver ``` The output I get is ``` Unknown command: 'runserver' Type 'manage.py help' for usage. ``` I've looked at my environment's PYTHONPATH and PATH variables, but I can't figure out why its not running.
I've found the answer to my question. * If you've got an error in your settings, manage.py will swallow the exception and report as if the command does not exist. * This lead me down the path of incorrectly assuming my python path or venv environment was messed up. If you want to diagnose this issue, run... ``` pyth...
What is needed to use gdb 7's support for debugging Python programs?
14,885,328
10
2013-02-14T22:33:55Z
14,905,356
14
2013-02-16T00:01:39Z
[ "python", "debugging", "ubuntu", "gdb", "centos" ]
I'd like to use gdb 7's support for debugging Python "inferior processes". What do I need to be able to do that? For example: * What flags does the inferior Python's configure script need to have been run with? * Does the inferior Python process have to be Python 2.7 or newer (I see that's when the part of the gdb s...
Python seems to need to have been compiled with `--with-pydebug` (on Ubuntu 12.04, package `python-dbg` contains a suitable Python executable, itself called `python-dbg`). The inferior Python does not need to be Python 2.7 -- 2.6 loads the 2.7 gdb extensions successfully (see the debugging session below). At least on U...
How to implement a particle engine
14,885,349
5
2013-02-14T22:35:25Z
14,892,607
12
2013-02-15T10:23:22Z
[ "python", "refactoring", "pygame", "particle-system" ]
So I have made a particle engine for smoke that I'm pretty happy with I think it fits my game pretty well. I now need to implement it into my game and I'm having a little bit of trouble. I was wondering if someone could explain how I would go about using my particle engine in my game. I added the both my codes(for ...
Beware! Long post! ## The particle First, let's take a look at your `Smoke` class. It contains some of the *smoke* behaviour, but also your main loop does. Let's fix that by creating a generic `Particle` class that does nothing but represent a particle: ``` class Particle(): def __init__(self, col, size, *strate...
strip white spaces from file csv
14,885,908
13
2013-02-14T23:24:48Z
17,117,621
16
2013-06-14T21:34:22Z
[ "python", "csv" ]
I need to stripe the white spaces from a csv file that i read import csv ``` aList=[] with open(self.filename, 'r') as f: reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE) for row in reader: aList.append(row) # i need to strip the extra white space from each string in the row return...
There's also the embedded formatting parameter: skipinitialspace (the default is false) <http://docs.python.org/2/library/csv.html#csv-fmt-params> ``` aList=[] with open(self.filename, 'r') as f: reader = csv.reader(f, skipinitialspace=False,delimiter=',', quoting=csv.QUOTE_NONE) for row in reader: aLi...
Python import module from sibling folder
14,886,143
12
2013-02-14T23:48:39Z
14,886,199
9
2013-02-14T23:53:04Z
[ "python", "import", "module", "relative" ]
I have gone through many Python relative import questions but I can't understand the issue/get it to work... My Directory structure is: ``` Driver.py A/ Account.py __init__.py B/ Test.py __init__.py ``` ==================== Driver.py ``` from B import Test ``` ========= Account.py ``` ...
This is happening because `A` and `B` are independent, unrelated, packages as far as Python is concerned. Create a `__init__.py` in the same directory as `Driver.py` and everything should work as expected.
"Unorderable types: int() < str()"
14,886,881
11
2013-02-15T01:08:18Z
14,886,894
17
2013-02-15T01:09:28Z
[ "python", "calculator" ]
Hey guys so I'm trying to make a retirement calculator right now on Python. There's nothing wrong with the syntax but when I run the following program: ``` def main(): print("Let me Retire Financial Calculator") deposit = input("Please input annual deposit in dollars: $") rate = input ("Please input annual...
The issue here is that `input()` returns a string in Python 3.x, so when you do your comparison, you are comparing a string and an integer, which isn't well defined (what if the string is a word, how does one compare a string and a number?) - in this case Python doesn't guess, it throws an error. To fix this, simply c...
How to return array from C++ function to Python using ctypes
14,887,378
10
2013-02-15T02:09:58Z
14,887,649
8
2013-02-15T02:56:40Z
[ "c++", "python", "arrays", "return", "ctypes" ]
I am using ctypes to implement a C++ function in Python. The C++ function should return a pointer to an array. Unfortunately I haven't figured out, how to access the array in Python. I tried numpy.frombuffer, but that was not successful. It just returned an array of arbitrary numbers. Obviously I didn't used it correct...
`function.cpp` returns an int array, while `wrapper.py` tries to interpret them as doubles. Change `ArrayType` to `ctypes.c_int * 10` and it should work. --- It's probably easier to just use [`np.ctypeslib`](http://docs.scipy.org/doc/numpy/reference/routines.ctypeslib.html) instead of `frombuffer` yourself. This shou...
How to return array from C++ function to Python using ctypes
14,887,378
10
2013-02-15T02:09:58Z
14,892,980
16
2013-02-15T10:45:28Z
[ "c++", "python", "arrays", "return", "ctypes" ]
I am using ctypes to implement a C++ function in Python. The C++ function should return a pointer to an array. Unfortunately I haven't figured out, how to access the array in Python. I tried numpy.frombuffer, but that was not successful. It just returned an array of arbitrary numbers. Obviously I didn't used it correct...
Your python code will work after some minor modifications: ``` import ctypes f = ctypes.CDLL('./library.so').function f.restype = ctypes.POINTER(ctypes.c_int * 10) print [i for i in f().contents] # output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ``` Basically there are two changes: 1. remove numpy-related code and `ctypes.c...
python pandas DataFrame subplot in columns and rows
14,888,473
11
2013-02-15T04:54:57Z
17,106,156
9
2013-06-14T10:13:23Z
[ "python", "dataframe", "pandas", "subplot" ]
I would like to produce a subplot from data 4 column DataFrame into 2 rows and 2 columns ``` df =pd.DataFrame(np.random.randn(6,4),index=pd.date_range('1/1/2000',periods=6, freq='1h')) ``` However below will give a 4 row and 1 column plot ``` df.plot(use_index=False, title=f, subplots=True, sharey=True, figsize=(8,...
cplcloud's answer works, but following code will give you a bit more structure so that you can start configuring more if you do not need the loop. ``` fig, axes = plt.subplots(nrows=2, ncols=2) fig.set_figheight(6) fig.set_figwidth(8) df[0].plot(ax=axes[0,0], style='r', label='Series'); axes[0,0].set_title(0) df[1].pl...
Disable console messages in Flask server
14,888,799
25
2013-02-15T05:29:24Z
18,379,764
36
2013-08-22T11:57:07Z
[ "python", "flask" ]
I have a Flask server running in standalone mode (using `app.run()`). But, I don't want any messages in the console, like ``` 127.0.0.1 - - [15/Feb/2013 10:52:22] "GET /index.html HTTP/1.1" 200 - ... ``` How do I disable verbose mode?
You can set set level of the Werkzeug logger to ERROR, in that case only errors are logged: ``` import logging log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) ``` Here are a full working example testet on OSX, Python 2.7.5, Flask 0.10.0: ``` from flask import Flask app = Flask(__name__) import loggi...
Django : <django.utils.functional.__proxy__ object at 0x7feaac2761d0> is not JSON serializable
14,890,263
8
2013-02-15T07:49:45Z
16,003,647
17
2013-04-14T19:55:21Z
[ "python", "django", "serialization" ]
I am getting a problem in django serialization Here is my model for the state ``` class State(models.Model): class Translation(translation.Translation): name = models.CharField(max_length=64) capital = models.ForeignKey('City', related_name="state_capital", null=True) country = models.For...
`django.utils.functional.__proxy__` object is a lazy translation. Django documentation says that calling unicode() with the lazy translation as the argument will generate a Unicode string in the current locale (<https://docs.djangoproject.com/en/dev/ref/unicode/#translated-strings>). When the translation is done, seria...
Installing PocketSphinx on a MAC OS X
14,890,546
6
2013-02-15T08:15:29Z
14,890,599
12
2013-02-15T08:19:30Z
[ "python", "osx", "cmusphinx", "sphinx4" ]
I'm trying to learn pocketsphinx using python, and therefore wanted to install the same on my Mac OSX Lion. However, I'm really not experienced with installing packages and modules in Python, and the documentation on this one is slightly confusing for me. Here's what I've done till now. I downloaded the pocketsphinx 0....
There is a [homebrew formula](https://github.com/mxcl/homebrew/blob/master/Library/Formula/cmu-pocketsphinx.rb) for pocketsphinx, which (just) installed fine on my system (Mountain Lion). Maybe try that? `brew install cmu-pocketsphinx` worked for me...
Passing arguments into os.system
14,892,355
3
2013-02-15T10:11:00Z
14,892,402
7
2013-02-15T10:13:37Z
[ "python", "argparse", "os.system" ]
I need to execute the following command through python. rtl2gds is a tool which reads in 2 parameters: Path to a file and a module name ``` rtl2gds -rtl=/home/users/name/file.v -rtl_top=module_name -syn ``` I am reading in the path to the file and module name from the user through argparse as shown below: ``` parser...
Don't use `os.system()`; `subprocess` is definitely the way to go. Your problem though is that you expect Python to understand that you want to interpolate `args.fileread` into a string. As great as Python is, it is not able to read your mind like that! Use string formatting instead: ``` os.system("rtl2gds -rtl={arg...
How do you load .ui files onto python classes with PySide?
14,892,713
14
2013-02-15T10:29:12Z
14,894,550
18
2013-02-15T12:14:43Z
[ "python", "qt", "user-interface", "pyqt", "pyside" ]
I've used PyQt for quite a while, and the entire time I've used it, there has been a pretty consistent programming pattern. 1. Use Qt Designer to create a .ui file. 2. Create a python class of the same type as the widget you created in the .ui file. 3. When initializing the python class, use uic to dynamically load th...
I'm doing exactly that with PySide. :) You use this <https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8> (original by Sebastian Wiesner was at <https://github.com/lunaryorn/snippets/blob/master/qt4/designer/pyside_dynamic.py> but has disappeared) - which overrides PySide.QtUiTools.QUiLoader and supplies a new `loadU...
Running windows shell commands with python
14,894,993
14
2013-02-15T11:29:43Z
14,898,162
28
2013-02-15T15:41:09Z
[ "python", "windows", "operating-system", "shell" ]
How can we interact with OS shell using Python ? I want to run windows cmd commands via python. How can it be achieved ?
The newer `subprocess.check_output` and similar commands are supposed to replace `os.system`. See [this page](http://docs.python.org/2/library/subprocess.html) for details. While I can't test this on Windows, the following should work: ``` from subprocess import check_output check_output("dir C:", shell=True) ``` `ch...
Insert an element at specific index in a list and return updated list
14,895,599
24
2013-02-15T13:16:03Z
14,895,600
10
2013-02-15T13:16:03Z
[ "python", "list", "python-2.7" ]
I have this: ``` >>> a = [1, 2, 4] >>> print a [1, 2, 4] >>> print a.insert(2, 3) None >>> print a [1, 2, 3, 4] >>> b = a.insert(3, 6) >>> print b None >>> print a [1, 2, 3, 6, 4] >>> ``` Is there anyway I can get the updated list as result, instead of updating the original list in place?
Shortest I got: `b = a[:2] + [3] + a[2:]` ``` >>> >>> a = [1, 2, 4] >>> print a [1, 2, 4] >>> b = a[:2] + [3] + a[2:] >>> print a [1, 2, 4] >>> print b [1, 2, 3, 4] ```
Insert an element at specific index in a list and return updated list
14,895,599
24
2013-02-15T13:16:03Z
14,895,767
19
2013-02-15T13:23:50Z
[ "python", "list", "python-2.7" ]
I have this: ``` >>> a = [1, 2, 4] >>> print a [1, 2, 4] >>> print a.insert(2, 3) None >>> print a [1, 2, 3, 4] >>> b = a.insert(3, 6) >>> print b None >>> print a [1, 2, 3, 6, 4] >>> ``` Is there anyway I can get the updated list as result, instead of updating the original list in place?
`l.insert(index, obj)` doesn't actually return anything, it just updates the list. As ATO said, you can do `b = a[:index] + [obj] + a[index:]`. However, another way is: ``` a = [1, 2, 4] a.insert(2, 3) b = a[:] ```
Django remove unicode in values_list
14,895,981
6
2013-02-15T13:37:44Z
14,896,038
12
2013-02-15T13:40:53Z
[ "python", "django", "django-views", "django-queryset" ]
I did this operation: ``` definitions.objects.values_list('title', flat=True) ``` And it returns these results: ``` [u'accelerate', u'acute', u'bear', u'big'...] ``` You will realize that the results are all in unicode (u'). How do I remove them all so that I get the result: ``` ['accelerate', 'acute', 'bear', 'bi...
If you want to encode in utf8, you can simply do: ``` definitions_list = [definition.encode("utf8") for definition in definitions.objects.values_list('title', flat=True)] ```
Get the inner HTML of a element in lxml
14,896,302
10
2013-02-15T13:56:30Z
14,896,448
18
2013-02-15T14:05:25Z
[ "python", "xpath", "lxml" ]
I am trying to get the HTML content of child node with lxml and xpath in Python. As shown in code below, I want to find the html content of the each of product nodes. Does it have any methods like product.html? ``` productGrids = tree.xpath("//div[@class='name']/parent::*") for product in productGrids: print #html...
``` from lxml import etree print(etree.tostring(root, pretty_print=True)) ``` you may see more examples here: <http://lxml.de/tutorial.html>
matplotlib hooking in to home/back/forward button events
14,896,580
7
2013-02-15T14:12:44Z
15,109,266
8
2013-02-27T10:06:06Z
[ "python", "matplotlib" ]
Does anyone know how to 'get' the 'home', 'back' and 'forward' button events from a matplotlib figure? I need the events to call some of my functions such that my plots behave correctly when those button are pressed, i.e. the default behaviour isn't doing what i need it to do Matplotlib assumes the underlying dataset...
Matplotlib doesn't provide 'home', 'back' or 'forward' button event. To add a callback that will be called with 'home', 'back' or 'forward' button event, a common approach is to subclass a matplotlib backend. But I am not in favor of this approach. I think it has two cons: 1. If you want to use different backends,...
Create multiple columns in pandas aggregation function
14,897,100
7
2013-02-15T14:42:40Z
14,906,226
8
2013-02-16T02:15:53Z
[ "python", "pandas", "time-series" ]
I'd like to create multiple columns while resampling a pandas DataFrame like the built-in ohlc method. ``` def mhl(data): return pandas.Series([np.mean(data),np.max(data),np.min(data)],index = ['mean','high','low']) ts.resample('30Min',how=mhl) ``` Dies with ``` Exception: Must produce aggregated value ``` Any...
You can pass a dictionary of functions to the `resample` method: ``` In [35]: ts Out[35]: 2013-01-01 00:00:00 0 2013-01-01 00:15:00 1 2013-01-01 00:30:00 2 2013-01-01 00:45:00 3 2013-01-01 01:00:00 4 2013-01-01 01:15:00 5 ... 2013-01-01 23:00:00 92 2013-01-01 23:15:00 93 2013-01-01 23:30:...
What causes "no viable alternative at input 'None'" error with Cassandra CQL
14,897,599
9
2013-02-15T15:10:56Z
14,897,898
13
2013-02-15T15:27:42Z
[ "python", "cassandra", "cql" ]
I'm attempting to insert a modified document back to Cassandra DB with a new key. I'm having hard time figuring out what is the issue the error message is pointing at. When looking for others that have had similar problems the answers seem to be related to the keys, and in my case the None is just a value of few of the...
The "no viable alternative" means that the data type for some key doesn't match the schema for that column family column, unfortunately it doesn't plainly say that in the error message. In my case the data type for meta was: ``` map<text,text> ``` for this reason None was considered a bad value at insertion time. I ...
Python multiprocessing, ValueError: I/O operation on closed file
14,899,355
3
2013-02-15T16:46:11Z
14,899,817
7
2013-02-15T17:11:13Z
[ "python", "file", "multiprocessing" ]
I'm having a problem with the Python multiprocessing package. Below is a simple example code that illustrates my problem. ``` import multiprocessing as mp import time def test_file(f): f.write("Testing...\n") print f.name return None if __name__ == "__main__": f = open("test.txt", 'w') proc = mp.Process(ta...
I had similar issues in the past. Not sure whether it is done within the multiprocessing module or whether `open` sets the close-on-exec flag by default but I know for sure that file handles opened in the main process are *closed* in the multiprocessing children. The obvious work around is to pass the filename as a pa...
Displaying better error message than "No JSON object could be decoded"
14,899,506
73
2013-02-15T16:54:12Z
14,899,579
13
2013-02-15T16:58:05Z
[ "python", "json" ]
Python code to load data from some long complicated JSON file: ``` with open(filename, "r") as f: data = json.loads(f.read()) ``` For many types of JSON error (missing delimiters, incorrect backslashes in strings, etc), this prints a nice helpful message containing the line and column number where the JSON error wa...
You wont be able to get python to tell you where the JSON is incorrect. You will need to use a linter online somewhere like [this](http://jsonformatter.curiousconcept.com/) This will show you error in the JSON you are trying to decode.
Displaying better error message than "No JSON object could be decoded"
14,899,506
73
2013-02-15T16:54:12Z
14,956,465
92
2013-02-19T11:33:45Z
[ "python", "json" ]
Python code to load data from some long complicated JSON file: ``` with open(filename, "r") as f: data = json.loads(f.read()) ``` For many types of JSON error (missing delimiters, incorrect backslashes in strings, etc), this prints a nice helpful message containing the line and column number where the JSON error wa...
I've found that the `simplejson` module gives more descriptive errors in many cases where the built-in `json` module is vague. For instance, for the case of having a comma after the last item in a list: ``` json.loads('[1,2,]') .... ValueError: No JSON object could be decoded ``` which is not very descriptive. The sa...
format output data in pandas to_html
14,899,818
3
2013-02-15T17:11:12Z
14,899,978
7
2013-02-15T17:21:21Z
[ "python", "pandas" ]
I use pandas' to\_html to generate output file, when data are written to the file they have many digits after the decimal point. The pandas' to\_html float\_format method can limit the digits, but when I used 'float\_format' as below: ``` DataFormat.to_html(header=True,index=False,na_rep='NaN',float_format='%10.2f') `...
From the `to_html` docs: ``` float_format : one-parameter function, optional formatter function to apply to columns' elements if they are floats default None ``` You need to pass a function. For example: ``` >>> df = pd.DataFrame({"A": [1.0/3]}) >>> df A 0 0.333333 >>> print df.to_html() <table b...
Plotting function that returns complex values using pyplot
14,901,376
3
2013-02-15T18:48:20Z
14,901,655
7
2013-02-15T19:09:19Z
[ "python", "numpy", "matplotlib", "scipy" ]
I found this image on Facebook and wanted to plot it, as I thought it will be a good opportunity to learn something new. ![ love formula ](https://fbcdn-sphotos-c-a.akamaihd.net/hphotos-ak-ash4/482615_550821728272176_1584451064_n.jpg) The code: ``` import numpy as np import scipy.special import pylab x = np.linspac...
``` import matplotlib.pyplot as plt import numpy as np y, x = np.ogrid[-1:2:100j, -1:1:100j] plt.contour(x.ravel(), y.ravel(), x**2 + (y-((x**2)**(1.0/3)))**2, [1]) plt.axis('equal') plt.show() ``` ![enter image description here](http://i.stack.imgur.com/A3pZk.png) --- You can play with the aspect-ratio to make the...
Can PyCharm list all of Python errors in a project?
14,902,181
44
2013-02-15T19:44:51Z
14,902,200
51
2013-02-15T19:46:32Z
[ "python", "python-2.7", "compiler-errors", "pycharm" ]
I use python 2.7 in a virtual environment and PyCharm 2.7 (new build as of feb 07 2013). Whenever I open a python file in it that has unambiguous errors (equivalent to compile errors in other languages, e.g. using undeclared variables, calling non-existing functions), it shows red stripes in the gutter of the file. S...
You can call [Code|Inspect Code](http://www.jetbrains.com/pycharm/webhelp/running-inspections.html) (formerly Analyze|Inspect Code, thanks to @CrackerJack9) to get all errors and warnings and ways to fix them. In result panel you can choose to see only errors (red/yellow button at the left side).
Can PyCharm list all of Python errors in a project?
14,902,181
44
2013-02-15T19:44:51Z
14,902,247
11
2013-02-15T19:49:10Z
[ "python", "python-2.7", "compiler-errors", "pycharm" ]
I use python 2.7 in a virtual environment and PyCharm 2.7 (new build as of feb 07 2013). Whenever I open a python file in it that has unambiguous errors (equivalent to compile errors in other languages, e.g. using undeclared variables, calling non-existing functions), it shows red stripes in the gutter of the file. S...
Yes, run Analyze|Inspect Code and specify Whole project as the scope of analysis.
json.loads allows duplicate keys in a dictionary, overwriting the first value
14,902,299
10
2013-02-15T19:52:40Z
14,902,564
17
2013-02-15T20:10:18Z
[ "python", "json" ]
``` >>> raw_post_data = request.raw_post_data >>> print raw_post_data {"group":{"groupId":"2", "groupName":"GroupName"}, "members":{"1":{"firstName":"fName","lastName":"LName","address":"address"},"1": {"firstName":"f_Name","lastName":"L_Name","address":"_address"}}} >>> create_request = json.loads(raw_post_data) >>> p...
[The rfc 4627 for `application/json` media type](http://tools.ietf.org/html/rfc4627#section-2.2) recommends unique keys but it doesn't forbid them explicitly: > The names within an object SHOULD be unique. From [rfc 2119](http://tools.ietf.org/html/rfc2119): > **SHOULD** This word, or the adjective "RECOMMENDED", me...
What is PasteDeploy and do I need to learn it if Eggs in Python are considered gone?
14,902,732
5
2013-02-15T20:22:20Z
14,905,095
9
2013-02-15T23:31:16Z
[ "python", "pyramid", "egg", "python-3.3" ]
I'm quite new to Python. I've downloaded the Pyramid Framework and have been trying to understand it. It uses many separate tools for its work. For example some `PasteDeploy`. I tried to read [`PasteDeploy`'s manual](http://pythonpaste.org/deploy/) but can't understand anything. There is almost no valuable examples and...
The egg format is absolutely not deprecated and anywhere that you read that is lying to you. There are a lot of issues with Python packaging, but Pyramid embraces the state of the art. Your link discusses goals for the future, but you can't deprecate something that does not yet have a replacement. It will be many year...
How to create a dict with letters as keys in a concise way?
14,902,904
8
2013-02-15T20:34:17Z
14,902,939
15
2013-02-15T20:37:08Z
[ "python", "dictionary" ]
I created an dictionary of the 26 alphabet letters like this: ``` aDict={ "a": 1, "b": 2, "c": 3, "d": 4, etc... } ``` I'm trying make my code better and my question is, is there any shorter way to do this without typing all these numbers out?
You can use [`string.ascii_lowercase`](https://docs.python.org/2/library/string.html#string.ascii_lowercase) and dict comprehension here. ``` In [4]: from string import ascii_lowercase as al ``` For Python 2.7+: ``` In [5]: dic = {x:i for i, x in enumerate(al, 1)} ``` For Python 2.6 or earlier: ``` In [7]: dic = d...
Converting SVG with Embedded CSS to PDF in Python
14,903,233
11
2013-02-15T20:58:39Z
17,912,664
8
2013-07-28T20:41:03Z
[ "python", "svg", "pdf-generation" ]
I'm trying to generate a PDF image from an SVG image using Python. I've tried both [CairoSVG](http://cairosvg.org) and [svglib](http://pypi.python.org/pypi/svglib/). The problem is that in both cases the generated PDFs do not have any of the embedded CSS styles applied. Here is a simple SVG file which should render a ...
(With help from @MonkeyWrench, since he didn't post an answer.) According to the [documentation](http://cairosvg.org/user_documentation/), > CairoSVG can use lxml to parse the SVG file, and tinycss plus cssselect to apply CSS not included in the style attribute of the tags. If these packages are not available, CSS wi...
How can I do a batch insert into an Oracle database using Python?
14,904,033
8
2013-02-15T21:58:37Z
14,905,823
11
2013-02-16T01:07:29Z
[ "python", "oracle", "python-2.7", "cx-oracle", "batch-insert" ]
I have some monthly weather data that I want to insert into an Oracle database table but I want to insert the corresponding records in a batch in order to be more efficient. Can anyone advise as to how I'd go about doing this in Python? For example let's say my table has four fields: a station ID, a date, and two valu...
Here's what I've come up with which appears to work well (but please comment if there's a way to improve this): ``` # build rows for each date and add to a list of rows we'll use to insert as a batch rows = [] numberOfYears = endYear - startYear + 1 for i in range(numberOfYears): for j in range(12): # ma...
In Fabric, how can I check if a Debian or Ubuntu package exists and install it if it does not?
14,904,560
2
2013-02-15T22:38:13Z
14,904,561
9
2013-02-15T22:38:13Z
[ "python", "ubuntu", "debian", "fabric" ]
I required this to quickly install memcached as part of a Fabric script setting up test servers. Figured I'd record it here for future reference.
Pieced this together from this [superuser comment](http://superuser.com/questions/427318/#comment490784_427339) and this [stackoverflow answer](http://stackoverflow.com/a/10439058/1093087). (Note: I'm running as `root` rather than using `sudo`): ``` def package_installed(pkg_name): """ref: http:superuser.com/quest...
NameError: global name 'long' is not defined
14,904,814
6
2013-02-15T23:01:21Z
14,904,834
16
2013-02-15T23:02:53Z
[ "python", "long-integer", "nameerror" ]
I have a Python version 3.3.0 and I am not sure why it does not let me do long for b and m here... I tried to look up the answers on here and but nothing helped...thanks im getting an error saying ``` NameError: global name 'long' is not defined power = long(b) % long(m) ```
In Python 3.x, [use `int` instead of `long`](http://docs.python.org/3.3/whatsnew/3.0.html#integers).
Is there's any python library to output dictionary in beautiful ascii table?
14,906,144
3
2013-02-16T02:00:51Z
14,906,346
8
2013-02-16T02:37:27Z
[ "python", "ascii" ]
I have quite huge dictionary in here, which just repeats all over again, and I'm searching for any code to display that dictionary in some ascii table, which would be outputed to command line. At least to have some generated columns for non-dimentional dictionary, and the rest could go as a key:value in cells, somethin...
you can use [`prettytable`](http://code.google.com/p/prettytable/wiki/Tutorial). ``` t = PrettyTable(['key', 'value']) for key, val in dictionary.items(): t.add_row([key, val]) print t ``` You can also play with [`textwrap`](http://docs.python.org/2/library/textwrap.html) module to split the value on multiple line...
matplotlib: aspect ratio in subplots with various y-axes
14,907,062
5
2013-02-16T04:47:01Z
14,911,939
7
2013-02-16T15:34:07Z
[ "python", "matplotlib" ]
I would like the following code to produce 4 subplots of the same size with a common aspect ratio between the size of x-axis and y-axis set by me. Referring to the below example, I would like all of the subplots look exactly like the first one (upper left). What is wrong right now is that the size of the y-axis is corr...
I can't quite tell what you want from your question. Do you want all of the plots to have the same data limits? If so, use shared axes (I'm using `subplots` here, but you can avoid it if you want to stick to matlab-style code): ``` import matplotlib.pyplot as plt import numpy as np fig, axes = plt.subplots(nrows=2,...
Python Tornado – how can I fix 'URLhandler takes exactly X arguments' error?
14,907,489
4
2013-02-16T06:02:06Z
14,908,972
8
2013-02-16T09:48:47Z
[ "python", "tornado" ]
Here is the error: ``` TypeError: __init__() takes exactly 1 argument (3 given) ERROR:root:Exception in callback <tornado.stack_context._StackContextWrapper object at 0x1017d4470> Traceback (most recent call last): File "/Library/Python/2.7/site-packages/tornado-2.4.1-py2.7.egg/tornado/ioloop.py", line 421, in _run...
@Princess of the Universe is right, but maybe this needs a bit of elaboration. Tornado is going to call `__init__` on `RequestHandler` subclasses with the parameters `application, request, **kwargs`, so you need to allow for that. You can do this: ``` def __init__(self, application, request, **kwargs): self.titl...
How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)
14,908,576
29
2013-02-16T08:49:38Z
14,913,405
51
2013-02-16T18:03:21Z
[ "python", "matplotlib" ]
To remove frame in figure, I write ``` frameon=False ``` works perfect with `pyplot.figure`, but with `matplotlib.Figure` it only removes the gray background, the frame stays . Also, I only want the lines to show, and all the rest of figure be transparent. with pyplot I can do what I want, I want to do it with matpl...
First off, if you're using `savefig`, be aware that it will override the figure's background color when saving unless you specify otherwise (e.g. `fig.savefig('blah.png', transparent=True)`). However, to remove the axes' and figure's background on-screen, you'll need to set both `ax.patch` and `fig.patch` to be invisi...
How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)
14,908,576
29
2013-02-16T08:49:38Z
28,720,127
33
2015-02-25T13:22:29Z
[ "python", "matplotlib" ]
To remove frame in figure, I write ``` frameon=False ``` works perfect with `pyplot.figure`, but with `matplotlib.Figure` it only removes the gray background, the frame stays . Also, I only want the lines to show, and all the rest of figure be transparent. with pyplot I can do what I want, I want to do it with matpl...
`ax.axis('off')`, will as Joe Kington pointed out, remove everything except the plotted line. For those wanting to only remove the frame (border), and keep labels, tickers etc, one can do that by accessing the `spines` object on the axis. Given an axis object `ax`, the following should remove borders on all four sides...
how can I use data posted from ajax in flask?
14,908,864
31
2013-02-16T09:32:47Z
17,082,422
28
2013-06-13T08:20:59Z
[ "jquery", "python", "ajax", "flask" ]
I'm having trouble getting data POSTed from jquery ajax. ``` $('#clickme').click( function() { var data = save_input(); // data data['_sid'] = $survey_id; // survey_id injected from flask data['_uip'] = $user_ip; // user_ip injected from flask, request.remote_addr $.ajax({ type : "POST", ...
Try ``` $.ajax({ type : "POST", url : "{{ url_for('mod.load_ajax') }}", data: JSON.stringify(data, null, '\t'), contentType: 'application/json;charset=UTF-8', success: function(result) { console.log(result); } }); ``` Then from the server, you can refer to the variables in data like t...
Difference between "global" and "import __main__"
14,909,285
6
2013-02-16T10:29:35Z
14,909,332
8
2013-02-16T10:35:11Z
[ "python" ]
I defined three functions that should change a global variable `x`. ``` def changeXto1(): global x x = 1 def changeXto2(): from __main__ import x x = 2 def changeXto3(): import __main__ __main__.x = 3 x = 0 print x changeXto1() print x changeXto2() print x changeXto3() print x ``` It gives ...
> Why doesn't `from __main__ import` work in `changeXto2`, while `import __main__` is working in `changeXto3`? It works fine, it just doesn't do what you want. It copies the name and value into the local namespace instead of having the code access `__main__`'s namespace. > Why do we need a global statement in Python ...
Difference between "global" and "import __main__"
14,909,285
6
2013-02-16T10:29:35Z
14,909,627
7
2013-02-16T11:11:36Z
[ "python" ]
I defined three functions that should change a global variable `x`. ``` def changeXto1(): global x x = 1 def changeXto2(): from __main__ import x x = 2 def changeXto3(): import __main__ __main__.x = 3 x = 0 print x changeXto1() print x changeXto2() print x changeXto3() print x ``` It gives ...
This is related to how Python translate your code to bytecode (the compilation step). When compiling a function, Python treat all variable that are assigned as local variable and perform an optimisation to reduce the number of name lookup it would have to do. Each local variable get assigned an index, and when the fun...
How to specify where a Tkinter window opens?
14,910,858
20
2013-02-16T13:30:49Z
14,910,894
14
2013-02-16T13:35:25Z
[ "python", "python-2.7", "tkinter" ]
How can I tell a Tkinter window where to open, based on screen dimensions? I would like it to open in the middle.
Try this ``` import tkinter as tk def center_window(width=300, height=200): # get screen width and height screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() # calculate position x and y coordinates x = (screen_width/2) - (width/2) y = (screen_height/2) - (heigh...
How to specify where a Tkinter window opens?
14,910,858
20
2013-02-16T13:30:49Z
14,912,644
24
2013-02-16T16:47:26Z
[ "python", "python-2.7", "tkinter" ]
How can I tell a Tkinter window where to open, based on screen dimensions? I would like it to open in the middle.
This answer is based on [Rachel's answer](http://stackoverflow.com/a/14910894/839601). Her code did not work originally, but with some tweaking I was able to fix the mistakes. ``` import tkinter as tk root = tk.Tk() # create a Tk root window w = 800 # width for the Tk root h = 650 # height for the Tk root # get sc...
Parsing \ in command line argument - python 2.7.3
14,912,771
5
2013-02-16T16:58:27Z
14,912,784
8
2013-02-16T16:59:40Z
[ "python", "bash", "parsing", "command-line-arguments" ]
I am calling a python script, `parse_input.py` from bash `parse_input.py` takes a command line argument that has many `'\n'` characters in it. Example input: `$ python parse_input.py "1\n2\n"` ``` import sys import pdb if __name__ == "__main__": assert(len(sys.argv) == 2) data = sys.argv[1] pdb.set_...
Bash doesn't interpret `\n` the way python does, it sees that as two characters. You *can* interpret a literal `\n` (so two characters) as a newline in python by 'decoding' from `string_escape`: ``` data = data.decode('string_escape') ``` Demonstration: ``` >>> literal_backslash_n = '\\n' >>> len(literal_backslash_...
Parsing \ in command line argument - python 2.7.3
14,912,771
5
2013-02-16T16:58:27Z
14,912,803
7
2013-02-16T17:02:04Z
[ "python", "bash", "parsing", "command-line-arguments" ]
I am calling a python script, `parse_input.py` from bash `parse_input.py` takes a command line argument that has many `'\n'` characters in it. Example input: `$ python parse_input.py "1\n2\n"` ``` import sys import pdb if __name__ == "__main__": assert(len(sys.argv) == 2) data = sys.argv[1] pdb.set_...
Bash doesn't interpret escape characters in regular single and double-quoted strings. To get it to interpret (some) escape characters, you can use `$'...'`: ``` Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI ...
How to install win32com module in a virtualenv?
14,913,607
9
2013-02-16T18:24:25Z
24,545,697
17
2014-07-03T05:36:45Z
[ "python", "virtualenv", "pywin32" ]
I have installed both `virtualenv` and `pywin32` on my Windows 7 64-bit laptop, and each of them seems to work, but not with each other. More specifically, if a virtualenv is active, then running `import win32com.client` in a python interactive shell fails with `No module named win32com.client`. The same expression su...
### UPDATE 2016 There is now a version of pywin32 on PyPI that can be installed with pip. It is called `pypiwin32`, and it installs the package using the binary `wheel` format. <https://pypi.python.org/pypi/pypiwin32> ``` pip install pypiwin32 ``` That will work in a virtualenv, or with tox, etc. --- Below this l...
Python: how to distinguish between socket error and timeout?
14,913,880
6
2013-02-16T18:54:23Z
14,913,897
14
2013-02-16T18:56:17Z
[ "python", "sockets", "exception" ]
I'm having the following code: ``` try: while 1: s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.settimeout(5); s.connect((HOST,PORT)) print("before send") #time.sleep(10); #s.sendall('GET / HTTP/1.1\r\nConnection: Keep-Alive\r\nHost: www.google.lt\r\n\r\n') ...
`socket.timeout` is a subclass of `socket.error`. Really it's `socket.timeout`. When you catch a `socket.error` first, you catch a more general case. ``` >>> issubclass(socket.timeout, socket.error) True ``` This code is correct: ``` except socket.timeout: print("timeout error") except socket.error: print("socket ...
How to apply max & min boundaries to a value without using conditional statements
14,914,254
4
2013-02-16T19:30:25Z
14,914,573
8
2013-02-16T20:02:48Z
[ "python" ]
**Problem:** Write a Python function, clip(lo, x, hi) that returns lo if x is less than lo; hi if x is greater than hi; and x otherwise. For this problem, you can assume that lo < hi. Don't use any conditional statements for this problem. Instead, use the built in Python functions min and max. You may wish to read th...
Here is a solution, assuming that lo < hi. ``` def clip(lo, x, hi): return max(lo, min(hi, x)) ``` How it works in each case: * **lo, when x < lo**: *if lo < hi*, then x < hi, so `min(hi, x)` returns `x` and `max(lo, x)` returns `lo`. * **hi, when x > hi**: `min(hi, x)` returns `hi` and *if lo < hi*, `max(lo, hi...
In Python, find out number of differences between two ordered lists
14,914,615
6
2013-02-16T20:08:31Z
14,914,635
13
2013-02-16T20:10:31Z
[ "python", "list" ]
I want to compare two lists of same length ``` a = [1, 3, 5, 7, 9] b = [1, 2, 5, 7, 3] ``` and find out the number of differences `n`, in this case it'll be `n = 2`, and also return an error if the length are not equal. What's the pythonic way of doing this?
The simplest way to do this is to use [the `sum()` built-in](http://docs.python.org/3/library/functions.html#sum) and a [generator expression](http://www.youtube.com/watch?v=pShL9DCSIUw): ``` def differences(a, b): if len(a) != len(b): raise ValueError("Lists of different length.") return sum(i != j fo...
In class object, how to auto update attributes?
14,916,284
6
2013-02-16T23:26:54Z
14,916,491
10
2013-02-16T23:53:18Z
[ "python", "class", "attributes" ]
I have a class which has multiple attributes that are related, for example: ``` class SomeClass: def __init__(self, n=0): self.list = range(n) self.listsquare = [ x**2 for x in self.a ] ``` If I make an object normally that would no problem, with ``` a = SomeClass(10) ``` I will get 2 lists, `...
if updating one property due to an update on another property is what you're looking for (instead of recomputing the value of the downstream property on access) use property setters: ``` class SomeClass(object): def __init__(self, n): self.list = range(0, n) @property def list(self): retur...
Reshaping dataframes in pandas based on column labels
14,916,358
9
2013-02-16T23:37:04Z
14,917,572
11
2013-02-17T03:05:57Z
[ "python", "numpy", "pandas", "scipy", "multi-index" ]
What is the best way to reshape the following dataframe in pandas? This DataFrame `df` has `x,y` values for each sample (`s1` and `s2` in this case) and looks like this: ``` In [23]: df = pandas.DataFrame({"s1_x": scipy.randn(10), "s1_y": scipy.randn(10), "s2_x": scipy.randn(10), "s2_y": scipy.randn(10)}) In [24]: df ...
I'm assuming you already have the DataFrame. In which case you can just turn the columns into a MultiIndex and use stack then reset\_index. Note that you'll then have to rename and reorder the columns and sort by sample to get *exactly* what you posted in the question: ``` In [4]: df = pandas.DataFrame({"s1_x": scipy....
How do I stack vectors of different lengths in NumPy?
14,916,407
7
2013-02-16T23:42:41Z
14,916,455
15
2013-02-16T23:48:15Z
[ "python", "numpy" ]
How do I stack column-wise `n` vectors of shape `(x,)` where x could be any number? For example, ``` from numpy import * a = ones((3,)) b = ones((2,)) c = vstack((a,b)) # <-- gives an error c = vstack((a[:,newaxis],b[:,newaxis])) #<-- also gives an error ``` `hstack` works fine but concatenates along the wrong dime...
Short answer: you can't. NumPy does not support jagged arrays natively. Long answer: ``` >>> a = ones((3,)) >>> b = ones((2,)) >>> c = array([a, b]) >>> c array([[ 1. 1. 1.], [ 1. 1.]], dtype=object) ``` gives an array that *may or may not* behave as you expect. E.g. it doesn't support basic methods like `sum` or...
Multiply Adjacent Elements
14,916,957
3
2013-02-17T01:01:08Z
14,917,025
10
2013-02-17T01:13:14Z
[ "python", "tuples", "multiplication" ]
I have a tuple of integers such as `(1, 2, 3, 4, 5)` and I want to produce the tuple `(1*2, 2*3, 3*4, 4*5)` by multiplying adjacent elements. Is it possible to do this with a one-liner?
Short and sweet. Remember that `zip` only runs as long as the shortest input. ``` print tuple(x*y for x,y in zip(t,t[1:])) ```
sum of nested list in Python
14,917,092
4
2013-02-17T01:25:01Z
14,917,111
15
2013-02-17T01:29:07Z
[ "python", "list" ]
I try to sum a list of nested elements e.g, numbers=[1,3,5,6,[7,8]], sum=30 I wrote the following code ``` def nested_sum(L): sum=0 for i in range(len(L)): if (len(L[i])>1): sum=sum+nested_sum(L[i]) else: sum=sum+L[i] return sum ``` The above code gives following error...
You need to use `isinstance` to check whether an element is a list or not. Also, you might want to iterate over the actual list, to make things simpler. ``` def nested_sum(L): total = 0 # don't use `sum` as a variable name for i in L: if isinstance(i, list): # checks if `i` is a list tota...
python - lxml: enforcing a specific order for attributes
14,917,943
4
2013-02-17T04:20:23Z
17,654,556
7
2013-07-15T12:43:42Z
[ "python", "xml", "lxml" ]
I have an XML writing script that outputs XML for a specific 3rd party tool. I've used the original XML as a template to make sure that I'm building all the correct elements, but the final XML does not appear like the original. I write the attributes in the same order, but lxml is writing them in its own order. I'm ...
It looks like lxml serializes attributes in the order you set them: ``` >>> from lxml import etree as ET >>> x = ET.Element("x") >>> x.attrib['a'] = '1' >>> x.attrib['b'] = '2' >>> ET.tostring(x) '<x a="1" b="2"/>' >>> y = ET.Element('y') >>> y.attrib['b'] = '2' >>> y.attrib['a'] = '1' >>> ET.tostring(y) '<y b="2" a="...
python - lxml: enforcing a specific order for attributes
14,917,943
4
2013-02-17T04:20:23Z
22,596,064
9
2014-03-23T19:38:37Z
[ "python", "xml", "lxml" ]
I have an XML writing script that outputs XML for a specific 3rd party tool. I've used the original XML as a template to make sure that I'm building all the correct elements, but the final XML does not appear like the original. I write the attributes in the same order, but lxml is writing them in its own order. I'm ...
# OrderedDict of attributes As of lxml 3.3.3 (perhaps also in earlier versions) you can pass an [OrderedDict](http://docs.python.org/2/library/collections.html#collections.OrderedDict) of attributes to the `lxml.etree.(Sub)Element` constructor and the order will be preserved when using `lxml.etree.tostring(root)`: ``...
Generating postgresql user password
14,918,763
10
2013-02-17T07:01:35Z
14,941,263
14
2013-02-18T16:50:28Z
[ "python", "postgresql" ]
I tried to generate password for `postgres` using `hashlib` from Python. ``` >>> import hashlib >>> hashlib.md5("psql123").hexdigest() 2636d1ddc54901f98d011ffe050c0eb7 ``` But postgresql requires `md5` prefix, so then ``` sudo -u postgres psql ALTER USER postgres PASSWORD 'md52636d1ddc54901f98d011ffe050c0eb7'; ``` ...
Postgres' password hash is very close to what you did, it just needs the username to be included as follows: ``` pghash = "md5" + hashlib.md5(password + username).hexdigest() ``` AFAIK, the postgres docs don't really document this hash format at all, and seem to assume admins will rarely deal with these hashes direc...
How to create sqlalchemy to json
14,920,080
4
2013-02-17T10:22:26Z
14,929,005
15
2013-02-18T03:24:17Z
[ "python", "json", "sqlalchemy" ]
I have a sqlalchemy result ``` labels = session.query( LabelsData, LabelsData.id, LabelsData.name, LabelsData.color ).filter(LabelsData.deleted==False).all() ``` And I want convert this result to JSON, but how I can do it?
It looks like your `LabelsData` object is a SQLAlchemy model. You need to serialize it before dumping it to JSON. Here's a short example that extracts all the columns from your `LabelsData` object and converts the results of your query to JSON: ``` from json import dumps from sqlalchemy.orm import class_mapper def se...
Time difference in seconds from numpy.timedelta64
14,920,903
29
2013-02-17T12:07:10Z
14,920,923
23
2013-02-17T12:09:25Z
[ "python", "datetime", "numpy" ]
How to get time difference in seconds from numpy.timedelta64 variable? ``` time1 = '2012-10-05 04:45:18' time2 = '2012-10-05 04:44:13' dt = np.datetime64(time1) - np.datetime64(time2) print dt 0:01:05 ``` I'd like to convert `dt` to number (int or float) representing time difference in seconds.
You can access it through the "wrapped" datetime item: ``` >>> dt.item().total_seconds() 65.0 ``` *Explanation*: here `dt` is an [array scalar](http://docs.scipy.org/doc/numpy/reference/arrays.scalars.html) in `numpy`, which is a zero rank array or 0-dimensional array. So you will find the `dt` here also has all the ...
Time difference in seconds from numpy.timedelta64
14,920,903
29
2013-02-17T12:07:10Z
14,921,192
43
2013-02-17T12:39:20Z
[ "python", "datetime", "numpy" ]
How to get time difference in seconds from numpy.timedelta64 variable? ``` time1 = '2012-10-05 04:45:18' time2 = '2012-10-05 04:44:13' dt = np.datetime64(time1) - np.datetime64(time2) print dt 0:01:05 ``` I'd like to convert `dt` to number (int or float) representing time difference in seconds.
To get number of seconds from `numpy.timedelta64()` object using [`numpy` 1.7 experimental datetime API](http://docs.scipy.org/doc/numpy-dev/reference/arrays.datetime.html#datetime-and-timedelta-arithmetic): ``` seconds = dt / np.timedelta64(1, 's') ```
python Image PIL to binary Hex
14,921,055
2
2013-02-17T12:24:21Z
14,921,165
9
2013-02-17T12:34:13Z
[ "python", "image", "hex", "python-imaging-library", "binaryfiles" ]
``` from PIL import Image from PIL import ImageDraw from PIL import ImageFont import urllib.request import io import binascii data = urllib.request.urlopen('http://pastebin.ca/raw/2311595').read() r_data = binascii.unhexlify(data) stream = io.BytesIO(r_data) img = Image.open(stream) draw = ImageDraw.Draw(img) font = I...
The `img` object needs to be saved again; write it to another `BytesIO` object: ``` output = io.BytesIO() img.save(output, format='JPEG') ``` then get the written data with the [`.getvalue()` method](http://docs.python.org/3/library/io.html#io.BytesIO.getvalue): ``` hex_data = output.getvalue() ``` The PIL-for-pyth...
Python - Finding word frequencies of list of words in text file
14,921,436
8
2013-02-17T13:11:48Z
14,921,469
9
2013-02-17T13:15:07Z
[ "python", "text", "frequency" ]
I am trying to speed up my project to count word frequencies. I have 360+ text files, and I need to get the total number of words and the number of times each word from another list of words appears. I know how to do this with a single text file. ``` >>> import nltk >>> import os >>> os.chdir("C:\Users\Cameron\Desktop...
[collections.Counter()](http://docs.python.org/2/library/collections.html#collections.Counter) has this covered if I understand your problem. The example from the docs would seem to match your problem. ``` # Tally occurrences of words in a list cnt = Counter() for word in ['red', 'blue', 'red', 'green', 'blue', 'blue...
How can I return a default value for an attribute?
14,923,465
20
2013-02-17T16:48:25Z
14,923,478
10
2013-02-17T16:49:44Z
[ "python", "attributes", "default", "void" ]
I have an object "`myobject`", which might return `None`. If it returns `None`, it won't return an attribute "`id`": ``` a = myobject.id ``` So when myobject is `None`, the stament above results in a AttributeError: ``` AttributeError: 'NoneType' object has no attribute 'id' ``` If `myobject` is None, then I want "...
The simplest way is to use the ternary operator: ``` a = myobject.id if myobject is not None else None ``` The ternary operator returns the first expression if the middle value is true, otherwise it returns the latter expression. Note that you could also do this in another way, using exceptions: ``` try: a = my...
How can I return a default value for an attribute?
14,923,465
20
2013-02-17T16:48:25Z
14,923,509
48
2013-02-17T16:52:59Z
[ "python", "attributes", "default", "void" ]
I have an object "`myobject`", which might return `None`. If it returns `None`, it won't return an attribute "`id`": ``` a = myobject.id ``` So when myobject is `None`, the stament above results in a AttributeError: ``` AttributeError: 'NoneType' object has no attribute 'id' ``` If `myobject` is None, then I want "...
You should use the [`getattr`](http://docs.python.org/2/library/functions.html#getattr) wrapper instead of directly retrieving the value of `id`. ``` a = getattr(myobject, 'id', None) ``` This is like saying "I would like to retrieve the attribute `id` from the object `myobject`, but if there is no attribute `id` ins...
Loading huge XML files and dealing with MemoryError
14,924,200
6
2013-02-17T17:58:47Z
14,924,389
8
2013-02-17T18:18:13Z
[ "python", "xml", "beautifulsoup", "mediawiki" ]
I have a very large XML file (20GB to be exact, and yes, I need all of it). When I attempt to load the file, I receive this error: ``` Python(23358) malloc: *** mmap(size=140736680968192) failed (error code=12) *** error: can't allocate region *** set a breakpoint in malloc_error_break to debug Traceback (most recent ...
Do *not* use BeautifulSoup to try and such a large parse XML file. Use the [ElementTree API](http://docs.python.org/2/library/xml.etree.elementtree.html) instead. Specifically, use the [`iterparse()` function](http://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.iterparse) to parse your fil...
how to choose a random line from a text file
14,924,721
6
2013-02-17T18:48:46Z
14,924,739
12
2013-02-17T18:50:38Z
[ "python", "file", "random", "python-3.3" ]
I am trying to make a lottery program for my school (we have an economic system). My program generates numbers and saves it off into a text file. When I want to "pull" numbers out of my generator I want it to ensure that there is a winner. Q: How do I have Python select a random line out of my text file and give my o...
> How do I have python select a random line out of my text file and give my output as that number? Assuming the file is relatively small, the following is perhaps the easiest way to do it: ``` import random line = random.choice(open('data.txt').readlines()) ```
Default filter in Django model
14,925,090
3
2013-02-17T19:24:35Z
14,925,152
11
2013-02-17T19:30:34Z
[ "python", "django", "model" ]
Is is possible to set a default filter in Django models? Something like: ``` class MyModel(models.Model): timestamp = models.DateTimeField(default=datetime.utcnow) active = models.BooleanField(default=True) class Meta: ordering = ['-timestamp'] filtering = [active=True] ```
You'll have to override the [manager](https://docs.djangoproject.com/en/dev/topics/db/managers/): ``` class MyModelManager(models.Manager): def get_queryset(self): return super(MyModelManager, self).get_queryset().filter(active=True) class MyModel(models.Model): timestamp = models.DateTimeField(defaul...
Upsert and Multi flag in pymongo
14,925,134
6
2013-02-17T19:28:50Z
14,928,445
18
2013-02-18T02:04:08Z
[ "python", "mongodb", "pymongo" ]
I am working on pymongo and this is my document: ``` { "_id": ObjectId("51211b57f07ddaa377000000"), "assignments": { "0": { "0": { "_id": ObjectId("5120dd7400a4453d58a0d0ec") }, "1": { "_id": ObjectId("5120dd8e00a4453d58a0d0ed") }, "2": { "_id": ...
The problem is that the two flags you are passing in aren't `upsert` and `multi`. Based on the documentation of PyMongo's `Collection.update` (found [here](http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update)), it looks like you might be passing in values for the `upse...
Gevent-Websocket Detecting closed connection
14,925,413
6
2013-02-17T19:57:20Z
15,286,867
7
2013-03-08T04:43:31Z
[ "python", "websocket", "bottle", "gevent" ]
I'm using gevent-websocket with bottle.py to serve log-files. How can I detect that the websocket connection is closed from the client-side? At the moment I'm just writing until I get a broken pipe error: ``` return sock.send(data, flags) error: [Errno 32] Broken pipe ``` But I would like to properly detect on the s...
Try testing for `if ws.socket is not None:` before sending data out on the socket.
Add remember headers to json response using json renderer
14,925,652
4
2013-02-17T20:21:56Z
14,926,243
10
2013-02-17T21:25:40Z
[ "python", "json", "authentication", "pyramid" ]
this is the current way I use to add remeber headers to response: ``` @view_config(route_name='login', renderer='json', request_method='POST') def post_login(request): ... ... authentication logic ... headers = remeber(request, login) return HTTPFound(location=came_from, headers=headers) ``` but my js ...
You can set that information on the response directly, as documented in the [Vary Attributes of Rendered Responses section](http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/renderers.html#varying-attributes-of-rendered-responses) of the Pyramid manual: ``` @view_config(route_name='login', renderer='json',...