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
Using exponentiation **0.5 less efficient than math.sqrt?
6,637,589
9
2011-07-09T21:30:39Z
6,637,615
15
2011-07-09T21:35:24Z
[ "python", "exponentiation" ]
A quote from "[Python Programming: An Introduction to Computer Science](http://rads.stackoverflow.com/amzn/click/1887902996)" > We could have taken the square root > using exponentiation \*\*. Using > math.sqrt is somewhat more efficient. "Somewhat", but to what extent, and how?
Theoretically, [hammar's answer](http://stackoverflow.com/questions/6637589/using-exponentiation-less-efficient-than-math-sqrt/6637608#6637608) and [duffymo's answer](http://stackoverflow.com/questions/6637589/using-exponentiation-less-efficient-than-math-sqrt/6637620#6637620) are good guesses. But in practice, on my m...
Using exponentiation **0.5 less efficient than math.sqrt?
6,637,589
9
2011-07-09T21:30:39Z
6,637,899
11
2011-07-09T22:28:05Z
[ "python", "exponentiation" ]
A quote from "[Python Programming: An Introduction to Computer Science](http://rads.stackoverflow.com/amzn/click/1887902996)" > We could have taken the square root > using exponentiation \*\*. Using > math.sqrt is somewhat more efficient. "Somewhat", but to what extent, and how?
No need to guess the implementation, we can read the code! `math.sqrt` is a thin wrapper about `sqrt` from the standard C library: see [`mathmodule.c`, line 956](http://hg.python.org/cpython/file/661195a92131/Modules/mathmodule.c#l956) The `**` operator has multiple implementations depending on the types of the argum...
Class Name and File Name
6,637,811
5
2011-07-09T22:11:59Z
6,637,827
7
2011-07-09T22:15:29Z
[ "python", "class", "filenames" ]
I am from Java background. I am going through the official Python tutorials but can't seem to find the information in relation to Python source file names and classes. In Java, file name is the same as main class name plus the .java extension. In Python what's the case? In the examples of official tutorials, they are ...
In Python a single file constitutes a *module*, which is similar to a namespace in Java, so you would have all the classes for a single namespace in the same file.
What is the Python way to walk a directory tree?
6,639,394
16
2011-07-10T05:31:54Z
6,639,409
27
2011-07-10T05:34:50Z
[ "python", "directory-walk" ]
I feel that assigning files, and folders and doing the += [item] part is a bit hackish. Any suggestions? I'm using Python 3.2 ``` from os import * from os.path import * def dir_contents(path): contents = listdir(path) files = [] folders = [] for i, item in enumerate(contents): if isfile(conten...
Take a look at the [`os.walk`](http://docs.python.org/dev/py3k/library/os.html#os.walk) function which returns the path along with the directories and files it contains. That should considerably shorten your solution.
re.sub(...) replacing leftmost occurrences?
6,639,522
5
2011-07-10T06:02:00Z
6,639,527
9
2011-07-10T06:04:48Z
[ "python", "regex" ]
`$ pydoc re.sub` : ``` sub(pattern, repl, string, count=0, flags=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. >>> re.sub('ROAD', 'RD.', 'BRRROADBBRROAD ROAD ROAD MY ROAD') 'BRRRD.BBRRD. RD. RD. MY RD.' ``` I don't qu...
Note the 's' ending *leftmost non-overlapping occurrences*. `re.sub` replaces all occurrences. You can use the optional *count* argument to limit the amount of replacements it does. "Leftmost non-overlapping" means that if several occurrences are overlapping and can be potentially replaced, only the leftmost will: `...
difference b/w [ab] and (a|b) in regex match?
6,639,820
6
2011-07-10T07:23:32Z
6,639,835
9
2011-07-10T07:25:49Z
[ "python", "regex" ]
I knew that `[]` denotes a set of allowable characters - ``` >>> p = r'^[ab]$' >>> >>> re.search(p, '') >>> re.search(p, 'a') <_sre.SRE_Match object at 0x1004823d8> >>> re.search(p, 'b') <_sre.SRE_Match object at 0x100482370> >>> re.search(p, 'ab') >>> re.search(p, 'ba') ``` But ... today I came across an expression...
In this case it is the same. However, the alternation is not just limited to a single character. For instance, ``` ^(hello|world)$ ``` will match "hello" or "world" (and *only* these two inputs) while ``` ^[helloworld]$ ``` would just match a single character ("h" or "w" or "d" or whatnot). Happy coding.
difference b/w [ab] and (a|b) in regex match?
6,639,820
6
2011-07-10T07:23:32Z
6,639,838
11
2011-07-10T07:26:38Z
[ "python", "regex" ]
I knew that `[]` denotes a set of allowable characters - ``` >>> p = r'^[ab]$' >>> >>> re.search(p, '') >>> re.search(p, 'a') <_sre.SRE_Match object at 0x1004823d8> >>> re.search(p, 'b') <_sre.SRE_Match object at 0x100482370> >>> re.search(p, 'ab') >>> re.search(p, 'ba') ``` But ... today I came across an expression...
`[ab]` matches one character (a or b) and doesn't capture the group. `(a|b)` captures a or b, and matches it. In this case, no big difference, but in more complex cases `[]` can only contain characters and character classes, while `(|)` can contain arbitrarily complex regex's on either side of the pipe
Memory management in Python
6,640,151
6
2011-07-10T08:55:57Z
6,640,188
15
2011-07-10T09:05:28Z
[ "python" ]
I'm new to python.To find the sizeof an integer i used getsizeof method available in sys module. It returns 24 bytes for integer and 34 bytes for char. ``` >>> sys.getsizeof(1) 24 >>> sys.getsizeof('a') 34 ``` I feel this size (24 bytes or 34 bytes) is very large to hold an integer or char... I feel that memory is ge...
Because everything is an object, everything has an object bookkeeping overhead. In CPython, it's at least size of a type pointer and reference count for every object. Plus whatever specific objects need for their data. And there's also garbage collector overhead for some objects. Certainly nothing is 'wasted', it's a s...
Encrypting 30 bit Number into 6 Character Alphanumeric String
6,640,341
2
2011-07-10T09:41:04Z
6,640,947
7
2011-07-10T11:56:35Z
[ "python", "security", "encryption", "cryptography", "bit-manipulation" ]
I'm looking for an approach to encrypt/obfuscate a 30 bit number. The results will be grouped into sets of 3 and visible to users as a 6 character alphanumeric encoded with a base32 alphabet, but the user should not be able to pick up a pattern in the alphnumeric strings. For example, the users could see 3 strings: AS...
[Format preserving encryption](http://en.wikipedia.org/wiki/Format-preserving_encryption) might be helpful here. For example, the cycle-walking method described in the paper "Ciphers with Arbitrary Finite Domains" by Black and Rogaway seems like a potential solution. E.g. use a 32-bit cipher (Skip32 by Greg Rose is an...
python continuous integration
6,640,385
8
2011-07-10T09:50:27Z
6,640,417
11
2011-07-10T09:56:49Z
[ "python", "continuous-integration" ]
I am looking to set up a continuous integration server for a python project. Normally this would build the project however as python is not built as such, what should be done instead? Just unit tests? Or are there additional steps that anyone can recommend?
There are a couple of excellent recourses on how to use [Jenkins](http://jenkins-ci.org) together with Python: * [Talk from PyCon](http://jenkins-ci.org/content/hudson-pycon) * [A blog post](http://jenkins-ci.org/content/python-love-story-virtualenv-and-hudson). * [Another blog post](http://www.rhonabwy.com/wp/2009/11...
Programmatically `git checkout .` with dulwich
6,640,546
5
2011-07-10T10:28:23Z
6,640,755
8
2011-07-10T11:20:24Z
[ "python", "git", "dulwich" ]
Having this code ``` from dulwich.objects import Blob, Tree, Commit, parse_timezone from dulwich.repo import Repo from time import time repo = Repo.init("myrepo", mkdir=True) blob = Blob.from_string("my file content\n") tree = Tree() tree.add("spam", 0100644, blob.id) commit = Commit() commit.tree = tree.id author ...
Git status says it's deleted because the file doesn't exist in the working copy, that's why checking it out fixes the status. It looks like there's no support for high-level working copy classes and functions in dulwich yet. You'd have to deal with trees and blobs and unpacking objects. OK, took the challenge: I coul...
how to put gap between y axis and first bar in vertical barchart matplotlib
6,642,482
9
2011-07-10T16:57:03Z
6,642,792
13
2011-07-10T17:51:47Z
[ "python", "matplotlib", "bar-chart" ]
I have a barchart code snippet as below..When you run this,you get 4 bars ,the first of which lies against the y axis.Is it possible to put some gap between y axis and the first bar? ``` def plot_graph1(): xvals = range(4) xnames=["one","two","three","four"] yvals = [10,30,40,20] width = 0.25 yinte...
In your specific case, it's easiest to use `plt.margins` and `plt.ylim(ymin=0)`. `margins` will act like `axis('tight')`, but leave the specified percentage of "padding", instead of scaling to the exact limits of the data. Also, `plt.bar` has an `align="center"` option that simplifies your example somewhat. Here's a ...
How to resolve "Could not import django.contrib.syndication.views.feed" error in Django admin?
6,642,829
5
2011-07-10T17:58:13Z
6,692,886
11
2011-07-14T12:08:17Z
[ "python", "django", "django-admin" ]
I've updated my Django version to the latest nightly, and I'm getting the following error in the admin; ``` Could not import django.contrib.syndication.views.feed. View does not exist in module django.contrib.syndication.views. ``` I had this error in several views too because, indeed, `django.contrib.syndication.v...
[user643511](http://stackoverflow.com/users/643511/user643511) suggested that the error might be in my own code, not Django. However she didn't point out the real problem (which I understand since I didn't provide the right information). Only after days of digging I found that I had ``` url(r'^feeds/(?P<url>.*)/$', 'd...
Commenting/Uncommenting a block of Python code in TextWrangler
6,643,251
9
2011-07-10T19:01:53Z
6,643,313
21
2011-07-10T19:12:03Z
[ "python", "comments", "textwrangler" ]
Searched this a bit before asking. There is another [thread](http://stackoverflow.com/questions/675442/comment-out-a-python-code-block) that seems to be asking about this same issue in the IDLE editor, but I'm wondering about TextWrangler. The [manual](http://pine.barebones.com/manual/TextWrangler_User_Manual.pdf) lis...
It's in the "Text" menu (5th entry). The command doesn't have a keyboard shortcut by default, but you should be able to add one with the system's keyboard preferences. Exact instructions for adding block comment shortcut for TextWrangler: 1. System Preferences 2. Keyboard 3. Keyboard Shortcuts 4. Application Shortcut...
Given a bunch of ranges of numbers, get all the numbers within those ranges?
6,643,747
2
2011-07-10T21:15:08Z
6,643,775
9
2011-07-10T21:20:07Z
[ "python", "algorithm" ]
In Python, you can get the numbers in a range by calling `range(x,y)`. But given two ranges, say `5-15`, and `10-20` how can you get all the numbers `5-20` without duplicates? The ranges may also be disjoint. I could concat all the results and then uniquify the list, but is that the fastest solution?
``` >>> a = range(5, 15) >>> b = range(10, 20) >>> print sorted(set(a + b)) [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] ``` Or if you want a more general expansion of the lists to their elements for inclusion in the set: ``` >>> list_of_lists = [a, b] >>> print sorted(set(elem for l in list_of_lists for e...
Setting up Pyramid to use MySQL raw instead of SQLAlchemy
6,643,780
4
2011-07-10T21:21:16Z
6,644,728
10
2011-07-11T00:43:49Z
[ "python", "mysql", "pylons", "pyramid" ]
We're trying to set up a Pyramid project that will use MySQL instead of SQLAlchemy. My experience with Pyramid/Python is limited, so I was hoping to find a guide online. Unfortunately, I haven't been able to find anything to push us in the right direction. Most search results were for people trying to use raw SQL/MySQ...
Pyramid at its base does not assume that you will use any one specific library to help you with your persistence. In order to make things easier, then, for people who DO wish to use libraries such as SQLALchemy, the Pyramid library contains [Scaffolding](http://docs.pylonsproject.org/projects/pyramid/dev/narr/project.h...
What is the Python 3 equivalent of find ()?
6,644,074
11
2011-07-10T22:10:40Z
6,644,095
16
2011-07-10T22:14:36Z
[ "python", "python-3.x" ]
I'm working on the MIT open courseware for python but have having a hard time with the following example: > To get started, we are going to use some built-in Python functions. To use these functions, include the statement > **from string import \*** > at the beginning of your file. This will allow you to use Python st...
Use the `.find()` method of a string, rather than `string.find()`. (This also works, and is probably preferable, in python 2).
Equivalent of Matlab's cluster quality function?
6,644,445
15
2011-07-10T23:29:19Z
6,725,320
16
2011-07-17T16:49:08Z
[ "python", "matlab", "numpy", "cluster-analysis", "scipy" ]
MATLAB has a nice [silhouette function](http://www.mathworks.com/help/stats/k-means-clustering.html#brah7fp-1) to help evaluate the number of clusters for k-means. Is there an equivalent for Python's Numpy/Scipy as well?
I present below a sample [silhouette](http://en.wikipedia.org/wiki/Silhouette_%28clustering%29) implementation in both MATLAB and Python/Numpy (keep in mind that I am more fluent in MATLAB): # 1) MATLAB ``` function s = mySilhouette(X, IDX) %# X : matrix of size N-by-p, data where rows are instances %# IDX: ...
How does the Python range function have a default parameter before the actual one?
6,644,537
9
2011-07-10T23:50:33Z
6,644,570
7
2011-07-10T23:58:38Z
[ "python", "range", "overloading", "default-value" ]
So I'm writing a function that takes an optional list and extends it to the length specified. Rather than writing it as foo(n, list=None) I was wondering how I might emulate the behavior of Python's range function which works like: ``` >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(5, 10) [5, 6, 7, 8, 9] ``` ...
One way to write `range` in pure python would be ``` def range(*args): if len(args) > 3: raise TypeError, 'range expected at most 3 arguments, got %d' % len(args) if len(args) == 2: return range(args[0], args[1], 1) if len(args) == 1: return range(0, args[0], 1) else: # ...
How does the Python range function have a default parameter before the actual one?
6,644,537
9
2011-07-10T23:50:33Z
6,646,065
7
2011-07-11T05:23:43Z
[ "python", "range", "overloading", "default-value" ]
So I'm writing a function that takes an optional list and extends it to the length specified. Rather than writing it as foo(n, list=None) I was wondering how I might emulate the behavior of Python's range function which works like: ``` >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(5, 10) [5, 6, 7, 8, 9] ``` ...
Others have shown how it can be done using argument counting. If I were to implement it myself in Python, though, I'd do it more like this. ``` def range(start, limit=None, stride=1): if limit is None: start, limit = 0, start # ... ```
There is a way to add features to an existing django command?
6,645,051
14
2011-07-11T01:54:17Z
6,645,384
14
2011-07-11T03:05:33Z
[ "python", "django" ]
I want to run a command just before the a django command is started. For example: ``` $ python manage.py runserver Validating models... 0 errors found Django version 1.3, using settings 'creat1va.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. (started some command i...
Just realize that you can override the commands just easily as making an app with a command with the same name. So I create an app and create a file with the same name as runserver, and later on that extend the runserver base class to add a new feature before it runs. For example, I want to run the command $ compass ...
Use four CPUs to run a python script
6,645,100
2
2011-07-11T02:02:05Z
6,645,116
8
2011-07-11T02:05:25Z
[ "python", "multicore" ]
I'm running a python script that does some operations over a large graph, so I would like to take advantage of the 4 cores of my PC. Watching the task manager I can see that all CPUs are running but the total CPU usage is up to 50%. As I set this PC exclusively to run this script I would like to use its CPUs as much as...
C Python has a rather generous lock that precludes most threaded operations from truly happening in parallel. You might want to look at the [Multiprocessing](http://docs.python.org/library/multiprocessing.html) module. Otherwise, you could use a Python implementation that allows for concurrent threading: * [IronPytho...
Doing math to a list in python
6,645,357
7
2011-07-11T00:19:24Z
6,645,358
14
2011-07-11T01:15:08Z
[ "python", "list" ]
How do I, say, take `[111, 222, 333]` and multiply it by 3 to get `[333, 666, 999]`?
``` [3*x for x in [111, 222, 333]] ```
Doing math to a list in python
6,645,357
7
2011-07-11T00:19:24Z
6,678,847
9
2011-07-13T12:27:48Z
[ "python", "list" ]
How do I, say, take `[111, 222, 333]` and multiply it by 3 to get `[333, 666, 999]`?
If you're going to be doing lots of array operations, then you will probably find it useful to install [Numpy](http://numpy.scipy.org/). Then you can use ordinary arithmetic operations element-wise on arrays, and there are lots of useful functions for computing with arrays. ``` >>> import numpy >>> a = numpy.array([11...
Django and Django CMS Error
6,645,661
4
2011-07-11T04:07:19Z
6,719,124
16
2011-07-16T17:45:22Z
[ "python", "django", "django-cms" ]
I've just done a fresh install of Django and Django-CMS from the ground up (including a brand new virtualenv and python build). I'm getting this bizzarre error.. google has been no help. Ideas? ``` TemplateSyntaxError at / Caught AttributeError while rendering: 'str' object has no attribute 'regex' In template /Users...
Just had this error. In my case it was caused by having tripple quoted string (comment) in urls.py patterns. Actually it was not interpreted as a comment and was passed to function!
node.js performance with zeromq vs. Python vs. Java
6,645,796
28
2011-07-11T04:36:46Z
6,657,105
9
2011-07-11T21:52:17Z
[ "java", "python", "node.js", "zeromq" ]
I've written a simple echo request/reply test for zeromq using node.js, Python, and Java. The code runs a loop of 100K requests. The platform is a 5yo MacBook Pro with 2 cores and 3G of RAM running Snow Leopard. node.js is consistently an order of magnitude slower than the other two platforms. Java: `real 0m18.823s u...
"can you try to simulate logic from your Python example (e.i send next message only after receiving previous)?" – Andrey Sidorov Jul 11 at 6:24 I think that's part of it: ``` var zeromq = require("zeromq"); var counter = 0; var startTime = new Date(); var maxnum = 100000; var socket = zeromq.createSocket('req');...
node.js performance with zeromq vs. Python vs. Java
6,645,796
28
2011-07-11T04:36:46Z
7,204,415
17
2011-08-26T12:08:03Z
[ "java", "python", "node.js", "zeromq" ]
I've written a simple echo request/reply test for zeromq using node.js, Python, and Java. The code runs a loop of 100K requests. The platform is a 5yo MacBook Pro with 2 cores and 3G of RAM running Snow Leopard. node.js is consistently an order of magnitude slower than the other two platforms. Java: `real 0m18.823s u...
You're using a third party C++ binding. As far as I understand it, the crossover between v8's "js-land" and bindings to v8 written in "c++ land", is very expensive. If you notice, some popular [database](https://github.com/christkv/node-mongodb-native) [bindings](https://github.com/felixge/node-mysql) for node are impl...
node.js performance with zeromq vs. Python vs. Java
6,645,796
28
2011-07-11T04:36:46Z
11,286,672
9
2012-07-02T00:22:52Z
[ "java", "python", "node.js", "zeromq" ]
I've written a simple echo request/reply test for zeromq using node.js, Python, and Java. The code runs a loop of 100K requests. The platform is a 5yo MacBook Pro with 2 cores and 3G of RAM running Snow Leopard. node.js is consistently an order of magnitude slower than the other two platforms. Java: `real 0m18.823s u...
This was a problem with the zeroMQ bindings of node. I don't know since when, but it is fixed and you get the same results as with the other languages.
Calculating the percentage of variance measure for k-means?
6,645,895
21
2011-07-11T04:55:55Z
6,657,095
33
2011-07-11T21:51:44Z
[ "python", "numpy", "statistics", "cluster-analysis", "k-means" ]
On the [Wikipedia page](http://en.wikipedia.org/wiki/Determining_the_number_of_clusters_in_a_data_set), an elbow method is described for determining the number of clusters in k-means. [The built-in method of scipy](http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.vq.kmeans.html#scipy.cluster.vq.kmeans)...
The distortion, as far as [Kmeans](http://en.wikipedia.org/wiki/K-means_clustering) is concerned, is used as a stopping criterion (if the change between two iterations is less than some threshold, we assume convergence) If you want to calculate it from a set of points and the centroids, you can do the following (the c...
How to get to the SSL/TLS internals from Python?
6,646,633
9
2011-07-11T06:47:31Z
6,732,447
11
2011-07-18T11:49:56Z
[ "python", "ssl" ]
I am implementing the XMPP protocol in Python (2.7 and 3.2) and I found one important thing stopping me from making the implementation fully compliant. The current specification ([RFC 6120](http://xmpp.org/rfcs/rfc6120.html)) requires implementation of the SCRAM-SHA-1-PLUS SASL mechanism ([RFC 5802](http://tools.ietf....
It seems the easiest way to get the data from the Python `SSLSocket` is to fix the standard Python library. So I did it, the patch will be included in Python 3.3. <http://bugs.python.org/issue12551#msg140450>
open file for both reading and writing?
6,648,493
69
2011-07-11T09:59:26Z
6,648,594
21
2011-07-11T10:09:12Z
[ "python", "file", "binary" ]
Is there a way to open a file for both reading and writing? I thought "r+" was for that. Because I'm working on binary files I tried the mode "r+b", but I get an error that the file is not open for reading.
`r+` is the canonical mode for reading and writing at the same time. This is not different from using the `fopen()` system call since `file()` / `open()` is just a tiny wrapper around this operating system call.
open file for both reading and writing?
6,648,493
69
2011-07-11T09:59:26Z
6,648,657
12
2011-07-11T10:16:26Z
[ "python", "file", "binary" ]
Is there a way to open a file for both reading and writing? I thought "r+" was for that. Because I'm working on binary files I tried the mode "r+b", but I get an error that the file is not open for reading.
I have tried something like this and it works as expected: ``` f = open("c:\\log.log", 'r+b') f.write("\x5F\x9D\x3E") f.read(100) f.close() ``` Where: > f.read(size) - To read a file’s contents, call f.read(size), which > reads some quantity of data and returns it as a string. And: > f.write(string) writes the c...
open file for both reading and writing?
6,648,493
69
2011-07-11T09:59:26Z
15,976,014
86
2013-04-12T16:04:28Z
[ "python", "file", "binary" ]
Is there a way to open a file for both reading and writing? I thought "r+" was for that. Because I'm working on binary files I tried the mode "r+b", but I get an error that the file is not open for reading.
Here's how you read a file, and then write to it (overwriting any existing data), without closing and reopening: ``` with open(filename, "r+") as f: data = f.read() f.seek(0) f.write(output) f.truncate() ```
Urllib and validation of server certificate
6,648,952
14
2011-07-11T10:46:22Z
14,320,202
9
2013-01-14T14:20:50Z
[ "python", "ssl", "ssl-certificate", "urllib" ]
I use python 2.6 and request Facebook API (https). I guess my service could be target of Man In The Middle attacks. I discovered this morning reading again urllib module documentation that : Citation: ``` Warning : When opening HTTPS URLs, it is not attempted to validate the server certificate. Use at your own risk! `...
You could create a urllib2 opener which can do the validation for you using a custom handler. The following code is an example that works with Python 2.7.3 . It assumes you have downloaded <http://curl.haxx.se/ca/cacert.pem> to the same folder where the script is saved. ``` #!/usr/bin/env python import urllib2 import ...
Detect numbers in string
6,649,096
5
2011-07-11T11:01:40Z
6,649,156
10
2011-07-11T11:05:42Z
[ "python" ]
``` value = 'ad.41.bd' if len(value) == len(value.strip({0,1,2,3,4,5,6,7,8,9})): # no numbers else: # numbers present ``` There a cleaner way of detecting numbers in a string in Python?
What about this? ``` import re if not re.search('\d+', value): # no numbers else: # numbers present ```
Detect numbers in string
6,649,096
5
2011-07-11T11:01:40Z
6,649,195
7
2011-07-11T11:10:19Z
[ "python" ]
``` value = 'ad.41.bd' if len(value) == len(value.strip({0,1,2,3,4,5,6,7,8,9})): # no numbers else: # numbers present ``` There a cleaner way of detecting numbers in a string in Python?
``` >>> value="ab3asdf" >>> any(c.isdigit() for c in value) True >>> value="asf" >>> any(c.isdigit() for c in value) False >>> value = 'ad.41.bd' >>> any(map(lambda c:c.isdigit(),value)) True ``` EDIT: ``` >>> value="1"+"a"*10**6 >>> any(map(lambda c:c.isdigit(),value)) True >>> from itertools import imap >>> any...
Python web service with Twisted
6,649,143
7
2011-07-11T11:04:51Z
6,650,139
8
2011-07-11T12:33:59Z
[ "python", "twisted" ]
This is connected with my previous question [Python web service](http://stackoverflow.com/questions/6642999/python-web-service). I'll use Tornado to exchange information between server and clients. There will be one server and N clients. Clients will send information (disk usage, processes etc.) periodically (every 2 ...
I recommend [AMP](http://amp-protocol.net/). It's a very simple key-value pair based protocol, ideal for what you're doing. Perspective broker is another alternative.. but it's slightly complicated, and usually unnecessary. AMP runs directly over TCP (why bother with HTTP?), the serialization format is both minimal an...
Python - decimal places (putting floats into a string)
6,649,597
2
2011-07-11T11:45:16Z
6,649,651
7
2011-07-11T11:49:41Z
[ "python", "string", "floating-point" ]
I have been using the format: ``` print 'blah, blah %f' %variable ``` to put variables into strings. I heard it was more pythonic than the '+str()+' approach, and have got quite used to it. Is there a way of specifying the decimal places added to the string with %f? I have tried rounding the number before supplying t...
``` >>> variable = 12 >>> print 'blah, blah %4.3f' %variable blah, blah 12.000 >>> print 'blah, blah %1.1f' %variable blah, blah 12.0 ``` Here is the [Python Doc Link](http://docs.python.org/tutorial/inputoutput.html#old-string-formatting), please consider: > Since str.format() is quite new, a lot of Python code stil...
Can a Python list, set or dictionary be implemented invisibly using a database?
6,650,275
11
2011-07-11T12:46:11Z
6,651,215
8
2011-07-11T13:57:51Z
[ "python", "database", "google-app-engine", "list", "volume" ]
The Python native capabilities for lists, sets & dictionaries totally rock. Is there a way to continue using the native capability when the data becomes really big? The problem I'm working on involved matching (intersection) of very large lists. I haven't pushed the limits yet -- actually I don't really know what the l...
I'm not quite sure what you mean by *native capabilities for lists, sets & dictionaries*. However, you can create classes that emulate [container types](http://docs.python.org/reference/datamodel.html#emulating-container-types) and [sequence types](http://docs.python.org/reference/datamodel.html#additional-methods-for-...
How does a python method automatically receive 'self' as the first argument?
6,650,906
10
2011-07-11T13:35:26Z
6,651,105
7
2011-07-11T13:50:41Z
[ "python", "oop", "methods", "self" ]
Consider this example of a strategy pattern in Python (adapted from the example [here](http://stackoverflow.com/questions/963965/how-is-this-strategy-pattern-written-in-python-the-sample-in-wikipedia)). In this case the alternate strategy is a function. ``` class StrategyExample(object): def __init__(self, strateg...
You need to assign an unbound method (i.e. with a `self` parameter) to the class or a bound method to the object. Via the [descriptor mechanism](http://docs.python.org/reference/datamodel.html#descriptors), you can make your own bound methods, it's also why it works when you assign the (unbound) function to a class: ...
InterfaceError (0, '')
6,650,940
18
2011-07-11T13:38:28Z
7,293,609
19
2011-09-03T14:10:08Z
[ "python", "mysql", "django" ]
I have built a site using Django and I am receiving this annoying error when I am trying to execute a query. If I restart the Apache server, the error will go away for a short time. ``` Traceback: File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 100. respo...
This is caused by a global cursor. Try creating and closing the cursor within each method a raw query is needed. ``` cursor = connection.cursor() cursor.execute(query) cursor.close() ```
InterfaceError (0, '')
6,650,940
18
2011-07-11T13:38:28Z
27,962,750
9
2015-01-15T11:47:54Z
[ "python", "mysql", "django" ]
I have built a site using Django and I am receiving this annoying error when I am trying to execute a query. If I restart the Apache server, the error will go away for a short time. ``` Traceback: File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 100. respo...
You get this error when you have a `db.close()` call and later try to access the database without creating a new connection. Try to find if you close the connection to the database when you don't mean to.
How to get the current URL of a page in a Django template?
6,652,584
4
2011-07-11T15:29:59Z
6,652,728
8
2011-07-11T15:40:39Z
[ "python", "django" ]
I know there is another question with virtually the same title as mine but the solution in that one didn't work for me. My url is like this: ``` http://domain.com/videos/dvd/1/ ``` If I use either `{{baseurl}}` or `{{ request.get_full_path }}` I get just this part: ``` http://domain.com/videos/ ``` How can I get th...
You could get it in your view and pass it along into your template context so that it is available to you there. <https://docs.djangoproject.com/en/1.3/ref/request-response/#django.http.HttpRequest.build_absolute_uri> ``` full_url = request.build_absolute_uri(None) # pass full_url into the template context. ```
Efficient method of calculating density of irregularly spaced points
6,652,671
35
2011-07-11T15:37:08Z
6,653,496
15
2011-07-11T16:43:07Z
[ "python", "numpy", "scipy", "matplotlib" ]
I am attempting to generate map overlay images that would assist in identifying hot-spots, that is areas on the map that have high density of data points. None of the approaches that I've tried are fast enough for my needs. Note: I forgot to mention that the algorithm should work well under both low and high zoom scena...
A very simple implementation that could be done (with C) in realtime and that only takes fractions of a second in pure python is to just compute the result in screen space. The algorithm is 1. Allocate the final matrix (e.g. 256x256) with all zeros 2. For each point in the dataset increment the corresponding cell 3. ...
Efficient method of calculating density of irregularly spaced points
6,652,671
35
2011-07-11T15:37:08Z
6,658,307
25
2011-07-12T00:34:15Z
[ "python", "numpy", "scipy", "matplotlib" ]
I am attempting to generate map overlay images that would assist in identifying hot-spots, that is areas on the map that have high density of data points. None of the approaches that I've tried are fast enough for my needs. Note: I forgot to mention that the algorithm should work well under both low and high zoom scena...
This approach is along the lines of some previous answers: increment a pixel for each spot, then smooth the image with a gaussian filter. A 256x256 image runs in about 350ms on my 6-year-old laptop. ``` import numpy as np import scipy.ndimage as ndi data = np.random.rand(30000,2)*255 ## create random dataset i...
Different logging levels for filehandler and display in Python
6,652,727
10
2011-07-11T15:40:38Z
6,744,676
9
2011-07-19T09:02:27Z
[ "python", "logging" ]
I am using the `logging` module in Python to write debug and error messages. I want to write to file all messages of `logging.DEBUG` or greater. However, I only want to print to the screen messages of `logging.WARNING` or greater. Is this possible using just one `Logger` and one `FileHandler`?
As it has been mentioned, handlers are so easy to create and add that you're probably better off just using two handlers. If, however, for some reason you want to stick to one, the [Python logging cookbook](http://docs.python.org/howto/logging-cookbook.html#logging-to-multiple-destinations) has a section describing mor...
Explanation needed regarding explanation of hashable objects
6,652,878
9
2011-07-11T15:50:43Z
6,652,926
10
2011-07-11T15:54:32Z
[ "python", "hash" ]
[Mark Ransom](http://stackoverflow.com/users/5987/mark-ransom) answered on a [SO question about hashes](http://stackoverflow.com/questions/2671376/hashable-immutable/2671476#2671476) here in SO: > [...] An > object is hashable if it has a hash value **which never changes during > its lifetime**. So by the official def...
Instances of this class are hashable if you *promise* never to reset `id` or `name` on them. You can't guarantee that these attributes will never be reset, by the Python principle that ["we are all consenting adults here"](http://mail.python.org/pipermail/tutor/2003-October/025932.html), but it would be very bad style ...
Merging and sorting log files in Python
6,653,371
10
2011-07-11T16:31:34Z
6,653,511
7
2011-07-11T16:44:12Z
[ "python", "sorting", "merge", "timestamp" ]
I am completely new to python and I have a serious problem which I cannot solve. I have a few log files with identical structure: ``` [timestamp] [level] [source] message ``` For example: ``` [Wed Oct 11 14:32:52 2000] [error] [client 127.0.0.1] error message ``` I need to write a program in pure Python which shou...
First off, you will want to use the `fileinput` module for getting data from multiple files, like: ``` data = fileinput.FileInput() for line in data.readlines(): print line ``` Which will then print all of the lines together. You also want to sort, which you can do with the sorted keyword. Assuming your lines ha...
Merging and sorting log files in Python
6,653,371
10
2011-07-11T16:31:34Z
6,653,815
10
2011-07-11T17:10:51Z
[ "python", "sorting", "merge", "timestamp" ]
I am completely new to python and I have a serious problem which I cannot solve. I have a few log files with identical structure: ``` [timestamp] [level] [source] message ``` For example: ``` [Wed Oct 11 14:32:52 2000] [error] [client 127.0.0.1] error message ``` I need to write a program in pure Python which shou...
You can do this ``` import fileinput import re from time import strptime f_names = ['1.log', '2.log'] # names of log files lines = list(fileinput.input(f_names)) t_fmt = '%a %b %d %H:%M:%S %Y' # format of time stamps t_pat = re.compile(r'\[(.+?)\]') # pattern to extract timestamp for l in sorted(lines, key=lambda l: ...
Python Django - Load column from Database into list
6,653,382
7
2011-07-11T16:32:31Z
6,653,873
10
2011-07-11T17:17:16Z
[ "python", "database", "django", "models" ]
How do you load a database column into a list with Django? I have a 'name' column of various names in my database and I want to be able to load all those names (ordered by id) into a list. So that I can iterate over that list and print the names, like this: ``` for name in name_list: print name ``` I've googled...
Check out [the docs for `values_list()`](https://docs.djangoproject.com/en/dev/ref/models/querysets/#values-list). Django does a great job of creating the query specific to your request. ``` chat_messages.objects.all().values_list('name') ``` Will generate a query similar to: ``` SELECT `projectname_chat_messages`.`...
Is string interning really useful?
6,653,961
17
2011-07-11T17:25:55Z
6,654,011
23
2011-07-11T17:31:08Z
[ "java", ".net", "python", "ruby", "string-interning" ]
I was having a conversation about strings and various languages a while back, and the topic of [string interning](http://en.wikipedia.org/wiki/String_interning) came up. Apparently Java and the .NET framework do this automatically with all strings, as well as several scripting languages. Theoretically, it saves memory ...
No, Java and .NET don't do it "automatically with all strings". They (well, Java and C#) do it with *constant* string expressions expressed in bytecode/IL, and on demand via the [`String.intern`](http://download.oracle.com/javase/6/docs/api/java/lang/String.html#intern%28%29) and [`String.Intern`](http://msdn.microsoft...
Python pattern-matching. Match 'c[any number of consecutive a's, b's, or c's or b's, c's, or a's etc.]t'
6,654,147
12
2011-07-11T17:42:53Z
6,654,368
14
2011-07-11T18:01:45Z
[ "python", "regex", "pattern-matching" ]
Sorry about the title, I couldn't come up with a clean way to ask my question. In Python I would like to match an expression 'c[some stuff]t', where [some stuff] could be any number of consecutive a's, b's, or c's and in any order. For example, these work: **'ct'**, **'cat'**, **'cbbt'**, **'caaabbct'**, **'cbbccaat'...
Not thoroughly tested, but I think this should work: ``` import re words = ['ct', 'cat', 'cbbt', 'caaabbct', 'cbbccaat', 'cbcbbaat', 'caaccbabbt'] pat = re.compile(r'^c(?:([abc])\1*(?!.*\1))*t$') for w in words: print w, "matches" if pat.match(w) else "doesn't match" #ct matches #cat matches #cbbt matches #caaa...
Parsing reStructuredText into HTML
6,654,519
50
2011-07-11T18:11:19Z
6,654,576
53
2011-07-11T18:16:25Z
[ "python", "restructuredtext", "python-sphinx", "docutils" ]
I'm making a framework in which I let developers describe their package using reStructuredText. I want to parse that reStructuredText into HTML so I can show it in a GUI. I'm familiar with the excellent Sphinx, but I've never otherwise parsed reStructuredText. I imagined something like a function that takes a string o...
Try something like this: ``` >>> from docutils.core import publish_string >>> publish_string("*anurag*", writer_name='html') ``` `publish_string` accepts a strings and outputs a string or you can use [publish\_parts](http://docutils.sourceforge.net/docs/api/publisher.html#publish-parts-details) to get specific parts ...
What is an InstrumentedList in Python?
6,654,613
5
2011-07-11T18:20:06Z
6,654,668
7
2011-07-11T18:24:09Z
[ "python" ]
During some set operations I encountered this error in Python: ``` TypeError: unhashable type: 'InstrumentedList' ``` What is an `InstrumentedList` in Python? I only found a few references related to SQLAlchemy. Is this a SQLAlchemy implementation of lists or something? By the way, it happens while doing: ``` set(s...
Yes, SQLAlchemy uses it to implement a list-like object which is aware of insertions and deletions of related objects to an object (via one-to-many and many-to-many relationships).
How to write a custom `.assertFoo()` method in Python?
6,655,724
21
2011-07-11T19:54:38Z
6,657,088
14
2011-07-11T21:51:28Z
[ "python", "unit-testing" ]
I'm writing some test cases for my application using Python's [`unittest`](http://docs.python.org/library/unittest.html). Now I need to compare a list of objects with a list of another objects to check if the objects from the first list are what I'm expecting. How can I write a custom `.assertFoo()` method? What shoul...
You should create your own TestCase class, derived from unittest.TestCase. Then put your custom assert method into that test case class. If your test fails, raise an AssertionError. Your message should be a string. If you want to test all objects in the list rather than stop on a failure, then collect a list of failing...
How to write a custom `.assertFoo()` method in Python?
6,655,724
21
2011-07-11T19:54:38Z
15,868,615
22
2013-04-07T22:29:17Z
[ "python", "unit-testing" ]
I'm writing some test cases for my application using Python's [`unittest`](http://docs.python.org/library/unittest.html). Now I need to compare a list of objects with a list of another objects to check if the objects from the first list are what I'm expecting. How can I write a custom `.assertFoo()` method? What shoul...
I use the multiple inheritance in these cases. For example: First. I define a class with methods that will incorporate. ``` import os class CustomAssertions: def assertFileExists(self, path): if not os.path.lexists(path): raise AssertionError('File not exists in path "' + path + '".') ``` No...
Python: speeding up geographic comparison
6,656,475
10
2011-07-11T20:58:13Z
6,659,808
13
2011-07-12T05:24:53Z
[ "python", "optimization", "distance", "geography" ]
I've written some code that includes a nested loop where the inner loop is executed about 1.5 million times. I have a function in this loop that I'm trying to optimize. I've done some work, and got some results, but I need a little input to check if what I'm doing is sensible. Some background: I have two collections ...
This is the kind of calculation that [numpy](http://numpy.scipy.org/) is really good at. Rather than looping over the entire large set of coordinates, you can compute the distance between a single point and the entire dataset in a single calculation. With my tests below, you can get an order of magnitude speed increase...
match until a certain pattern using regex
6,656,515
6
2011-07-11T21:01:36Z
6,656,611
7
2011-07-11T21:11:21Z
[ "python", "regex" ]
I have string in a text file containing some text as follows: ``` txt = "java.awt.GridBagLayout.layoutContainer" ``` I am looking to get everything before the Class Name, `"GridBagLayout"`. I have tried something the following , but I can't figure out how to get rid of the `"."` ``` txt = re.findall(r'java\S?[^A-Z]...
Without using capture groups (like @inTide used, which is fine), you can use lookahead (the `(?= ... )` business). `java\s?[^A-Z]*(?=\.[A-Z])` should capture everything you're after. Here it is broken down: ``` java //Literal word "java" \s? //Match for an optional space character. (can change ...
Most optimized way to delete all sessions for a specific user in Django?
6,656,708
9
2011-07-11T21:18:56Z
6,657,043
11
2011-07-11T21:47:49Z
[ "python", "django", "session-cookies", "django-authentication", "django-sessions" ]
I'm running Django 1.3, using Sessions Middleware and Auth Middleware: ``` # settings.py SESSION_ENGINE = django.contrib.sessions.backends.db # Persist sessions to DB SESSION_COOKIE_AGE = 1209600 # Cookies last 2 weeks ``` Each time a user logs in from a different location (different comp...
If you return a QuerySet from your `all_unexpired_sessions_for_user` function, you could limit your database hits to two: ``` def all_unexpired_sessions_for_user(user): user_sessions = [] all_sessions = Session.objects.filter(expire_date__gte=datetime.datetime.now()) for session in all_sessions: s...
filepath autocompletion using users input
6,656,819
10
2011-07-11T21:28:13Z
6,657,975
25
2011-07-11T23:36:54Z
[ "python", "bash", "input", "autocomplete" ]
(python) I'm looking to grab a users input for a filepath. It seems pretty basic, but I can't seem to get readline or rlcompleter working. Pretty much: variable = raw\_input(' Filepath: ') and then the filepath has autocomplete functions like it would in a shell. I'm not restricted to python, I'm willing to use any ...
Something like this? ``` import readline, glob def complete(text, state): return (glob.glob(text+'*')+[None])[state] readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(complete) raw_input('file? ') ```
If statement returning the wrong value?
6,656,861
2
2011-07-11T21:31:14Z
6,656,924
9
2011-07-11T21:37:00Z
[ "python", "string", "if-statement" ]
An `if` statement in Python evaluates and it appears returns the non-expected value. ``` p = sub.Popen('md5.exe -n md5.exe',stdout=sub.PIPE,stderr=sub.PIPE) md5, errors = p.communicate() print md5 abc = "8D443F2E93A3F0B67F442E4F1D5A4D6D" print abc if md5 == abc: print 'TRUE' else: print 'FALSE' ``` `repr(md5)` is `'8...
Your `md5` contains trailing whitespace, which the `abc` value does not have. Most command-line programs end with a line break because it can be disruptive to shell users not to. It's possible to output this to the [standard error](http://en.wikipedia.org/wiki/Stderr#Standard_error_.28stderr.29) stream so as not to int...
Why doesn't virtualenv create DLLs folder?
6,657,541
8
2011-07-11T22:39:05Z
14,359,651
7
2013-01-16T13:32:25Z
[ "python", "windows", "dll", "pydev", "virtualenv" ]
I'm wondering what's the reason virtualenv doesn't create `DLLs` folder the same way it creates `Lib` and `Scripts` ones? The question came to me when I had the following problem with PyDev; I set one of my virtualenvs as a Python interpreter and everything was ok with one exception. I've kept getting warnings about...
I investigated this subject a little more. I started from *techtonik's* statement - *The answer is simple - nobody implemented it.* This however, begs another question - why nobody implemented it? I suspect the answer is because it works. This leads to yet another question - why does it work? The reason everything wor...
python getoutput() equivalent in subprocess
6,657,690
27
2011-07-11T22:59:05Z
6,657,718
48
2011-07-11T23:03:11Z
[ "python", "shell", "command", "subprocess" ]
I want to get the output from some shell commands like `ls` or `df` in a python script. I see that `commands.getoutput('ls')` is deprecated but `subprocess.call('ls')` will only get me the return code. I'll hope there is some simple solution.
Use **subprocess.Popen**: ``` import subprocess process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE) out, err = process.communicate() print(out) ``` Note that communicate blocks until the process terminates. You could use **process.stdout.readline()** if you need the output before it terminates. For more ...
python getoutput() equivalent in subprocess
6,657,690
27
2011-07-11T22:59:05Z
17,330,481
17
2013-06-26T21:09:13Z
[ "python", "shell", "command", "subprocess" ]
I want to get the output from some shell commands like `ls` or `df` in a python script. I see that `commands.getoutput('ls')` is deprecated but `subprocess.call('ls')` will only get me the return code. I'll hope there is some simple solution.
For Python >= 2.7, use `subprocess.check_output()`. <http://docs.python.org/2/library/subprocess.html#subprocess.check_output>
Python: Convert an iterable to a stream?
6,657,820
9
2011-07-11T23:18:20Z
6,658,130
10
2011-07-12T00:01:49Z
[ "python", "stream", "iterator" ]
If I've got an iterable containing strings, is there a simple way to turn it into a stream? I want to do something like this: ``` def make_file(): yield "hello\n" yield "world\n" output = tarfile.TarFile(…) stream = iterable_to_stream(make_file()) output.addfile(…, stream) ```
Since it doesn't look like there is a "standard" way of doing it, I've banged together a simple implementation: ``` class iter_to_stream(object): def __init__(self, iterable): self.buffered = "" self.iter = iter(iterable) def read(self, size): result = "" while size > 0: ...
Python: Convert an iterable to a stream?
6,657,820
9
2011-07-11T23:18:20Z
6,658,949
10
2011-07-12T02:40:28Z
[ "python", "stream", "iterator" ]
If I've got an iterable containing strings, is there a simple way to turn it into a stream? I want to do something like this: ``` def make_file(): yield "hello\n" yield "world\n" output = tarfile.TarFile(…) stream = iterable_to_stream(make_file()) output.addfile(…, stream) ```
Here's my streaming iterator an experimental branch of [urllib3](http://code.google.com/p/urllib3/) supporting streaming chunked request via iterables: ``` class IterStreamer(object): """ File-like streaming iterator. """ def __init__(self, generator): self.generator = generator self.it...
Python: Convert an iterable to a stream?
6,657,820
9
2011-07-11T23:18:20Z
20,260,030
10
2013-11-28T07:22:45Z
[ "python", "stream", "iterator" ]
If I've got an iterable containing strings, is there a simple way to turn it into a stream? I want to do something like this: ``` def make_file(): yield "hello\n" yield "world\n" output = tarfile.TarFile(…) stream = iterable_to_stream(make_file()) output.addfile(…, stream) ```
Python 3 has [a new I/O stream API](http://www.python.org/dev/peps/pep-3116/) ([library docs](http://docs.python.org/dev/library/io.html)), replacing the old file-like object protocol. (The new API is also available in Python 2 in the [`io`](http://docs.python.org/2.7/library/io.html) module, and it's backwards-compati...
cherrypy handle all request with one function or class
6,657,848
4
2011-07-11T23:22:00Z
7,408,809
11
2011-09-13T21:32:40Z
[ "python", "routes", "cherrypy", "dispatcher" ]
i'd like to use cherrypy but i don't want to use the normal dispatcher, i'd like to have a function that catch all the requests and then perform my code. I think that i have to implement my own dispatcher but i can't find any valid example. Can you help me by posting some code or link ? Thanks
make a default function: ``` import cherrypy class server(object): @cherrypy.expose def default(self,*args,**kwargs): return "It works!" cherrypy.quickstart(server()) ```
Can WordNetLemmatizer in Nltk stem words?
6,658,380
3
2011-07-12T00:49:56Z
6,662,433
9
2011-07-12T10:02:02Z
[ "python", "nltk", "wordnet", "stemming", "lemmatization" ]
I want to find word stems with `Wordnet`. Does `wordnet` have a function for stemming? I use this import for my stemming, but it doesn't work as expected. ``` from nltk.stem.wordnet import WordNetLemmatizer WordNetLemmatizer().lemmatize('Having','v') ```
Seems like you have to input a lowercase string to the `lemmatize` method: ``` >>> WordNetLemmatizer().lemmatize('having','v') 'have' >>> WordNetLemmatizer().lemmatize('has','v') 'have' ```
Understanding some Python code
6,659,073
5
2011-07-12T03:04:14Z
6,659,082
13
2011-07-12T03:06:28Z
[ "python" ]
I'm working my way through Gmail access using imaplib and came across: ``` # Count the unread emails status, response = imap_server.status('INBOX', "(UNSEEN)") unreadcount = int(response[0].split()[2].strip(').,]')) print unreadcount ``` I just wish to know what: ``` status, ``` does in front of the "response =". I...
When a function returns a tuple, it can be read by more than one variable. ``` def ret_tup(): return 1,2 # can also be written with parens a,b = ret_tup() ``` a and b are now 1 and 2 respectively
Error "The object invoked has disconnected from its clients" - automate IE 8 with python and win32com
6,661,005
9
2011-07-12T07:48:58Z
6,676,547
8
2011-07-13T09:04:08Z
[ "python", "scripting", "ole", "win32com" ]
I would like to automate Internet Explorer 8 (using python 2.7 on Windows 7) machine. Here is my code after [a post found on SO](http://stackoverflow.com/questions/2994486/monitor-web-sites-visited-using-internet-explorer-opera-chrome-firefox-and-saf): ``` import sys, time from win32com.client import WithEvents, Dispa...
On IE9, you need to lower security settings to make the script work: ``` IE9 -> Internet Options -> Security -> Trusted Sites : Low IE9 -> Internet Options -> Security -> Internet : Medium + unchecked Enable Protected Mode IE9 -> Internet Options -> Security -> Restricted Sites : unchecked Enable Protected ...
Import WordNet In NLTK
6,661,108
2
2011-07-12T08:00:34Z
6,662,494
10
2011-07-12T10:06:32Z
[ "python", "dictionary", "nltk", "wordnet", "stemming" ]
I want to import *`wordnet`* dictionary but when i import Dictionary form *`wordnet`* i see this error : ``` for l in open(WNSEARCHDIR+'/lexnames').readlines(): IOError: [Errno 2] No such file or directory: 'C:\\Program Files\\WordNet\\2.0\\dict/lexnames' ``` I install wordnet2.1 in this directory but i cant import ...
The following works for me: ``` >>> nltk.download() # Download window opens, fetch wordnet >>> from nltk.corpus import wordnet as wn ``` Now I've a `WordNetCorpusReader` called `wn`. I don't know why you're looking for a `Dictionary` class, since there's no such class listed in the [docs](http://nltk.googlecode.com/s...
dealing with python global variables when using recursive functions
6,661,189
2
2011-07-12T08:09:15Z
6,661,265
11
2011-07-12T08:15:18Z
[ "python", "global-variables" ]
I made a program that extracts the text from a HTML file. It recurses down the HTML document and returns the list of tags. For eg, input **< li >no way < b > you < /b > are doing this < /li >** output **['no','way','you','are'...]**. Here is a highly simplified pseudocode for this: ``` def get_leaves(node): kid...
You can pass the result list as optional argument. ``` def get_leaves(node, list_of_leaves=None): list_of_leaves = [] if list_of_leaves is None else list_of_leaves kids=getchildren(node) for i in kids: if leafnode(i): get_leaves(i, list_of_leaves) else: a=process_lea...
dealing with python global variables when using recursive functions
6,661,189
2
2011-07-12T08:09:15Z
6,662,183
7
2011-07-12T09:41:16Z
[ "python", "global-variables" ]
I made a program that extracts the text from a HTML file. It recurses down the HTML document and returns the list of tags. For eg, input **< li >no way < b > you < /b > are doing this < /li >** output **['no','way','you','are'...]**. Here is a highly simplified pseudocode for this: ``` def get_leaves(node): kid...
No need to pass an accumulator to the function or accessing it through a global name if you turn `get_leaves()` into a generator: ``` def get_leaves(node): for child in getchildren(node): if leafnode(child): for each in get_leaves(child): yield each else: yie...
Problem installing pywin32
6,662,536
5
2011-07-12T10:10:25Z
6,662,762
11
2011-07-12T10:28:51Z
[ "python", "pywin32" ]
I am trying to install pywin32 for Python 2.6. I have python installed but it's not in the regular c: drive but on the d: drive . The pywin32 installer does not find it and I cannot give the custom path to it. I checked, thepython folder is the path. Is there a workaround this issue ?
From the pywin32 README > If the installation process informs you that Python is not found in the > registry, it almost certainly means you have downloaded the wrong version - > either for the wrong version of Python, or the wrong "bittedness". Are you sure you got the right version for your python and your cpu archi...
How to fit polynomial to data with error bars
6,663,127
6
2011-07-12T10:58:36Z
12,710,462
11
2012-10-03T14:18:29Z
[ "python", "numpy", "scipy", "curve-fitting" ]
I am currently using numpy.polyfit(x,y,deg) to fit a polynomial to experimental data. I would however like to fit a polynomial that uses weighting based on the errors of the points. I have found [scipy.curve\_fit](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html) which makes use of wei...
For weighted polynomial fitting you can use: ``` numpy.polynomial.polynomial.polyfit(x, y, deg, rcond=None, full=False, w=weights) ``` see <http://docs.scipy.org/doc/numpy/reference/generated/numpy.polynomial.polynomial.polyfit.html> Important to note that in this function the weights should ***not*** be supplied as...
Double precision floating values in Python?
6,663,272
27
2011-07-12T11:09:25Z
6,663,292
50
2011-07-12T11:11:16Z
[ "python", "types" ]
Are there data types with better precision than float?
Python's built-in `float` type has double precision (it's a C `double` in CPython, a Java `double` in Jython). If you need more precision, get [NumPy](http://numpy.scipy.org/) and use its `numpy.float128`.
Double precision floating values in Python?
6,663,272
27
2011-07-12T11:09:25Z
6,663,299
26
2011-07-12T11:11:25Z
[ "python", "types" ]
Are there data types with better precision than float?
[Decimal datatype](http://docs.python.org/library/decimal.html) * Unlike hardware based binary floating point, the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for a given problem. If you are pressed by performance issuses, have a look at [GMPY](http://www.al...
Double precision floating values in Python?
6,663,272
27
2011-07-12T11:09:25Z
6,663,334
7
2011-07-12T11:15:06Z
[ "python", "types" ]
Are there data types with better precision than float?
May be you need Decimal ``` >>> from decimal import Decimal >>> Decimal(2.675) Decimal('2.67499999999999982236431605997495353221893310546875') ``` [Floating Point Arithmetic](http://docs.python.org/tutorial/floatingpoint.html)
Double precision floating values in Python?
6,663,272
27
2011-07-12T11:09:25Z
6,663,344
11
2011-07-12T11:16:06Z
[ "python", "types" ]
Are there data types with better precision than float?
For some applications you can use [`Fraction`](http://docs.python.org/library/fractions.html) instead of floating-point numbers. ``` >>> from fractions import Fraction >>> Fraction(1, 3**54) Fraction(1, 58149737003040059690390169) ``` (For other applications, there's [`decimal`](http://docs.python.org/library/decimal...
stderr.write; printing strings
6,663,778
3
2011-07-12T11:57:16Z
6,663,817
7
2011-07-12T11:59:49Z
[ "python", "stderr" ]
I am new to Python and having some trouble with the `stderr.write` function. I will try to illustrate it with code. Before I was doing this: ``` print "Unexpected error! File {0} could not be converted." .format(src) ``` But then I wanted to separate the error messages from other status messages so I tried doing this...
In Python 2.x: ``` sys.stderr.write("Unexpected error! File %s could not be converted." % src) ``` Or, in Python 2.x and 3.x: ``` sys.stderr.write("Unexpected error! File {0} could not be converted.".format(src)) ```
In Python is augumented addition of sets are not supported?
6,664,356
2
2011-07-12T12:46:09Z
6,664,395
9
2011-07-12T12:49:06Z
[ "python", "set" ]
In the Python sets, why augmented removal of elements are supported but addition is not supported? For example if `s` is a mutable set: ``` s = set(['e', 'd', 'h', 's']) ``` `s -= set('ds')` gives `s = set(['e', 'h'])` but this does not work for `s += set('pk')` and results in `TypeError`.
The correct syntax for what you want to do is ``` s |= set('ds') ``` For sets, the binary operators `|`, `&` and `^` are used for union, intersection and symmetric difference, respectively. I guess the reason `+` is not considered a valid set operation is because it is not used [in set theory](http://en.wikipedia.org...
Calling statistics functions from Scipy
6,664,996
8
2011-07-12T13:32:51Z
6,665,059
9
2011-07-12T13:37:28Z
[ "python", "numpy", "scipy" ]
This may well be completely trivial. I want to call the spearmanr function from scipy: (the data are just examples) ``` import scipy from numpy import * Len = [2,3,5,7,2] Pop = [5,2,6,3,2] a = array(Len) b = array(Pop) print scipy.stats.spearmanr(a,b) ``` This generates the error: ``` AttributeError: 'module' ob...
Use `import scipy.stats`. Then it works. Importing a package does not automatically import all the subpackages/modules. In these cases you have to do this explicitly.
How to pass an 'if' statement to a python method?
6,665,082
3
2011-07-12T13:38:52Z
6,665,107
12
2011-07-12T13:40:46Z
[ "python" ]
I want to pass an optional 'if' statement to a python method to be executed. For example, the method might copy some files from one folder to another, but the method could take an optional condition. So, for example, one call to the method could say "copy the files from source to dest **if source.endswith(".exe")** T...
Functions are objects. It's just a function that returns a boolean result. ``` def do_something( condition, argument ): if condition(argument): # whatever def the_exe_rule( argument ): return argument.endswith('.exe') do_something( the_exe_rule, some_file ) ``` Lambda is another way to create such a f...
Python sort list of lists / ascending and then decending
6,666,748
19
2011-07-12T15:27:03Z
6,666,834
25
2011-07-12T15:32:31Z
[ "python", "sorting" ]
if i have a list that contains a list that looks like this ... ``` ['a',1] ['a',2] ['a',3] ['b',1] ['b',2] ['b',3] ``` how can i sort them so that element 0 is sorted descending and element 1 sorted ascending so the result would look like... ``` ['b',1] ['b',2] ['b',3] ['a',1] ['a',2] ['a',3] ``` Using `itemgetter`...
``` L = [['a',1], ['a',2], ['a',3], ['b',1], ['b',2], ['b',3]] L.sort(key=lambda k: (k[0], -k[1]), reverse=True) ``` `L` now contains: ``` [['b', 1], ['b', 2], ['b', 3], ['a', 1], ['a', 2], ['a', 3]] ```
Python sort list of lists / ascending and then decending
6,666,748
19
2011-07-12T15:27:03Z
6,667,177
22
2011-07-12T15:53:19Z
[ "python", "sorting" ]
if i have a list that contains a list that looks like this ... ``` ['a',1] ['a',2] ['a',3] ['b',1] ['b',2] ['b',3] ``` how can i sort them so that element 0 is sorted descending and element 1 sorted ascending so the result would look like... ``` ['b',1] ['b',2] ['b',3] ['a',1] ['a',2] ['a',3] ``` Using `itemgetter`...
You *can* do successive rounds of sorting as python's `sort` is [stable](http://en.wikipedia.org/wiki/Stable_sort#Stability). You need to first sort on the *secondary key* though. See also the [official HOW TO](http://docs.python.org/howto/sorting.html#sort-stability-and-complex-sorts). ``` from operator import itemge...
Why does `type(myField)` return `<type 'instance'>` and not `<type 'Field'>`?
6,666,856
25
2011-07-12T15:33:57Z
6,667,098
66
2011-07-12T15:47:23Z
[ "python" ]
I am confronted to a python problem. I want to use `type()` to find out what type of variable I am using. The code looks similar to this one: ``` class Foo(): array=[ myField(23),myField(42),myField("foo"), myField("bar")] def returnArr(self): for i in self.array: print type(i) ...
in python 2, all of your classes should inherit from `object`. If you don't, you end up with "old style classes", which are always of type `classobj`, and whose instances are always of type `instance`. ``` >>> class myField(): ... pass ... >>> class yourField(object): ... pass ... >>> m = myField() >>> y = y...
How to define two-dimensional array in python
6,667,201
300
2011-07-12T15:54:38Z
6,667,288
424
2011-07-12T15:59:36Z
[ "python", "matrix", "syntax-error" ]
I want to define a two-dimensional array without an initialized length like this : ``` Matrix = [][] ``` but it does not work... I've tried the code below, but it is wrong too: ``` Matrix = [5][5] ``` ***Error:*** ``` Traceback ... IndexError: list index out of range ``` What is my mistake?
You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this "list comprehension". ``` # Creates a list containing 5 lists, each of 8 items, all set to 0 w, h = 8, 5. Matrix = [[0 for x in range(w)] for y in range(h)] ``` # Y...
How to define two-dimensional array in python
6,667,201
300
2011-07-12T15:54:38Z
6,667,306
45
2011-07-12T16:00:49Z
[ "python", "matrix", "syntax-error" ]
I want to define a two-dimensional array without an initialized length like this : ``` Matrix = [][] ``` but it does not work... I've tried the code below, but it is wrong too: ``` Matrix = [5][5] ``` ***Error:*** ``` Traceback ... IndexError: list index out of range ``` What is my mistake?
If you want to create an empty matrix, the correct syntax is ``` matrix = [[]] ``` And if you want to generate a matrix of size 5 filled with 0, ``` matrix = [[0 for i in xrange(5)] for i in xrange(5)] ```
How to define two-dimensional array in python
6,667,201
300
2011-07-12T15:54:38Z
6,667,308
10
2011-07-12T16:00:58Z
[ "python", "matrix", "syntax-error" ]
I want to define a two-dimensional array without an initialized length like this : ``` Matrix = [][] ``` but it does not work... I've tried the code below, but it is wrong too: ``` Matrix = [5][5] ``` ***Error:*** ``` Traceback ... IndexError: list index out of range ``` What is my mistake?
You should make a list of lists, the best way is use nested comprehensions: ``` >>> matrix = [[0 for i in range(5)] for j in range(5)] >>> pprint.pprint(matrix) [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] ``` On your `[5][5]` example, you are creating a list with an integ...
How to define two-dimensional array in python
6,667,201
300
2011-07-12T15:54:38Z
6,667,352
18
2011-07-12T16:04:15Z
[ "python", "matrix", "syntax-error" ]
I want to define a two-dimensional array without an initialized length like this : ``` Matrix = [][] ``` but it does not work... I've tried the code below, but it is wrong too: ``` Matrix = [5][5] ``` ***Error:*** ``` Traceback ... IndexError: list index out of range ``` What is my mistake?
In Python you will be creating a list of lists. You do not have to declare the dimensions ahead of time, but you can. For example: ``` matrix = [] matrix.append([]) matrix.append([]) matrix[0].append(2) matrix[1].append(3) ``` Now matrix[0][0] == 2 and matrix[1][0] == 3. You can also use the list comprehension syntax...
How to define two-dimensional array in python
6,667,201
300
2011-07-12T15:54:38Z
6,667,361
205
2011-07-12T16:04:52Z
[ "python", "matrix", "syntax-error" ]
I want to define a two-dimensional array without an initialized length like this : ``` Matrix = [][] ``` but it does not work... I've tried the code below, but it is wrong too: ``` Matrix = [5][5] ``` ***Error:*** ``` Traceback ... IndexError: list index out of range ``` What is my mistake?
If you really want a matrix, you might be better off using numpy. ``` >>> import numpy >>> numpy.zeros((5, 5)) array([[ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.]]) >>> numpy.matrix([[1, 2],[3, 4]]) mat...
How to define two-dimensional array in python
6,667,201
300
2011-07-12T15:54:38Z
6,667,529
148
2011-07-12T16:17:19Z
[ "python", "matrix", "syntax-error" ]
I want to define a two-dimensional array without an initialized length like this : ``` Matrix = [][] ``` but it does not work... I've tried the code below, but it is wrong too: ``` Matrix = [5][5] ``` ***Error:*** ``` Traceback ... IndexError: list index out of range ``` What is my mistake?
Here is a shorter notation for initializing a list of lists: ``` matrix = [[0]*5 for i in range(5)] ``` Unfortunately shortening this to something like `5*[5*[0]]` doesn't really work because you end up with 5 copies of the same list, so when you modify one of them they all change, for example: ``` >>> matrix = 5*[5...
How to define two-dimensional array in python
6,667,201
300
2011-07-12T15:54:38Z
20,446,414
8
2013-12-07T20:45:17Z
[ "python", "matrix", "syntax-error" ]
I want to define a two-dimensional array without an initialized length like this : ``` Matrix = [][] ``` but it does not work... I've tried the code below, but it is wrong too: ``` Matrix = [5][5] ``` ***Error:*** ``` Traceback ... IndexError: list index out of range ``` What is my mistake?
To declare a matrix of zeros (ones): ``` numpy.zeros((x, y)) ``` e.g. ``` >>> numpy.zeros((3, 5)) array([[ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.]]) ``` or numpy.ones((x, y)) e.g. ``` >>> np.ones((3, 5)) array([[ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.],...
How to define two-dimensional array in python
6,667,201
300
2011-07-12T15:54:38Z
23,927,979
41
2014-05-29T07:23:00Z
[ "python", "matrix", "syntax-error" ]
I want to define a two-dimensional array without an initialized length like this : ``` Matrix = [][] ``` but it does not work... I've tried the code below, but it is wrong too: ``` Matrix = [5][5] ``` ***Error:*** ``` Traceback ... IndexError: list index out of range ``` What is my mistake?
If all you want is a two dimensional container to hold some elements, you could conveniently use a dictionary instead: ``` Matrix = {} ``` Then you can do: ``` Matrix[1,2] = 15 print Matrix[1,2] ``` This works because `1,2` is a tuple, and you're using it as a key to index the dictionary. The result is similar to a...
Is a python script aware of its stored location path?
6,667,460
3
2011-07-12T16:12:32Z
6,667,561
7
2011-07-12T16:20:19Z
[ "python" ]
``` /home/bar/foo/test.py: ``` I am trying `test.py` to print `/home/bar/foo` irrespective of from where I run the script from: ``` import os def foo(): print os.getcwd() ``` test run: ``` [/home/bar $] python /home/bar/foo/test.py # echoes /home/bar [/tmp $] python /home/bar/foo/test.py # echo...
Try this: ``` import os.path p = os.path.abspath(__file__) ```
How to use the option skip-name-resolve when using MySQLdb for Python?
6,668,073
3
2011-07-12T17:00:38Z
15,786,867
11
2013-04-03T12:04:52Z
[ "python", "mysql", "mysql-python", "resolve" ]
I try to connect to database in a domain from my virtual machine. It works on XP, but somehow does not work on Win7 and quitting with: "OperationalError: (1042, "Can't get hostname for your address")" Now I tried disable Firewall and stuff, but that doesn't matter anyway. I don't need the DNS resolving, which will onl...
Add the following line(skip-name-resolve) in the /etc/mysql/my.cnf file ``` [mysqld] port = 3306 socket = /tmp/mysql.sock skip-locking skip-name-resolve ``` And restart the mysql server
How can i successfully use UNICODE characters in my .py files without causing trouble?
6,668,218
4
2011-07-12T17:13:47Z
6,668,334
9
2011-07-12T17:22:13Z
[ "python", "unicode" ]
I am writing a test for a database which has Swedish characters in it. In the test, i directly use characters with umlauts and other such Swedish ligatures and it runs just fine, reading filenames in from a database and doing string compares successfully. However, upon importing this file to do pydoc generation, i get...
You need to set your encoding in your editor and the database so that they match. If your database is utf-8 encoded, and not iso-8859-15, then setting your editor to utf-8 should fix it. However, since your u'string' comparisons fail, this might not be the case. Replace ``` # -*- coding: iso-8859-15 -*- ``` with ``...
Method for indexing an object database
6,668,234
5
2011-07-12T17:14:49Z
6,674,416
8
2011-07-13T05:23:47Z
[ "python", "indexing", "zodb", "oodbms" ]
I'm using an object database (ZODB) in order to store complex relationships between many objects but am running into performance issues. As a result I started to construct indexes in order to speed up object retrieval and insertion. Here is my story and I hope that you can help. Initially when I would add an object to...
Yes, repoze.catalog is nice, and well documented. ## In short : don't make indexing part of your site structure! 1. Look at using a container/item hierarchy to store and traverse content item objects; plan to be able to traverse content by either (a) path (graph edges look like a filesystem) or (b) by identifying sin...
n-largest elements in an sequence (need to retain duplicates)
6,669,632
8
2011-07-12T19:06:26Z
6,670,141
7
2011-07-12T19:48:05Z
[ "python", "algorithm", "sorting", "heap", "sequence" ]
I need to find the n largest elements in a list of tuples. Here is an example for top 3 elements. ``` # I have a list of tuples of the form (category-1, category-2, value) # For each category-1, ***values are already sorted descending by default*** # The list can potentially be approximately a million elements long. l...
I take it from your code snippet that `lot` is grouped w.r.t. *category-1*. Following should work then: ``` from itertools import groupby, islice from operator import itemgetter ans = [] for x, g1 in groupby(lot, itemgetter(0)): for y, g2 in islice(groupby(g1, itemgetter(2)), 0, 3): ans.extend(list(g2)) ...