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
Nested lists python
8,189,169
4
2011-11-18T21:08:43Z
8,189,196
13
2011-11-18T21:10:32Z
[ "python" ]
Can anyone tell me how can I call for indexes in a nested list? Generally I just write: ``` for i in range (list) ``` but what if I have a list with nested lists like that one: ``` Nlist = [[2,2,2],[3,3,3],[4,4,4]...] ``` and I want to go through the indexes of each one separtly? Thank you...
If you really need the indices you can just do what you said again for the inner list: ``` l = [[2,2,2],[3,3,3],[4,4,4] for i1 in xrange(len(l)): for i2 in xrange(len(l[i1])): print i1, i2, l[i1][i2] ``` But it is more pythonic to iterate through the list itself: ``` for inner_l in l: for item in inn...
how to install a library with a different name in waf build system?
8,189,796
2
2011-11-18T22:12:01Z
9,225,136
7
2012-02-10T08:56:17Z
[ "c++", "python", "waf" ]
I want to build a library with waf, but install it under a different name than the target name. It seems you can do ``` bld.shlib(..., install_path='${PREFIX}/lib') ``` but I need to be able to do something like: ``` bld.shlib(..., install_as='${PREFIX}/lib/xyz') ``` Also, bld.install\_as() wont work, as it doesn't...
You can do this: ``` hello_lib = bld.shlib( includes='/usr/include/python', source='a.cpp', target='hello', uselib='BOOST_PYTHON', vnum='0.0.1') hello_lib.env.cxxshlib_PATTERN = '%s.so' ``` This code changes naming pattern for only one task.
Migrating a password field to Django
8,190,642
5
2011-11-18T23:57:47Z
8,854,384
7
2012-01-13T17:05:18Z
[ "python", "mysql", "django", "postgresql", "passwords" ]
I have used Django before (version 1.2) and generally I like it... it is especially good at getting a brand new project up and running quickly. But, in this case, I'm rewriting and existing system and moving it to Python/Django. So, I already have a MySQL database that has a "users" table in it... this table stores the...
Here is what I did to get things working. I created a custom authentication backend. Note: I'm using the email address as the username. Here is my code: ``` from django.db.models import get_model from django.contrib.auth.models import User from hashlib import sha1 class MyUserAuthBackend(object): def check_lega...
Why is an empty function call in python around 15% slower for dynamically compiled python code
8,191,390
7
2011-11-19T02:22:39Z
8,191,559
10
2011-11-19T03:02:31Z
[ "python", "optimization", "dynamic", "python-2.7", "micro-optimization" ]
This is pretty bad micro-optimizing, but I'm just curious. It usually doesn't make a difference in the "real" world. So I'm compiling a function (that does nothing) using `compile()` then calling `exec` on that code and getting a reference to the function I compiled. Then I'm executing it a couple million times and ti...
The *[dis.dis()](http://docs.python.org/library/dis.html#module-dis)* function shows that the code object for each version is identical: ``` aa 1 0 LOAD_CONST 0 (None) 3 RETURN_VALUE localFunc 10 0 LOAD_CONST 0 (None) 3 RETURN_VALUE...
Python 2.7 on App Engine, simplejson vs native json, who's faster?
8,191,945
9
2011-11-19T04:39:33Z
8,191,970
23
2011-11-19T04:45:23Z
[ "python", "json", "google-app-engine", "python-2.7", "simplejson" ]
I've had the understanding that simplejson is much faster than the native json in Python, such as this thread: [`json` and `simplejson` module differences in Python](http://stackoverflow.com/questions/712791/json-and-simplejson-module-differences-in-python) However, I was just thrown for a loop when I read in App Engi...
Before the release of the Python 2.7 runtime, nearly every module included with App Engine, and literally every module you could include yourself were pure python. With the 2.7 release, the `json` module includes speedups written in C, making it much faster than any `simplejson` you can run on App Engine. The benefits...
How to read stdin to a 2d python array of integers?
8,192,379
7
2011-11-19T06:35:19Z
8,192,426
9
2011-11-19T06:45:22Z
[ "python", "arrays", "stdin" ]
I would like to read a 2d array of integers from stdin (or from a file) in Python. Non-working code: ``` from StringIO import StringIO from array import array # fake stdin stdin = StringIO("""1 2 3 4 5 6""") a = array('i') a.fromstring(stdin.read()) ``` This gives me an error: a.fromstring(stdin.read()) ValueError...
Several approaches to accomplish this are available. Below are a few of the possibilities. # Using an `array` ## From a list Replace the last line of code in the question with the following. ``` a.fromlist([int(val) for val in stdin.read().split()]) ``` Now: ``` >>> a array('i', [1, 2, 3, 4, 5, 6]) ``` Con: does...
Get Queue Size in Pika (AMQP Python)
8,192,584
17
2011-11-19T07:24:50Z
13,629,296
24
2012-11-29T15:39:36Z
[ "python", "amqp" ]
Simple question, but Google or the Pika open source code did not help. Is there a way to query the current queue size (item counter) in Pika?
I know that this question is a bit old, but here is an example of doing this with pika. Regarding AMQP and RabbitMQ, if you have already declared the queue, you can re-declare the queue with the [passive flag](http://www.rabbitmq.com/amqp-0-9-1-reference.html#queue.declare.passive) on and keeping all other queue param...
Get Queue Size in Pika (AMQP Python)
8,192,584
17
2011-11-19T07:24:50Z
25,034,168
8
2014-07-30T10:11:25Z
[ "python", "amqp" ]
Simple question, but Google or the Pika open source code did not help. Is there a way to query the current queue size (item counter) in Pika?
Here is how you can get queue length using pika(Considering you are using default user and password on localhost) replace q\_name by your queue name. ``` import pika connection = pika.BlockingConnection() channel = connection.channel() q = channel.queue_declare(q_name) q_len = q.method.message_count ```
Predicting Values with k-Means Clustering Algorithm
8,193,563
2
2011-11-19T10:58:31Z
8,193,849
7
2011-11-19T11:50:34Z
[ "python", "machine-learning", "data-mining", "k-means", "prediction" ]
I'm messing around with machine learning, and I've written a K Means algorithm implementation in Python. It takes a two dimensional data and organises them into clusters. Each data point also has a class value of either a 0 or a 1. What confuses me about the algorithm is how I can then use it to predict some values fo...
To assign a new data point to one of a set of clusters created by k-means, you just ***find the centroid nearest*** to that point. In other words, the same steps you used for the iterative assignment of each point in your original data set to one of k clusters. The only difference here is that the centroids you are us...
Print A Text Through A Printer Using PyQt4
8,193,920
2
2011-11-19T12:04:48Z
8,196,526
9
2011-11-19T19:09:08Z
[ "python", "printing", "pyqt", "pyqt4" ]
I want to preview, and then print, a report through a printer using PyQt4. I tried the following code : ``` printer = QtGui.QPrinter() doc = QtGui.QTextDocument("testing") dialog = QtGui.QPrintDialog(printer) dialog.setModal(True) dialog.setWindowTitle("printerrr") pdialog = QtGui.QPrintPreviewDialog(printer) pdialog...
Basic demo of Qt's print dialogs: ``` from PyQt4 import QtGui, QtCore class Window(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.setWindowTitle(self.tr('Document Printer')) self.editor = QtGui.QTextEdit(self) self.editor.textChanged.connect(self.handleTextCh...
Python topological sort using lists indicating edges
8,194,078
6
2011-11-19T12:31:40Z
8,221,932
8
2011-11-22T04:18:18Z
[ "python", "algorithm" ]
Given lists: [1, 5, 6], [2, 3, 5, 6], [2, 5] etc. (not necessarily in any sorted order) such that if x precedes y in one list, then x precedes y in every list that have x and y, I want to find the list of all elements topologically sorted (so that x precedes y in this list if x precedes y in any other list.) There migh...
Here is a slightly simpler version of @unutbu's networkx solution: ``` import networkx as nx data=[[1, 5, 6], [2, 3, 5, 6], [2, 5], [7]] G = nx.DiGraph() for path in data: G.add_nodes_from(path) G.add_path(path) ts=nx.topological_sort(G) print(ts) # [7, 2, 3, 1, 5, 6] ```
How to subtract two lists in python
8,194,156
6
2011-11-19T12:50:52Z
8,194,178
9
2011-11-19T12:54:10Z
[ "python", "list", "zip", "subtraction" ]
I can't figure out how to make a function in python that can calculate this: ``` List1=[3,5,6] List2=[3,7,2] ``` and the result should be a new list that substracts List2 from List1, `List3=[0,-2,4]`! I know, that I somehow have to use the zip-function. By doing that I get: `([(3,3), (5,7), (6,2)])`, but I don't know...
Try this: ``` [x1 - x2 for (x1, x2) in zip(List1, List2)] ``` This uses `zip`, list comprehensions, and destructuring.
How to subtract two lists in python
8,194,156
6
2011-11-19T12:50:52Z
8,194,568
8
2011-11-19T14:11:13Z
[ "python", "list", "zip", "subtraction" ]
I can't figure out how to make a function in python that can calculate this: ``` List1=[3,5,6] List2=[3,7,2] ``` and the result should be a new list that substracts List2 from List1, `List3=[0,-2,4]`! I know, that I somehow have to use the zip-function. By doing that I get: `([(3,3), (5,7), (6,2)])`, but I don't know...
This solution uses [numpy](http://numpy.scipy.org/). It makes sense only for largish lists as there is some overhead in instantiate the numpy arrays. OTOH, for anything but short lists, this will be blazingly fast. ``` >>> import numpy as np >>> a = [3,5,6] >>> b = [3,7,2] >>> list(np.array(a) - np.array(b)) [0, -2, 4...
Python regex with look behind and alternatives
8,194,470
5
2011-11-19T13:49:39Z
8,194,828
12
2011-11-19T14:56:38Z
[ "python", "regex" ]
I want to have a regular expression that finds the texts that are "wrapped" in between "HEAD or HEADa" and "HEAD. That is, I may have a text that starts with the first word as HEAD or HEADa and the following "heads" are of type HEAD. 1. `HEAD\n\n text...text...HEAD \n\n text....text HEAD\n\n text....text .....` 2. `HE...
Currently, the first part of your regex looks like this: ``` (?<=^\bHEADa|HEAD\b) ``` You have two alternatives; one matches five characters and the other matches four, and that's why you get the error. Some regex flavors will let you do that even though they say they don't allow variable-length lookbehinds, but not ...
repeated numpy subarrays
8,194,739
4
2011-11-19T14:42:07Z
8,195,809
7
2011-11-19T17:22:20Z
[ "python", "numpy" ]
This is a simplification of my question. I have a numpy array: ``` x = np.array([0,1,2,3]) ``` and I have a function: ``` def f(y): return y**2 ``` I can compute f(x). Now suppose I really want to compute f(x) for a repeated x: ``` x = np.array([0,1,2,3,0,1,2,3,0,1,2,3]) ``` Is there a way to do this without cre...
You can (almost) do this by using a few tricks with strides. However, there are some major caveats... ``` import numpy as np x = np.arange(4) numrepeats = 3 y = np.lib.stride_tricks.as_strided(x, (numrepeats,)+x.shape, (0,)+x.strides) print y x[0] = 9 print y ``` So, `y` is now a view into `x` where each row is `x...
In Python how will you multiply individual elements of an array with a floating point or integer number?
8,194,959
19
2011-11-19T15:19:24Z
8,194,982
21
2011-11-19T15:22:46Z
[ "python", "numpy" ]
``` S=[22 33 45.6 21.6 51.8] P=2.45 ``` Here S is an array How will I multiply this and get the value? ``` SP=[53.9 80.85 111.72 52.92 126.91] ```
You can use built-in [`map`](http://docs.python.org/library/functions.html#map) function: ``` result = map(lambda x: x * P, S) ``` or [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) that is a bit more pythonic: ``` result = [x * P for x in S] ```
In Python how will you multiply individual elements of an array with a floating point or integer number?
8,194,959
19
2011-11-19T15:19:24Z
8,194,994
31
2011-11-19T15:25:09Z
[ "python", "numpy" ]
``` S=[22 33 45.6 21.6 51.8] P=2.45 ``` Here S is an array How will I multiply this and get the value? ``` SP=[53.9 80.85 111.72 52.92 126.91] ```
In numpy it is quite simple ``` import numpy as np P=2.45 S=[22, 33, 45.6, 21.6, 51.8] SP = P*np.array(S) ``` I recommend taking a look at the numpy tutorial for an explanation of the full capabilities of numpy's arrays: <http://www.scipy.org/Tentative_NumPy_Tutorial>
In Python how will you multiply individual elements of an array with a floating point or integer number?
8,194,959
19
2011-11-19T15:19:24Z
16,549,635
7
2013-05-14T17:50:36Z
[ "python", "numpy" ]
``` S=[22 33 45.6 21.6 51.8] P=2.45 ``` Here S is an array How will I multiply this and get the value? ``` SP=[53.9 80.85 111.72 52.92 126.91] ```
If you use numpy.multiply ``` S=[22 ,33 ,45.6 ,21.6 ,51.8] P=2.45 multiply(S,P) ``` Gives ``` array([ 53.9 , 80.85, 111.72, 52.92, 126.91]) ``` HTH
How to use GIMP inside a Python script?
8,196,210
8
2011-11-19T18:24:55Z
8,202,224
10
2011-11-20T14:36:17Z
[ "python", "gimp" ]
GIMP enables you to make plugin in in Python, what I would like to do is to call GIMP function like I would do inside one of this plugin but this return the following error since GIMP doesn't find any running GIMP Core to use. ``` LibGimpBase-ERROR **: gimp_wire_write_msg: the wire protocol has not been initialized ab...
GIMP's Python extensions need to be run from inside a GIMP instance. If you want to use GIMPś API from Python you have to run a GIMP without a graphical UI (passing the `-i` parameter from the command line) and running a custom call to the api - with the `-b` command line parameter - so, you can run your python\_fu\_d...
Iterating Queue.Queue items
8,196,254
9
2011-11-19T18:31:10Z
8,196,904
20
2011-11-19T20:06:46Z
[ "python", "queue", "producer-consumer" ]
Does anyone know a pythonic way of iterating over the elements of a `Queue.Queue` *without* removing them from the Queue. I have a producer/consumer-type program where items to be processed are passed by using a `Queue.Queue`, and I want to be able to print what the remaining items are. Any ideas?
You can loop over a copy of the underlying data store: ``` for elem in list(q.queue) ``` Eventhough this bypasses the locks for Queue objects, the list copy is an atomic operation and it should work out fine. If you want to keep the locks, why not pull all the tasks out of the queue, make your list copy, and then pu...
How do you change file association for .py Python files in XP?
8,196,314
4
2011-11-19T18:39:35Z
8,196,691
9
2011-11-19T19:36:04Z
[ "python", "cmd", "windows-xp", "file-association" ]
When I type `assoc .py` I get `.py=py_auto_file`. When I type `ftype py_auto_file` I get `py_auto_file="C:\Program Files\Adobe\Photoshop 7.0\Photoshop.exe" "%1"` How do I make `py_auto_file="C:\Python27"`?
It appears Photoshop may recognize a .py file format and has associated "py\_auto\_file" with the .py extension. You can use the following command to locate the python file types: ``` C:\>ftype | findstr -i python Python.CompiledFile="C:\Python27\python.exe" "%1" %* Python.File="C:\Python27\python.exe" "%1" %* Python...
is there some kind of expression evaluation within list/tuple slicing syntax within Python?
8,196,349
4
2011-11-19T18:44:30Z
8,196,360
7
2011-11-19T18:46:07Z
[ "python", "list", "expression", "tuples", "slice" ]
with numpy arrays, you can use some kind of inequality within the square bracket slicing syntax: ``` >>>arr = numpy.array([1,2,3]) >>>arr[arr>=2] array([2, 3]) ``` is there some kind of equivalent syntax within regular python data structures? I expected to get an error when I tried: ``` >>>lis = [1,2,3] >>>lis[lis >...
In Python 2.x `lis > 2` returns `True`. This is because the operands have different types and there is no comparison operator defined for those two types, so it compares the class names in alphabetical order (`"list" > "int"`). Since `True` is the same as `1`, you get the item at index 1. In Python 3.x this expression...
How To Generate Tcp,ip And Udp Packets In Python?
8,196,886
6
2011-11-19T20:04:47Z
8,201,443
8
2011-11-20T12:21:40Z
[ "python", "network-programming", "network-protocols" ]
Can anyone tell me what is the basic step to generate UDP, TCP and IP Packets. And how can i generate it using Python?
as suggested by jokeysmurf you might craft packets with scapy if you you want to send/receive usual packets then you should use socket or socketserver * <http://docs.python.org/library/socket.html#module-socket> * <http://docs.python.org/library/socketserver.html#module-SocketServer> to send TCP to google's port 80 ...
list.index() function for Python that doesn't throw exception when nothing found
8,197,323
35
2011-11-19T21:03:01Z
8,197,564
42
2011-11-19T21:38:10Z
[ "python" ]
Python's `list.index(x)` throws an exception if the item doesn't exist. Is there a better way to do this that doesn't require handling exceptions?
If you don't care where the matching element is, then use: ``` found = x in somelist ``` If you do care, then use a [LBYL](http://docs.python.org/glossary.html#term-lbyl) style with a [conditional expression](http://docs.python.org/reference/expressions.html#conditional-expressions): ``` i = somelist.index(x) if x i...
Pass date to a variable from the script
8,198,162
4
2011-11-19T23:26:21Z
8,198,170
15
2011-11-19T23:27:57Z
[ "python" ]
I have this script for delete images older than a date. Mi question is if I can pass the date when I call to run the script. Example: The script is called delete\_images.py and delete images older than a data (YYYY-MM-DD) ``` python delete_images.py 2010-12-31 ``` Script (works with a fixed date (xDate variable...
The quick but crude way is to use `sys.argv`. ``` import sys xDate = sys.argv[1] ``` A more robust, extendable way is to use the [argparse](http://docs.python.org/library/argparse.html#module-argparse) module: ``` import argparse parser=argparse.ArgumentParser() parser.add_argument('xDate') args=parser.parse_args()...
Iterable property
8,198,240
6
2011-11-19T23:42:27Z
8,198,300
10
2011-11-19T23:51:48Z
[ "python", "class-properties" ]
I have a library (django-piston) which is expecting some parameters of the class as class properties. I would like to define this value dynamically in a method. So I wanted to do something like: ``` class MyHandler(BaseHandler): @property def fields(self): fields = self.model._meta.fields + self.model....
Your original code looks fine (though I wouldn't have named the local variable the same name as the enclosing function). Note, properties only work in new-style classes, so you will need to inherit from *object*. Also, you need to call the property attribute from an instance. If you need a class attribute, then *prop...
Writing a Python list into a single CSV column
8,199,041
4
2011-11-20T02:37:19Z
8,199,055
10
2011-11-20T02:40:23Z
[ "python", "csv", "writer" ]
I have a list of numbers that I want to put in a single column in a .csv file. The code below writes the values across a single row. How can I change the code so that Python writes the each value on a separate row? Thanks. ``` with open('returns.csv', 'wb') as f: writer = csv.writer(f) ...
``` with open('returns.csv', 'wb') as f: writer = csv.writer(f) for val in daily_returns: writer.writerow([val]) ```
Extracting only characters from a string in Python
8,199,398
14
2011-11-20T04:13:18Z
8,199,422
18
2011-11-20T04:20:42Z
[ "python", "regex", "string" ]
In Python, I want to extract only the characters from a string. Consider I have the following string, ``` input = "{('players',): 24, ('year',): 28, ('money',): 19, ('ipod',): 36, ('case',): 23, ('mini',): 46}" ``` I want the result as, ``` output = "players year money ipod case mini" ``` I tried to split conside...
You could do it with re, but the string split method doesnt take a regex, it takes a string. Heres one way to do it with re: ``` import re word1 = " ".join(re.findall("[a-zA-Z]+", st)) ```
Python title() with apostrophes
8,199,966
19
2011-11-20T06:50:41Z
8,199,981
40
2011-11-20T06:57:14Z
[ "python" ]
Is there a way to use `.title()` to get the correct output from a title with apostrophes? For example: ``` "john's school".title() --> "John'S School" ``` How would I get the correct title here, `"John's School"` ?
If your titles do not contain several whitespace characters in a row (which would be collapsed), you can use [string.capwords()](http://docs.python.org/library/string.html#string.capwords) instead: ``` >>> import string >>> string.capwords("john's school") "John's School" ``` **EDIT:** As Chris Morgan rightfully says...
Python title() with apostrophes
8,199,966
19
2011-11-20T06:50:41Z
8,200,033
10
2011-11-20T07:14:40Z
[ "python" ]
Is there a way to use `.title()` to get the correct output from a title with apostrophes? For example: ``` "john's school".title() --> "John'S School" ``` How would I get the correct title here, `"John's School"` ?
This is difficult in the general case, because some single apostrophes are legitimately followed by an uppercase character, such as Irish names starting with "O'". string.capwords() will work in many cases, but ignores anything in quotes. string.capwords("john's principal says,'no'") will not return the result you may ...
Checking for nan in Cython
8,200,311
6
2011-11-20T08:23:49Z
8,200,381
7
2011-11-20T08:38:00Z
[ "python", "cython" ]
I'm looking for a way to check for NaN values in Cython code. At the moment, I'm using: ``` if value != value: # value is NaN else: # value is not NaN ``` Is there a better way to do this? Is it possible to use a function like Numpy's `isnan`?
Taken from <http://groups.google.com/group/cython-users/msg/1315dd0606389416>, you could do this: ``` cdef extern from "math.h": bint isnan(double x) ``` Then you can just use `isnan(value)`. In newer versions of Cython, it is even easier: ``` from libc.math cimport isnan ```
ndimage missing from scipy
8,200,348
10
2011-11-20T08:32:06Z
8,200,409
15
2011-11-20T08:42:43Z
[ "python", "scipy" ]
I'm trying to use the ndimage library from scipy, but its apparently missing. I have run the tests from both numpy and scipy and the results were OK. I am using numpy 1.6.1 and scipy 0.10.0 installed from the official packages on sourceforge. Running ``` import numpy import scipy import pprint print(scipy.version.ve...
You have to import the module: ``` import scipy.ndimage ```
Convert numbered pinyin to pinyin with tone marks
8,200,349
11
2011-11-20T08:32:07Z
8,200,388
15
2011-11-20T08:39:44Z
[ "python", "bash", "cjk" ]
Are there any scripts, libraries, or programs using `Python`, or `BASH` tools (e.g. `awk`, `perl`, `sed`) which can correctly convert numbered pinyin (e.g. dian4 nao3) to UTF-8 pinyin with tone marks (e.g. diàn​ nǎo)? I have found the following examples, but they require `PHP` or `#C`: * PHP [Convert numbered to ...
I've got some Python 3 code that does this, and it's small enough to just put directly in the answer here. ``` PinyinToneMark = { 0: "aoeiuv\u00fc", 1: "\u0101\u014d\u0113\u012b\u016b\u01d6\u01d6", 2: "\u00e1\u00f3\u00e9\u00ed\u00fa\u01d8\u01d8", 3: "\u01ce\u01d2\u011b\u01d0\u01d4\u01da\u01da", 4: ...
Serving Files with Pyramid
8,201,200
8
2011-11-20T11:28:17Z
8,201,325
7
2011-11-20T11:57:23Z
[ "python", "download", "pylons", "paste", "pyramid" ]
I am serving quite large files from a Pyramid Application I have written. My only problem is download managers don't want to play nice. I can't get resume downloading or segmenting to work with download manager like DownThemAll. ``` size = os.path.getsize(Path + dFile) response = Response(content_type='application/fo...
The web server on the python side needs to support partial downloads, which happens through the [HTTP Accept-Ranges header](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.5). This blog post digs a bit into this matter with an example in python: * [Python sample: Downloading file through HTTP protocol wit...
Serving Files with Pyramid
8,201,200
8
2011-11-20T11:28:17Z
9,545,952
8
2012-03-03T11:57:12Z
[ "python", "download", "pylons", "paste", "pyramid" ]
I am serving quite large files from a Pyramid Application I have written. My only problem is download managers don't want to play nice. I can't get resume downloading or segmenting to work with download manager like DownThemAll. ``` size = os.path.getsize(Path + dFile) response = Response(content_type='application/fo...
Pyramid 1.3 adds new response classes, [FileResponse](http://docs.pylonsproject.org/projects/pyramid/en/latest/api/response.html#pyramid.response.FileResponse) and [FileIter](http://docs.pylonsproject.org/projects/pyramid/en/latest/api/response.html#pyramid.response.FileIter) for manually serving files.
checking if there is a folder with a name that start with a specific string
8,201,295
3
2011-11-20T11:51:27Z
8,201,312
7
2011-11-20T11:55:45Z
[ "python" ]
I'm writing a python script that is supposed to manage my running files. I want to make sure that the source and target folder exist before I run it and I can do this with `os.path.exists`. However, I have a set of foldernames `runner<i>`. Is there a way to check that there is some folders begining with that name? For...
You could do the following: ``` import os if any(x.startswith('runner') for x in os.listdir('/path/to/runners')): print "At least one entry begins with 'runner'" ``` That uses the helpful [`any` function](http://docs.python.org/library/functions.html#any) and a [generator expression](http://en.wikipedia.org/wiki/...
Assigning list to one value in that list
8,201,478
8
2011-11-20T12:31:13Z
8,201,543
13
2011-11-20T12:43:08Z
[ "python" ]
I have a slight problem understanding the behaviour of lists. My exercise question is: *Draw a memory model showing the effect of the following statements:* ``` values = [0, 1, 2] values[1] = values ``` My thinking was that executing these statements will change the list to something like this `[0, [0, 1, 2], 3]` , ...
You've created a recursive data structure. The second element in the list is a reference to the list itself. When you print this out, normally you would expect to see the original list in the second place, as you suggest in your question. However, you aren't inserting a *copy* of the original list, you are inserting a...
How to: Macports select python
8,201,760
16
2011-11-20T13:21:10Z
8,201,825
14
2011-11-20T13:31:56Z
[ "python", "version", "macports", "python-2.7", "python-2.5" ]
When I enter: ``` port select list python ``` This is the result: ``` Available versions for python: none python25 (active) python25-apple python26-apple python27 python27-apple ``` I thought when I use python I would be using version `2.5`. Instead when I enter "python", version 2.7 seems t...
## Why this happens MacPorts installs binaries into `/opt/local` [by default](https://trac.macports.org/wiki/FAQ#defaultprefix). There is also a [preinstalled](http://www.python.org/getit/mac/) python on your Mac. When just typing `python` to start, it will start the preinstalled python version not affected by MacPor...
How to: Macports select python
8,201,760
16
2011-11-20T13:21:10Z
18,056,046
27
2013-08-05T10:33:11Z
[ "python", "version", "macports", "python-2.7", "python-2.5" ]
When I enter: ``` port select list python ``` This is the result: ``` Available versions for python: none python25 (active) python25-apple python26-apple python27 python27-apple ``` I thought when I use python I would be using version `2.5`. Instead when I enter "python", version 2.7 seems t...
Use ``` osx$ port select --list python ``` to list your available Python installations. Then use the "--set" option to "port select" to set the port you wish to use. ``` osx$ sudo port select --set python python27 ```
Python: does it have a argc argument?
8,201,955
42
2011-11-20T13:52:45Z
8,201,975
70
2011-11-20T13:54:54Z
[ "python", "linux", "file-io", "error-handling", "arguments" ]
I have written the same program (open text file and display contents) in C and C++. Now am doing the same in Python (on a Linux machine). In the C programs I used the code if (argc!=2) {//exit program} **Question: What is used in Python to check the number of arguments** ``` #!/usr/bin/python import sys try: in_...
In python a list knows its length, so you can just do `len(sys.argv)` to get the number of elements in `argv`.
Python: does it have a argc argument?
8,201,955
42
2011-11-20T13:52:45Z
8,201,990
9
2011-11-20T13:58:49Z
[ "python", "linux", "file-io", "error-handling", "arguments" ]
I have written the same program (open text file and display contents) in C and C++. Now am doing the same in Python (on a Linux machine). In the C programs I used the code if (argc!=2) {//exit program} **Question: What is used in Python to check the number of arguments** ``` #!/usr/bin/python import sys try: in_...
I often use a quick-n-dirty trick to read a fixed number of arguments from the command-line: ``` [filename] = sys.argv[1:] in_file = open(filename) # Don't need the "r" ``` This will assign the one argument to `filename` and raise an exception if there isn't exactly one argument.
make matplotlib plotting window pop up as the active one
8,202,228
22
2011-11-20T14:36:49Z
16,961,770
12
2013-06-06T12:11:49Z
[ "python", "osx", "matplotlib" ]
I'm working with python and matplotlib on mac os x. When I'm working on many different windows and I have to run a script which produces a plot, the plot window always open behind the active window and is very frustration having to switch between windows for looking at the image. Is it any why to decide the location of...
I was bothered by exactly the same problem. I found finally a solution (in pylab mode, with qt4agg backend): ``` get_current_fig_manager().window.raise_() ``` or ``` fig = gcf() fig.canvas.manager.window.raise_() ``` Regards, Markus
wxPython, Disabling buttons?
8,202,280
3
2011-11-20T14:46:06Z
8,202,371
8
2011-11-20T15:00:50Z
[ "python", "wxpython" ]
I have a list of buttons and I have made a loop to find out what button is pressed, then disable that button on click. Here is the snippet of code: ``` def change(self,event): self.Disable() for i in enumerate(file_pool): self.button_pool.append(wx.Button(self.sizer, -1, i[1], pos=(20, i[0]*...
you can get your object from the event: ``` def change(self, event): myobject = event.GetEventObject() myobject.Disable() ```
Tornado celery integration hacks
8,202,282
10
2011-11-20T14:46:37Z
8,214,009
9
2011-11-21T15:16:15Z
[ "python", "celery", "tornado" ]
Since nobody provided a solution to [this post](http://stackoverflow.com/questions/7934675/invoke-celery-task-from-tornado) plus the fact that I desperately need a workaround, here is my situation and some abstract solutions/ideas for debate. **My stack:** 1. Tornado 2. Celery 3. MongoDB 4. Redis 5. RabbitMQ My prob...
My solution involves polling from tornado to celery: ``` class CeleryHandler(tornado.web.RequestHandlerr): @tornado.web.asynchronous def get(self): task = yourCeleryTask.delay(**kwargs) def check_celery_task(): if task.ready(): self.write({'success':True} ) ...
Tornado celery integration hacks
8,202,282
10
2011-11-20T14:46:37Z
11,714,959
7
2012-07-30T03:07:40Z
[ "python", "celery", "tornado" ]
Since nobody provided a solution to [this post](http://stackoverflow.com/questions/7934675/invoke-celery-task-from-tornado) plus the fact that I desperately need a workaround, here is my situation and some abstract solutions/ideas for debate. **My stack:** 1. Tornado 2. Celery 3. MongoDB 4. Redis 5. RabbitMQ My prob...
Here is our solution to the problem. Since we look for result in several handlers in our application we made the celery lookup a mixin class. This also makes code more readable with the tornado.gen pattern. ``` from functools import partial class CeleryResultMixin(object): """ Adds a callback function which ...
Matplotlib scatterplot; colour as a function of a third variable
8,202,605
66
2011-11-20T15:38:12Z
8,202,986
12
2011-11-20T16:43:33Z
[ "python", "matplotlib", "plot", "scatter" ]
I want to make a scatterplot (using matplotlib) where the points are shaded according to a third variable. I've got very close with this: ``` plt.scatter(w, M, c=p, marker='s') ``` where w and M are the datapoints and p is the variable I want to shade with respect to. However I want to do it in greyscale rather tha...
In matplotlib grey colors can be given as a string of a numerical value between 0-1. For example `c = '0.1'` Then you can convert your third variable in a value inside this range and to use it to color your points. In the following example I used the y position of the point as the value that determines the color: ...
Matplotlib scatterplot; colour as a function of a third variable
8,202,605
66
2011-11-20T15:38:12Z
8,204,981
68
2011-11-20T21:43:19Z
[ "python", "matplotlib", "plot", "scatter" ]
I want to make a scatterplot (using matplotlib) where the points are shaded according to a third variable. I've got very close with this: ``` plt.scatter(w, M, c=p, marker='s') ``` where w and M are the datapoints and p is the variable I want to shade with respect to. However I want to do it in greyscale rather tha...
There's no need to manually set the colors. Instead, specify a grayscale colormap... ``` import numpy as np import matplotlib.pyplot as plt # Generate data... x = np.random.random(10) y = np.random.random(10) # Plot... plt.scatter(x, y, c=y, s=500) plt.gray() plt.show() ``` ![enter image description here](http://i...
How do I inspect a Python's class hierarchy?
8,202,949
7
2011-11-20T16:35:38Z
8,202,983
8
2011-11-20T16:42:37Z
[ "python", "class", "inheritance", "pydev", "hierarchy" ]
Assuming I have a class X, how do I check which is the base class/classes, and their base class/classes etc? I'm using Eclipse with PyDev, and for Java for example you could type CTRL + T on a class' name and see the hierarchy, like: ``` java.lang.Object java.lang.Number java.lang.Integer ``` Is it possibl...
Hit f4 with class name highlighted to open hierarchy view.
Difference between int and numbers.Integral in Python
8,203,336
6
2011-11-20T17:36:09Z
8,203,401
8
2011-11-20T17:45:17Z
[ "python" ]
I'm trying to get a deeper understanding in Python's data model and I don't fully understand the following code: ``` >>> x = 1 >>> isinstance(x,int) True >>> isinstance(x,numbers.Integral) True >>> inspect.getmro(int) (<type 'int'>, <type 'object'>) >>> inspect.getmro(numbers.Integral) (<class 'numbers.Integral'>,...
`numbers` defines a hierarchy of abstract classes that define operations possible on numeric types. See [PEP 3141](http://www.python.org/dev/peps/pep-3141/). The difference between `int` and `Integral` is that `int` is a concrete type that supports all the operations `Integral` defines.
argparse store false if unspecified
8,203,622
24
2011-11-20T18:20:18Z
8,203,679
36
2011-11-20T18:31:42Z
[ "python", "command-line-arguments", "argparse" ]
``` parser.add_argument('-auto', action='store_true') ``` How can I store false if `-auto` is unspecified? I can faintly remember that this way, it stores None if unspecified
The `store_true` option automatically creates a default value of *False*. Likewise, `store_false` will default to *True* when the command-line argument is not present. The source for this behavior is succinct and clear: <http://hg.python.org/cpython/file/2.7/Lib/argparse.py#l861> The argparse docs aren't clear on th...
Why does removing the else slow down my code?
8,203,696
23
2011-11-20T18:35:04Z
8,203,734
12
2011-11-20T18:41:03Z
[ "python", "performance", "recursion" ]
Consider the following functions: ``` def fact1(n): if n < 2: return 1 else: return n * fact1(n-1) def fact2(n): if n < 2: return 1 return n * fact2(n-1) ``` They should be equivalent. But there's a performance difference: ``` >>> T(lambda : fact1(1)).repeat(number=10000000) ...
For me, they are virtually the same speed: (Python 2.6.6 on Debian) ``` In [4]: %timeit fact1(1) 10000000 loops, best of 3: 151 ns per loop In [5]: %timeit fact2(1) 10000000 loops, best of 3: 154 ns per loop ``` The byte code is also very similar: ``` In [6]: dis.dis(fact1) 2 0 LOAD_FAST ...
Why does removing the else slow down my code?
8,203,696
23
2011-11-20T18:35:04Z
8,204,063
9
2011-11-20T19:29:38Z
[ "python", "performance", "recursion" ]
Consider the following functions: ``` def fact1(n): if n < 2: return 1 else: return n * fact1(n-1) def fact2(n): if n < 2: return 1 return n * fact2(n-1) ``` They should be equivalent. But there's a performance difference: ``` >>> T(lambda : fact1(1)).repeat(number=10000000) ...
I question the timings. The two functions aren't recursing to themselves. *fact1* and *fact2* both call *fact* which isn't shown. Once that is fixed, the disassembly (in both Py2.6 and Py2.7) shows that both are running the same op codes except for the name of the recursed into function. The choice of name trigger a s...
Why does removing the else slow down my code?
8,203,696
23
2011-11-20T18:35:04Z
8,293,490
12
2011-11-28T08:58:19Z
[ "python", "performance", "recursion" ]
Consider the following functions: ``` def fact1(n): if n < 2: return 1 else: return n * fact1(n-1) def fact2(n): if n < 2: return 1 return n * fact2(n-1) ``` They should be equivalent. But there's a performance difference: ``` >>> T(lambda : fact1(1)).repeat(number=10000000) ...
What is happening here is that `fact2` has a hash conflict with `__name__` in your module globals. That makes the lookup of the global `fact2` ever so slightly slower. ``` >>> [(k, hash(k) % 32) for k in globals().keys() ] [('__builtins__', 8), ('__package__', 15), ('fact2', 25), ('__name__', 25), ('fact1', 26), ('__d...
generate cartesian product of boolean parameter values
8,203,737
2
2011-11-20T18:41:21Z
8,203,749
10
2011-11-20T18:43:14Z
[ "python" ]
``` class Config: def __init__(self, a=False, b=False, c=False, d=False): ... ``` I need to generate all instances of Config with different values for a, b, c, d. They can be True or False. What's the best way to do this?
Use [`itertools.product()`](http://docs.python.org/library/itertools.html#itertools.product): ``` [Config(*x) for x in itertools.product([False, True], repeat=4)] ``` (Note that these are not permutations.)
Python3: What is the difference between keywords and builtins?
8,204,542
11
2011-11-20T20:39:42Z
8,204,559
14
2011-11-20T20:41:32Z
[ "python", "python-3.x" ]
In python 3, ``` >>> import keyword >>> keyword.kwlist ``` and ``` >>> import builtins >>> dir(builtins) ``` are two different lists, yet they have some common values, specifically ``` >>> set(dir(builtins)) & set(keyword.kwlist) {'False', 'True', 'None'} ``` What is the difference of keywords and builtins in pyt...
Keywords are core language constructs handled by the parser. These words are reserved and cannot be used as identifiers: <http://docs.python.org/reference/lexical_analysis.html#keywords> Builtins are a list of commonly used, preloaded functions, constants, types, and exceptions: <http://docs.python.org/library/functio...
Calling 'del' on a list
8,205,102
5
2011-11-20T22:02:22Z
8,205,113
8
2011-11-20T22:04:43Z
[ "python", "list", "del" ]
``` class ToBeDeleted: def __init__(self, value): self.value = val # Whatever... def __del__(self): print self.value l = [ToBeDeleted(i) for i in range(3)] del l ``` This prints `2, 1, 0`. --- * Now, is the order of the deleted elements defined somewhere in specification or is it imple...
Running `del l` will remove any reference to the list, so the symbol *l* will be gone. In contrast, running `del l[:]` removes the contents of the list, leaving *l* as an empty list. The [\_\_del\_\_](http://docs.python.org/reference/datamodel.html#object.__del__) method is what runs when the last reference to an inst...
Parsing FIX protocol in regex?
8,207,711
4
2011-11-21T05:35:59Z
8,902,038
8
2012-01-17T21:34:50Z
[ "python", "regex", "fix" ]
I need to parse a logfiles that contains FIX protocol messages. Each line contains header information (timestamp, logging level, endpoint), followed by a FIX payload. I've used regex to parse the header information into named groups. E.g.: ``` <?P<datetime>\d{2}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}.\d{6}) (?<process_id>\d...
No need to split on "\x01" then regex then filter. If you wanted just tags 34,49 and 56 (MsgSeqNum, SenderCompId and TargetCompId) you could regex: ``` dict(re.findall("(?:^|\x01)(34|49|56)=(.*?)\x01", raw_msg)) ``` Simple regexes like this will work if you know your sender does not have embedded data that could caus...
Split string, ignoring delimiter within quotation marks (python)
8,208,358
9
2011-11-21T07:07:57Z
8,208,869
20
2011-11-21T08:06:42Z
[ "python", "csv" ]
I would like to split a string on a comma, but ignore cases when it is within quotation marks: for example: ``` teststring = '48, "one, two", "2011/11/03"' teststring.split(",") ['48', ' "one', ' two"', ' "2011/11/03"'] ``` and the output I would like is: ``` ['48', ' "one, two"', ' "2011/11/03"'] ``` Is this poss...
The [csv module](http://docs.python.org/library/csv.html#module-csv) will work if you set options to handle this dialect: ``` >>> import csv >>> teststring = '48, "one, two", "2011/11/03"' >>> for line in csv.reader([teststring], skipinitialspace=True): print line ['48', 'one, two', '2011/11/03'] ```
How do I draw a grid onto a plot in Python?
8,209,568
52
2011-11-21T09:18:06Z
8,210,686
83
2011-11-21T11:00:23Z
[ "python", "matplotlib" ]
I just finished writing code to make a plot using [pylab](https://en.wikipedia.org/wiki/Matplotlib#Comparison_with_MATLAB) in Python and now I would like to superimpose a grid of 10x10 onto the scatter plot. How do I do that?
May be you want `pyplot.grid`? ``` x = numpy.arange(0,1,0.05) y = numpy.power(x, 2) fig = plt.figure() ax = fig.gca() ax.set_xticks(numpy.arange(0,1,0.1)) ax.set_yticks(numpy.arange(0,1.,0.1)) plt.scatter(x,y) plt.grid() plt.show() ``` `ax.xaxis.grid` and `ax.yaxis.grid` can control grid lines properties. ![enter i...
How do I draw a grid onto a plot in Python?
8,209,568
52
2011-11-21T09:18:06Z
8,210,731
7
2011-11-21T11:03:52Z
[ "python", "matplotlib" ]
I just finished writing code to make a plot using [pylab](https://en.wikipedia.org/wiki/Matplotlib#Comparison_with_MATLAB) in Python and now I would like to superimpose a grid of 10x10 onto the scatter plot. How do I do that?
The [pylab examples page](http://matplotlib.sourceforge.net/examples/index.html) is a very useful source. The example relevant for your question: <http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/scatter_demo2.py> <http://matplotlib.sourceforge.net/users/screenshots.html#scatter-demo>
Private Constructor in Python
8,212,053
23
2011-11-21T12:48:08Z
8,212,438
9
2011-11-21T13:17:11Z
[ "python", "static", "constructor", "private" ]
I'm new to Python. How do I create a private constructor which should be called only by the static function of the class and not from else where?
> How do I create a private constructor? In essence, **it's impossible** both because python does not use constructors the way you may think it does if you come from other OOP languages and because python does not *enforce* privacy, it just has a specific syntax to suggest that a given method/property *should* be cons...
How to check if a value exists in a dictionary (python)
8,214,932
105
2011-11-21T16:20:47Z
8,214,966
19
2011-11-21T16:22:19Z
[ "python", "dictionary", "find" ]
Hi I have the following dictionary in python: ``` d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'} ``` I need a way to find if a value such as "one" or "two" exists in this dictionary. For example, if I wanted to know if the index "1" existed I would simply have to type: ``` "1" in d ``` And th...
You can use ``` "one" in d.itervalues() ``` to test if `"one"` is among the values of your dictionary.
How to check if a value exists in a dictionary (python)
8,214,932
105
2011-11-21T16:20:47Z
8,214,998
166
2011-11-21T16:24:19Z
[ "python", "dictionary", "find" ]
Hi I have the following dictionary in python: ``` d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'} ``` I need a way to find if a value such as "one" or "two" exists in this dictionary. For example, if I wanted to know if the index "1" existed I would simply have to type: ``` "1" in d ``` And th...
``` >>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'} >>> 'one' in d.values() True ``` Out of curiosity, some comparative timing: ``` >>> T(lambda : 'one' in d.itervalues()).repeat() [0.28107285499572754, 0.29107213020324707, 0.27941107749938965] >>> T(lambda : 'one' in d.values()).repeat() [0....
How to check if a value exists in a dictionary (python)
8,214,932
105
2011-11-21T16:20:47Z
8,215,012
7
2011-11-21T16:25:08Z
[ "python", "dictionary", "find" ]
Hi I have the following dictionary in python: ``` d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'} ``` I need a way to find if a value such as "one" or "two" exists in this dictionary. For example, if I wanted to know if the index "1" existed I would simply have to type: ``` "1" in d ``` And th...
Use dictionary views: ``` if x in d.viewvalues(): dosomething().. ```
SciPy interp1d results are different than MatLab interp1
8,215,419
9
2011-11-21T16:53:27Z
8,217,059
11
2011-11-21T18:59:56Z
[ "python", "matlab", "scipy", "interpolation" ]
I'm converting a MatLab program to Python, and I'm having problems understanding why scipy.interpolate.interp1d is giving different results than MatLab interp1. In MatLab the usage is slightly different: ``` yi = interp1(x,Y,xi,'cubic') ``` SciPy: ``` f = interp1d(x,Y,kind='cubic') yi = f(xi) ``` For a trivial exa...
The underlying interpolation method that `scipy.interpolate.interp1d` and `interp1` are different. Scipy uses the netlib `fitpack` routines, which yields standard, C2 continuous cubic splines. The "cubic" argument in `interp1` uses piecewise cubic hermite interpolating polynomials, which are not C2 continuous. See [her...
Using a context manager with Python assertRaises
8,215,653
5
2011-11-21T17:10:20Z
13,585,289
11
2012-11-27T13:27:52Z
[ "python", "unit-testing" ]
The Python documentation for `unittest` implies that the `assertRaises()` method can be used as a context manager. The code below shows gives a simple example of the unittest from the Python docs. The `assertRaises()` call in the `testsample()` method works fine. Now I'd like to access the exception in when it is rais...
It seems no-one has yet suggested: ``` import unittest # For python < 2.7, do import unittest2 as unittest class Class(object): def should_raise(self): raise ValueError('expected arg') class test_Class(unittest.TestCase): def test_something(self): DUT = Class() with self.assertRaises(...
How to check the size of a float in python?
8,216,088
5
2011-11-21T17:43:45Z
8,216,110
12
2011-11-21T17:45:25Z
[ "python", "numpy" ]
I want to check whether a float is actually 32 or 64bits (and the number of bits of a numpy float array). There should be a built-in, but just didn't find out...
The size of a Python `float` can be requested via [`sys.float_info`](http://docs.python.org/library/sys.html#sys.float_info). I never encountered anything else than 64 bit, though, on many different architectures. The items of a NumPy array might have different size, but you can check their size in bytes by `a.itemsiz...
Django update one field using ModelForm
8,216,353
6
2011-11-21T18:07:01Z
8,216,428
7
2011-11-21T18:12:16Z
[ "python", "django" ]
**How do I update just one field in an instance using ModelForm if the POST request has only that one field as parameter**? ModelField tries to override the fields that were not passed in the POST request with None leading to loss of data. I have a model with +25 fields say ``` class C(models.Model): a = models.C...
You could use a subset of the fields in your ModelForm by specifying those fields as follows: ``` class PartialAuthorForm(ModelForm): class Meta: model = Author fields = ('name', 'title') ``` From the docs: > If you specify fields or exclude when creating a form with ModelForm, > then the fields ...
Django update one field using ModelForm
8,216,353
6
2011-11-21T18:07:01Z
8,228,026
8
2011-11-22T14:00:07Z
[ "python", "django" ]
**How do I update just one field in an instance using ModelForm if the POST request has only that one field as parameter**? ModelField tries to override the fields that were not passed in the POST request with None leading to loss of data. I have a model with +25 fields say ``` class C(models.Model): a = models.C...
Got this figured. What I do is update the request.POST dictionary with values from the instance - so that all unchanged fields are automatically present. This will do it: ``` from django.forms.models import model_to_dict from copy import copy def UPOST(post, obj): '''Updates request's POST dictionary with values ...
How to install standard Python module into Iron Python?
8,216,842
5
2011-11-21T18:44:42Z
8,217,743
7
2011-11-21T19:58:03Z
[ "python", "ironpython" ]
I'm writing some ETL scripts in Iron Python and have found that I could benefit from using the date parser in module `dateutil`. I know I can use my standard python library by pointing Iron Python at the appropriate location. My scripts, however, will likely run on a machine with Iron Python but without plain vanilla P...
IronPython doesn't support eggs (because it [doesn't support zipimport](http://ironpython.codeplex.com/workitem/391)), but if you just place the folder containing the .py files in `site-packages` it should work (as long as it doesn't use a C extension). Eggs are just zip files, so you may have to rename it to get at t...
Terminology: Python and Numpy - `iterable` versus `array_like`
8,216,975
15
2011-11-21T18:52:32Z
8,217,068
16
2011-11-21T19:00:53Z
[ "python", "documentation", "numpy" ]
What is the difference between an `iterable` and an `array_like` object in Python programs which use `Numpy`? Both `iterable` and `array_like` are often seen in Python documentation and they share some similar properties. I understand that in this context an `array_like` object should support `Numpy` type operations ...
The term ["array-like"](http://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays) is indeed only used in NumPy and refers to anything that can be passed as first parameter to `numpy.array()` to create an array. The term ["iterable"](http://docs.python.org/glossary....
Decrypting strings in Python that were encrypted with MCRYPT_RIJNDAEL_256 in PHP
8,217,269
9
2011-11-21T19:19:30Z
8,232,171
16
2011-11-22T18:52:03Z
[ "php", "python", "encryption", "mcrypt" ]
I have a function in PHP that encrypts text as follows: ``` function encrypt($text) { $Key = "MyKey"; return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $Key, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)))); } ``` How do I decrypt ...
To decrypt this form of encryption, you will need to get a version of Rijndael. One can be found [here](http://wiki.birth-online.de/snippets/python/aes-rijndael). Then you will need to simulate the key and text padding used in the PHP Mcrypt module. They add `'\0'` to pad out the text and key to the correct size. They ...
How to get data from command line from within a Python program?
8,217,613
11
2011-11-21T19:46:01Z
8,217,646
13
2011-11-21T19:49:22Z
[ "python", "command-line", "pipe" ]
I want to run a command line program from within a python script and get the output. How do I get the information that is displayed by foo so that I can use it in my script? For example, I call `foo file1` from the command line and it prints out ``` Size: 3KB Name: file1.txt Other stuff: blah ``` How can I get the ...
Use the subprocess module: ``` import subprocess command = ['ls', '-l'] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.IGNORE) text = p.stdout.read() retcode = p.wait() ``` Then you can do whatever you want with variable `text`: regular expression, splitting, etc. The 2nd and 3rd parameters...
change some lowercase letters to uppercase in string
8,217,650
3
2011-11-21T19:49:42Z
8,217,687
10
2011-11-21T19:53:40Z
[ "python", "string", "python-3.x", "uppercase" ]
``` index = [0, 2, 5] s = "I am like stackoverflow-python" for i in index: s = s[i].upper() print(s) IndexError: string index out of range ``` I understand that in the first iteration the string, `s`, become just the first character, an uppercase "I" in this particular case. But, I have tried to do it without...
Strings are immutable in Python, so you need to create a new string object. One way to do it: ``` indices = set([0, 7, 12, 25]) s = "i like stackoverflow and python" print("".join(c.upper() if i in indices else c for i, c in enumerate(s))) ``` printing ``` I like StackOverflow and Python ```
How to give with-statement-like functionality to class?
8,217,968
5
2011-11-21T20:15:25Z
8,218,079
8
2011-11-21T20:25:37Z
[ "python", "concurrency", "with-statement" ]
[I apologize for the inept title; I could not come up with anything better. Suggestions for a better title are welcome.] I want to implement an interface to [HDF5](http://www.hdfgroup.org/HDF5/) files that supports multiprocess-level concurrency through file-locking. The intended environment for this module is a Linux...
objects that can be used in `with` statements are called context managers; and they implement a simple interface. They must provide two methods, an `__enter__` method, which takes no arguments and may return anything (which will be assigned to the variable in the `as` portion), and an `__exit__` method, which takes thr...
How to turn a boolean array into index array in numpy
8,218,032
32
2011-11-21T20:21:52Z
8,218,269
17
2011-11-21T20:41:23Z
[ "python", "arrays", "numpy" ]
Is there an efficient Numpy mechanism to retrieve the integer indexes of locations in an array based on a condition is true as opposed to the Boolean mask array? For example: ``` x=np.array([range(100,1,-1)]) #generate a mask to find all values that are a power of 2 mask=x&(x-1)==0 #This will tell me those values pri...
You should be able to use [`numpy.nonzero()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html) to find this information.
How to turn a boolean array into index array in numpy
8,218,032
32
2011-11-21T20:21:52Z
8,218,361
33
2011-11-21T20:49:05Z
[ "python", "arrays", "numpy" ]
Is there an efficient Numpy mechanism to retrieve the integer indexes of locations in an array based on a condition is true as opposed to the Boolean mask array? For example: ``` x=np.array([range(100,1,-1)]) #generate a mask to find all values that are a power of 2 mask=x&(x-1)==0 #This will tell me those values pri...
Another option: ``` In [13]: numpy.where(mask) Out[13]: (array([36, 68, 84, 92, 96, 98]),) ``` which is the same thing as `numpy.where(mask==True)`.
How to add extra whitespace between section header and a paragraph
8,218,039
15
2011-11-21T20:22:26Z
8,218,320
18
2011-11-21T20:46:15Z
[ "python", "python-sphinx", "restructuredtext" ]
I want to have more space between the header and the paragraph and between the paragraphs. I doesn't want this to be a global setting but I want to use it where and when required. Appreciate any suggestions.
You can use vertical bars at the beginning of lines to produce blank lines in the output. Like this: ``` Heading ------- | | Paragraph with text. ```
scipy: savefig without frames, axes, only content
8,218,608
28
2011-11-21T21:13:47Z
8,218,887
47
2011-11-21T21:38:21Z
[ "python", "image", "numpy", "matplotlib", "scipy" ]
In numpy/scipy I have an image stored in an array. I can display it, I want to save it using `savefig` *without* any borders, axes, labels, titles,... Just pure image, nothing else. I want to avoid packages like `PyPNG` or `scipy.misc.imsave`, they are sometimes problematic (they do not always install well, only basic...
Assuming : ``` import matplotlib.pyplot as plt ``` To make a figure without the frame : ``` fig = plt.figure(frameon=False) fig.set_size_inches(w,h) ``` To make the content fill the whole figure ``` ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) ``` Then draw your image on it : ``` ax.im...
scipy: savefig without frames, axes, only content
8,218,608
28
2011-11-21T21:13:47Z
8,219,171
10
2011-11-21T22:06:00Z
[ "python", "image", "numpy", "matplotlib", "scipy" ]
In numpy/scipy I have an image stored in an array. I can display it, I want to save it using `savefig` *without* any borders, axes, labels, titles,... Just pure image, nothing else. I want to avoid packages like `PyPNG` or `scipy.misc.imsave`, they are sometimes problematic (they do not always install well, only basic...
You can find the bbox of the image inside the axis (using `get_window_extent`), and use the `bbox_inches` parameter to save only that portion of the image: ``` import numpy as np import matplotlib.pyplot as plt data=np.arange(9).reshape((3,3)) fig=plt.figure() ax=fig.add_subplot(1,1,1) plt.axis('off') plt.imshow(data...
scipy: savefig without frames, axes, only content
8,218,608
28
2011-11-21T21:13:47Z
13,707,849
25
2012-12-04T16:51:23Z
[ "python", "image", "numpy", "matplotlib", "scipy" ]
In numpy/scipy I have an image stored in an array. I can display it, I want to save it using `savefig` *without* any borders, axes, labels, titles,... Just pure image, nothing else. I want to avoid packages like `PyPNG` or `scipy.misc.imsave`, they are sometimes problematic (they do not always install well, only basic...
An easier solution seems to be: ``` fig.savefig('out.png', bbox_inches='tight', pad_inches=0) ```
How can I change the cursor shape with PyQt?
8,218,900
10
2011-11-21T21:39:16Z
8,219,324
24
2011-11-21T22:19:17Z
[ "python", "cursor", "pyqt", "pyqt4" ]
I have a simple application that runs a process that can last for several minutes before completing. So I am trying to provide an indicator to the user that it is processing the request, such as changing the cursor to an hourglass. But I cannot quite get it to work right. All of my attempts have resulted in either an ...
I think [QApplication.setOverrideCursor](http://doc.qt.io/qt-4.8/qapplication.html#setOverrideCursor) is what you're looking for: ``` from PyQt4.QtCore import Qt from PyQt4.QtGui import QApplication, QCursor ... QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) # do lengthy process QApplication.restoreOverrideCur...
Keeping the WebSocket connection alive
8,218,936
10
2011-11-21T21:42:25Z
8,228,841
7
2011-11-22T14:56:48Z
[ "javascript", "python", "sockets", "http-headers", "websocket" ]
I'm doing a study on WebSocket protocol and trying to implement a simple ECHO service for now with Python on the backend. It seems to work fine but the connection drops right after being established. Here is my client: ``` <!doctype html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="t...
The connection is closed each time after `handle`. You should rather stay there reading incoming data: ``` # incoming connection def setup(self): print "connection established", self.client_address def handle(self): while 1: try: self.data = self.request.recv(1024).strip() # i...
How could I remove newlines from all quoted pieces of text in a file?
8,219,502
3
2011-11-21T22:36:24Z
8,219,581
7
2011-11-21T22:43:13Z
[ "python", "bash", "command-line", "csv", "text-processing" ]
I have exported a CSV file from a database. Certain fields are longer text chunks, and can contain newlines. What would be the simplest way of removing only newlines from this file that are inside double quotes, but preserving all others? I don't care if it uses a Bash command line one liner or a simple script as long...
Here's a solution in Python: ``` import re pattern = re.compile(r'".*?"', re.DOTALL) print pattern.sub(lambda x: x.group().replace('\n', ''), text) ``` See it working online: [ideone](http://ideone.com/Fbp96)
Difference between binary string, byte string, unicode string and an ordinary string (str)
8,219,706
12
2011-11-21T22:55:13Z
8,219,749
14
2011-11-21T22:59:23Z
[ "python" ]
I'm a little confused. In Python what is the difference between a binary string, byte string, unicode string and a plain old string (str)? I'm using Python 2.6.
It depends on the version on Python you are using. In Python 2.x if you write `'abc'` it has type `str` but this means a byte string. If you want a Unicode string you must write `u'abc'`. In Python 3.x if you write `'abc'` it still has type `str` but now this means that is a string of Unicode characters. If you want ...
How do I check the operating system in Python?
8,220,108
43
2011-11-21T23:40:15Z
8,220,132
11
2011-11-21T23:43:33Z
[ "python", "linux", "operating-system" ]
I want to check the operating system (on the computer where the script runs). I know I can use `os.system('uname -o')` in Linux, but it gives me a message in the console, and I want to write to a variable. It will be okay if the script can tell if it is Mac, Windows or Linux. How can I check it?
You can get a pretty coarse idea of the OS you're using by checking [`sys.platform`](http://docs.python.org/library/sys.html#sys.platform). Once you have that information you can use it to determine if calling something like [`os.uname()`](http://docs.python.org/library/os.html#os.uname) is appropriate to gather more ...
How do I check the operating system in Python?
8,220,108
43
2011-11-21T23:40:15Z
8,220,141
86
2011-11-21T23:45:16Z
[ "python", "linux", "operating-system" ]
I want to check the operating system (on the computer where the script runs). I know I can use `os.system('uname -o')` in Linux, but it gives me a message in the console, and I want to write to a variable. It will be okay if the script can tell if it is Mac, Windows or Linux. How can I check it?
You can use [`sys.platform`](https://docs.python.org/2/library/sys.html#platform): ``` from sys import platform if platform == "linux" or platform == "linux2": # linux elif platform == "darwin": # OS X elif platform == "win32": # Windows... ``` For the valid values, consult [the documentation](https://doc...
Python - How to calculate the elapsed time since X date?
8,220,140
4
2011-11-21T23:45:11Z
8,220,198
9
2011-11-21T23:51:53Z
[ "python", "elapsedtime" ]
I have a database table with articles and each one of this articles have a submitted date. I need to calculate the days and hours since the article have been published in the database, like: ``` This article has been published 4 hours ago. This article has been published 3 days and 4 hours ago. ``` There are already ...
Have a look at the [`datetime` package](http://docs.python.org/library/datetime.html), it has everything you need. when you subtract one datetime from another, you get a `timedelta` object. You can use `total_seconds()` to get the duration in seconds and use division to convert it to hours and days. Then your only job...
Error: 'int' object is not subscriptable
8,220,702
11
2011-11-22T01:01:33Z
8,220,730
9
2011-11-22T01:05:15Z
[ "python" ]
I was trying a simple piece of code, get someone's name and age and let him/her know when they turn 21... not considering negatives and all that, just random. I keep getting this `'int' object is not subscriptable` error. ``` name1 = raw_input("What's your name? ") age1 = raw_input ("how old are you? ") x = 0 int([x[...
The problem is in the line, ``` int([x[age1]]) ``` What you want is ``` x = int(age1) ``` You also need to convert the int to a string for the output... ``` print "Hi, " + name1+ " you will be 21 in: " + str(twentyone) + " years." ``` The complete script looks like, ``` name1 = raw_input("What's your name? ") ag...
Error: 'int' object is not subscriptable
8,220,702
11
2011-11-22T01:01:33Z
8,220,735
11
2011-11-22T01:05:44Z
[ "python" ]
I was trying a simple piece of code, get someone's name and age and let him/her know when they turn 21... not considering negatives and all that, just random. I keep getting this `'int' object is not subscriptable` error. ``` name1 = raw_input("What's your name? ") age1 = raw_input ("how old are you? ") x = 0 int([x[...
When you type `x = 0` that is creating a new `int` variable (name) and assigning a zero to it. When you type `x[age1]` that is trying to access the `age1`'th entry, as if `x` were an array.
parsing json python
8,220,748
8
2011-11-22T01:06:49Z
8,220,804
17
2011-11-22T01:15:31Z
[ "python", "json" ]
How can I iterate through the following json file and if fa="cc.ee" then add a value inside fb? ``` { "pk": 1, "fa": "cc.ee", "fb": { "fc": "", "fd_id": "12345", } }, #!/usr/bin/env python import json,urllib json_data=open("my.json") data = json.load...
JSON objects behave like dictionaries. You can add a value by assigning to the new key like you would for a dictionary: ``` json_string = """ { "pk": 1, "fa": "cc.ee", "fb": { "fc": "", "fd_id": "12345" } }""" import json data = json.loads(json_string) if data["fa"] == "cc.ee": ...
How to use timeit module
8,220,801
161
2011-11-22T01:15:00Z
8,220,890
33
2011-11-22T01:28:22Z
[ "python", "time", "timeit" ]
I understand the concept of what `timeit` does but I am not sure how to implement it in my code. How can I compare two functions, say `insertion_sort` and `tim_sort`, with `timeit`?
I find the easiest way to use timeit is from the command line: Given **test.py**: ``` def InsertionSort(): ... def TimSort(): ... ``` run timeit like this: ``` % python -mtimeit -s'import test' 'test.InsertionSort()' % python -mtimeit -s'import test' 'test.TimSort()' ```
How to use timeit module
8,220,801
161
2011-11-22T01:15:00Z
8,220,943
126
2011-11-22T01:38:10Z
[ "python", "time", "timeit" ]
I understand the concept of what `timeit` does but I am not sure how to implement it in my code. How can I compare two functions, say `insertion_sort` and `tim_sort`, with `timeit`?
The way *[timeit](http://docs.python.org/library/timeit.html#module-timeit)* works is to run setup code once and then make repeated calls to a series of statements. So, if you want to test sorting, some care is required so that one pass at an in-place sort doesn't affect the next pass with already sorted data (that, of...
How to use timeit module
8,220,801
161
2011-11-22T01:15:00Z
8,220,961
137
2011-11-22T01:41:48Z
[ "python", "time", "timeit" ]
I understand the concept of what `timeit` does but I am not sure how to implement it in my code. How can I compare two functions, say `insertion_sort` and `tim_sort`, with `timeit`?
If you want to use `timeit` in an interactive Python session, there are two convenient options: 1. Use the [IPython](http://ipython.org/) shell. It features the convenient `%timeit` special function: ``` In [1]: def f(x): ...: return x*x ...: In [2]: %timeit for x in range(100): f(x) 100...
How to use timeit module
8,220,801
161
2011-11-22T01:15:00Z
24,105,845
63
2014-06-08T11:51:43Z
[ "python", "time", "timeit" ]
I understand the concept of what `timeit` does but I am not sure how to implement it in my code. How can I compare two functions, say `insertion_sort` and `tim_sort`, with `timeit`?
I'll let you in on a secret: the best way to use `timeit` is on the command line. On the command line, `timeit` does proper statistical analysis: it tells you how long the shortest run took. This is good because *all* error in timing is positive. So the shortest time has the least error in it. There's no way to get ne...
How to use timeit module
8,220,801
161
2011-11-22T01:15:00Z
29,512,249
29
2015-04-08T10:33:05Z
[ "python", "time", "timeit" ]
I understand the concept of what `timeit` does but I am not sure how to implement it in my code. How can I compare two functions, say `insertion_sort` and `tim_sort`, with `timeit`?
If you want to compare two blocks of code / functions quickly you could do: ``` import timeit start_time = timeit.default_timer() func1() print(timeit.default_timer() - start_time) start_time = timeit.default_timer() func2() print(timeit.default_timer() - start_time) ```
Limiting Admin Choices Using limit_choices_to
8,221,885
5
2011-11-22T04:09:22Z
8,222,157
10
2011-11-22T04:53:00Z
[ "python", "django" ]
I would like to limit the choices for a ForeignKey in the admin UI using limit\_choices\_to; however, I would like to achieve this without changing the model, since the model is brought in from a library, that I don't have control over. What is the way of dynamically achieving this? Or could I use a field on the admin ...
Django provides an admin hook to modify a foreign keys queryset: [`formfield_for_foreignkey`](http://docs.djangoproject.com/en/1.3/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey) ``` class MyModelAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): ...
how to generate a graph/diagram like Google Analytics's Visitor Flow?
8,222,356
36
2011-11-22T05:23:27Z
8,290,846
55
2011-11-28T02:14:56Z
[ "python", "visualization", "graphviz", "d3.js" ]
I am trying to generate a diagram similar to that presented by the recent Google Analytics "Visitor Flow". These are also known as [Alluvial diagrams](http://en.wikipedia.org/wiki/Alluvial_diagram "similar to this"). I can use a web or non-web based solution, as long as I can run it myself. The data I want to visuali...
I thought this was an interesting question, so I made an example alluvial diagram using d3: <http://nickrabinowitz.com/projects/d3/alluvial/alluvial.html> And, because d3 is so good at animation, and I thought it would look cool, I made an animated version as well: <http://nickrabinowitz.com/projects/d3/alluvial/alluv...
Check if string is upper, lower, or mixed case in Python
8,222,855
34
2011-11-22T06:29:02Z
8,222,878
71
2011-11-22T06:31:59Z
[ "python", "string" ]
I want to classify a list of string in Python depending on whether they are upper case, lower case, or mixed case How can I do this?
There are a number of "is methods" on strings. [`islower()`](https://docs.python.org/library/stdtypes.html#str.islower) and [`isupper()`](https://docs.python.org/library/stdtypes.html#str.isupper) should meet your needs: ``` >>> 'hello'.islower() True >>> [m for m in dir(str) if m.startswith('is')] ['isalnum', 'isalp...
Preventing django from appending "_id" to a foreign key field
8,223,519
22
2011-11-22T07:46:48Z
8,223,745
24
2011-11-22T08:12:30Z
[ "python", "django" ]
In django, if I set a field in a model to a foreign key, `"_id"` is appended to the name of that field. How can this be prevented?
You can set the field's [`db_column`](https://docs.djangoproject.com/en/dev/ref/models/fields/#db-column) attribute to whatever you'd like.