title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Is there a difference between using a dict literal and a dict constructor?
6,610,606
92
2011-07-07T12:29:41Z
6,610,830
12
2011-07-07T12:47:26Z
[ "python", "pycharm" ]
Using PyCharm, I noticed it offers to convert a **dict literal**: ``` d = { 'one': '1', 'two': '2', } ``` into a **dict constructor**: ``` d = dict(one='1', two='2') ``` **Do these different approaches differ in some significant way?** (While writing this question I noticed that using `dict()` it seems imp...
These two approaches produce identical dictionaries, except, as you've noted, where the lexical rules of Python interfere. Dictionary literals are a little more obviously dictionaries, and you can create any kind of key, but you need to quote the key names. On the other hand, you can use variables for keys if you need...
Is there a difference between using a dict literal and a dict constructor?
6,610,606
92
2011-07-07T12:29:41Z
6,610,973
30
2011-07-07T12:58:14Z
[ "python", "pycharm" ]
Using PyCharm, I noticed it offers to convert a **dict literal**: ``` d = { 'one': '1', 'two': '2', } ``` into a **dict constructor**: ``` d = dict(one='1', two='2') ``` **Do these different approaches differ in some significant way?** (While writing this question I noticed that using `dict()` it seems imp...
They look pretty much the same on Python 3.2. As gnibbler pointed out, the first doesn't need to lookup `dict`, which should make it a tiny bit faster. ``` >>> def literal(): ... d = {'one': 1, 'two': 2} ... >>> def constructor(): ... d = dict(one='1', two='2') ... >>> import dis >>> dis.dis(literal) 2 ...
Is there a difference between using a dict literal and a dict constructor?
6,610,606
92
2011-07-07T12:29:41Z
6,612,024
23
2011-07-07T14:14:59Z
[ "python", "pycharm" ]
Using PyCharm, I noticed it offers to convert a **dict literal**: ``` d = { 'one': '1', 'two': '2', } ``` into a **dict constructor**: ``` d = dict(one='1', two='2') ``` **Do these different approaches differ in some significant way?** (While writing this question I noticed that using `dict()` it seems imp...
Literal is much faster, since it uses optimized BUILD\_MAP and STORE\_MAP opcodes rather than generic CALL\_FUNCTION: ``` > python2.7 -m timeit "d = dict(a=1, b=2, c=3, d=4, e=5)" 1000000 loops, best of 3: 0.958 usec per loop > python2.7 -m timeit "d = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}" 1000000 loops, best of 3: 0....
Running a .py file in browser
6,611,311
5
2011-07-07T13:25:15Z
10,345,290
7
2012-04-27T05:37:14Z
[ "python", "apache", "cgi" ]
I want to run python file in browser. I have installed apache. and configured `httd.conf` file. I have created `test.py`file. I then tried running `test.py` with my browser by typing `htt://localhost/test.py`. When I do this, I get the following error: ``` Internal Server Error The server encountered an internal error...
It may also happened if your shebang is not correct (for example, an Unix one like `#!/usr/bin/env python`). If this is the case, change it to the correct path to your Python executable (for example: `#!C:\Python26\python.exe`) or look at this answer: [How do I ignore the Perl shebang on Windows with Apache 2?](http://...
SQLAlchemy ON DUPLICATE KEY UPDATE
6,611,563
22
2011-07-07T13:43:08Z
10,561,643
29
2012-05-12T06:39:33Z
[ "python", "mysql", "sqlalchemy" ]
Is there an elegant way to do an `INSERT ... ON DUPLICATE KEY UPDATE` in SQLAlchemy? I mean something with a syntax similar to `inserter.insert().execute(list_of_dictionaries)` ?
# `ON DUPLICATE KEY UPDATE` in the SQL statement If you want the generated SQL to actually include `ON DUPLICATE KEY UPDATE`, the simplest way involves using a `@compiles` decorator. The code (linked from a good thread on the subject [on reddit](http://www.reddit.com/r/Python/comments/p5grh/sqlalchemy_whats_the_idiom...
how to run easy_install using a particular python version
6,611,730
18
2011-07-07T13:54:21Z
6,611,773
12
2011-07-07T13:57:03Z
[ "python", "easy-install", "orange" ]
I have 3 python versions, I want to easy\_install Orange using the second version. How can I do this? Unnecessary info: 1. 2.1 in /usr/bin/python 2. 2.6 in /Library/Frameworks/Python.framework/Versions/2.6/bin/python 3. 3.1 in /Library/Frameworks/Python.framework/Versions/3.1/bin/python Answer: Ok found it [here](ht...
easy\_install is usually/always installed *per Python version*. So you run the related version of easy\_install installed for your particular Python version/interpreter you want to use here.
how to run easy_install using a particular python version
6,611,730
18
2011-07-07T13:54:21Z
14,807,399
35
2013-02-11T07:05:23Z
[ "python", "easy-install", "orange" ]
I have 3 python versions, I want to easy\_install Orange using the second version. How can I do this? Unnecessary info: 1. 2.1 in /usr/bin/python 2. 2.6 in /Library/Frameworks/Python.framework/Versions/2.6/bin/python 3. 3.1 in /Library/Frameworks/Python.framework/Versions/3.1/bin/python Answer: Ok found it [here](ht...
Just so the answer is easy to find: Using "Python-version" with the m-parameter and easy\_install afterwards does the trick. Example: ``` python2.7 -m easy_install https://bitbucket.org/james_taylor/bx-python/get/tip.tar.bz2 ```
Macports Port Select Commands
6,612,009
20
2011-07-07T14:14:14Z
6,612,075
42
2011-07-07T14:18:58Z
[ "python", "macports" ]
What are the new commands & or equivalents of: ``` python_select -L (shows available python versions) python_select -s (sets the default version of your choice of python). ``` I know they have changed to `--list`, `--set`, `--show` but there doesn't seem to be an example of how to properly use each one. For example,...
To list: ``` port select --list python ``` To show: ``` port select --show python ``` To select: ``` sudo port select --set python <the python version> ```
Is there a more elegant way for unpacking keys and values of a dictionary into two lists, without losing consistence?
6,612,769
4
2011-07-07T15:04:50Z
6,612,795
8
2011-07-07T15:07:25Z
[ "python", "list", "dictionary", "iterable-unpacking" ]
What I came up with is: ``` keys, values = zip(*[(key, value) for (key, value) in my_dict.iteritems()]) ``` But I am not satisfied. What do the pythonistas say?
What about using [`dict.keys()`](http://docs.python.org/library/stdtypes.html#dict.keys) and [`dict.values()`](http://docs.python.org/library/stdtypes.html#dict.values)? ``` keys, values = dict.keys(), dict.values() ```
Is there a more elegant way for unpacking keys and values of a dictionary into two lists, without losing consistence?
6,612,769
4
2011-07-07T15:04:50Z
6,612,821
17
2011-07-07T15:08:42Z
[ "python", "list", "dictionary", "iterable-unpacking" ]
What I came up with is: ``` keys, values = zip(*[(key, value) for (key, value) in my_dict.iteritems()]) ``` But I am not satisfied. What do the pythonistas say?
``` keys, values = zip(*d.items()) ```
logging setLevel, how it works
6,614,078
19
2011-07-07T16:43:33Z
6,614,296
25
2011-07-07T17:01:29Z
[ "python", "logging" ]
In the [logging howto documentation](http://docs.python.org/dev/howto/logging.html) there is this example: ``` import logging # create logger logger = logging.getLogger('simple_example') logger.setLevel(logging.DEBUG) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DE...
It's there for fine-tuning (you can have multiple handlers, and each could have different levels set) — you can safely not set level on the handler, which will cause it to process all messages (a.k.a. NOTSET level), and leave level filtering to the logger. Logger is also the first to filter the message based on a le...
"<method> takes no arguments (1 given)" but I gave none
6,614,123
21
2011-07-07T16:48:07Z
6,614,153
34
2011-07-07T16:50:16Z
[ "python", "methods", "call" ]
I am new to Python and I have written this simple script: ``` #!/usr/bin/python3 import sys class Hello: def printHello(): print('Hello!') def main(): helloObject = Hello() helloObject.printHello() # Here is the error if __name__ == '__main__': main() ``` When I run it (`./hello.py`) I ge...
The error is referring to the implicit `self` argument that is passed implicitly when calling a method like `helloObject.printHello()`. This parameter needs to be included explicitly in the definition of an instance method. It should look like this: ``` class Hello: def printHello(self): print('Hello!') ```
How can I turn a list into an array in python?
6,614,261
3
2011-07-07T16:58:11Z
6,614,280
15
2011-07-07T16:59:35Z
[ "python", "list", "multidimensional-array", "numpy" ]
How can I turn a list such as: ``` data_list = [0,1,2,3,4,5,6,7,8,9] ``` into a array (I'm using numpy) that looks like: ``` data_array = [ [0,1] , [2,3] , [4,5] , [6,7] , [8,9] ] ``` Can I slice segments off the beginning of the list and append them to an empty array? Thanks
``` >>> import numpy as np >>> np.array(data_list).reshape(-1, 2) array([[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]) ``` (The [`reshape`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.reshape.html#numpy.ndarray.reshape) method returns a new "view" on the array; it doesn't c...
Turning a list into nested lists in python
6,614,891
3
2011-07-07T17:47:53Z
6,615,011
20
2011-07-07T17:57:49Z
[ "python", "list", "nested" ]
> **Possible Duplicate:** > [How can I turn a list into an array in python?](http://stackoverflow.com/questions/6614261/how-can-i-turn-a-list-into-an-array-in-python) How can I turn a list such as: ``` data_list = [0,1,2,3,4,5,6,7,8] ``` into a list of lists such as: ``` new_list = [ [0,1,2] , [3,4,5] , [6,7,8] ]...
This groups each 3 elements in the order they appear: ``` new_list = [data_list[i:i+3] for i in range(0, len(data_list), 3)] ``` Give us a better example if it is not what you want.
Fitting distributions, goodness of fit, p-value. Is it possible to do this with Scipy (Python)?
6,615,489
15
2011-07-07T18:40:31Z
16,651,524
22
2013-05-20T14:16:54Z
[ "python", "numpy", "scipy", "statistics", "probability" ]
INTRODUCTION: I'm a bioinformatician. In my analysis which I perform on all human genes (about 20 000) I search for a particular short sequence motif to check how many times this motif occurs in each gene. Genes are 'written' in a linear sequence in four letters (A,T,G,C). For example: CGTAGGGGGTTTAC... This is the fo...
[In SciPy documentation](http://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions) you will find a list of all implemented continuous distribution functions. Each one has [a `fit()` method](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.fit.html#scipy.stats.rv_continu...
DateTime.TryParse() in Python?
6,615,533
9
2011-07-07T18:44:26Z
6,617,824
8
2011-07-07T22:21:04Z
[ "python", "parsing", "datetime", "tryparse" ]
Is there an equivalent to C#'s `DateTime.TryParse()` in Python? ### Edit: I'm referring to the fact that it avoids throwing an exception, not the fact that it guesses the format.
If you don't want the exception, catch the exception. ``` try: d = datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S") except ValueError: d = None ``` In the zen of python, explicit is better than implicit. `strptime` ***always*** returns a datetime parsed in the exact format specified. This makes sense, becau...
Eclipse Pydev: 'Error: Python stdlib not found'
6,615,629
25
2011-07-07T18:54:37Z
6,617,822
22
2011-07-07T22:20:54Z
[ "python", "eclipse", "pydev", "virtualenv" ]
I am trying to add an interpreter (created using virtualenv) to PyDev but I get the following error: > It seems that the Python /Lib folder > (which contains the standard library) > was not found /selected during the > instal process. > > This folder (which contains files such > as threading.py and traceback.py) is > ...
I've come across this myself before. When adding an interpreter created using virtualenv in PyDev, when it asks for the folders that need to be added to the SYSTEM pythonpath, I had to select `/usr/lib/python2.7` `/usr/lib/python2.7/lib-tk` `/usr/lib/python2.7/plat-linux2` See the screenshot for what I had to d...
Python Right Click Menu Using PyGTK
6,616,270
9
2011-07-07T19:51:12Z
6,617,707
12
2011-07-07T22:07:05Z
[ "python", "linux", "menu", "click" ]
So I'm still fairly new to Python, and have been learning for a couple months, but one thing I'm trying to figure out is say you have a basic window... ``` #!/usr/bin/env python import sys, os import pygtk, gtk, gobject class app: def __init__(self): window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.set_ti...
There is a example for doing this very thing found at <http://www.pygtk.org/pygtk2tutorial/sec-ManualMenuExample.html> It shows you how to create a menu attach it to a menu bar and also listen for a mouse button click event and popup the very same menu that was created. I think this is what you are after. EDIT: (add...
Python @property versus getters and setters
6,618,002
493
2011-07-07T22:42:25Z
6,618,078
63
2011-07-07T22:52:44Z
[ "python", "properties", "getter-setter" ]
Here is a pure Python-specific design question: ``` class MyClass(object): ... def get_my_attr(self): ... def set_my_attr(self, value): ... ``` and ``` class MyClass(object): ... @property def my_attr(self): ... @my_attr.setter def my_attr(self, value...
The short answer is: **properties wins hands down**. Always. There is sometimes a need for getters and setters, but even then, I would "hide" them to the outside world. There are plenty of ways to do this in Python (`getattr`, `setattr`, `__getattribute__`, etc..., but a very concise and clean one is: ``` def set_ema...
Python @property versus getters and setters
6,618,002
493
2011-07-07T22:42:25Z
6,618,087
16
2011-07-07T22:53:40Z
[ "python", "properties", "getter-setter" ]
Here is a pure Python-specific design question: ``` class MyClass(object): ... def get_my_attr(self): ... def set_my_attr(self, value): ... ``` and ``` class MyClass(object): ... @property def my_attr(self): ... @my_attr.setter def my_attr(self, value...
Using properties is to me more intuitive and fits better into most code. Comparing ``` o.x = 5 ox = o.x ``` vs. ``` o.setX(5) ox = o.getX() ``` is to me quite obvious which is easier to read. Also properties allows for private variables much easier.
Python @property versus getters and setters
6,618,002
493
2011-07-07T22:42:25Z
6,618,117
100
2011-07-07T22:57:27Z
[ "python", "properties", "getter-setter" ]
Here is a pure Python-specific design question: ``` class MyClass(object): ... def get_my_attr(self): ... def set_my_attr(self, value): ... ``` and ``` class MyClass(object): ... @property def my_attr(self): ... @my_attr.setter def my_attr(self, value...
Using properties lets you begin with normal attribute accesses and then [back them up with getters and setters afterwards as necessary](http://www.archive.org/details/SeanKellyRecoveryfromAddiction).
Python @property versus getters and setters
6,618,002
493
2011-07-07T22:42:25Z
6,618,155
9
2011-07-07T23:02:30Z
[ "python", "properties", "getter-setter" ]
Here is a pure Python-specific design question: ``` class MyClass(object): ... def get_my_attr(self): ... def set_my_attr(self, value): ... ``` and ``` class MyClass(object): ... @property def my_attr(self): ... @my_attr.setter def my_attr(self, value...
I feel like properties are about letting you get the overhead of writing getters and setters only when you actually need them. Java Programming culture strongly advise to never give access to properties, and instead, go through getters and setters, and only those which are actually needed. It's a bit verbose to always...
Python @property versus getters and setters
6,618,002
493
2011-07-07T22:42:25Z
6,618,176
431
2011-07-07T23:06:42Z
[ "python", "properties", "getter-setter" ]
Here is a pure Python-specific design question: ``` class MyClass(object): ... def get_my_attr(self): ... def set_my_attr(self, value): ... ``` and ``` class MyClass(object): ... @property def my_attr(self): ... @my_attr.setter def my_attr(self, value...
*Prefer properties*. It's what they're there for. The reason is that all attributes are public in Python. Starting names with an underscore or two is just a warning that the given attribute is an implementation detail that may not stay the same in future versions of the code. It doesn't prevent you from actually getti...
Python @property versus getters and setters
6,618,002
493
2011-07-07T22:42:25Z
6,618,184
100
2011-07-07T23:08:18Z
[ "python", "properties", "getter-setter" ]
Here is a pure Python-specific design question: ``` class MyClass(object): ... def get_my_attr(self): ... def set_my_attr(self, value): ... ``` and ``` class MyClass(object): ... @property def my_attr(self): ... @my_attr.setter def my_attr(self, value...
In Python you don't use getters or setters or properties just for the fun of it. You first just use attributes and then later, only if needed, eventually migrate to a property without having to change the code using your classes. There is indeed a lot of code with extension .py that uses getters and setters and inheri...
Python @property versus getters and setters
6,618,002
493
2011-07-07T22:42:25Z
8,615,910
22
2011-12-23T12:09:33Z
[ "python", "properties", "getter-setter" ]
Here is a pure Python-specific design question: ``` class MyClass(object): ... def get_my_attr(self): ... def set_my_attr(self, value): ... ``` and ``` class MyClass(object): ... @property def my_attr(self): ... @my_attr.setter def my_attr(self, value...
I think both have their place. One issue with using `@property` is that it is hard to extend the behaviour of getters or setters in subclasses using standard class mechanisms. The problem is that the actual getter/setter functions are hidden in the property. You can actually get hold of the functions, e.g. with ``` c...
Python @property versus getters and setters
6,618,002
493
2011-07-07T22:42:25Z
15,783,606
9
2013-04-03T09:28:56Z
[ "python", "properties", "getter-setter" ]
Here is a pure Python-specific design question: ``` class MyClass(object): ... def get_my_attr(self): ... def set_my_attr(self, value): ... ``` and ``` class MyClass(object): ... @property def my_attr(self): ... @my_attr.setter def my_attr(self, value...
I would prefer to use neither in most cases. The problem with properties is that they make the class less transparent. Especially, this is an issue if you were to raise an exception from a setter. For example, if you have an Account.email property: ``` class Account(object): @property def email(self): ...
Python @property versus getters and setters
6,618,002
493
2011-07-07T22:42:25Z
16,849,769
41
2013-05-31T04:27:56Z
[ "python", "properties", "getter-setter" ]
Here is a pure Python-specific design question: ``` class MyClass(object): ... def get_my_attr(self): ... def set_my_attr(self, value): ... ``` and ``` class MyClass(object): ... @property def my_attr(self): ... @my_attr.setter def my_attr(self, value...
[**TL;DR?** You can **skip to the end for a code example**.] I actually prefer to use a different idiom, which is a little involved for using as a one off, but is nice if you have a more complex use case. A bit of background first. Properties are useful in that they allow us to handle both setting and getting values...
Download a specific email from Gmail using Python
6,618,091
11
2011-07-07T22:54:21Z
6,618,585
14
2011-07-08T00:09:24Z
[ "python", "gmail", "imap" ]
Can someone help me customize an existing code sample? I can see from the following article how to connect to gmail and download content, but I can't figure out how to search for a specific email and only download the timestamp and body? ARTICLE: [How can I download all emails with attachments from Gmail?](http://sta...
I suggest using [IMAPClient](http://imapclient.freshfoo.com/) as it papers over many of the more esoteric aspects of IMAP. The following snippet will pull messages based on your criteria, parse the message strings to [`email.message.Message`](http://docs.python.org/library/email.message.html#email.message.Message) ins...
Sorting list based on values from another list?
6,618,515
110
2011-07-07T23:56:57Z
6,618,543
142
2011-07-08T00:02:14Z
[ "python", "sorting" ]
I am a list of strings like this: ``` X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1] ``` What is the shortest way of sorting X using values from Y to get the following output? ``` ["a", "d", "h", "b", "c", "e", "i", "f", "g"] ``` The order for the elements ha...
``` [x for (y,x) in sorted(zip(Y,X))] ```
Sorting list based on values from another list?
6,618,515
110
2011-07-07T23:56:57Z
6,618,548
19
2011-07-08T00:02:32Z
[ "python", "sorting" ]
I am a list of strings like this: ``` X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1] ``` What is the shortest way of sorting X using values from Y to get the following output? ``` ["a", "d", "h", "b", "c", "e", "i", "f", "g"] ``` The order for the elements ha...
The most obvious solution to me is to use the `key` keyword arg. ``` >>> X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] >>> Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1] >>> keydict = dict(zip(X, Y)) >>> X.sort(key=keydict.get) >>> X ['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g'] ``` Note that you can shorten t...
Sorting list based on values from another list?
6,618,515
110
2011-07-07T23:56:57Z
6,618,553
46
2011-07-08T00:03:04Z
[ "python", "sorting" ]
I am a list of strings like this: ``` X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1] ``` What is the shortest way of sorting X using values from Y to get the following output? ``` ["a", "d", "h", "b", "c", "e", "i", "f", "g"] ``` The order for the elements ha...
Zip the two lists together, sort it, then take the parts you want: ``` >>> yx = zip(Y, X) >>> yx [(0, 'a'), (1, 'b'), (1, 'c'), (0, 'd'), (1, 'e'), (2, 'f'), (2, 'g'), (0, 'h'), (1, 'i')] >>> yx.sort() >>> yx [(0, 'a'), (0, 'd'), (0, 'h'), (1, 'b'), (1, 'c'), (1, 'e'), (1, 'i'), (2, 'f'), (2, 'g')] >>> x_sorted = [x f...
Sorting list based on values from another list?
6,618,515
110
2011-07-07T23:56:57Z
21,077,060
20
2014-01-12T16:18:40Z
[ "python", "sorting" ]
I am a list of strings like this: ``` X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1] ``` What is the shortest way of sorting X using values from Y to get the following output? ``` ["a", "d", "h", "b", "c", "e", "i", "f", "g"] ``` The order for the elements ha...
Also, if you don't mind using numpy arrays (or in fact already are dealing with numpy arrays...), here is another nice solution: ``` people = ['Jim', 'Pam', 'Micheal', 'Dwight'] ages = [27, 25, 4, 9] import numpy people = numpy.array(people) ages = numpy.array(ages) inds = ages.argsort() sortedPeople = people[inds] `...
Get locals from calling namespace in Python
6,618,795
14
2011-07-08T00:47:06Z
6,618,825
39
2011-07-08T00:52:24Z
[ "python", "metaprogramming" ]
I want to retrieve the local variables from Python from a called function. Is there any way to do this? I realize this isn't right for most programming, but I am basically building a debugger. For example: ``` def show_locals(): # put something in here that shows local_1. local_1 = 123 show_locals() # I want this ...
If you're writing a debugger, you'll want to make heavy use of the [`inspect`](http://docs.python.org/library/inspect.html) module: ``` def show_callers_locals(): """Print the local variables in the caller's frame.""" import inspect frame = inspect.currentframe() try: print(frame.f_back.f_local...
Gzipping all HTTP traffic with Pyramid
6,618,985
12
2011-07-08T01:24:49Z
6,619,450
21
2011-07-08T02:42:51Z
[ "python", "http", "gzip", "pyramid" ]
I am creating a mobile service based on Pyramid framework. Because it's mobile everything to reduce bandwidth usage is plus. I am considering gzipping all the traffic, even dynamic HTML pages. What kind of hooks Pyramid framework provides for this? Or is there WSGI middleware for the task? I'd like to do this still on...
First of all I should stress that you should do this on the web server level (nginx or apache). There are several reasons for this: 1. Performance - If you do this in Python you are using one of your threads that could be handling requests to do cpu-intensive compression. This is way less efficient than allowing your ...
virtualenv command not found after installed with MacPorts
6,619,307
6
2011-07-08T02:21:09Z
15,818,822
33
2013-04-04T18:23:38Z
[ "python", "virtualenv", "macports" ]
I have python 2.7 installed via mac ports on a mac. I installed virtualenv via macports (py27-virtualenv @1.6.1\_0 (active). When issue the command: virtualenv demo\_venv --no-site-packages, I get this error: -bash: virtualenv:command not found. It's not picking virtualenv up @ all, so do I need to symlink it to my pyt...
As you noted, MacPorts offers several versions of pyXX-virtualenv packages. You need to tell MacPorts which of those versions you want to use by default: ``` port select --list virtualenv port select --set virtualenv virtualenv27 which virtualenv ``` After this, you should be able to just type `virtualenv` (assuming ...
how to loop down in python list (countdown)
6,620,106
7
2011-07-08T04:52:46Z
6,620,114
16
2011-07-08T04:53:59Z
[ "python", "loops" ]
how to loop down in python list? for example loop: ``` L = [1,2,3] for item in L print item #-->1,2,3 ``` loop down: ``` L = [1,2,3] for ??? print item #-->3,2,1 ``` thank you
[Batteries included.](http://docs.python.org/library/functions.html#reversed) ``` for i in reversed([1, 2, 3]): print i ``` Slicing the list (`ls[::-1]`) is great for making a reversed copy, but on my machine it's slower for iteration, even if the list is already in memory: ``` >>> def sliceit(x): ... l = ra...
how to loop down in python list (countdown)
6,620,106
7
2011-07-08T04:52:46Z
6,620,118
7
2011-07-08T04:54:23Z
[ "python", "loops" ]
how to loop down in python list? for example loop: ``` L = [1,2,3] for item in L print item #-->1,2,3 ``` loop down: ``` L = [1,2,3] for ??? print item #-->3,2,1 ``` thank you
Reverse the sequence. ``` L = [1,2,3] for item in reversed(L) print item #-->3,2,1 ```
Fitting empirical distribution to theoretical ones with Scipy (Python)?
6,620,471
28
2011-07-08T06:00:48Z
16,651,955
47
2013-05-20T14:40:13Z
[ "python", "numpy", "statistics", "scipy", "distribution" ]
INTRODUCTION: I have a list of more than 30 000 values ranging from 0 to 47 e.g.[0,0,0,0,..,1,1,1,1,...,2,2,2,2,..., 47 etc.] which is the continuous distribution. PROBLEM: Based on my distribution I would like to calculate p-value (the probability of seeing greater values) for any given value. For example, as you can...
There are [82 implemented distribution functions in SciPy 0.12.0](http://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions). You can test how some of them fit to your data using their [`fit()` method](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.fit.html#scipy.stats...
Fitting empirical distribution to theoretical ones with Scipy (Python)?
6,620,471
28
2011-07-08T06:00:48Z
37,616,966
13
2016-06-03T14:26:26Z
[ "python", "numpy", "statistics", "scipy", "distribution" ]
INTRODUCTION: I have a list of more than 30 000 values ranging from 0 to 47 e.g.[0,0,0,0,..,1,1,1,1,...,2,2,2,2,..., 47 etc.] which is the continuous distribution. PROBLEM: Based on my distribution I would like to calculate p-value (the probability of seeing greater values) for any given value. For example, as you can...
# Distribution Fitting with Sum of Square Error (SSE) This is an update and modification to [suallo's answer](http://stackoverflow.com/a/16651955/2087463), that uses the full list of the current [`scipy.stats` distributions](http://docs.scipy.org/doc/scipy/reference/stats.html) and returns the distribution with the le...
Writing comments to files with ConfigParser
6,620,637
16
2011-07-08T06:22:21Z
19,432,072
10
2013-10-17T16:20:29Z
[ "python", "configparser" ]
How can one write comments to a given file within sections? If I have: ``` import ConfigParser with open('./config.ini', 'w') as f: conf = ConfigParser.ConfigParser() conf.set('DEFAULT', 'test', 1) conf.write(f) ``` I will get the file: ``` [DEFAULT] test = 1 ``` But how can I get a file with comments ...
You can use the allow\_no\_value option if you have Version >= 2.7 This snippet: ``` import ConfigParser config = ConfigParser.ConfigParser(allow_no_value = True) config.add_section('default_settings') config.set('default_settings', '; comment here') config.set('default_settings', 'test', 1) with open('config.ini', ...
Problem with IF statement in mako template
6,621,401
5
2011-07-08T07:38:09Z
6,622,610
11
2011-07-08T09:38:30Z
[ "python", "pylons", "mako" ]
I have mako template where i check conditions from a simple dict in for loop, like: ``` % for el in seq: % if el["attr"] == 1: ... elif: .... else: ..... % endif ``` And if i want add another IF statement in this loop, like: ``` %if el["attr1"] == 1: .... %endif ``...
You're missing the %endfor and the % from elif and else statements: ``` %for el in seq: %if foo: pass %elif bar: pass %else: pass %endif %endfor ```
Ipython no readline available and pip install readline error
6,622,490
34
2011-07-08T09:28:30Z
14,149,244
59
2013-01-04T00:02:02Z
[ "python", "readline", "ipython", "pip" ]
I installed ipython but it doesn't have the readline option. I first downloaded gnu readline and compiled and installed. DIdn't know whether it was a proper solution but was the first thing I thought of. It still wouldn't work to no avail with the same error as before: ``` WARNING: Readline services not available on t...
[tmaric](http://stackoverflow.com/users/704028/tmaric) is right. I had the same problem while installing iPython (Ubuntu 12.10, quantal, 32-bit). I was missing the dev version of the ncurses5 library. Try: ``` sudo apt-get install libncurses5-dev ``` and then installing the readline module again through pip ``` pip ...
What's the correct way to convert bytes to a hex string in Python 3?
6,624,453
42
2011-07-08T12:31:54Z
6,624,521
48
2011-07-08T12:37:56Z
[ "python", "python-3.x", "hex" ]
What's the correct way to convert bytes to a hex string in Python 3? I see claims of a `bytes.hex` method, `bytes.decode` codecs, and have tried [other](http://docs.python.org/py3k/library/functions.html#hex) possible functions of least astonishment without avail. I just want my bytes as hex!
Use the `binascii` module: ``` >>> import binascii >>> binascii.hexlify('foo'.encode('utf8')) b'666f6f' >>> binascii.unhexlify(_).decode('utf8') 'foo' ``` See this answer: [Python 3.1.1 string to hex](http://stackoverflow.com/questions/2340319/python-3-1-1-string-to-hex/2340358#2340358)
What's the correct way to convert bytes to a hex string in Python 3?
6,624,453
42
2011-07-08T12:31:54Z
16,033,232
23
2013-04-16T09:21:52Z
[ "python", "python-3.x", "hex" ]
What's the correct way to convert bytes to a hex string in Python 3? I see claims of a `bytes.hex` method, `bytes.decode` codecs, and have tried [other](http://docs.python.org/py3k/library/functions.html#hex) possible functions of least astonishment without avail. I just want my bytes as hex!
Python has bytes-to-bytes [standard codecs](http://docs.python.org/dev/library/codecs.html#binary-transforms) that perform convenient transformations like quoted-printable (fits into 7bits ascii), base64 (fits into alphanumerics), hex escaping, gzip and bz2 compression. In Python 2, you could do: ``` b'foo'.encode('he...
What's the correct way to convert bytes to a hex string in Python 3?
6,624,453
42
2011-07-08T12:31:54Z
22,465,079
7
2014-03-17T20:49:49Z
[ "python", "python-3.x", "hex" ]
What's the correct way to convert bytes to a hex string in Python 3? I see claims of a `bytes.hex` method, `bytes.decode` codecs, and have tried [other](http://docs.python.org/py3k/library/functions.html#hex) possible functions of least astonishment without avail. I just want my bytes as hex!
``` import codecs codecs.getencoder('hex_codec')(b'foo')[0] ``` works in Python 3.3 (so "hex\_codec" instead of "hex").
What's the correct way to convert bytes to a hex string in Python 3?
6,624,453
42
2011-07-08T12:31:54Z
36,149,089
16
2016-03-22T08:07:50Z
[ "python", "python-3.x", "hex" ]
What's the correct way to convert bytes to a hex string in Python 3? I see claims of a `bytes.hex` method, `bytes.decode` codecs, and have tried [other](http://docs.python.org/py3k/library/functions.html#hex) possible functions of least astonishment without avail. I just want my bytes as hex!
Since Python 3.5 this is finally no longer awkward: ``` >>> b'\xde\xad\xbe\xef'.hex() 'deadbeef' ``` and reverse: ``` >>> bytes.fromhex('deadbeef') b'\xde\xad\xbe\xef' ``` works also with the mutable `bytearray` type.
Call Python from .NET
6,624,503
10
2011-07-08T12:35:49Z
6,625,001
8
2011-07-08T13:18:17Z
[ "c#", "python", ".net", "python.net" ]
I have some code written in Python which can not be transferred to a .NET language. I need to call one of these functions from my .NET WinForms application. Now, I do it by starting the Python script as a separate process and pass parameters to it as command line arguments. It works, but I don't really like this solut...
This might be a lot more work than launching the Python process, but here's an alternate solution. You can [embed Python](http://docs.python.org/extending/embedding.html) into another program. The API is for C and Interop from .NET will probably be a major pain. If you're into a bit of a safer way to handle the native...
How to use the win32gui module with Python?
6,624,672
12
2011-07-08T12:50:33Z
6,624,724
16
2011-07-08T12:55:38Z
[ "python", "win32gui", "activestate" ]
Im my Python file, I have imported the `win32gui` module like this: ``` import win32gui ``` I have also downloaded `win32gui` but don't know how to make my script run. How can I run my Python script which imports `win32gui`? When I run it, I get: ``` ImportError: No module named win32gui ``` Sorry for the newbie qu...
When on a windows platform, I usually go for the executables. They should work all the time. Try perhaps one of the files listed here: <http://sourceforge.net/projects/pywin32/files/pywin32/Build216/> It's the most recent build. Choose the one appropriate to your Python's version.
Installing/uninstalling my module with pip
6,625,597
30
2011-07-08T14:04:36Z
6,625,649
36
2011-07-08T14:08:46Z
[ "python", "install", "uninstall", "pip" ]
I am going through the *Learn Python the Hard Way, 2nd Edition* book, and I am stuck on this problem: "Use your setup.py to install your own module and make sure it works, then use pip to uninstall it." If I type ``` setup.py install ``` in the command line, I can install the module. But when I type ``` pip unins...
You're giving pip a Python file and not a package name, so it doesn't know what to do. If you want pip to remove it, try providing the name of the package this setup.py file is actually part of. There are some good suggestions in this related thread: [python setup.py uninstall](http://stackoverflow.com/questions/15502...
Unicode literals that work in python 3 and 2
6,625,782
33
2011-07-08T14:19:34Z
6,633,040
25
2011-07-09T05:49:02Z
[ "python", "python-3.x", "unicode", "python-2.x", "unicode-literals" ]
So I have a python script that I'd prefer worked on python 3.2 and 2.7 just for convenience. Is there a way to have unicode literals that work in both? E.g. ``` #coding: utf-8 whatever = 'שלום' ``` The above code would require a unicode string in python 2.x (u'') and in python 3.x that little 'u' causes a syntax...
**Edit - Since Python 3.3, the `u''` literal works again, so the `u()` function isn't needed.** The best option is to make a method that creates unicode objects from string objects in Python 2, but leaves the string objects alone in Python 3 (as they are already unicode). ``` import sys if sys.version < '3': impo...
Build a PyObject* from a C function?
6,626,167
9
2011-07-08T14:47:09Z
6,626,817
20
2011-07-08T15:35:06Z
[ "python", "c", "python-c-api" ]
I am embedding Python in a C++ library which I am making. I would like users to be able to pass C functions in the form of function pointers `PyObject* (fpFunc*)(PyObject*,PyObject*);` so that I can use those functions in the embedded Python. So I have a function pointer and I know that it is possible to put this func...
Found it. Though it's not in the docs and it's hardly explicit in the source. ``` PyObject* (*fpFunc)(PyObject*,PyObject*) = someFunction; PyMethodDef methd = {"methd",fpFunc,METH_VARARGS,"A new function"}; PyObject* name = PyString_FromString(methd.ml_name); PyObject* pyfoo = PyCFunction_NewEx(&methd,NULL,name); Py_D...
Multiple columns index when using the declarative ORM extension of sqlalchemy
6,626,810
39
2011-07-08T15:34:23Z
6,627,154
61
2011-07-08T16:00:49Z
[ "python", "database", "orm", "indexing", "sqlalchemy" ]
According to the documentation: <http://docs.sqlalchemy.org/en/latest/core/constraints.html#indexes> and the comments in the sqlalchemy.Column class, we should use the class `sqlalchemy.schema.Index` to specify an index that contain multiple multiple index. However, the example shows how to do it by directly using th...
those are just `Column` objects, index=True flag works normally: ``` class A(Base): __tablename__ = 'table_A' id = Column(Integer, primary_key=True) a = Column(String(32), index=True) b = Column(String(32), index=True) ``` if you'd like a composite index, again `Table` is present here as usual you jus...
How to pass a variable to an exception when raised and retrieve it when excepted?
6,626,816
6
2011-07-08T15:35:03Z
6,626,842
11
2011-07-08T15:38:18Z
[ "python", "exception" ]
Right now I just have a blank exception class. I was wondering how I can give it a variable when it gets raised and then retrieve that variable when I handle it in the try...except. ``` class ExampleException (Exception): pass ```
Give its constructor an argument, store that as an attribute, then retrieve it in the `except` clause: ``` class FooException(Exception): def __init__(self, foo): self.foo = foo try: raise FooException("Foo!") except FooException as e: print e.foo ```
Why does pip freeze report some packages in a fresh virtualenv created with --no-site-packages?
6,627,035
49
2011-07-08T15:51:27Z
6,631,635
42
2011-07-08T23:35:36Z
[ "python", "ubuntu", "virtualenv", "pip" ]
When I create a fresh virtualenv, `pip freeze` shows that I have a couple of packages installed even though I've not installed anything into the environment. I was expecting `pip freeze` to return empty output until after my first `pip install` into the environment. [wsgiref is part of the standard library](http://docs...
Everytime you create a virtualenv with --no-site-packages it installs `setuptools` or `distribute`. And the reason `wsgiref` appears is because python 2.5+ standard library provides egg info to `wsgiref` lib (and `pip` does not know if it stdlib or 3rd party package). It seems to be solved on Python3.3+: <http://bugs....
Why does pip freeze report some packages in a fresh virtualenv created with --no-site-packages?
6,627,035
49
2011-07-08T15:51:27Z
17,336,454
29
2013-06-27T06:53:53Z
[ "python", "ubuntu", "virtualenv", "pip" ]
When I create a fresh virtualenv, `pip freeze` shows that I have a couple of packages installed even though I've not installed anything into the environment. I was expecting `pip freeze` to return empty output until after my first `pip install` into the environment. [wsgiref is part of the standard library](http://docs...
To answer a slightly different question: you can exclude `wsgiref` (and any other similarly-problematic `.egg` files if you are unfortunate enough to have any for some reason) by doing `pip freeze -l` instead of `pip freeze`. `pip help freeze` describes this option: > -l, --local If in a virtualenv, do not report glo...
How do I bind an existing instance method in one class to another class?
6,627,387
4
2011-07-08T16:20:41Z
6,627,593
7
2011-07-08T16:36:40Z
[ "python" ]
I'm trying to do a limited form of dynamic mixin on a class, taking methods from a third-party library class and binding them to my class. But nothing I've tried has worked correctly. All examples I've seen elsewhere bind a unbound function to a class but, in my case, I need to bind an already bound method to a differe...
Add it as a parent class dynamically, by modifying `YourClass.__bases__`: ``` >>> class Base: pass >>> class Foo(Base): pass >>> class Bar(Base): attr = True >>> Foo.__bases__ = (Bar,) + Foo.__bases__ >>> Foo.attr True ``` Alternatively, get the bound method object and extract the original function, then attach that ...
Is JSON syntax a strict subset of Python syntax?
6,627,635
14
2011-07-08T16:41:49Z
6,627,669
17
2011-07-08T16:45:02Z
[ "javascript", "python", "json", "syntax" ]
JSON is very similar to Python syntax. Can all JSON objects directly convert to Python without error? **Example** The following is a valid JSON object: ``` // Valid JSON {"foo":"bar"} ``` This object will directly translate to a Python dictionary with key "foo" and value "bar": ``` # Python json_dict = eval('{"foo...
No. In particular, `true`, `false`, and `null` are not Python, although they do have direct equivalents in Python (`True`, `False`, and `None` respectively). ``` // Valid JSON {"sky_is_blue":true} ``` But when used in Python... ``` # Python >>> json_dict = eval('{"sky_is_blue":true}') Traceback (most recent call las...
How to configure TASK_SERIALIZER with django-celery
6,627,885
3
2011-07-08T17:06:18Z
6,631,612
15
2011-07-08T23:30:42Z
[ "python", "django", "celery", "django-celery" ]
I'm using django-celery and I'd like to set the `TASK_SERIALIZER` to JSON instead of pickle. I can do this on a per-method basis by changing my task decorators from ``` @task ``` to ``` @task(serializer="json") ``` But I'd like to do it globally. Setting ``` TASK_SERIALIZER="json" ``` in `settings.py` doesn't wo...
Figured it out. In `settings.py` you need to set ``` CELERY_TASK_SERIALIZER = "json" ``` Docs are confusing, at least to me.
How to disallow pickle serialization in celery
6,628,016
35
2011-07-08T17:18:26Z
6,682,247
9
2011-07-13T16:27:46Z
[ "python", "security", "celery" ]
Celery defaults to using pickle as its serialization method for tasks. As noted in the [FAQ](http://ask.github.com/celery/faq.html#isn-t-using-pickle-a-security-concern), this represents a security hole. Celery allows you to configure how tasks get serialized using the `CELERY_TASK_SERIALIZER` configuration parameter. ...
I got an answer from the celery-users mailing list (From Ask Solem to be specific). Add these two lines to the config (celeryconfig/settings): ``` from kombu import serialization serialization.registry._decoders.pop("application/x-python-serialize") ```
How to disallow pickle serialization in celery
6,628,016
35
2011-07-08T17:18:26Z
20,928,529
52
2014-01-05T00:29:47Z
[ "python", "security", "celery" ]
Celery defaults to using pickle as its serialization method for tasks. As noted in the [FAQ](http://ask.github.com/celery/faq.html#isn-t-using-pickle-a-security-concern), this represents a security hole. Celery allows you to configure how tasks get serialized using the `CELERY_TASK_SERIALIZER` configuration parameter. ...
I was getting "ContentDisallowed: Refusing to deserialize untrusted content of type pickle (application/x-python-serialize)" having: ``` CELERY_ACCEPT_CONTENT = ['json'] ``` wasn't enough... I had to also add the followings to settings: ``` CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' ```
Python Fabric: How to retrieve a filelist of a dir
6,628,263
8
2011-07-08T17:42:45Z
6,632,279
16
2011-07-09T02:18:57Z
[ "python", "file", "fabric", "dir", "filelist" ]
I'm building a remote server admin tool using the python-fabric library and am looking for a good way of retrieving a filelist for a directory on the remote server. Currently I'm using run("ls dir") and am manually splitting the return string, which seems horrendous and very much architecture dependent. fabric.contrib....
What's wrong with this? ``` output = run('ls /path/to/files') files = output.split() print files ``` Check the [documentation on `run()`](http://docs.fabfile.org/en/1.10/api/core/operations.html#fabric.operations.run) for more tricks.
Which file is used in import statement for 'MultipleObjectsReturne' exception
6,628,272
2
2011-07-08T17:43:14Z
6,628,362
10
2011-07-08T17:51:30Z
[ "python", "exception-handling" ]
I am using this code ``` except MultipleObjectsReturned: return HttpResponse('some error') ``` but i get this error `global name 'MultipleObjectsReturned' is not defined`
You can do either: ``` from django.core.exceptions import MultipleObjectsReturned except MultipleObjectsReturned as e: return HttpResponse(e) ``` Or: ``` except yourmodel.MultipleObjectsReturned as e: return HttpResponse(e) ``` <https://docs.djangoproject.com/en/1.3/ref/exceptions/#django.core.exceptions.M...
How can I have Django user registration single step (instead of two step)process with email compulsory?
6,628,452
2
2011-07-08T18:00:21Z
6,630,174
7
2011-07-08T20:32:30Z
[ "python", "django", "django-admin", "django-views" ]
I want Django to send an email to user email-address with Login details once admin adds a new user to admin site.So I tried using Django signals for that but just becoz django user registration is a two step process signals get notified in first step only and called email function without email address(which comes in s...
If you look in django.contrib.auth admin.py, you'll see that the UserAdmin class specifies the add\_form as UserCreationForm. UserCreationForm only includes the 'username' field from the User model. Since you're providing your own UserAdmin, you can just override the add\_form to a custom UserCreationForm that includ...
Renaming a virtualenv folder without breaking it
6,628,476
93
2011-07-08T18:02:15Z
6,628,642
102
2011-07-08T18:17:26Z
[ "python", "ubuntu", "virtualenv", "pip" ]
I've created folder and initialized a virtualenv instance in it. ``` $ mkdir myproject $ cd myproject $ virtualenv env ``` When I run `(env)$ pip freeze`, it shows the installed packages as it should. Now I want to rename `myproject/` to `project/`. ``` $ mv myproject/ project/ ``` However, now when I run ``` $ ....
You need to adjust your install to use relative paths. `virtualenv` provides for this with the `--relocatable` option. From [the docs](https://virtualenv.pypa.io/en/latest/userguide.html#making-environments-relocatable): > Normally environments are tied to a > specific path. That means that you > cannot move an enviro...
Renaming a virtualenv folder without breaking it
6,628,476
93
2011-07-08T18:02:15Z
16,683,703
57
2013-05-22T04:52:50Z
[ "python", "ubuntu", "virtualenv", "pip" ]
I've created folder and initialized a virtualenv instance in it. ``` $ mkdir myproject $ cd myproject $ virtualenv env ``` When I run `(env)$ pip freeze`, it shows the installed packages as it should. Now I want to rename `myproject/` to `project/`. ``` $ mv myproject/ project/ ``` However, now when I run ``` $ ....
What I believe is that `"knowing why" matters more than "knowing how"`. So, here is another approach to fix this. When you run: `$ . env/bin/activate` it actually execute the following commands: ( I test this in `/tmp` ) ``` VIRTUAL_ENV="/tmp/myproject/env" export VIRTUAL_ENV ``` However, you have just renamed `m...
Renaming a virtualenv folder without breaking it
6,628,476
93
2011-07-08T18:02:15Z
19,640,078
18
2013-10-28T16:26:20Z
[ "python", "ubuntu", "virtualenv", "pip" ]
I've created folder and initialized a virtualenv instance in it. ``` $ mkdir myproject $ cd myproject $ virtualenv env ``` When I run `(env)$ pip freeze`, it shows the installed packages as it should. Now I want to rename `myproject/` to `project/`. ``` $ mv myproject/ project/ ``` However, now when I run ``` $ ....
**NOTE:** As @jb. points out, this solution only applies to easily (re)created `virtualenv`s. If an environment takes several hours to install this solution is not recommended --- Virtualenvs are great because they are easy to make and switch around; they keep you from getting locked into a single configuration. If y...
Comparing elements of numpy arrays in python
6,628,793
3
2011-07-08T18:29:37Z
6,629,172
7
2011-07-08T19:01:02Z
[ "python", "arrays", "comparison", "numpy" ]
I want to compare two 1x3 arrays such as: ``` if output[x][y] != [150,25,75] ``` (`output` here is a 3x3x3 so `output[x][y]` is only a 1x3). I'm getting an error that says: ``` ValueError: The truth value of an array with more than one element is ambiguous. ``` Does that mean I need to do it like: ``` if output[y...
The numpy way is to use [np.allclose](http://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html#numpy-allclose): ``` np.allclose(a,b) ``` Though for integers, ``` not (a-b).any() ``` is quicker.
k-fold Cross Validation for determining k in k-means?
6,629,165
4
2011-07-08T19:00:11Z
6,631,714
7
2011-07-08T23:48:17Z
[ "python", "statistics", "numpy", "nlp", "machine-learning" ]
In a document clustering process, as a data pre-processing step, I first applied singular vector decomposition to obtain `U`, `S` and `Vt` and then by choosing a suitable number of eigen values I truncated `Vt`, which now gives me a good document-document correlation from what I read [here](http://en.wikipedia.org/wiki...
To run k-fold cross validation, you'd need some measure of quality to optimize for. This could be either a classification measure such as accuracy or [F1](https://secure.wikimedia.org/wikipedia/en/wiki/F1_score), or a specialized one such as the [V-measure](http://acl.ldc.upenn.edu/D/D07/D07-1043.pdf). Even the cluste...
How to make an anonymous function in Python without Christening it?
6,629,876
43
2011-07-08T20:05:00Z
6,629,999
11
2011-07-08T20:16:00Z
[ "python", "anonymous-function", "lambda" ]
Is it possible to put a function in a data structure, without first giving it a name with `def`? ``` # This is the behaviour I want. Prints "hi". def myprint(msg): print msg f_list = [ myprint ] f_list[0]('hi') # The word "myprint" is never used again. Why litter the namespace with it? ``` The body of a lambda fu...
If you want to keep a clean namespace, use del: ``` def myprint(msg): print msg f_list = [ myprint ] del myprint f_list[0]('hi') ```
How to make an anonymous function in Python without Christening it?
6,629,876
43
2011-07-08T20:05:00Z
6,630,703
15
2011-07-08T21:28:19Z
[ "python", "anonymous-function", "lambda" ]
Is it possible to put a function in a data structure, without first giving it a name with `def`? ``` # This is the behaviour I want. Prints "hi". def myprint(msg): print msg f_list = [ myprint ] f_list[0]('hi') # The word "myprint" is never used again. Why litter the namespace with it? ``` The body of a lambda fu...
Nicer DRY way to solve your actual problem: ``` def message(msg): print msg message.re = '^<\w+> (.*)' def warning(msg): global num_warnings, num_fatals num_warnings += 1 if ( is_fatal( msg ) ): num_fatals += 1 warning.re = '^\*{3} (.*)' handlers = [(re.compile(x.re), x) for x in [ me...
How to make an anonymous function in Python without Christening it?
6,629,876
43
2011-07-08T20:05:00Z
6,631,098
34
2011-07-08T22:11:45Z
[ "python", "anonymous-function", "lambda" ]
Is it possible to put a function in a data structure, without first giving it a name with `def`? ``` # This is the behaviour I want. Prints "hi". def myprint(msg): print msg f_list = [ myprint ] f_list[0]('hi') # The word "myprint" is never used again. Why litter the namespace with it? ``` The body of a lambda fu...
This is based on [Udi's nice answer](http://stackoverflow.com/questions/6629876/how-to-make-an-anonymous-function-in-python-without-christening-it/6630179#6630179). I think that the difficulty of creating anonymous functions is a bit of a red herring. What you really want to do is to keep related code together, and ma...
How to make an anonymous function in Python without Christening it?
6,629,876
43
2011-07-08T20:05:00Z
6,635,029
10
2011-07-09T13:30:37Z
[ "python", "anonymous-function", "lambda" ]
Is it possible to put a function in a data structure, without first giving it a name with `def`? ``` # This is the behaviour I want. Prints "hi". def myprint(msg): print msg f_list = [ myprint ] f_list[0]('hi') # The word "myprint" is never used again. Why litter the namespace with it? ``` The body of a lambda fu...
Continuing [Gareth's](http://stackoverflow.com/questions/6629876/how-to-make-an-anonymous-function-in-python-without-christening-it/6631098#6631098) clean approach with a modular self contained solution: ``` import re # in util.py class GenericLogProcessor(object): def __init__(self): self.handlers = [] # ...
import python modules with the same name
6,630,394
3
2011-07-08T20:52:20Z
6,630,415
8
2011-07-08T20:55:01Z
[ "python", "import", "module" ]
I have several python projects and they all have a conf package: ``` /some_folder/project_1/ conf/ __init__.py some_source_file.py /another_folder/project_2/ conf/ __init__.py another_source_file.py ``` For each project, I have created a .pth file in the site-packages folder with this contents: ...
No. You will need to either rename one of them or turn the project directory into a package and import via that.
Assignment in While Loop in Python?
6,631,128
36
2011-07-08T22:16:05Z
6,631,140
12
2011-07-08T22:17:34Z
[ "python", "while-loop", "variable-assignment" ]
I just came across this piece of code ``` while 1: line = data.readline() if not line: break #... ``` and thought, there *must* be a better way to do this, than using an infinite loop with `break`. So I tried: ``` while line = data.readline(): #... ``` and, obviously, got an error. Is ther...
This isn't much better, but this is the way I usually do it. Python doesn't return the value upon variable assignment like other languages (e.g., Java). ``` line = data.readline() while line: # ... do stuff ... line = data.readline() ```
Assignment in While Loop in Python?
6,631,128
36
2011-07-08T22:16:05Z
6,631,156
19
2011-07-08T22:18:58Z
[ "python", "while-loop", "variable-assignment" ]
I just came across this piece of code ``` while 1: line = data.readline() if not line: break #... ``` and thought, there *must* be a better way to do this, than using an infinite loop with `break`. So I tried: ``` while line = data.readline(): #... ``` and, obviously, got an error. Is ther...
If you aren't doing anything fancier with data, like reading more lines later on, there's always: ``` for line in data: ... do stuff ... ```
Assignment in While Loop in Python?
6,631,128
36
2011-07-08T22:16:05Z
12,944,855
31
2012-10-17T23:18:17Z
[ "python", "while-loop", "variable-assignment" ]
I just came across this piece of code ``` while 1: line = data.readline() if not line: break #... ``` and thought, there *must* be a better way to do this, than using an infinite loop with `break`. So I tried: ``` while line = data.readline(): #... ``` and, obviously, got an error. Is ther...
Try this one, works for files opened with `open('filename')` ``` for line in iter(data.readline, b''): ```
Python: Opening a folder in Explorer/Nautilus/Mac-thingie
6,631,299
23
2011-07-08T22:41:44Z
6,631,329
13
2011-07-08T22:46:41Z
[ "python", "cross-platform", "folder" ]
I'm in Python, and I have the path of a certain folder. I want to open it using the default folder explorer for that system. For example, if it's a Windows computer, I want to use Explorer, if it's Linux, I want to use Nautilus or whatever is the default there, if it's Mac, I want to use whatever Mac OS's explorer is c...
You can use `subprocess`. ``` import subprocess import sys if sys.platform == 'darwin': def openFolder(path): subprocess.check_call(['open', '--', path]) elif sys.platform == 'linux2': def openFolder(path): subprocess.check_call(['xdg-open', '--', path]) elif sys.platform == 'win32': def o...
Python: Opening a folder in Explorer/Nautilus/Mac-thingie
6,631,299
23
2011-07-08T22:41:44Z
16,204,023
14
2013-04-24T23:36:25Z
[ "python", "cross-platform", "folder" ]
I'm in Python, and I have the path of a certain folder. I want to open it using the default folder explorer for that system. For example, if it's a Windows computer, I want to use Explorer, if it's Linux, I want to use Nautilus or whatever is the default there, if it's Mac, I want to use whatever Mac OS's explorer is c...
I am surprised no one has mentioned using `xdg-open` for \**nix* which will work for both files and folders: ``` import os import platform import subprocess def open_file(path): if platform.system() == "Windows": os.startfile(path) elif platform.system() == "Darwin": subprocess.Popen(["open", ...
Why does \w+ match a newline in Python?
6,631,481
5
2011-07-08T23:11:38Z
6,631,503
8
2011-07-08T23:15:05Z
[ "python", "regex" ]
I am curious why the following would output that there was a match: ``` import re foo = 'test\n' match = re.search('^\w+$', foo) if match == None: print "It did not match" else: print "Match!" ``` The newline is before the end of the string, yes? Why is this matching?
`^` and `$` mean "start of line" and "end of line", not "start of string" and "end of string". Use `\A` for "start of string" and `\Z` for "end of string".
Why does \w+ match a newline in Python?
6,631,481
5
2011-07-08T23:11:38Z
6,631,506
9
2011-07-08T23:15:36Z
[ "python", "regex" ]
I am curious why the following would output that there was a match: ``` import re foo = 'test\n' match = re.search('^\w+$', foo) if match == None: print "It did not match" else: print "Match!" ``` The newline is before the end of the string, yes? Why is this matching?
From Python's [`re`](http://docs.python.org/library/re.html#regular-expression-syntax) documentation. > **'$'** > Matches the end of the string or just before the newline at the end of the string, and in MULTILINE mode also matches before a newline. *foo* matches both ‘foo’ and ‘foobar’, while the regular ex...
wxpython frame on top
6,631,670
2
2011-07-08T23:42:09Z
6,631,777
7
2011-07-09T00:02:06Z
[ "python", "wxpython" ]
how can i create a frame that is on top of all the other windows ? also i don't want the frame to be created as an on top window, i want the user to have a button that can be clicked so the frame becomes in on top mode and if it is clicked again then it becomes a normal frame ! i tried using ``` frame= wx.Frame.__ini...
I think you might want to look at something like self.ToggleWindowStyle(wx.STAY\_ON\_TOP) <http://docs.wxwidgets.org/stable/wx_wxwindow.html#wxwindowtogglewindowstyle> and <http://docs.wxwidgets.org/stable/wx_wxframe.html#wxframe>
Explicitly select items from a Python list or tuple
6,632,188
47
2011-07-09T01:49:10Z
6,632,205
21
2011-07-09T01:52:44Z
[ "python", "list", "select", "indexing", "tuples" ]
I have the following Python list (can also be a tuple): ``` myList = ['foo', 'bar', 'baz', 'quux'] ``` I can say ``` >>> myList[0:3] ['foo', 'bar', 'baz'] >>> myList[::2] ['foo', 'baz'] >>> myList[1::2] ['bar', 'quux'] ``` How do I explicitly pick out items whose indices have no specific patterns? For example, I wa...
What about this: ``` from operator import itemgetter itemgetter(0,2,3)(myList) ('foo', 'baz', 'quux') ```
Explicitly select items from a Python list or tuple
6,632,188
47
2011-07-09T01:49:10Z
6,632,209
57
2011-07-09T01:53:48Z
[ "python", "list", "select", "indexing", "tuples" ]
I have the following Python list (can also be a tuple): ``` myList = ['foo', 'bar', 'baz', 'quux'] ``` I can say ``` >>> myList[0:3] ['foo', 'bar', 'baz'] >>> myList[::2] ['foo', 'baz'] >>> myList[1::2] ['bar', 'quux'] ``` How do I explicitly pick out items whose indices have no specific patterns? For example, I wa...
``` list( myBigList[i] for i in [87, 342, 217, 998, 500] ) ``` --- I compared the answers with python 2.5.2: * 19.7 usec: `[ myBigList[i] for i in [87, 342, 217, 998, 500] ]` * 20.6 usec: `map(myBigList.__getitem__, (87, 342, 217, 998, 500))` * 22.7 usec: `itemgetter(87, 342, 217, 998, 500)(myBigList)` * 24.6 usec: ...
Explicitly select items from a Python list or tuple
6,632,188
47
2011-07-09T01:49:10Z
6,632,219
7
2011-07-09T01:57:35Z
[ "python", "list", "select", "indexing", "tuples" ]
I have the following Python list (can also be a tuple): ``` myList = ['foo', 'bar', 'baz', 'quux'] ``` I can say ``` >>> myList[0:3] ['foo', 'bar', 'baz'] >>> myList[::2] ['foo', 'baz'] >>> myList[1::2] ['bar', 'quux'] ``` How do I explicitly pick out items whose indices have no specific patterns? For example, I wa...
It isn't built-in, but you can make a subclass of list that takes tuples as "indexes" if you'd like: ``` class MyList(list): def __getitem__(self, index): if isinstance(index, tuple): return [self[i] for i in index] return super(MyList, self).__getitem__(index) seq = MyList("foo bar ...
python array_walk() alternative
6,632,315
3
2011-07-09T02:30:42Z
6,632,338
11
2011-07-09T02:36:23Z
[ "python" ]
i have a list that looks like this: ``` list = [1,2,3,4] ``` I would like to add 12 to each value. In PHP you can use array\_walk to process each item in the array. Is there a similar function or easier way than doing a for loop such as: ``` for i in list: ``` Thanks
Use [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions). Try this: ``` list = [i+12 for i in list] ```
GAE: unit testing taskqueue with testbed
6,632,809
17
2011-07-09T04:52:43Z
6,635,042
8
2011-07-09T13:32:05Z
[ "python", "unit-testing", "google-app-engine", "task-queue" ]
I'm using testbed to unit test my google app engine app, and my app uses a taskqueue. When I submit a task to a taskqueue during a unit test, it appears that the task is in the queue, but the task does not execute. How do I get the task to execute during a unit test?
The dev app server is single-threaded, so it can't run tasks in the background while the foreground thread is running the tests. I modified TaskQueueTestCase in taskqueue.py in gaetestbed to add the following function: ``` def execute_tasks(self, application): """ Executes all currently queued tasks, and also...
GAE: unit testing taskqueue with testbed
6,632,809
17
2011-07-09T04:52:43Z
6,635,947
24
2011-07-09T16:12:34Z
[ "python", "unit-testing", "google-app-engine", "task-queue" ]
I'm using testbed to unit test my google app engine app, and my app uses a taskqueue. When I submit a task to a taskqueue during a unit test, it appears that the task is in the queue, but the task does not execute. How do I get the task to execute during a unit test?
Using Saxon's excellent answer, I was able to do the same thing using testbed instead of gaetestbed. Here is what I did. Added this to my `setUp()`: ``` self.taskqueue_stub = apiproxy_stub_map.apiproxy.GetStub('taskqueue') ``` Then, in my test, I used the following: ``` # Execute the task in the taskqueue ...
GAE: unit testing taskqueue with testbed
6,632,809
17
2011-07-09T04:52:43Z
7,333,837
13
2011-09-07T12:23:32Z
[ "python", "unit-testing", "google-app-engine", "task-queue" ]
I'm using testbed to unit test my google app engine app, and my app uses a taskqueue. When I submit a task to a taskqueue during a unit test, it appears that the task is in the queue, but the task does not execute. How do I get the task to execute during a unit test?
Another (cleaner) option to achieve this is to use the task queue stub within the testbed. To do this you first have to initialize the task queue stub by adding the following to your `setUp()` method: ``` self.testbed = init_testbed() self.testbed.init_taskqueue_stub() ``` The tasks scheduler can be accessed using th...
How can I convert a string with dot and comma into a float number in Python
6,633,523
22
2011-07-09T07:59:37Z
6,633,537
38
2011-07-09T08:02:02Z
[ "python" ]
How can I convert a string like "123,456.908" to float number 123456.908 in Python? Thanks a lot.
Just remove the `,` with `replace()`: ``` float("123,456.908".replace(',','')) ```
How can I convert a string with dot and comma into a float number in Python
6,633,523
22
2011-07-09T07:59:37Z
6,633,912
75
2011-07-09T09:22:21Z
[ "python" ]
How can I convert a string like "123,456.908" to float number 123456.908 in Python? Thanks a lot.
... Or instead of treating the commas as garbage to be filtered out, we could treat the overall string as a localized formatting of the float, and use the localization services: ``` from locale import * setlocale(LC_NUMERIC, '') # set to your default locale; for me this is # 'English_Canada.1252'. Or you could explici...
How to specify header files in setup.py script for Python extension module?
6,633,624
10
2011-07-09T08:19:47Z
6,681,343
12
2011-07-13T15:24:18Z
[ "python", "distutils" ]
How do I specify the header files in a setup.py script for a Python extension module? Listing them with source files as follows does not work. But I can not figure out where else to list them. ``` from distutils.core import setup, Extension from glob import glob setup( name = "Foo", version = "0.1.0", ext...
Add *MANIFEST.in* file besides setup.py with following contents: ``` graft relative/path/to/directory/of/your/headers/ ```
Finding words after keyword in python
6,633,678
10
2011-07-09T08:30:56Z
6,633,693
22
2011-07-09T08:33:53Z
[ "python", "regex", "matching", "keyword" ]
I want to find words that appear after a keyword (specified and searched by me) and print out the result. I know that i am suppose to use regex to do it, and i tried it out too, like this: ``` import re s = "hi my name is ryan, and i am new to python and would like to learn more" m = re.search("^name: (\w+)", s) print...
Instead of using regexes you could just (for example) separate your string [with `str.partition(separator)`](http://docs.python.org/library/stdtypes.html) like this: ``` mystring = "hi my name is ryan, and i am new to python and would like to learn more" keyword = 'name' befor_keyowrd, keyword, after_keyword = mystri...
TypeError: 'dict' object is not callable
6,634,708
18
2011-07-09T12:25:00Z
6,634,727
19
2011-07-09T12:28:27Z
[ "python" ]
Can some one please explain this. ``` number_map = { 1: -3, 2: -2, 3: -1, 4: 1, 5: 2, 6: 3 } input_str = raw_input("Enter something: ") strikes = [number_map(int(x)) for x in input_str.split()] strikes = [number_map(int(x)) for x in input_str.split()] TypeError: 'dict' object is not callable ```
The syntax for accessing a dict given a key is `number_map[int(x)]`. `number_map(int(x))` would actually be a function call but since `number_map` is not a callable, an exception is raised.
TypeError: 'dict' object is not callable
6,634,708
18
2011-07-09T12:25:00Z
6,634,749
7
2011-07-09T12:31:58Z
[ "python" ]
Can some one please explain this. ``` number_map = { 1: -3, 2: -2, 3: -1, 4: 1, 5: 2, 6: 3 } input_str = raw_input("Enter something: ") strikes = [number_map(int(x)) for x in input_str.split()] strikes = [number_map(int(x)) for x in input_str.split()] TypeError: 'dict' object is not callable ```
Access the dictionary with square brackets. ``` strikes = [number_map[int(x)] for x in input_str.split()] ```
Django: Caught NoReverseMatch while rendering: Reverse for '*' with arguments '()' and keyword arguments '{}' not found
6,635,051
5
2011-07-09T13:33:44Z
6,635,189
9
2011-07-09T14:00:36Z
[ "python", "django" ]
Error: ``` Caught NoReverseMatch while rendering: Reverse for 'archive' with arguments '()' and keyword arguments '{}' not found. Template error In template /home/bravedick/Aptana Studio 3 Workspace/blog/templates/homepage/index.html, error at line 7 ``` line 7: ``` 6 <a href="{% url index %}">Index</a> 7 <a h...
I can see one immediate problem with your main url configuration. You have a '$' symbol, signifying end of the url in your include statement. That line should read: ``` (r'^', include('blog.apps.homepage.urls')), ``` Here's [the documentation for `include`](https://docs.djangoproject.com/en/dev/topics/http/urls/#inc...
Pickle all attributes except one
6,635,331
19
2011-07-09T14:22:38Z
6,635,376
8
2011-07-09T14:31:33Z
[ "python", "pickle" ]
What is the best way to write a `__getstate__` method that pickles *almost* all of an object's attributes, but excludes a few? I have an object with many properties, including one that references an instancemethod. instancemethod's are not pickleable, so I'm getting an error when I try to pickle this object: ``` clas...
> The only alternative I can think of is some kind of helper function that iterates through an object's properties and adds them (or not) to the dictionary, based on the type. Yeah, I think that's pretty much what you're left with, if you want enough "magic" to allow yourself to be lazy (and/or allow for dynamically a...
Recent-ish changes to the Python execution model?
6,636,127
15
2011-07-09T16:50:57Z
6,636,272
22
2011-07-09T17:20:20Z
[ "python", "execution", "pypy", "psyco" ]
I just re-read the section on execution models in the 3rd edition of *Learning Python* (late 2007), and it felt fairly tentative. So, I looked at the same section in the 4th edition (late 2009) and was pretty disappointed that it was completely unchanged. What is the status for executing Python beyond CPython? It feel...
The developer of Psyco, Armin Rigo, now works on PyPy along with a lot of other brilliant developers. PyPy is very actively developed and a lot of [exciting stuff](http://morepypy.blogspot.com/2011/06/global-interpreter-lock-or-how-to-kill.html) is planned for it in the future. PyPy compiled with JIT is almost always f...
Python Django Templates and testing if a variable is null or empty string
6,637,168
21
2011-07-09T20:03:17Z
6,637,323
36
2011-07-09T20:38:14Z
[ "python", "django", "django-templates" ]
I am pretty new to django, but have many years experience coding in the java world, so I feel ridiculous asking this question - I am sure the answer is obvious and I am just missing it. I can't seem to find the right way to query this in google or something... I have searched through the django docs and it either isn't...
``` {% if lesson.assignment and lesson.assignment.strip %} ``` The `.strip` calls `str.strip()` so you can handle whitespace-only strings as empty, while the preceding check makes sure we weed out `None` first (which would not have the `.strip()` method) Proof that it works (in `./manage.py shell`): ``` >>> import d...
Incorrect exit code in python when calling windows script
6,637,468
5
2011-07-09T21:07:32Z
6,639,120
7
2011-07-10T04:14:57Z
[ "python", "windows" ]
I don't seem to be getting the correct exit code from subprocess.call on Windows. ``` import subprocess exit_code = subprocess.call(['ant.bat', 'fail']) print exit_code # prints 0 ``` Doing the same thing on windows seems to return something other than 0 ``` > echo %errorlevel% 0 > ant fail > echo %errorlevel% 1 ```...
A process exit code and the errorlevel environment variable aren't the same: ``` ant.bat: if "%1"=="batch_fail" exit /B 1 if "%1"=="proc_fail" exit 1 >>> import subprocess >>> subprocess.call(['ant.bat', 'batch_fail']) 0 >>> subprocess.call(['ant.bat', 'proc_fail']) 1 ``` batch\_fail will set the errorlevel to 1, ...
Bit-operations on large number of bytes
6,637,581
4
2011-07-09T21:28:28Z
6,637,701
7
2011-07-09T21:49:33Z
[ "python", "encryption", "bitwise-operators" ]
Doing some exercises with simple file encryption/decryption and am currently just reading in a bunch of bytes and performing the appropriate bit-operations on each byte one at a time, then writing them to the output file. This method seems pretty slow. For example, if I want to XOR every byte by 0xFF, I would loop ove...
Using the [bitwise array operations](http://docs.scipy.org/doc/numpy/reference/routines.bitwise.html) from `numpy` may be what you're looking for.