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
How can I use python itertools.groupby() to group a list of strings by their first character?
2,472,001
4
2010-03-18T17:25:27Z
2,472,176
7
2010-03-18T17:48:43Z
[ "python", "string", "itertools" ]
I have a list of strings similar to this list: ``` tags = ('apples', 'apricots', 'oranges', 'pears', 'peaches') ``` How should I go about grouping this list by the first character in each string using itertools.groupby()? How should I supply the 'key' argument required by itertools.groupby()?
You might want to create `dict` afterwards: ``` from itertools import groupby d = {k: list(v) for k, v in groupby(tags, key=lambda x: x[0])} ```
In Sphinx, can I register a bunch of keywords that should always be translated into links?
2,472,364
5
2010-03-18T18:20:29Z
2,472,605
7
2010-03-18T19:01:41Z
[ "python", "python-sphinx" ]
My doc strings have references to other python classes that I've defined. Every time Sphinx encounters one of these classes, I want it to insert a link to the documentation for that other class. Is this possible in Sphinx? Specifically, I have a doc string like: ``` '''This class contains a bunch of Foo objects''' ``...
You can use macros. In my project, I have a header file that contains all "important" classes and global functions and their abbreviation. Two example lines: ``` .. |PostItem| replace:: :class:`PostItem <hklib.PostItem>` .. |PostNotFoundError| replace:: :class:`PostNotFoundError <hklib.PostNotFoundError>` ``` In my ...
Python way to clone a git repository
2,472,552
19
2010-03-18T18:55:14Z
2,472,616
9
2010-03-18T19:04:57Z
[ "python", "git", "module" ]
Is there a Python way without using a subprocess to clone a git repository? I'm up for using any sort of modules you recommend.
There is <http://gitorious.org/git-python/> . Haven’t heard of it before and internally, it relies on having the git executables somewhere; additionally, they might have plenty of bugs. But it could be worth a try. How to clone: ``` import git git.Git().clone("git://gitorious.org/git-python/mainline.git") ``` (Itâ...
Python way to clone a git repository
2,472,552
19
2010-03-18T18:55:14Z
15,388,550
33
2013-03-13T14:47:51Z
[ "python", "git", "module" ]
Is there a Python way without using a subprocess to clone a git repository? I'm up for using any sort of modules you recommend.
Using [GitPython](https://github.com/gitpython-developers/GitPython) will give you a good python interface to Git. For example, after installing it (`pip install gitpython`), for cloning a new repository you can use [clone\_from](http://gitpython.readthedocs.org/en/stable/reference.html?highlight=clone#git.repo.base.R...
"Bootstrap" python script in the Windows shell without .py / .pyw associations
2,472,558
7
2010-03-18T18:56:00Z
2,472,660
9
2010-03-18T19:12:50Z
[ "python", "shell" ]
Sometimes (in customer's PCs) I need a python script to execute in the Windows shell like a .CMD or .BAT, but without having the .py or .pyw extensions associated with PYTHON / PYTHONW. I came out with a pair of 'quick'n dirty' solutions: 1) ``` """ e:\devtool\python\python.exe %0 :: or %PYTHONPATH%\python.exe goto ...
You can try to create a script what is both `python` and `windows shell script`. In this case you can name you file `my_flexible_script.bat` and execute it either directly or via `python ...`. See a content of `pylint.bat` file from [pylint](http://www.logilab.org/cgi-bin/hgwebdir.cgi/pylint/file/f5f084e5267a/bin/pyli...
Checkout/List remote branches in git-python
2,473,035
6
2010-03-18T20:09:24Z
2,473,118
7
2010-03-18T20:23:41Z
[ "python", "git" ]
I don't see an option to checkout or list remote/local branches in this module <http://gitorious.org/git-python/>
After you’ve done ``` from git import Git g = Git() ``` (and possibly some other command to init `g` to the repository you care about) all attribute requests on `g` are more or less transformed into a call of `git attr *args`. Therefore: ``` g.checkout("mybranch") ``` should do what you want. ``` g.branch() ```...
How to make a call to an executable from Python script?
2,473,655
5
2010-03-18T22:06:07Z
2,473,728
8
2010-03-18T22:17:18Z
[ "python", "linux", "executable", "system-calls" ]
I need to execute this script from my Python script. Is it possible? The script generate some outputs with some files being written. How do I access these files? I have tried with subprocess call function but without success. ``` fx@fx-ubuntu:~/Documents/projects/foo$ bin/bar -c somefile.xml -d text.txt -r aString -f...
The simplest way is: ``` import os cmd = 'bin/bar --option --otheroption' os.system(cmd) # returns the exit status ``` You access the files in the usual way, by using `open()`. If you need to do more complicated subprocess management then the [subprocess](http://docs.python.org/library/subprocess.html) module is the...
How to make a call to an executable from Python script?
2,473,655
5
2010-03-18T22:06:07Z
2,474,508
19
2010-03-19T01:47:04Z
[ "python", "linux", "executable", "system-calls" ]
I need to execute this script from my Python script. Is it possible? The script generate some outputs with some files being written. How do I access these files? I have tried with subprocess call function but without success. ``` fx@fx-ubuntu:~/Documents/projects/foo$ bin/bar -c somefile.xml -d text.txt -r aString -f...
For executing the external program, do this: ``` import subprocess args = ("bin/bar", "-c", "somefile.xml", "-d", "text.txt", "-r", "aString", "-f", "anotherString") #Or just: #args = "bin/bar -c somefile.xml -d text.txt -r aString -f anotherString".split() popen = subprocess.Popen(args, stdout=subprocess.PIPE) popen....
Python: speed up removal of every n-th element from list
2,473,710
8
2010-03-18T22:14:01Z
2,474,809
7
2010-03-19T03:27:28Z
[ "python", "performance", "algorithm" ]
I'm trying to solve [this programming riddle](http://www.spoj.pl/problems/ASSIST/) and although the solution (see code below) **works** correctly, it is too slow for succesful submission. * Any pointers as how to make this run faster (removal of every n-th element from a list)? * Or suggestions for a better algorith...
This series is called **[ludic numbers](http://www.research.att.com/~njas/sequences/A003309)** `__delslice__` should be faster than `__setslice__`+`filter` ``` >>> L=[2,3,4,5,6,7,8,9,10,11,12] >>> lucky=[] >>> lucky.append(L[0]) >>> del L[::L[0]] >>> L [3, 5, 7, 9, 11] >>> lucky.append(L[0]) >>> del L[::L[0]] >>> L [...
Is there a way to circumvent Python list.append() becoming progressively slower in a loop as the list grows?
2,473,783
35
2010-03-18T22:30:08Z
2,474,076
12
2010-03-18T23:37:09Z
[ "python", "class", "list", "performance", "append" ]
I have a big file I'm reading from, and convert every few lines to an instance of an Object. Since I'm looping through the file, I stash the instance to a list using list.append(instance), and then continue looping. This is a file that's around ~100MB so it isn't too large, but as the list grows larger, the looping s...
There is nothing to circumvent: **appending to a list is O(1) amortized.** A list (in CPython) is an array at least as long as the list and up to twice as long. If the array isn't full, appending to a list is just as simple as assigning one of the array members (O(1)). Every time the array is full, it is automatically...
Is there a way to circumvent Python list.append() becoming progressively slower in a loop as the list grows?
2,473,783
35
2010-03-18T22:30:08Z
2,480,015
80
2010-03-19T19:20:21Z
[ "python", "class", "list", "performance", "append" ]
I have a big file I'm reading from, and convert every few lines to an instance of an Object. Since I'm looping through the file, I stash the instance to a list using list.append(instance), and then continue looping. This is a file that's around ~100MB so it isn't too large, but as the list grows larger, the looping s...
*The poor performance you observe is caused by a bug in the Python garbage collector. **To resolve this issue, disable garbage collection as you build the list and turn it on after you finish.** You will find that performance approximates the amoritized 0(1) behavior expected of list appending in Python.* (You can als...
Python 3 Gui Development?
2,473,949
17
2010-03-18T23:03:52Z
2,482,691
7
2010-03-20T10:45:23Z
[ "python", "python-3.x" ]
Are there any good gui libraries for python 3 (NOT 2)? I would love to use tkinter but it's widgets are not native and it is extremely ugly in my opinion. I was wondering if there were any other gui libraries for python 3.
PyQt has had [support for Python 3 since version 4.5](http://www.riverbankcomputing.com/news/pyqt-45). The dual license for PyQt may not be suitable for your purposes. Nokia is keen to have Qt bindings for Python freely available for use, including commercial. Negotiating for PyQt to have a freer license didn't work o...
Calculate Matrix Rank using scipy
2,473,983
32
2010-03-18T23:10:19Z
3,356,123
11
2010-07-28T18:24:14Z
[ "python", "matrix", "numpy", "scipy" ]
I'd like to calculate the [mathematical rank](http://en.wikipedia.org/wiki/Rank_%28linear_algebra%29) of a matrix using scipy. The most obvious function `numpy.rank` calculates the dimension of an array (ie. scalars have dimension 0, vectors 1, matrices 2, etc...). I am aware that the `numpy.linalg.lstsq` module has th...
To provide a rough code snippet for people who need to get this done in practice. Feel free to improve. ``` u, s, v = np.linalg.svd(A) rank = np.sum(s > 1e-10) ```
Calculate Matrix Rank using scipy
2,473,983
32
2010-03-18T23:10:19Z
6,900,786
45
2011-08-01T15:32:57Z
[ "python", "matrix", "numpy", "scipy" ]
I'd like to calculate the [mathematical rank](http://en.wikipedia.org/wiki/Rank_%28linear_algebra%29) of a matrix using scipy. The most obvious function `numpy.rank` calculates the dimension of an array (ie. scalars have dimension 0, vectors 1, matrices 2, etc...). I am aware that the `numpy.linalg.lstsq` module has th...
Numpy provides `numpy.linalg.matrix_rank()`: ``` >>> import numpy >>> numpy.__version__ '1.5.1' >>> A = numpy.matrix([[1,3,7],[2,8,3],[7,8,1]]) >>> numpy.linalg.matrix_rank(A) 3 ```
Getting the index of the returned max or min item using max()/min() on a list
2,474,015
121
2010-03-18T23:20:35Z
2,474,030
94
2010-03-18T23:23:08Z
[ "python" ]
I'm using Python's `max` and `min` functions on lists for a minimax algorithm, and I need the index of the value returned by `max()` or `min()`. In other words, I need to know which move produced the max (at a first player's turn) or min (second player) value. ``` for i in range(9): newBoard = currentBoard.newBoar...
``` if isMinLevel: return values.index(min(values)) else: return values.index(max(values)) ```
Getting the index of the returned max or min item using max()/min() on a list
2,474,015
121
2010-03-18T23:20:35Z
2,474,238
175
2010-03-19T00:18:32Z
[ "python" ]
I'm using Python's `max` and `min` functions on lists for a minimax algorithm, and I need the index of the value returned by `max()` or `min()`. In other words, I need to know which move produced the max (at a first player's turn) or min (second player) value. ``` for i in range(9): newBoard = currentBoard.newBoar...
You can find the min/max index and value at the same time if you enumerate the items in the list, but perform min/max on the original values of the list. Like so: ``` import operator min_index, min_value = min(enumerate(values), key=operator.itemgetter(1)) max_index, max_value = max(enumerate(values), key=operator.ite...
Getting the index of the returned max or min item using max()/min() on a list
2,474,015
121
2010-03-18T23:20:35Z
11,825,864
113
2012-08-06T09:43:48Z
[ "python" ]
I'm using Python's `max` and `min` functions on lists for a minimax algorithm, and I need the index of the value returned by `max()` or `min()`. In other words, I need to know which move produced the max (at a first player's turn) or min (second player) value. ``` for i in range(9): newBoard = currentBoard.newBoar...
Say that you have a list `values = [3,6,1,5]`, and need the index of the smallest element, i.e. `index_min = 2` in this case. Avoid the solution with `itemgetter()` presented in the other answers, and use instead ``` index_min = min(xrange(len(values)), key=values.__getitem__) ``` because it doesn't require to `impo...
Getting the index of the returned max or min item using max()/min() on a list
2,474,015
121
2010-03-18T23:20:35Z
13,533,657
52
2012-11-23T17:41:42Z
[ "python" ]
I'm using Python's `max` and `min` functions on lists for a minimax algorithm, and I need the index of the value returned by `max()` or `min()`. In other words, I need to know which move produced the max (at a first player's turn) or min (second player) value. ``` for i in range(9): newBoard = currentBoard.newBoar...
If you want to find the index of max within a list of numbers (which seems your case), then I suggest you use numpy: ``` import numpy as np ind = np.argmax(mylist) ```
Getting the index of the returned max or min item using max()/min() on a list
2,474,015
121
2010-03-18T23:20:35Z
13,989,707
19
2012-12-21T11:53:50Z
[ "python" ]
I'm using Python's `max` and `min` functions on lists for a minimax algorithm, and I need the index of the value returned by `max()` or `min()`. In other words, I need to know which move produced the max (at a first player's turn) or min (second player) value. ``` for i in range(9): newBoard = currentBoard.newBoar...
Possibly a simpler solution would be to turn the array of values into an array of value,index-pairs, and take the max/min of that. This would give the largest/smallest index that has the max/min (i.e. pairs are compared by first comparing the first element, and then comparing the second element if the first ones are th...
Getting the index of the returned max or min item using max()/min() on a list
2,474,015
121
2010-03-18T23:20:35Z
18,678,087
11
2013-09-07T21:30:44Z
[ "python" ]
I'm using Python's `max` and `min` functions on lists for a minimax algorithm, and I need the index of the value returned by `max()` or `min()`. In other words, I need to know which move produced the max (at a first player's turn) or min (second player) value. ``` for i in range(9): newBoard = currentBoard.newBoar...
``` list=[1.1412, 4.3453, 5.8709, 0.1314] list.index(min(list)) ``` Will give you first index of minimum.
Python for a hobbyist programmer ( a few questions)
2,474,224
9
2010-03-19T00:14:23Z
2,474,240
14
2010-03-19T00:18:36Z
[ "python", "networking", "programming-languages", "robust" ]
I'm a hobbyist programmer (only in TI-Basic before now), and after much, much, much debating with myself, I've decided to learn Python. I don't have a ton of free time to teach myself a hundred languages and all programming I do will be for personal use or for distributing to people who need them, so I decided that I n...
> Is python powerful enough to handle > most things? Yes. Period. Study [EveOnline](http://play.eveonline.com/en/home.aspx) game for more information. Look at [pygame](http://www.pygame.org/news.html) framework. Free free to use Google to find more. > Does python handle networking tasks > fairly well? Yes. Look at t...
Precomputed Kernels with LibSVM in Python
2,474,460
6
2010-03-19T01:32:12Z
2,476,353
12
2010-03-19T10:07:27Z
[ "python", "machine-learning", "libsvm" ]
I've been searching the net for ~3 hours but I couldn't find a solution yet. I want to give a precomputed kernel to libsvm and classify a dataset, but: * How can I generate a precomputed kernel? (for example, what is the basic precomputed kernel for [Iris data](http://archive.ics.uci.edu/ml/machine-learning-databases/...
**First of all**, some background to kernels and SVMs... If you want to pre-compute a kernel for `n` vectors (of any dimension), what need to do is calculate the kernel function between each pair of examples. The kernel function takes two vectors and gives a scalar, so you can think of a precomputed kernel as a `nxn` ...
From escaped html -> to regular html? - Python
2,474,971
3
2010-03-19T04:25:24Z
2,474,992
10
2010-03-19T04:31:55Z
[ "python", "html", "escaping", "beautifulsoup", "lxml" ]
I used BeautifulSoup to handle XML files that I have collected through a REST API. The responses contain HTML code, but BeautifulSoup escapes all the HTML tags so it can be displayed nicely. Unfortunately I need the HTML code. --- How would I go on about transforming the escaped HTML into proper markup? --- Help ...
I think you want [xml.sax.saxutils.unescape](http://docs.python.org/library/xml.sax.utils.html?highlight=xml#xml.sax.saxutils.unescape) from the Python standard library. E.g.: ``` >>> from xml.sax import saxutils as su >>> s = '&lt;foo&gt;bar&lt;/foo&gt;' >>> su.unescape(s) '<foo>bar</foo>' ```
Python | How to append elements to a list randomly
2,475,518
5
2010-03-19T07:03:46Z
2,475,536
10
2010-03-19T07:08:59Z
[ "python" ]
Is there a way to append elements to a list randomly, built in function ex: ``` def random_append(): lst = ['a'] lst.append('b') lst.append('c') lst.append('d') lst.append('e') return print lst ``` this will out put `['a', 'b', 'c', 'd', 'e']` But I want it to add elements randomly and...
If there is supposed to be exactly one of each item ``` >>> from random import randint >>> a=[] >>> for x in "abcde": ... a.insert(randint(0,len(a)),x) ... >>> a ['b', 'a', 'd', 'c', 'e'] ``` If you are allowing duplicates (as the output indicates) ``` >>> from random import choice >>> a=[choice("abcde") for x in ...
writing 'bits' to c++ file streams
2,476,748
10
2010-03-19T11:18:23Z
2,476,806
13
2010-03-19T11:29:24Z
[ "c#", "java", "c++", "python", "bit-fiddling" ]
How can i write 'one bit' into a file stream or file structure each time? is it possible to write to a queue and then flush it ? is it possible with c# or java? this was needed when i try to implement an instance of Huffman codding. i can't write bits into files. so write them to a bitset and then (when compression was...
Buffering the individual bits until you've accumulated a whole byte seems like a good idea: ``` byte b; int s; void WriteBit(bool x) { b |= (x ? 1 : 0) << s; s++; if (s == 8) { WriteByte(b); b = 0; s = 0; } } ``` You just have to deal with the case when the number of bits...
writing 'bits' to c++ file streams
2,476,748
10
2010-03-19T11:18:23Z
2,477,696
8
2010-03-19T13:39:06Z
[ "c#", "java", "c++", "python", "bit-fiddling" ]
How can i write 'one bit' into a file stream or file structure each time? is it possible to write to a queue and then flush it ? is it possible with c# or java? this was needed when i try to implement an instance of Huffman codding. i can't write bits into files. so write them to a bitset and then (when compression was...
You can use [`boost::dynamic_bitset`](http://www.boost.org/doc/libs/release/libs/dynamic_bitset/dynamic_bitset.html) along with [`std::ostream_iterator`](http://en.cppreference.com/w/cpp/iterator/ostream_iterator) to achieve the desired result in a concise manner: ``` #include <fstream> #include <iterator> #include <b...
pip requirements.txt with alternative index
2,477,117
14
2010-03-19T12:17:22Z
2,477,610
20
2010-03-19T13:27:47Z
[ "python", "pip", "pypi" ]
I want to put all the requirements of a repoze Zope2 install in a pip [requirements file](http://pip.readthedocs.org/en/1.1/requirements.html#the-requirements-file-format). Most of the repoze packages don't seem to be on PyPi, but there's an alternative PyPi index for them [here](http://dist.repoze.org/zope2/2.10/simpl...
`requirements.txt`: ``` -i http://dist.repoze.org/zope2/2.10/simple zopelib ``` Example: ``` $ pip install -r requirements.txt ... Successfully installed zopelib ```
How do I parse a VCard to a Python dictionary?
2,478,027
5
2010-03-19T14:30:06Z
2,478,639
9
2010-03-19T15:47:07Z
[ "python", "vcard", "vcf" ]
I'm trying to figure out how to parse a VCard to a Python dictionary using [VObject](http://vobject.skyhouseconsulting.com/). ``` vobj=vobject.readOne(string) print vobj.behavior.knownChildren ``` This is all I get: ``` {'CATEGORIES': (0, None, None), 'ADR': (0, None, None), 'UID': (0, None, None), 'PHOTO': (0, None...
You don't want to look at the behavior, you want to look at `vobj` itself. The behavior is a data structure describing what children are required/expected, and how to translate those children into appropriate Python data structures. The `vobj` object is a vobject Component. Its contents attribute is a dictionary of vo...
Django/PIL Error - Caught an exception while rendering: The _imagingft C module is not installed
2,478,123
7
2010-03-19T14:43:28Z
5,047,537
9
2011-02-18T23:09:53Z
[ "python", "django", "osx", "python-imaging-library" ]
I'm trying to run a webapp/site on my machine, it's running on OSX 10.6.2 and I'm having some problems: ``` Caught an exeption while rending: The _imagingft C module is not installed ``` Doing import \_imagingft in python gives me this: ``` >>> import _imagingft Traceback (most recent call last): File "<stdin>", li...
Before (re)installing PIL add the following sysmlinks to enable freetype on Mac 10.6 Snow Leopard: ``` ln -s /usr/X11/include/freetype2 /usr/local/include/ ln -s /usr/X11/include/ft2build.h /usr/local/include/ ln -s /usr/X11/lib/libfreetype.6.dylib /usr/local/lib/ ln -s /usr/X11/lib/libfreetype.6.dylib /usr/local/lib/...
Python: Check if all dictionaries in list are empty
2,479,472
8
2010-03-19T17:54:44Z
2,479,487
19
2010-03-19T17:57:08Z
[ "python" ]
I have a list of dictionaries. I need to check if all the dictionaries in that list are empty. I am looking for a simple statement that will do it in one line. Is there a single line way to do the following (not including the print)? ``` l = [{},{},{}] # this list is generated elsewhere... all_empty = True for i in l...
``` all(not d for d in l) ```
Python: Check if all dictionaries in list are empty
2,479,472
8
2010-03-19T17:54:44Z
2,479,501
10
2010-03-19T18:00:09Z
[ "python" ]
I have a list of dictionaries. I need to check if all the dictionaries in that list are empty. I am looking for a simple statement that will do it in one line. Is there a single line way to do the following (not including the print)? ``` l = [{},{},{}] # this list is generated elsewhere... all_empty = True for i in l...
`not any(d for d in l)` is equivalent by [De Morgan's Law](http://en.wikipedia.org/wiki/De_Morgan%27s_laws) to `all(not d for d in l)`, but applies just one `not` operator. The short-circuiting behavior is also equivalent. **Edit 1**: the inner genexp is actually (innocuous but) redundant: `not any(l)` is faster and m...
Python: Check if all dictionaries in list are empty
2,479,472
8
2010-03-19T17:54:44Z
2,479,536
10
2010-03-19T18:05:12Z
[ "python" ]
I have a list of dictionaries. I need to check if all the dictionaries in that list are empty. I am looking for a simple statement that will do it in one line. Is there a single line way to do the following (not including the print)? ``` l = [{},{},{}] # this list is generated elsewhere... all_empty = True for i in l...
`not any(d for d in l)` could be shortened to just `not any(l)` in this case.
Creating temporary user accounts - Django
2,480,862
6
2010-03-19T22:04:54Z
2,481,015
11
2010-03-19T22:46:04Z
[ "python", "django", "session" ]
I need to setup temporary User models for each visitors, where the visitors are obviously tied by session data. I might not be aware of it, but does Django support attaching data to Anonymous users? --- The only way, I am currently aware of, is to use the session dictionary part of the request object. --- Help wou...
Have a look at [django-lazysignup](http://github.com/danfairs/django-lazysignup) > `django-lazysignup` is a package designed to allow users to interact with a site as if they were authenticated users, but without signing up. At any time, they can convert their temporary user account to a real user account.
Python: Creating directories
2,480,936
6
2010-03-19T22:23:12Z
2,480,953
14
2010-03-19T22:27:09Z
[ "python" ]
I want to create a directory (named 'downloaded') on in my desktop directory; isn't this working?: ``` import os os.mkdir('~/Desktop/downloaded/') ```
You can't simply use `~` You must use [os.path.expanduser](http://docs.python.org/library/os.path.html#os.path.expanduser) to replace the `~` with a proper path.
Python: Creating directories
2,480,936
6
2010-03-19T22:23:12Z
2,481,333
8
2010-03-20T00:23:04Z
[ "python" ]
I want to create a directory (named 'downloaded') on in my desktop directory; isn't this working?: ``` import os os.mkdir('~/Desktop/downloaded/') ```
Use ``` import os os.mkdir(os.path.expanduser("~/Desktop/downloaded")) ``` The `~` character is a POSIX shell convention that represents the contents of the HOME environment variable. So, when you type in a shell: ``` $ mkdir ~/Desktop/downloaded ``` it's the same as typing ``` $ mkdir $HOME/Desktop/downloaded ```...
How do I install boto?
2,481,287
33
2010-03-20T00:06:28Z
2,481,346
13
2010-03-20T00:26:28Z
[ "python", "installation", "boto" ]
So that I am able to work with it within my python scripts?
``` $ easy_install boto ``` Edit: pip is now by far the preferred way to install packages
How do I install boto?
2,481,287
33
2010-03-20T00:06:28Z
3,603,001
30
2010-08-30T18:08:24Z
[ "python", "installation", "boto" ]
So that I am able to work with it within my python scripts?
Installing Boto depends on the Operating system. For e.g in Ubuntu you can use the aptitude command: ``` sudo apt-get install python-boto ``` Or you can download the boto code from their site and move into the unzipped directory to run ``` python setup.py install ```
How do I install boto?
2,481,287
33
2010-03-20T00:06:28Z
8,191,581
49
2011-11-19T03:08:19Z
[ "python", "installation", "boto" ]
So that I am able to work with it within my python scripts?
1. If necessary, install pip: `sudo apt-get install python-pip` 2. Then install boto: `pip install -U boto`
difference between len() and .__len__()?
2,481,421
43
2010-03-20T00:53:24Z
2,481,433
45
2010-03-20T00:57:01Z
[ "python" ]
Is there any difference between calling `len([1,2,3])` or `[1,2,3].__len__()`? If there is no visible difference what is done differently behind the scenes?
`len` is a function to get the length of a collection. It works by calling an object's `__len__` method. `__something__` attributes are special and usually more than meets the eye, and generally should not be called directly. It was decided at some point long ago getting the length of something should be a function an...
difference between len() and .__len__()?
2,481,421
43
2010-03-20T00:53:24Z
2,481,445
12
2010-03-20T01:02:19Z
[ "python" ]
Is there any difference between calling `len([1,2,3])` or `[1,2,3].__len__()`? If there is no visible difference what is done differently behind the scenes?
You can think of len() as being roughly equivalent to ``` def len(x): return x.__len__() ``` One advantage is that it allows you to write things like ``` map(len, somelist) ``` instead of ``` map(list.__len__, somelist) ``` or ``` map(operator.attrgetter('__len__'), somelist) ``` There is slightly different...
difference between len() and .__len__()?
2,481,421
43
2010-03-20T00:53:24Z
2,481,631
45
2010-03-20T02:09:51Z
[ "python" ]
Is there any difference between calling `len([1,2,3])` or `[1,2,3].__len__()`? If there is no visible difference what is done differently behind the scenes?
It's often the case that the "typical" behavior of a built-in or operator is to call (with different and nicer syntax) suitable magic methods (ones with names like `__whatever__`) on the objects involved. Often the built-in or operator has "added value" (it's able to take different paths depending on the objects involv...
Mocking ImportError in Python
2,481,511
5
2010-03-20T01:21:51Z
2,481,588
8
2010-03-20T01:50:03Z
[ "python", "unit-testing", "mocking", "doctest", "zope.component" ]
I'm trying this for almost two hours now, without any luck. I have a module that looks like this: ``` try: from zope.component import queryUtility # and things like this except ImportError: # do some fallback operations <-- how to test this? ``` Later in the code: ``` try: queryUtility(foo) except Name...
Just monkeypatch into the `builtins` your own version of `__import__` -- it can raise whatever you wish when it recognizes it's being called on the specific modules for which you want to mock up errors. See [the docs](http://docs.python.org/library/functions.html?highlight=__import__#__import__) for copious detail. Rou...
Send an email using python script
2,482,160
9
2010-03-20T06:13:18Z
2,482,176
14
2010-03-20T06:20:23Z
[ "python", "email" ]
Today I needed to send email from a Python script. As always I searched Google and found the following script that fits to my need. ``` import smtplib SERVER = "localhost" FROM = "sender@example.com" TO = ["user@example.com"] # must be a list SUBJECT = "Hello!" TEXT = "This message was sent with Python's smtplib."...
You've named your module the same as one of Python's internal modules. When you import `smtplib`, it tries to import `email`, and finds your module instead of the internal one. When two modules import one another, only the variables in each module visible before the both import statements will be visible to one another...
Testing variable types in Python
2,482,230
3
2010-03-20T06:52:16Z
2,482,254
7
2010-03-20T07:04:33Z
[ "python", "testing", "variables" ]
I'm creating an initialising function for the class 'Room', and found that the program wouldn't accept the tests I was doing on the input variables. Why is this? ``` def __init__(self, code, name, type, size, description, objects, exits): self.code = code self.name = name self.type = type self.size = ...
Python is a dynamic language. It bad idea to test the types explicitly. In fact the code you write should in itself be such that you dont ever need to test the types of variables. If you are coming from C/C++/Java then takes some time to get over that.
Easiest way of unit testing C code with Python
2,482,270
13
2010-03-20T07:12:47Z
2,482,281
8
2010-03-20T07:19:18Z
[ "python", "c", "unit-testing", "swig" ]
I've got a pile of C code that I'd like to unit test using Python's unittest library (in Windows), but I'm trying to work out the best way of interfacing the C code so that Python can execute it (and get the results back). Does anybody have any experience in the easiest way to do it? Some ideas include: * Wrapping th...
Using ctypes would be my first instinct, though I must admit that if I was testing C code that was not going to be interfaced from Python in the first place, I would just use [check](http://check.sourceforge.net/). [Check](http://check.sourceforge.net/) has the strong advantage of being able to properly report test cas...
Label in PyQt4 GUI not updating with every loop of FOR loop
2,482,437
5
2010-03-20T08:45:13Z
2,482,527
9
2010-03-20T09:41:28Z
[ "python", "for-loop", "label", "pyqt4" ]
I'm having a problem, where I wish to run several command line functions from a python program using a GUI. I don't know if my problem is specific to **PyQt4** or if it has to do with my bad use of python code. What I wish to do is have a label on my GUI change its text value to inform the user which command is being ...
The label gets updated all right, *but the GUI isn't redrawn before the end of your loop.* Here's what you can do about it: * Move your long-running loop to a secondary thread, drawing the GUI is happening in the main thread. * Call `app.processEvents()` in your loop. This gives Qt the chance to process events and re...
a general tree implementation in python
2,482,602
22
2010-03-20T10:07:12Z
2,482,610
86
2010-03-20T10:11:15Z
[ "python", "python-3.x" ]
I want to build a general tree whose root node contains 'n' children, and those children may contain other children.....
A tree in Python is quite simple. Make a class that has data and a list of children. Each child is an instance of the same class. This is a general n-nary tree. ``` class Node(object): def __init__(self, data): self.data = data self.children = [] def add_child(self, obj): self.children...
a general tree implementation in python
2,482,602
22
2010-03-20T10:07:12Z
7,334,634
9
2011-09-07T13:27:07Z
[ "python", "python-3.x" ]
I want to build a general tree whose root node contains 'n' children, and those children may contain other children.....
I've published a Python [3] tree implementation on my site: <http://www.quesucede.com/page/show/id/python_3_tree_implementation>. Hope it is of use, Ok, here's the code: ``` import uuid def sanitize_id(id): return id.strip().replace(" ", "") (_ADD, _DELETE, _INSERT) = range(3) (_ROOT, _DEPTH, _WIDTH) = range(3...
Should I use fork or threads?
2,482,926
6
2010-03-20T12:07:21Z
2,483,065
7
2010-03-20T12:53:38Z
[ "python", "coding-style" ]
In my script, I have a **function foo** which basically uses **pynotify** to notify user about something repeatedly after a time interval say 15 minutes. ``` def foo: while True: """Does something""" time.sleep(900) ``` My main script has to interact with user & does all other things so I just can...
I won't tell you which one to use, but here are some of the advantages of each: **Threads** can start more quickly than processes, and threads use fewer operating system resources than processes, including memory, file handles, etc. Threads also give you the option of communicating through shared variables (although m...
Python development with Emacs?
2,483,406
12
2010-03-20T14:35:54Z
2,483,466
7
2010-03-20T14:54:54Z
[ "python", "emacs" ]
Anybody knows some actual documentation written? I can't find anything good for any of the 2 competing modes. Looks like Emacs is pretty much abandon when it comes to Python and it is a shame as there is no other programmable programming editor that comes close to Emacs.
This blog recently had a 2 part series that I found very helpful. [Part 1](http://jesselegg.com/archives/2010/02/25/emacs-python-programmers-part-1/) [Part 2](http://jesselegg.com/archives/2010/03/14/emacs-python-programmers-2-virtualenv-ipython-daemon-mode/) There was also an article in Python Magazine last year in e...
undo or reverse argsort(), python
2,483,696
8
2010-03-20T15:55:37Z
2,497,565
18
2010-03-23T04:25:00Z
[ "python", "arrays", "sorting", "numpy" ]
Given an array 'a' I would like to sort the array by columns "sort(a, axis=0)" do some stuff to the array and then undo the sort. By that I don't mean re sort but basically reversing how each element was moved. I assume argsort() is what I need but it is not clear to me how to sort an array with the results of argsort(...
There are probably better solutions to the problem you are actually trying to solve than this (performing an argsort usually precludes the need to actually sort), but here you go: ``` >>> import numpy as np >>> a = np.random.randint(0,10,10) >>> aa = np.argsort(a) >>> aaa = np.argsort(aa) >>> a # original array([6, 4,...
Is str.replace(..).replace(..) ad nauseam a standard idiom in Python?
2,484,156
28
2010-03-20T18:11:12Z
2,484,179
7
2010-03-20T18:16:07Z
[ "python", "performance", "replace", "idioms" ]
For instance, say I wanted a function to escape a string for use in HTML (as in Django's [escape filter](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#escape)): ``` def escape(string): """ Returns the given string with ampersands, quotes and angle brackets encoded. "...
That's what [Django does](http://www.google.com/codesearch/p?hl=ja#Y-66DYr1B_Q/django/utils/html.py&q=lang%3apy%20escape%20django&sa=N&cd=1&ct=rc&l=30): ``` def escape(html): """Returns the given HTML with ampersands, quotes and carets encoded.""" return mark_safe(force_unicode(html).replace('&', '&amp;').repl...
Is str.replace(..).replace(..) ad nauseam a standard idiom in Python?
2,484,156
28
2010-03-20T18:11:12Z
2,484,247
9
2010-03-20T18:40:44Z
[ "python", "performance", "replace", "idioms" ]
For instance, say I wanted a function to escape a string for use in HTML (as in Django's [escape filter](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#escape)): ``` def escape(string): """ Returns the given string with ampersands, quotes and angle brackets encoded. "...
I prefer something clean like: ``` substitutions = [ ('<', '&lt;'), ('>', '&gt;'), ...] for search, replacement in substitutions: string = string.replace(search, replacement) ```
Is str.replace(..).replace(..) ad nauseam a standard idiom in Python?
2,484,156
28
2010-03-20T18:11:12Z
2,484,369
18
2010-03-20T19:17:05Z
[ "python", "performance", "replace", "idioms" ]
For instance, say I wanted a function to escape a string for use in HTML (as in Django's [escape filter](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#escape)): ``` def escape(string): """ Returns the given string with ampersands, quotes and angle brackets encoded. "...
Do you have an application that is running too slow and you profiled it to find that a line like this snippet is causing it to be slow? Bottlenecks occur at unexpected places. The current snippet traverses the string 5 times, doing one thing each time. You are suggesting traversing it once, probably doing doing five t...
Is str.replace(..).replace(..) ad nauseam a standard idiom in Python?
2,484,156
28
2010-03-20T18:11:12Z
2,484,483
14
2010-03-20T19:50:11Z
[ "python", "performance", "replace", "idioms" ]
For instance, say I wanted a function to escape a string for use in HTML (as in Django's [escape filter](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#escape)): ``` def escape(string): """ Returns the given string with ampersands, quotes and angle brackets encoded. "...
How about we just test various ways of doing this and see which comes out faster (assuming we are only caring about the fastest way to do it). ``` def escape1(input): return input.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace("'", '&#39;').replace('"', '&quot;') translation_table = {...
How do I override a parent class's functions in python?
2,484,215
10
2010-03-20T18:30:38Z
2,484,291
32
2010-03-20T18:52:14Z
[ "python", "inheritance", "override", "parent" ]
I have a private method `def __pickSide(self):` in a parent class that I would like to override in the child class. However, the child class still calls the inherited `def __pickSide(self):`. How can I override the function? The child class's function name is exactly the same as the parent's function name.
Let's look at the easiest example: ``` from dis import dis class A(object): def __pick(self): print "1" def doitinA(self): self.__pick() class B(A): def __pick(self): print "2" def doitinB(self): self.__pick() b = B() b.doitinA() # prints 1 b.doitinB() # prints 2 dis(A.doitinA) pr...
Prevent python from printing newline
2,484,420
3
2010-03-20T19:33:46Z
2,484,426
7
2010-03-20T19:35:42Z
[ "python", "input", "newline", "user-input" ]
I have this code in Python ``` inputted = input("Enter in something: ") print("Input is {0}, including the return".format(inputted)) ``` that outputs ``` Enter in something: something Input is something , including the return ``` I am not sure what is happening; if I use variables that don't depend on user input, I...
You are correct - a newline is included in `inputted`. To remove it, you can just call `strip("\r\n")` to remove the newline from the end: ``` print("Input is {0}, including the return".format(inputted.strip("\r\n"))) ``` This won't cause any issues if `inputted` does not have a newline at the end, but will remove an...
Is it possible to plot implicit equations using Matplotlib?
2,484,527
16
2010-03-20T20:00:30Z
2,484,594
16
2010-03-20T20:16:52Z
[ "python", "matplotlib", "equation", "implicit", "sympy" ]
I would like to plot implicit equations (of the form f(x, y)=g(x, y) eg. X^y=y^x) in Matplotlib. Is this possible?
I don't believe there's very good support for this, but you could try something like ``` import matplotlib.pyplot from numpy import arange from numpy import meshgrid delta = 0.025 xrange = arange(-5.0, 20.0, delta) yrange = arange(-5.0, 20.0, delta) X, Y = meshgrid(xrange,yrange) # F is one side of the equation, G i...
Is it possible to plot implicit equations using Matplotlib?
2,484,527
16
2010-03-20T20:00:30Z
2,492,042
11
2010-03-22T12:10:15Z
[ "python", "matplotlib", "equation", "implicit", "sympy" ]
I would like to plot implicit equations (of the form f(x, y)=g(x, y) eg. X^y=y^x) in Matplotlib. Is this possible?
Since you've tagged this question with sympy, I will give such an example. From the documentation: <http://docs.sympy.org/modules/plotting.html>. ``` from sympy import var, Plot var('x y') Plot(x*y**3 - y*x**3) ```
what are the advantages of C# over Python
2,484,578
6
2010-03-20T20:12:53Z
2,484,591
11
2010-03-20T20:16:36Z
[ "c#", "python" ]
I like Python mostly for the great portability and the ease of coding, but I was wondering, what are some of the advantages that C# has over Python? The reason I ask is that one of my friends runs a private server for an online game (UO), and he offered to make me a dev if I wanted, but the software for the server is ...
A lot of us really [like working with strongly/statically-typed languages](http://stackoverflow.com/questions/859186/why-is-c-statically-typed/859226#859226). That's a big one there.
what are the advantages of C# over Python
2,484,578
6
2010-03-20T20:12:53Z
2,484,595
9
2010-03-20T20:16:59Z
[ "c#", "python" ]
I like Python mostly for the great portability and the ease of coding, but I was wondering, what are some of the advantages that C# has over Python? The reason I ask is that one of my friends runs a private server for an online game (UO), and he offered to make me a dev if I wanted, but the software for the server is ...
There are lots of differences, advantages as well as disadvantages. I guess the main advantages would be along the lines of * Excellent Windows integration, including access to all standard GUI functions and other libraries. * JIT compilation, resulting in better performance than Python, in some or most circumstances....
what are the advantages of C# over Python
2,484,578
6
2010-03-20T20:12:53Z
2,484,624
13
2010-03-20T20:22:12Z
[ "c#", "python" ]
I like Python mostly for the great portability and the ease of coding, but I was wondering, what are some of the advantages that C# has over Python? The reason I ask is that one of my friends runs a private server for an online game (UO), and he offered to make me a dev if I wanted, but the software for the server is ...
1. Visual Studio - the best IDE out there. 2. Of the statically typed languages in circulation, C# is very productive.
What's the Ruby equivalent of Python's output[:-1]?
2,484,863
5
2010-03-20T21:34:24Z
2,484,898
11
2010-03-20T21:44:39Z
[ "python", "ruby" ]
In Python, if I want to get the first n characters of a string minus the last character, I do: ``` output = 'stackoverflow' print output[:-1] ``` What's the Ruby equivalent?
I don't want to get too nitpicky, but if you want to be more like Python's approach, rather than doing `"StackOverflow"[0..-2]` you can do `"StackOverflow"[0...-1]` for the same result. In Ruby, a range with 3 dots excludes the right argument, where a range with two dots includes it. So, in the case of string slicing,...
The problem with installing PIL using virtualenv or buildout
2,485,295
68
2010-03-21T00:19:07Z
2,486,396
92
2010-03-21T08:22:30Z
[ "python", "python-imaging-library", "easy-install", "buildout", "pip" ]
When I install PIL using easy\_install or buildout it installs in such way, that I must do 'import Image', not 'from PIL import Image'. However, if I do "apt-get install python-imaging" or use "pip -E test\_pil install PIL", all work fine. Here are examples of how I trying to install PIL using virtualenv: ``` # virt...
The PIL version packaged on pypi (by the author) is incompatible with setuptools and thus not easy\_installable. People have created easy\_installable versions elsewhere. Currently, you need to specify a find-links URL and use [`pip`](https://pypi.python.org/pypi/pip) get a good package: ``` pip install --no-index -f ...
The problem with installing PIL using virtualenv or buildout
2,485,295
68
2010-03-21T00:19:07Z
7,770,547
76
2011-10-14T16:19:14Z
[ "python", "python-imaging-library", "easy-install", "buildout", "pip" ]
When I install PIL using easy\_install or buildout it installs in such way, that I must do 'import Image', not 'from PIL import Image'. However, if I do "apt-get install python-imaging" or use "pip -E test\_pil install PIL", all work fine. Here are examples of how I trying to install PIL using virtualenv: ``` # virt...
Use [Pillow: the "friendly" PIL fork](https://github.com/python-imaging/Pillow) :-) It offers: * Full setuptools compatibility * Faster release cycle * No image code changes that differ from PIL (i.e. it aims to track all PIL image code changes, and make none of its own changes without reporting them upstream.) * Wind...
The problem with installing PIL using virtualenv or buildout
2,485,295
68
2010-03-21T00:19:07Z
14,881,859
7
2013-02-14T18:45:03Z
[ "python", "python-imaging-library", "easy-install", "buildout", "pip" ]
When I install PIL using easy\_install or buildout it installs in such way, that I must do 'import Image', not 'from PIL import Image'. However, if I do "apt-get install python-imaging" or use "pip -E test\_pil install PIL", all work fine. Here are examples of how I trying to install PIL using virtualenv: ``` # virt...
For Ubuntu I found I needed to to install the C headers package for my python version (2.7) `sudo apt-get install python2.7-dev` Afterwards, `pip install pil` worked.
Python's equivalent of && in an if statement
2,485,466
340
2010-03-21T01:23:03Z
2,485,471
611
2010-03-21T01:25:05Z
[ "python", "if-statement" ]
Here's my code: ``` # F. front_back # Consider dividing a string into two halves. # If the length is even, the front and back halves are the same length. # If the length is odd, we'll say that the extra char goes in the front half. # e.g. 'abcde', the front half is 'abc', the back half 'de'. # Given 2 strings, a and b...
You would want `and` instead of `&&`.
Python's equivalent of && in an if statement
2,485,466
340
2010-03-21T01:23:03Z
2,485,473
113
2010-03-21T01:26:09Z
[ "python", "if-statement" ]
Here's my code: ``` # F. front_back # Consider dividing a string into two halves. # If the length is even, the front and back halves are the same length. # If the length is odd, we'll say that the extra char goes in the front half. # e.g. 'abcde', the front half is 'abc', the back half 'de'. # Given 2 strings, a and b...
Python uses `and` and `or` conditionals. i.e. ``` if foo == 'abc' and bar == 'bac' or zoo == '123': # do something ```
Python's equivalent of && in an if statement
2,485,466
340
2010-03-21T01:23:03Z
2,485,493
18
2010-03-21T01:35:16Z
[ "python", "if-statement" ]
Here's my code: ``` # F. front_back # Consider dividing a string into two halves. # If the length is even, the front and back halves are the same length. # If the length is odd, we'll say that the extra char goes in the front half. # e.g. 'abcde', the front half is 'abc', the back half 'de'. # Given 2 strings, a and b...
Two comments: * Use `and` and `or` for logical operations in Python. * Use 4 spaces to indent instead of 2. You will thank yourself later because your code will look pretty much the same as everyone else's code. See [PEP 8](http://www.python.org/dev/peps/pep-0008/) for more details.
Python's equivalent of && in an if statement
2,485,466
340
2010-03-21T01:23:03Z
24,149,079
7
2014-06-10T19:10:55Z
[ "python", "if-statement" ]
Here's my code: ``` # F. front_back # Consider dividing a string into two halves. # If the length is even, the front and back halves are the same length. # If the length is odd, we'll say that the extra char goes in the front half. # e.g. 'abcde', the front half is 'abc', the back half 'de'. # Given 2 strings, a and b...
I went with a purlely mathematical solution: ``` def front_back(a, b): return a[:(len(a)+1)//2]+b[:(len(b)+1)//2]+a[(len(a)+1)//2:]+b[(len(b)+1)//2:] ```
Consecutive, Overlapping Subsets of Array (NumPy, Python)
2,485,669
8
2010-03-21T02:38:38Z
2,485,777
12
2010-03-21T03:19:27Z
[ "python", "numpy", "scipy" ]
I have a [NumPy](http://en.wikipedia.org/wiki/NumPy) array `[1,2,3,4,5,6,7,8,9,10,11,12,13,14]` and want to have an array structured like `[[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]]`. Sure this is possible by looping over the large array and adding arrays of length four to the new array, but I'm curious if ...
The fastest way seems to be to preallocate the array, given as option 7 right at the bottom of this answer. ``` >>> import numpy as np >>> A=np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14]) >>> A array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) >>> np.array(zip(A,A[1:],A[2:],A[3:])) array([[ 1, 2, 3, 4],...
Consecutive, Overlapping Subsets of Array (NumPy, Python)
2,485,669
8
2010-03-21T02:38:38Z
2,487,551
17
2010-03-21T15:19:48Z
[ "python", "numpy", "scipy" ]
I have a [NumPy](http://en.wikipedia.org/wiki/NumPy) array `[1,2,3,4,5,6,7,8,9,10,11,12,13,14]` and want to have an array structured like `[[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]]`. Sure this is possible by looping over the large array and adding arrays of length four to the new array, but I'm curious if ...
You should use `stride_tricks`. When I first saw this, the word 'magic' did spring to mind. It's simple and is by far the fastest method. ``` >>> as_strided = numpy.lib.stride_tricks.as_strided >>> a = numpy.arange(1,15) >>> a array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) >>> b = as_strided(a,(11,4),...
very quickly getting total size of folder
2,485,719
39
2010-03-21T02:54:56Z
2,485,804
15
2010-03-21T03:31:50Z
[ "python", "optimization", "folders" ]
I want to quickly find the total size of any folder using python. ``` import os from os.path import join, getsize, isfile, isdir, splitext def GetFolderSize(path): TotalSize = 0 for item in os.walk(path): for file in item[2]: try: TotalSize = TotalSize + getsize(join(item[0]...
If you want same speed as explorer, why not use the windows scripting to access same functionality using pythoncom e.g. ``` import win32com.client as com folderPath = r"D:\Software\Downloads" fso = com.Dispatch("Scripting.FileSystemObject") folder = fso.GetFolder(folderPath) MB=1024*1024.0 print "%.2f MB"%(folder.Si...
very quickly getting total size of folder
2,485,719
39
2010-03-21T02:54:56Z
2,485,843
65
2010-03-21T03:47:22Z
[ "python", "optimization", "folders" ]
I want to quickly find the total size of any folder using python. ``` import os from os.path import join, getsize, isfile, isdir, splitext def GetFolderSize(path): TotalSize = 0 for item in os.walk(path): for file in item[2]: try: TotalSize = TotalSize + getsize(join(item[0]...
You are at a disadvantage. Windows Explorer almost certainly uses [`FindFirstFile`](http://msdn.microsoft.com/en-us/library/aa364418(VS.85).aspx)/[`FindNextFile`](http://msdn.microsoft.com/en-us/library/aa364428(VS.85).aspx) to both traverse the directory structure *and* collect size information (through `lpFindFileDa...
Clever way of building a tag cloud? - Python
2,485,800
4
2010-03-21T03:29:51Z
2,485,807
9
2010-03-21T03:34:16Z
[ "python", "django", "indexing", "keyword", "data-mining" ]
I've built a content aggregator and would like to add a tag cloud representing the current trends. Unfortunately this is quite complex, as I have to look for **keywords** that represent the context of each article. For example words such as **I**, **was**, **the**, **amazing**, **nice** have no relation to context. ...
Use [NLTK](http://www.acm.org/crossroads/xrds13-4/natural_language.html), and in particular its **Stopwords corpus**: > Besides regular content words, there > is another class of words called stop > words that perform important > grammatical functions, but are > unlikely to be interesting by > themselves. These includ...
Converting JSON into Python dict
2,485,817
20
2010-03-21T03:38:29Z
2,485,831
16
2010-03-21T03:43:49Z
[ "python", "django", "json", "dictionary" ]
I've been searching around trying to find an answer to this question, and I can't seem to track it down. Maybe it's too late in the evening to figure the answer out, so I turn to the excellent readers here. I have the following bit of JSON data that I am pulling out of a CouchDB record: ``` "{\"description\":\"fdsafs...
The string you show is not a JSON-coded object (eqv to a Python dict) — more like an array (eqv to a list) without brackets and with a stray extra comma at the end. So (using [simplejson](http://simplejson.googlecode.com/svn/tags/simplejson-2.1.0/docs/index.html) for version portability — the standard library's `js...
Converting JSON into Python dict
2,485,817
20
2010-03-21T03:38:29Z
2,485,833
31
2010-03-21T03:44:35Z
[ "python", "django", "json", "dictionary" ]
I've been searching around trying to find an answer to this question, and I can't seem to track it down. Maybe it's too late in the evening to figure the answer out, so I turn to the excellent readers here. I have the following bit of JSON data that I am pulling out of a CouchDB record: ``` "{\"description\":\"fdsafs...
* Use the `json` module for loading JSON. (Pre-2.6 use the third party `simplejson` module, which has the same exact API.) ``` >>> import json >>> s = '{"foo": 6, "bar": [1, 2, 3]}' >>> d = json.loads(s) >>> print d {u'foo': 6, u'bar': [1, 2, 3]} ``` * Your actual data cannot be loaded this way since it'...
python: check if url to jpg exists
2,486,145
19
2010-03-21T06:09:17Z
2,486,412
27
2010-03-21T08:27:44Z
[ "python", "url", "validation" ]
In python, how would I check if a url ending in .jpg exists? ex: <http://www.fakedomain.com/fakeImage.jpg> thanks
``` >>> import httplib >>> >>> def exists(site, path): ... conn = httplib.HTTPConnection(site) ... conn.request('HEAD', path) ... response = conn.getresponse() ... conn.close() ... return response.status == 200 ... >>> exists('http://www.fakedomain.com', '/fakeImage.jpg') False ``` If the status is...
python: check if url to jpg exists
2,486,145
19
2010-03-21T06:09:17Z
19,582,542
14
2013-10-25T06:26:18Z
[ "python", "url", "validation" ]
In python, how would I check if a url ending in .jpg exists? ex: <http://www.fakedomain.com/fakeImage.jpg> thanks
The code below is equivalent to [tikiboy's answer](http://stackoverflow.com/a/2486412/596361), but using a high-level and easy-to-use [requests](http://docs.python-requests.org/en/latest/) library. ``` import requests def exists(path): r = requests.head(path) return r.status_code == requests.codes.ok print e...
Catching typos in scripting languages
2,487,089
29
2010-03-21T12:43:56Z
2,487,685
31
2010-03-21T16:00:35Z
[ "python", "ruby", "unit-testing", "scripting", "groovy" ]
If your scripting language of choice doesn't have something like Perl's [strict](http://perldoc.perl.org/strict.html) mode, how are you catching typos? Are you unit testing everything? Every constructor, every method? Is this the only way to go about it?
Really-thorough unit tests are the most important technique (yes, I do always aim for 100% coverage), as they also catch many other typos (e.g. where I write `+` and meant `-`), off-by-one issues, etc. Integration and load tests exercising every feature are the second line of defense against all kinds of errors (mostly...
Python: date, time formatting
2,487,109
14
2010-03-21T12:52:18Z
2,487,117
7
2010-03-21T12:55:30Z
[ "python", "datetime" ]
I need to generate a local timestamp in a form of YYYYMMDDHHmmSSOHH'mm'. That OHH'mm' is one of +, -, Z and then there are hourhs and minutes followed by '. Please, how do I get such a timestamp, denoting both local time zone and possible daylight saving?
[time.strftime](http://docs.python.org/library/time.html#time.strftime) will do for that, And in linux, `%z` will just give you -HHMM format if environment variable is properly set. ``` >>> os.environ['TZ'] = 'EST' >>> time.strftime('%x %X %z') '03/21/10 08:16:33 -0500' ```
Python: date, time formatting
2,487,109
14
2010-03-21T12:52:18Z
2,487,161
23
2010-03-21T13:12:45Z
[ "python", "datetime" ]
I need to generate a local timestamp in a form of YYYYMMDDHHmmSSOHH'mm'. That OHH'mm' is one of +, -, Z and then there are hourhs and minutes followed by '. Please, how do I get such a timestamp, denoting both local time zone and possible daylight saving?
``` import time localtime = time.localtime() timeString = time.strftime("%Y%m%d%H%M%S", localtime) # is DST in effect? timezone = -(time.altzone if localtime.tm_isdst else time.timezone) timeString += "Z" if timezone == 0 else "+" if timezone > 0 else "-" timeString += time.strftime("%H'%M'", time.gmtime(abs(ti...
how to make python load dylib on osx
2,488,016
6
2010-03-21T17:42:05Z
2,582,504
10
2010-04-06T03:38:43Z
[ "python", "osx", "dylib" ]
Trying to load a shared lib out of the current '.' dir in a unit test on osx. What works on Linux and Netbsd there is a symlink `_mymodule.so --> ../.libs/libmymodule.so` but on osx, python's `import mymodule` won't find ``` _mymodule.dylib --> ../.libs/libmymodule.dylib ``` I've tried adding ``` export DYLD_LIBRA...
Just use \*.so as your module extensions in OS X too. I have a vague memory of not being able to load .dylib's and it turning out to be an issue with python itself. . . but I can't find the mailing list post now. However, rest assured you're following standard practice by using \*.so's even on OS X. The only \*.dylib'...
Python: Inheritance of a class attribute (list)
2,488,306
4
2010-03-21T19:00:55Z
2,488,362
9
2010-03-21T19:13:49Z
[ "python", "inheritance", "list", "deep-copy", "class-attributes" ]
inheriting a class attribute from a super class and later changing the value for the subclass works fine: ``` class Unit(object): value = 10 class Archer(Unit): pass print Unit.value print Archer.value Archer.value = 5 print Unit.value print Archer.value ``` leads to the output: 10 10 10 5 which...
It is not a matter of shallow or deep copies, it is a matter of references and assignments. It the first case `Unit.value` and `Archer.value` are two variables which reference the same value. When you do `Archer.value = 5`, you are assigning a new reference to Acher.value. To solve your problem you need to assign a n...
Framework for Implementing REST web service in Django
2,488,325
21
2010-03-21T19:06:36Z
2,488,734
17
2010-03-21T21:12:25Z
[ "python", "django", "web-services", "rest" ]
I'm looking to implement a RESTful interface for a Django application. It is primarily a data-service application - the interface will be (at this point) read-only. The question is which Django toolsets / frameworks make the most sense for this task. I see Django-rest and Django-piston. There's also the option of rol...
> NOTE: Since this post was written, `django-piston` is no longer > actively maintained. As others have mentioned, look into `tastypie` > or `django-rest-framework`. Indeed, you can roll your own, but there's a lot of boilerplate involved. [django-piston](http://bitbucket.org/jespern/django-piston/wiki/Home) is an ex...
Framework for Implementing REST web service in Django
2,488,325
21
2010-03-21T19:06:36Z
7,411,725
8
2011-09-14T05:37:22Z
[ "python", "django", "web-services", "rest" ]
I'm looking to implement a RESTful interface for a Django application. It is primarily a data-service application - the interface will be (at this point) read-only. The question is which Django toolsets / frameworks make the most sense for this task. I see Django-rest and Django-piston. There's also the option of rol...
And since this question still rated pretty highly in my searches on Google, I'll add this alternative to the mix: <http://django-rest-framework.org/> My initial impression is that it does a very good job of embodying the RESTful API design principles described here: <http://readthedocs.org/docs/restful-api-design/en/l...
How to increment variable names/Is this a bad idea
2,488,457
2
2010-03-21T19:43:35Z
2,488,467
11
2010-03-21T19:46:22Z
[ "python", "variables", "loops", "for-loop", "increment" ]
In Python, if I were to have a user input the number X, and then the program enters a for loop in which the user inputs X values, is there a way/is it a bad idea to have variable names automatically increment? ie: ``` user inputs '6' value_1 = ... value_2 = ... value_3 = ... value_4 = ... value_5 = ... va...
You should append all the values to a list, that allows you to easily iterate through the values later as well as not littering your namespace with useless variables and magic.
How to increment variable names/Is this a bad idea
2,488,457
2
2010-03-21T19:43:35Z
2,488,598
8
2010-03-21T20:29:04Z
[ "python", "variables", "loops", "for-loop", "increment" ]
In Python, if I were to have a user input the number X, and then the program enters a for loop in which the user inputs X values, is there a way/is it a bad idea to have variable names automatically increment? ie: ``` user inputs '6' value_1 = ... value_2 = ... value_3 = ... value_4 = ... value_5 = ... va...
> should I be using a completely > different method such as appending all > the new values onto a list? Yes, you can use a [list](http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange). You can also use a [mapping](http://docs.python.org/library/stdtypes.html#mapping-types-di...
What exactly are tuples in Python?
2,488,522
5
2010-03-21T20:07:57Z
2,488,535
14
2010-03-21T20:12:22Z
[ "python", "list", "tuples" ]
I'm following a couple of Pythone exercises and I'm stumped at this one. ``` # C. sort_last # Given a list of non-empty tuples, return a list sorted in increasing # order by the last element in each tuple. # e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields # [(2, 2), (1, 3), (3, 4, 5), (1, 7)] # Hint: use a custom key=...
The tuple is the simplest of Python's sequence types. You can think about it as an immutable (read-only) list: ``` >>> t = (1, 2, 3) >>> print t[0] 1 >>> t[0] = 2 TypeError: tuple object does not support item assignment ``` Tuples can be turned into new lists by just passing them to `list()` (like any iterable), and ...
What exactly are tuples in Python?
2,488,522
5
2010-03-21T20:07:57Z
2,488,665
11
2010-03-21T20:53:16Z
[ "python", "list", "tuples" ]
I'm following a couple of Pythone exercises and I'm stumped at this one. ``` # C. sort_last # Given a list of non-empty tuples, return a list sorted in increasing # order by the last element in each tuple. # e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields # [(2, 2), (1, 3), (3, 4, 5), (1, 7)] # Hint: use a custom key=...
* [Why are there separate tuple and list data types?](http://www.python.org/doc/faq/general/#why-are-there-separate-tuple-and-list-data-types) (Python FAQ) * [Python Tuples are Not Just Constant Lists](http://jtauber.com/blog/2006/04/15/python_tuples_are_not_just_constant_lists/) * [Understanding tuples vs. lists in Py...
pyopengl: Could it replace c++?
2,488,730
9
2010-03-21T21:10:42Z
2,489,409
24
2010-03-22T00:36:01Z
[ "python", "graphics", "3d", "pyopengl" ]
I'm starting a computer graphics course, and I have to choose a language. Choices are between C++ and Python. I have no problem with C++, python is a work in progress. So i was thinking to go down the python road, using pyopengl for graphics part. I have heard though, that performance is an issue. Is python / pyopen...
It depends a LOT on the contents of your computer graphics course. If you are doing anything like the introductory course I've taught in the past, it's basically spinning cubes and spheres, some texture mapping and some vertex animation, and that's about it. In this case, Python would be perfectly adequate, assuming yo...
Will Python 3 ever catch on?
2,489,299
22
2010-03-21T23:54:47Z
2,489,312
7
2010-03-22T00:01:08Z
[ "python", "python-3.x" ]
I have been learning a bit of Python 2 and Python 3 and it seems like Python 2 is overall better than Python 3. So that's where my question comes in. Are there any good reasons to actually switch over to python 3?
Python 3 is going to be the new standard going forward. As no major sweeping changes are planned to Python 3 anytime soon, more people will eventually be moving to it. So... although there are many Python 2 applications around now, eventually many of these applications will be migrated up. There is even at tool for th...
Will Python 3 ever catch on?
2,489,299
22
2010-03-21T23:54:47Z
2,489,398
31
2010-03-22T00:32:53Z
[ "python", "python-3.x" ]
I have been learning a bit of Python 2 and Python 3 and it seems like Python 2 is overall better than Python 3. So that's where my question comes in. Are there any good reasons to actually switch over to python 3?
On the whole, and even in most details, Python3 is better than Python2. The only area where **Python 3 is lagging** is **with regards to 3rd party libraries**. What makes Python great is not only its intrinsic characteristics as a language and its rather extensive standard library, but also the existence of a whole...
Will Python 3 ever catch on?
2,489,299
22
2010-03-21T23:54:47Z
2,489,451
19
2010-03-22T00:56:13Z
[ "python", "python-3.x" ]
I have been learning a bit of Python 2 and Python 3 and it seems like Python 2 is overall better than Python 3. So that's where my question comes in. Are there any good reasons to actually switch over to python 3?
As other answers mention, the only real (and crucial) current advantage of Python 2 over Python 3 is that the former already has a huge wealth of third-party extensions (and auxiliary tools, such as IDEs and the like), which the latter is only gradually moving towards. This is a situation that's gradually improving, as...
How could I check if a number is a perfect square?
2,489,435
35
2010-03-22T00:48:51Z
2,489,519
59
2010-03-22T01:20:45Z
[ "python", "math", "square" ]
I'm pretty stumped with this one guys. I'm trying to toy with Python (as you can see with my previous questions) so I'd really love some help here. :P Speeds is of no concern for now, just working.
The problem with relying on any floating point computation (`math.sqrt(x)`, or `x**0.5`) is that you can't really be sure it's exact (for sufficiently large integers `x`, it won't be, and might even overflow). Fortunately (if one's in no hurry;-) there are many pure integer approaches, such as the following...: ``` de...
How could I check if a number is a perfect square?
2,489,435
35
2010-03-22T00:48:51Z
2,489,540
15
2010-03-22T01:26:43Z
[ "python", "math", "square" ]
I'm pretty stumped with this one guys. I'm trying to toy with Python (as you can see with my previous questions) so I'd really love some help here. :P Speeds is of no concern for now, just working.
Use newton's method to quickly zero in on the nearest integer square root, then square it and see if it's your number. See [isqrt](http://en.wikipedia.org/wiki/Isqrt).
How could I check if a number is a perfect square?
2,489,435
35
2010-03-22T00:48:51Z
2,489,580
7
2010-03-22T01:39:50Z
[ "python", "math", "square" ]
I'm pretty stumped with this one guys. I'm trying to toy with Python (as you can see with my previous questions) so I'd really love some help here. :P Speeds is of no concern for now, just working.
Since you can never depend on exact comparisons when dealing with floating point computations (such as these ways of calculating the square root), a less error-prone implementation would be ``` import math def is_square(integer): root = math.sqrt(integer) if int(root + 0.5) ** 2 == integer: return Tru...
Tricky model inheritance - Django
2,489,620
14
2010-03-22T02:01:42Z
2,489,645
15
2010-03-22T02:09:11Z
[ "python", "django", "inheritance", "django-models", "django-orm" ]
I think this is a bit tricky, at least for me. :) So I have 4 models **Person**, **Singer**, **Bassist** and **Ninja**. Singer, Bassist and Ninja inherit from Person. --- The problem is that each Person can be any of its subclasses. e.g. A person can be a Singer and a Ninja. Another Person can be a Bassist and a N...
Multiple inheritance doesn't work well with databases (and your Django models do need to map down to a database in the end), and inheritance is often a bad way to model "roles" (because people's roles do change). I would have Singer, Bassist and Ninja as "roles", **not** as subclasses of Person, and connect them via fo...
Using QTDesigner with PyQT and Python 2.6
2,489,643
20
2010-03-22T02:08:09Z
2,506,843
19
2010-03-24T10:27:06Z
[ "python", "qt4", "pyqt4", "qt-designer" ]
I'm new to Python and am starting to teach myself GUI programming (hopefully) using PyQT4.7 and Python 2.6 I just downloaded the whole PyQT/QT4 package (including QTDesigner) from the PyQT website, however it seems QTDesigner, which looks amazing to use as a newbie (since you can see all the attributes/properties/defa...
I started to write my first PyQT application (PyQT is used only to handle GUI), and it seems, that good toolchain is: QtDesigner to generate .ui s and handle resources and some IDE, that can set QtDesigner to edit those. I use Eclipse, cause it is highly customisable. You can compile your .qrc and .ui by demand by doin...
Function parameter types in Python
2,489,669
76
2010-03-22T02:17:20Z
2,489,678
7
2010-03-22T02:20:17Z
[ "python", "function", "parameters" ]
Unless I'm mistaken, creating a function in Python works like this: ``` def my_func(param1, param2): # stuff ``` However, you don't actually give the types of those parameters. Also, if I remember, Python is a strongly typed language, as such, it seems like Python shouldn't let you pass in a parameter of a differ...
Python is not strongly typed in the sense of static or compile-time type checking. Most Python code falls under so-called ["Duck Typing"](http://en.wikipedia.org/wiki/Duck_typing) -- for example, you look for a method `read` on an object -- you don't care if the object is a file on disk or a socket, you just want to r...