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
django request.user.is_authenticated is always true?
9,316,666
8
2012-02-16T18:12:41Z
9,317,009
7
2012-02-16T18:33:39Z
[ "python", "django" ]
Can anyone tell me why in the following code I get redirected to yahoo.com instead of google.com? urls ``` urlpatterns = patterns('', (r'^$', initialRequest,)) ``` view ``` def initialRequest(request): if request.user.is_authenticated: return HttpResponseRedirect('http://yahoo.com') else: r...
As Richard mentioned is\_authenticated is a function, so in your view it should be called like: `request.user.is_authenticated()`. Because of django templating language there can be confusion, because calling this in a template makes it appear as a property and not a method. `{{ user.is_authenticated}}` <https://docs...
Python return list from function
9,317,025
15
2012-02-16T18:35:00Z
9,317,075
10
2012-02-16T18:37:44Z
[ "python", "list", "function" ]
I have a function that parses a file into a list. I'm trying to return that list so I can use it in other functions. ``` def splitNet(): network = [] for line in open("/home/tom/Dropbox/CN/Python/CW2/network.txt","r").readlines(): line = line.replace("\r\n", "") line = string.split(line, ',') ...
I assume you are not assigning the returned value to a variable in scope. ie. you can't do ``` splitNet() print network ``` instead you would ``` network = splitNet() print network ``` or for that matter ``` my_returned_network_in_scope = splitNet() print my_returned_network_in_scope ``` otherwise you could decl...
Python return list from function
9,317,025
15
2012-02-16T18:35:00Z
9,317,077
26
2012-02-16T18:37:50Z
[ "python", "list", "function" ]
I have a function that parses a file into a list. I'm trying to return that list so I can use it in other functions. ``` def splitNet(): network = [] for line in open("/home/tom/Dropbox/CN/Python/CW2/network.txt","r").readlines(): line = line.replace("\r\n", "") line = string.split(line, ',') ...
Variables cannot be accessed outside the scope of a function they were defined in. Simply do this: ``` network = splitNet() print network ```
Possible to do a string replace with a dictionary?
9,317,954
6
2012-02-16T19:41:23Z
9,318,042
8
2012-02-16T19:47:43Z
[ "python" ]
I would like to change all accented characters into non-accented characters: ``` conversion_dict = {"ä": "a", "ö": "o", "ü": "u","Ä": "A", "Ö": "O", "Ü": "U", "á": "a", "à": "a", "â": "a", "é": "e", "è": "e", "ê": "e", "ú": "u", "ù": "u", "û": "u", "ó": "o", "ò":...
**preferred method using third-party module** A much better alternative than the method below is to use the awesome [unidecode](http://pypi.python.org/pypi/Unidecode/) module: ``` >>> import unidecode >>> somestring = u"äüÊÂ" >>> unidecode.unidecode(somestring) 'auEA' ``` **built-in, slightly-hazardous method** ...
How to redefine the = in python?
9,318,305
3
2012-02-16T20:06:39Z
9,318,330
13
2012-02-16T20:08:27Z
[ "python", "methods", "operators", "operator-overloading", "redefine" ]
I would to know what Python call when I use the `=`: ``` a = b ``` Where do I look for this information? I would have the "assignment to variables" with my = a would have a similar behaviour ``` l=list() l.append(1) l.append(2) l.append(3) l1=l l1[2] = ’B’ print(l1) [1, 2, ’B’] print(l) [...
You can't redefine `=` in Python. It will always bind the object on the right-hand side to the name on the left-hand side. Note that this is quite different from e.g. C++, where the `=` operator typically involves copying data to the target variable. Python does not have variables in the sense C++ has. Python has name...
How to redefine the = in python?
9,318,305
3
2012-02-16T20:06:39Z
9,318,433
7
2012-02-16T20:17:32Z
[ "python", "methods", "operators", "operator-overloading", "redefine" ]
I would to know what Python call when I use the `=`: ``` a = b ``` Where do I look for this information? I would have the "assignment to variables" with my = a would have a similar behaviour ``` l=list() l.append(1) l.append(2) l.append(3) l1=l l1[2] = ’B’ print(l1) [1, 2, ’B’] print(l) [...
You can't redefine `=`, but you *can* redefine: ``` a[c] = b or a.c = b ``` Do this by implementing [`__setitem__`](http://docs.python.org/reference/datamodel.html#object.__setitem__) or [`__setattr__`](http://docs.python.org/reference/datamodel.html#object.__setattr__), respectively. For attributes, it's often m...
Why are some mysql connections selecting old data the mysql database after a delete + insert?
9,318,347
5
2012-02-16T20:09:35Z
9,318,495
8
2012-02-16T20:23:33Z
[ "python", "mysql", "session", "caching", "wsgi" ]
I'm having a problem with the sessions in my python/wsgi web app. There is a different, persistent mysqldb connection for each thread in each of 2 wsgi daemon processes. Sometimes, after deleting old sessions and creating a new one, some connections still fetch the old sessions in a select, which means they fail to val...
MySQL defaults to the isolation level "REPEATABLE READ" which means you will not see any changes in your transaction that were done after the transaction started - even if those (other) changes were committed. If you issue a COMMIT or ROLLBACK in those sessions, you should see the changed data (because that will end t...
How to make __repr__ to return unicode string
9,318,574
2
2012-02-16T20:29:35Z
9,318,611
7
2012-02-16T20:32:16Z
[ "python", "unicode", "repr" ]
I call a `__repr__()` function on object `x` as follows: `val = x.__repr__()` and then I want to store `val` string to `SQLite` database. The problem is that `val` should be unicode. I tried this with no success: `val = x.__repr__().encode("utf-8")` and `val = unicode(x.__repr__())` Do you know how to correct th...
`repr(x).decode("utf-8")` and `unicode(repr(x), "utf-8")` should work.
How to make __repr__ to return unicode string
9,318,574
2
2012-02-16T20:29:35Z
9,319,359
14
2012-02-16T21:27:59Z
[ "python", "unicode", "repr" ]
I call a `__repr__()` function on object `x` as follows: `val = x.__repr__()` and then I want to store `val` string to `SQLite` database. The problem is that `val` should be unicode. I tried this with no success: `val = x.__repr__().encode("utf-8")` and `val = unicode(x.__repr__())` Do you know how to correct th...
The representation of an object should not be Unicode. Define the `__unicode__` method and pass the object to `unicode()`.
Python - how do I call external python programs?
9,318,581
11
2012-02-16T20:30:30Z
9,318,637
14
2012-02-16T20:34:46Z
[ "python", "call", "external" ]
***I'll preface this by saying it's a homework assignment. I don't want code written out for me, just to be pointed in the right direction.*** We're able to work on a project of our choice so I'm working on a program to be a mini portfolio of everything I've written so far. So I'm going to make a program that the user...
If you want to call each as a Python script, you can do ``` import subprocess subprocess.call(["python", "myscript.py"]) subprocess.call(["python", "myscript2.py"]) ``` But a better way is to call functions you've written in other scripts, like this: ``` import myscript import myscript2 myscript.function_from_scrip...
Purpose of __init__
9,318,740
3
2012-02-16T20:43:21Z
9,318,867
15
2012-02-16T20:53:04Z
[ "python", "init" ]
I've done some reading and can't grasp this as fully as I'd like to. I'm making a little "choose your own adventure" game from the LPTHW tutorial, here's the full script: <http://codepad.org/YWVUlHnU> What I don't understand is the following: ``` class Game(object): def __init__(self, start): self.quips ...
When you call `Game("central_corridor")`, a new object is created and the `Game.__init__()` method is called with that new object as the first argument (`self`) and `"central_corridor"` as the second argument. Since you wrote `a_game = Game(...)`, you have assigned `a_game` to refer to that new object. This graphic ma...
Quick and easy file dialog in Python?
9,319,317
33
2012-02-16T21:24:41Z
9,319,726
14
2012-02-16T21:59:24Z
[ "python", "openfiledialog" ]
I have a simple script which parses a file and loads it's contents to a database. I don't need a UI, but right now I'm prompting the user for the file to parse using `raw_input` which is most unfriendly, especially because the user can't copy/paste the path. I would like a quick and easy way to present a file selection...
You can use [easygui](http://easygui.sourceforge.net): ``` import easygui path = easygui.fileopenbox() ``` To install [`easygui`](http://easygui.readthedocs.org/en/master/), you can use `pip`: ``` pip3 install easygui ``` It is a single pure Python module (`easygui.py`) that uses `tkinter`.
Quick and easy file dialog in Python?
9,319,317
33
2012-02-16T21:24:41Z
9,319,832
14
2012-02-16T22:07:26Z
[ "python", "openfiledialog" ]
I have a simple script which parses a file and loads it's contents to a database. I don't need a UI, but right now I'm prompting the user for the file to parse using `raw_input` which is most unfriendly, especially because the user can't copy/paste the path. I would like a quick and easy way to present a file selection...
Try with [wxPython](http://wxpython.org/): ``` import wx def get_path(wildcard): app = wx.App(None) style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST dialog = wx.FileDialog(None, 'Open', wildcard=wildcard, style=style) if dialog.ShowModal() == wx.ID_OK: path = dialog.GetPath() else: path ...
Quick and easy file dialog in Python?
9,319,317
33
2012-02-16T21:24:41Z
14,119,223
60
2013-01-02T08:58:32Z
[ "python", "openfiledialog" ]
I have a simple script which parses a file and loads it's contents to a database. I don't need a UI, but right now I'm prompting the user for the file to parse using `raw_input` which is most unfriendly, especially because the user can't copy/paste the path. I would like a quick and easy way to present a file selection...
Tkinter is the easiest way if you don't want to have any other dependencies. To show only the dialog without any other GUI elements, you have to hide the root window using the [`withdraw`](http://effbot.org/tkinterbook/wm.htm#Tkinter.Wm.withdraw-method) method: ``` import tkinter as tk from tkinter import filedialog ...
Moving django models into their own files
9,319,430
7
2012-02-16T21:33:50Z
9,319,479
9
2012-02-16T21:37:45Z
[ "python", "django", "orm", "model" ]
In the name of maintainability, I moved some of my larger models to their own files. So before i had this: ``` app/ models.py ``` and now I have this: ``` app/ models/ __init__.py model_a.py model_b.py ``` This works fine, but when I use manage.py to do sync db, it doesn't create a table for these m...
You need to set `Meta.app_label` for each of the models to the app name where it belongs and make sure they are imported from `models/__init__.py`. You can have a look here for more details: <https://code.djangoproject.com/wiki/CookBookSplitModelsToFiles>
Moving django models into their own files
9,319,430
7
2012-02-16T21:33:50Z
9,319,488
17
2012-02-16T21:38:20Z
[ "python", "django", "orm", "model" ]
In the name of maintainability, I moved some of my larger models to their own files. So before i had this: ``` app/ models.py ``` and now I have this: ``` app/ models/ __init__.py model_a.py model_b.py ``` This works fine, but when I use manage.py to do sync db, it doesn't create a table for these m...
Models must be found in module named `app.models` where `app` is an app name. So you should write in `app/models/__init__.py` file ``` from model_a import * from model_b import * ``` ### In Django < 1.7 Note fron django 1.7 onwards this is not neccessary. Moreover --- (that's what I had problem with) you will ha...
Accessing python dict with multiple key lookup string
9,320,335
8
2012-02-16T22:50:37Z
9,320,375
22
2012-02-16T22:53:43Z
[ "python", "dictionary" ]
I am looking to create a simple "lookup" mechanism in python, and wanted to make sure there wasn't already something somewhere hidden in the vast libraries in python that doesn't already do this before creating it. I am looking to take a dict that is formatted something like this ``` my_dict = { "root": { "se...
There's nothing in the standard library for this purpose, but it is rather easy to code this yourself: ``` >>> key = "root.secondary.user2" >>> reduce(dict.get, key.split("."), my_dict) {'age': 25, 'name': 'fred'} ``` This exploits the fact that the look-up for the key `k` in the dictionary `d` can be written as `dic...
Persistent memoization in Python
9,320,463
10
2012-02-16T23:02:24Z
9,320,661
7
2012-02-16T23:22:52Z
[ "python", "concurrency", "persistence", "memoization", "file-locking" ]
I have an expensive function that takes and returns a small amount of data (a few integers and floats). I have already [memoized](http://en.wikipedia.org/wiki/Memoization) this function, but I would like to make the memo persistent. There are already a couple of threads relating to this, but I'm unsure about potential ...
sqlite3 out of the box provides [ACID](http://en.wikipedia.org/wiki/ACID). File locking is prone to race-conditions and concurrency problems that you won't have using sqlite3. Basically, yeah, sqlite3 is more than what you need, but it's not a huge burden. It can run on mobile phones, so it's not like you're committin...
Python Math - TypeError: 'NoneType' object is not subscriptable
9,320,766
6
2012-02-16T23:33:44Z
9,320,799
11
2012-02-16T23:36:29Z
[ "python", "math", "sorting", "in-place" ]
I'm making a small program for math (no particular reason, just kind of wanted to) and I ran into the error "TypeError: 'NoneType' object is not subscriptable. I have never before seen this error, so I have no idea what it means. ``` import math print("The format you should consider:") print str("value 1a")+str(" + ...
``` lista = list.sort(lista) ``` This should be ``` lista.sort() ``` The `.sort()` method is in-place, and returns None. If you want something not in-place, which returns a value, you could use ``` sorted_list = sorted(lista) ``` Aside #1: please don't call your lists `list`. That clobbers the builtin list type. ...
Python Math - TypeError: 'NoneType' object is not subscriptable
9,320,766
6
2012-02-16T23:33:44Z
9,320,883
8
2012-02-16T23:45:53Z
[ "python", "math", "sorting", "in-place" ]
I'm making a small program for math (no particular reason, just kind of wanted to) and I ran into the error "TypeError: 'NoneType' object is not subscriptable. I have never before seen this error, so I have no idea what it means. ``` import math print("The format you should consider:") print str("value 1a")+str(" + ...
The exception `TypeError: 'NoneType' object is not subscriptable` happens because the value of `lista` is actually `None`. You can reproduce `TypeError` that you get in your code if you try this at the Python command line: ``` None[0] ``` The reason that `lista` gets set to None is because the return value of `list.s...
Printing to screen and writing to a file at the same time
9,321,741
8
2012-02-17T01:35:06Z
9,321,890
51
2012-02-17T01:55:47Z
[ "python" ]
I found some code online that generally works, but I want to use it multiple times in the same program (write different things to different files, while still printing to the screen the whole time). That is to say, when it closes, I think sys.stdout closes, so printing at all, and using this class again fails. I tried...
You are trying to reproduce poorly something that is done very well by the Python Standard Library; please check the [logging module](http://docs.python.org/library/logging.html). With this module you can do exactly what you want, but in a much simpler, standard, and extensible manner. You can proceed as follows (this...
Set encoding in Python 3 CGI scripts
9,322,410
9
2012-02-17T03:18:52Z
19,574,801
10
2013-10-24T19:24:37Z
[ "python", "unicode", "python-3.x", "cgi" ]
When writing a **Python 3.1** CGI script, I run into horrible UnicodeDecodeErrors. However, when running the script on the command line, everything works. It seems that `open()` and `print()` use the return value of `locale.getpreferredencoding()` to know what encoding to use by default. When running on the command li...
Answering this for late-comers because I don't think that the posted answers get to the root of the problem, which is the lack of locale environment variables in a CGI context. I'm using Python 3.2. 1. open() opens file objects in text (string) or binary (bytes) mode for reading and/or writing; in text mode the encodi...
Reply to Tweet with Tweepy - Python
9,322,465
4
2012-02-17T03:28:24Z
10,678,412
7
2012-05-21T00:36:34Z
[ "python", "twitter", "tweepy" ]
I can't seem to get tweepy to work with replying to a specific tweet: ``` auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) api = tweepy.API(auth) ### at this point I've grabbed the tweet and loaded it to JSON... tweetId = tweet['results'][0]['id'] api.updat...
I ran into the same problem, but luckily I found the solution. You just need to include the user's screen\_name in the tweet: ``` api.update_status('@<username> My status update', tweetId) ```
finding n largest differences between two lists
9,323,159
5
2012-02-17T05:02:25Z
9,323,276
8
2012-02-17T05:18:07Z
[ "python", "algorithm", "data-structures", "ordereddictionary" ]
I have two lists `old` and `new`, with the same number of elements. I'm trying to write an efficient function that takes `n` as a parameter, compares the elements of two lists at the same locations (by index), finds `n` largest differences, and returns the indices of those `n` elements. I was thinking this would be b...
Whenever you think "[n largest](http://docs.python.org/library/heapq.html#heapq.nlargest)", think [`heapq`](http://docs.python.org/library/heapq.html). ``` >>> import heapq >>> import random >>> l1 = [random.randrange(100) for _ in range(100)] >>> l2 = [random.randrange(100) for _ in range(100)] >>> heapq.nlargest(10,...
Python: Check if one dictionary is a subset of another larger dictionary
9,323,749
38
2012-02-17T06:15:30Z
9,323,769
47
2012-02-17T06:18:34Z
[ "python", "dictionary", "filter", "subset" ]
I'm trying to write a custom filter method that takes an arbitrary number of *kwargs* and returns a list containing the elements of a database-like list that contain those *kwargs*. For example, suppose `d1 = {'a':'2', 'b':'3'}` and `d2` = the same thing. `d1 == d2` results in True. But suppose `d2` = the same thing p...
Convert to item pairs and check for containment. ``` all(item in superset.items() for item in subset.items()) ``` Optimization is left as an exercise for the reader.
Python: Check if one dictionary is a subset of another larger dictionary
9,323,749
38
2012-02-17T06:15:30Z
9,323,883
7
2012-02-17T06:30:13Z
[ "python", "dictionary", "filter", "subset" ]
I'm trying to write a custom filter method that takes an arbitrary number of *kwargs* and returns a list containing the elements of a database-like list that contain those *kwargs*. For example, suppose `d1 = {'a':'2', 'b':'3'}` and `d2` = the same thing. `d1 == d2` results in True. But suppose `d2` = the same thing p...
``` >>> d1 = {'a':'2', 'b':'3'} >>> d2 = {'a':'2', 'b':'3','c':'4'} >>> all((k in d2 and d2[k]==v) for k,v in d1.iteritems()) True ``` context: ``` >>> d1 = {'a':'2', 'b':'3'} >>> d2 = {'a':'2', 'b':'3','c':'4'} >>> list(d1.iteritems()) [('a', '2'), ('b', '3')] >>> [(k,v) for k,v in d1.iteritems()] [('a', '2'), ('b',...
Python: Check if one dictionary is a subset of another larger dictionary
9,323,749
38
2012-02-17T06:15:30Z
11,924,754
13
2012-08-12T18:37:25Z
[ "python", "dictionary", "filter", "subset" ]
I'm trying to write a custom filter method that takes an arbitrary number of *kwargs* and returns a list containing the elements of a database-like list that contain those *kwargs*. For example, suppose `d1 = {'a':'2', 'b':'3'}` and `d2` = the same thing. `d1 == d2` results in True. But suppose `d2` = the same thing p...
for keys and values check use: `set(d1.items()).issubset(set(d2.items()))` if you need to check only keys: `set(d1).issubset(set(d2))`
Python: Check if one dictionary is a subset of another larger dictionary
9,323,749
38
2012-02-17T06:15:30Z
19,221,301
19
2013-10-07T09:32:30Z
[ "python", "dictionary", "filter", "subset" ]
I'm trying to write a custom filter method that takes an arbitrary number of *kwargs* and returns a list containing the elements of a database-like list that contain those *kwargs*. For example, suppose `d1 = {'a':'2', 'b':'3'}` and `d2` = the same thing. `d1 == d2` results in True. But suppose `d2` = the same thing p...
Note for people that need this for unit testing: there's also an `assertDictContainsSubset()` method in Python's `TestCase` class. <http://docs.python.org/2/library/unittest.html?highlight=assertdictcontainssubset#unittest.TestCase.assertDictContainsSubset> It's however deprecated in 3.2, not sure why, maybe there's ...
Python: How to get group ids of one username (like id -Gn )
9,323,834
8
2012-02-17T06:24:44Z
9,324,811
18
2012-02-17T08:06:20Z
[ "python", "linux" ]
`getpwname` can only get the `gid` of a `username`. ``` import pwd myGroupId = pwd.getpwnam(username).pw_gid ``` `getgroups` can only get `groups` of the script user. ``` import os myGroupIds = os.getgroups() ``` How can I get all `groups` of one arbitrary `username`, like the `id -Gn` command? ``` id -Gn `whoami`...
``` #!/usr/bin/env python import grp, pwd user = "myname" groups = [g.gr_name for g in grp.getgrall() if user in g.gr_mem] gid = pwd.getpwnam(user).pw_gid groups.append(grp.getgrgid(gid).gr_name) print groups ```
How to set application title in Gnome Shell?
9,324,163
6
2012-02-17T07:00:07Z
9,343,106
12
2012-02-18T16:53:23Z
[ "python", "gtk", "gnome-3" ]
I am new to Gtk+ development, and am trying to write an app using PyGObject and Gtk+3.0. When I run my app in Gnome Shell from the command line, however, the application name as it appears in the upper-left hand corner (immediately to the right of the Activities hot corner) is just set to the name of the Python source ...
gnome-shell tries to match the window to an an app (a `ShellApp` instance) and use that name. The code do that is here: <http://git.gnome.org/browse/gnome-shell/tree/src/shell-window-tracker.c#n328> But if it fails to find `ShellApp` for the window then it falls back to using the ICCCM specified `WM_CLASS` (spec is at...
Which of lxml and libxml2 is better for parsing malformed html in Python?
9,324,389
7
2012-02-17T07:22:36Z
9,324,560
12
2012-02-17T07:36:47Z
[ "python", "html-parsing", "lxml", "libxml2" ]
Which one is better and more useful for malformed html? I cannot find how to use libxml2. Thanks.
In the [libxml2 page](http://xmlsoft.org/python.html) you can see this note: > Note that some of the Python purist dislike the default set of Python bindings, rather than complaining I suggest they have a look at lxml the more pythonic bindings for libxml2 and libxslt and check the mailing-list. and in the [lxml](htt...
django models recursive imports - how to resolve
9,324,554
7
2012-02-17T07:36:13Z
9,324,649
16
2012-02-17T07:49:15Z
[ "python", "django", "django-models", "recursion" ]
I have a model **project\_phase**: ``` from django.db import models from django.utils import simplejson from core.models import pmo_review_task ``` it references **pmo\_review\_task** (because it creates a pmo\_review\_task in its save ovewrite) ``` from django.db import models from datetime import datet...
Two ways: 1. To import a model inside a method (as @YujiTomita suggested). 2. To use `get_model` function from `django.db.models` which is designed for lazy model imports.: ``` project_phase = get_model('core', 'project_phase') ``` I prefer the second one, but both methods are ok.
Python datetime to XML Schema timestamp format
9,327,791
10
2012-02-17T11:56:03Z
9,327,830
13
2012-02-17T11:59:00Z
[ "python", "xml", "xsd" ]
So, is there a easy way to create a timestamp, in XML Schema format? `datetime.datetime.now()` does not work. ``` .now(): 2012-02-17 09:52:35.033232 Desired: 2012-02-15T14:18:46.295-02:00 ``` Looks pretty much the same, but fails on schema validation. It is simple to create manually, but Python always have this kin...
``` >>> datetime.datetime.now(pytz.utc).isoformat() '2012-02-17T11:58:44.789024+00:00' >>> datetime.datetime.now(pytz.timezone('Europe/Paris')).isoformat() '2012-02-17T13:00:10.885743+01:00' ``` apply your own time zone if needed.
Chi-Squared test in Python
9,330,114
22
2012-02-17T14:36:26Z
9,330,332
32
2012-02-17T14:51:56Z
[ "python", "scipy" ]
I've used the following code in `R` to determine how well observed values (20, 20, 0 and 0 for example) fit expected values/ratios (25% for each of the four cases, for example): ``` > chisq.test(c(20,20,0,0), p=c(0.25, 0.25, 0.25, 0.25)) Chi-squared test for given probabilities data: c(20, 20, 0, 0) X-squared ...
[`scipy.stats.chisquare`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.mstats.chisquare.html) expects observed and expected absolute frequencies, not ratios. You can obtain what you want with ``` >>> observed = np.array([20., 20., 0., 0.]) >>> expected = np.array([.25, .25, .25, .25]) * np.sum(obser...
Python: how do I call `print` from `eval` in a loop?
9,330,182
2
2012-02-17T14:41:09Z
9,330,333
7
2012-02-17T14:51:57Z
[ "python", "eval" ]
When I call `print` from `eval`: ``` def printList(myList): maxDigits = len(str(len(myList))) Format = '0{0}d'.format(maxDigits) for i in myList: eval('print "#{0:' + Format + '}".format(i+1), myList[i]') ``` it gives an error: ``` print "#{0:01d}".format(i+1), myList[i] ^ SyntaxError...
You don't need eval: ``` def printList(myList): maxDigits = len(str(len(myList))) str_format = '#{0:0' + str(maxDigits) + '}' for i, elem in enumerate(myList, 1): print str_format.format(i), elem ``` or, as @SvenMarnach noted, you can put even the formatting parameter into one format call: ``` de...
Python: how do I call `print` from `eval` in a loop?
9,330,182
2
2012-02-17T14:41:09Z
9,330,336
8
2012-02-17T14:52:11Z
[ "python", "eval" ]
When I call `print` from `eval`: ``` def printList(myList): maxDigits = len(str(len(myList))) Format = '0{0}d'.format(maxDigits) for i in myList: eval('print "#{0:' + Format + '}".format(i+1), myList[i]') ``` it gives an error: ``` print "#{0:01d}".format(i+1), myList[i] ^ SyntaxError...
You can't `eval()` a `print`: `eval()` is used to evaluate expression, and print is a statement. If you want to execute a statement, use `exec()`. Check [this question for a better explanation](http://stackoverflow.com/questions/2220699/whats-the-difference-between-eval-exec-and-compile-in-python): ``` >>> exec('print...
What is the "soft private memory limit" in GAE?
9,331,592
18
2012-02-17T16:08:03Z
9,336,742
16
2012-02-17T23:10:47Z
[ "python", "google-app-engine", "memory-management", "python-2.7" ]
A user of my application attempted to send a file as an email attachment using my application. However, doing so raised the following exception which I'm having trouble deciphering ``` Exceeded soft private memory limit with 192.023 MB after servicing 2762 requests total While handling this request, the process that...
I assume you are using the lowest-class frontend or backend instance. (F1 or B1 class) Both have 128 MB memory quota, so your app most likely went over this quota limit. However, this quota appears to be not strictly enforced and Google have some leniency in this (thus the term `soft limit`), I had several F1 app insta...
What is the "soft private memory limit" in GAE?
9,331,592
18
2012-02-17T16:08:03Z
9,337,520
19
2012-02-18T01:01:40Z
[ "python", "google-app-engine", "memory-management", "python-2.7" ]
A user of my application attempted to send a file as an email attachment using my application. However, doing so raised the following exception which I'm having trouble deciphering ``` Exceeded soft private memory limit with 192.023 MB after servicing 2762 requests total While handling this request, the process that...
The "soft private memory limit" is the memory limit at which App Engine will stop an instance from receiving any more requests, wait for any outstanding requests, and terminate the instance. Think of it as a graceful shutdown when you're using too much memory. Hitting the soft limit once in a while is ok since all you...
Django: how to hide/overwrite default label with ModelForm?
9,332,638
8
2012-02-17T17:18:17Z
9,334,216
15
2012-02-17T19:32:22Z
[ "python", "django", "label", "hide", "modelform" ]
i have the following, but why does this not hide the label for book comment? I get the error 'textfield' is not defined: ``` from django.db import models from django.forms import ModelForm, Textarea class Booklog(models.Model): Author = models.ForeignKey(Author) Book_comment = models.TextField() Bookcomme...
To expand on my comment above, there isn't a TextField for forms. That's what your TextField error is telling you. There's no point worrying about the label until you have a valid form field. The solution is to use forms.CharField instead, with a Textarea widget. You could use the model form widgets option, but it's s...
Django: how to hide/overwrite default label with ModelForm?
9,332,638
8
2012-02-17T17:18:17Z
20,861,683
8
2013-12-31T18:21:28Z
[ "python", "django", "label", "hide", "modelform" ]
i have the following, but why does this not hide the label for book comment? I get the error 'textfield' is not defined: ``` from django.db import models from django.forms import ModelForm, Textarea class Booklog(models.Model): Author = models.ForeignKey(Author) Book_comment = models.TextField() Bookcomme...
If you're using Django 1.6+ a number of new overrides were added to the meta class of ModelForm, including labels. See: <https://docs.djangoproject.com/en/1.6/topics/forms/modelforms/#overriding-the-default-fields>
Why am I getting this error, "'NoneType' object has no attribute 'csrf_exempt'?
9,333,963
8
2012-02-17T19:11:54Z
9,334,024
17
2012-02-17T19:16:56Z
[ "python", "django", "django-views", "decorator" ]
I am attempting to invoke /save\_calendar, mapped to pim\_calendar.save\_calendar(), which begins: ``` @csrf_exempt @login_required def save_calendar(request): functions.ensure_profile_exists(request.user) now = time.localtime(time.time()) if request.POST.has_key('description') and request.POST['descriptio...
Your `save_calendar` view function isn't returning anything, which in Python is the same as returning `None`. The decorator tries to set an attribute on the returned response, and `None` can't be modified that way.
Pyramid: Equivalent of MVC in PHP Frameworks in Pyramid / Python?
9,334,181
10
2012-02-17T19:29:30Z
9,413,389
10
2012-02-23T12:48:20Z
[ "python", "model-view-controller", "pyramid" ]
What are the Pyramid / Python equivalents of Model - View - Controller of PHP Frameworks such as Kohana? ``` In Pyramid "Model" is .... and it is used for ..... In Pyramid "View" is .... and it is used for ..... In Pyramid "Controller" is .... and it is used for ..... ``` I am trying to understand Pyramid's logic. As...
If you want, with pyramid you can simulate the MVC pattern: * Model: For example using sqlalchemy (http://docs.sqlalchemy.org) * View: Using templates and view methods. * Controller: You can use the package pyramid\_handlers, to create controllers and map actions defined in a route to actions in the controller, for ex...
Pyramid: Equivalent of MVC in PHP Frameworks in Pyramid / Python?
9,334,181
10
2012-02-17T19:29:30Z
9,486,866
18
2012-02-28T17:33:07Z
[ "python", "model-view-controller", "pyramid" ]
What are the Pyramid / Python equivalents of Model - View - Controller of PHP Frameworks such as Kohana? ``` In Pyramid "Model" is .... and it is used for ..... In Pyramid "View" is .... and it is used for ..... In Pyramid "Controller" is .... and it is used for ..... ``` I am trying to understand Pyramid's logic. As...
Pylons, one of the two frameworks that joined together to be Pyramid ( the other was repoze.bfg ) was "close" to an MVC system. I put close in quotations, because over the past few years a lot of people have been fighting about what MVC means... and many projects that once touted themselves as "MVC" started to call th...
Python string as file argument to subprocess
9,334,259
3
2012-02-17T19:36:08Z
9,334,372
8
2012-02-17T19:43:14Z
[ "python", "string", "file", "subprocess" ]
I am trying to pass a file to a program (MolPro) that I start as subprocess with Python. It most commonly takes a file as argument, like this in console: ``` path/molpro filename.ext ``` Where filename.ex contains the code to execute. Alternatively a bash script (what I'm trying to do but in Python): ``` #!/usr/bin...
It seems like your second method should work if you remove `StdinCommand` from the `Popen()` arguments: ``` p = Popen(['/vol/thchem/x86_64-linux/bin/molpro'], shell = False, stdout = None, stderr = STDOUT, stdin = PIPE) p.communicate(input = StdinCommand) ```
Why does Python evaluate this expression incorrectly?
9,334,622
2
2012-02-17T20:02:29Z
9,334,661
8
2012-02-17T20:05:21Z
[ "python", "math", "order", "expression", "operations" ]
I've been experimenting with the mathematical abilities of Python and I came upon some interesting behavior. It's related to the following expression: ``` (4+4)+3/4/5*35-(3*(5+7))-6+434+5+5+5 >>> 415 ``` However, if you evaluate the expression with the standard order of operations in mind, the answer should be 420.2...
You want to use floating point division. Changing it to this works: ``` (4+4)+3.0/4/5*35-(3*(5+7))-6+434+5+5+5 ``` Some examples of integer division vs. floating point division: ``` Python 2.7.2+ (default, Oct 4 2011, 20:06:09) >>> 3/4 0 >>> 3.0/4 0.75 >>> 3.0/4.0 0.75 ``` A float divided by an integer is a float...
Python Classes: Variable subclass creation in the base class's methods
9,335,051
3
2012-02-17T20:38:17Z
9,335,128
10
2012-02-17T20:43:37Z
[ "python" ]
Here's the coding problem I am trying to solve... I have a base class, let's say Animal, and it has two subclasses, say Dog and Cat. My class Animal has a method, make\_baby(), that both Dog and Cat will inherit. The trick I'm having trouble pulling off is that I want the return value to be a new instance of the subcla...
You wrote: > this is no good because type() return a type object, not a class. A type *is* a class, if you're using new-style classes. If you're using Python 3, you're set; all Python 3 classes are "new-style." If you're using Python 2.x, derive your class from `object` (or from something else that derives from objec...
Python list difference
9,335,773
2
2012-02-17T21:37:51Z
9,335,786
9
2012-02-17T21:39:01Z
[ "python", "list" ]
I am trying to find all the elements that are in list A and not in list B. I thought something like `newList = list(set(a) & !set(b))` or `newList = list(set(a) & (not set(b)))` would work, but it's not. If there a better way to achieve what I'm trying to do other than this? ``` newList = [] for item in a: if it...
Did you try ``` list(set(a) - set(b)) ``` Here is a list of all [Python set operations](http://docs.python.org/library/stdtypes.html#set). But this unnecessarily creates a new set for `b`. As @phihag mentions, `difference` method would prevent this.
Python list difference
9,335,773
2
2012-02-17T21:37:51Z
9,335,790
10
2012-02-17T21:39:17Z
[ "python", "list" ]
I am trying to find all the elements that are in list A and not in list B. I thought something like `newList = list(set(a) & !set(b))` or `newList = list(set(a) & (not set(b)))` would work, but it's not. If there a better way to achieve what I'm trying to do other than this? ``` newList = [] for item in a: if it...
You're looking for the [set difference](http://docs.python.org/library/stdtypes.html#set.difference): ``` newList = list(set(a).difference(b)) ``` Alternatively, use the minus operator: ``` list(set(a) - set(b)) ```
Using a Python dict for a SQL INSERT statement
9,336,270
16
2012-02-17T22:21:29Z
9,336,427
11
2012-02-17T22:36:52Z
[ "python", "mysql", "sql" ]
I am trying to use a `dict` to do a SQL `INSERT`. The logic would basically be: ``` INSERT INTO table (dict.keys()) VALUES dict.values() ``` However, I am having a tough time figuring out the correct syntax / flow to do this. This is what I currently have: ``` # data = {...} sorted_column_headers_list = [] sorted_co...
You want to add parameter placeholders to the query. This might get you what you need: ``` qmarks = ', '.join('?' * len(myDict)) qry = "Insert Into Table (%s) Values (%s)" % (qmarks, qmarks) cursor.execute(qry, myDict.keys() + myDict.values()) ```
Using a Python dict for a SQL INSERT statement
9,336,270
16
2012-02-17T22:21:29Z
14,834,646
18
2013-02-12T14:19:10Z
[ "python", "mysql", "sql" ]
I am trying to use a `dict` to do a SQL `INSERT`. The logic would basically be: ``` INSERT INTO table (dict.keys()) VALUES dict.values() ``` However, I am having a tough time figuring out the correct syntax / flow to do this. This is what I currently have: ``` # data = {...} sorted_column_headers_list = [] sorted_co...
I think the comment on using this with MySQL is not quite complete. MySQLdb doesn't do parameter substitution in the columns, just the values (IIUC) - so maybe more like ``` placeholders = ', '.join(['%s'] * len(myDict)) columns = ', '.join(myDict.keys()) sql = "INSERT INTO %s ( %s ) VALUES ( %s )" % (table, columns, ...
Python decorator with multiprocessing fails
9,336,646
8
2012-02-17T22:59:43Z
9,336,868
7
2012-02-17T23:25:12Z
[ "python", "decorator", "multiprocessing" ]
I would like to use a decorator on a function that I will subsequently pass to a multiprocessing pool. However, the code fails with "PicklingError: Can't pickle : attribute lookup `__builtin__`.function failed". I don't quite see why it fails here. I feel certain that it's something simple, but I can't find it. Below i...
The problem is that pickle needs to have some way to reassemble everything that you pickle. See here for a list of what can be pickled: <http://docs.python.org/library/pickle.html#what-can-be-pickled-and-unpickled> When pickling my\_func, the following components need to be pickled: * An instance of my\_decorator\_c...
Python itertools - slow?
9,336,727
11
2012-02-17T23:09:31Z
9,336,781
9
2012-02-17T23:15:34Z
[ "python", "loops" ]
I am trying to use Python's `itertools` module to speed up a triple nested for loop. The test code below compares a standard triple nested loop with itertools' product method and outputs: Nested loop time = 2.35023 secs Itertools loop time = 2.67766 secs Am I missing something? ``` import numpy import itertools imp...
It does seem like `itertools.product` is slower for large values of `n`: ``` In [24]: print _23 from itertools import product def nested_loops(n): for i in range(n): for j in range(n): for k in range(n): pass def itertools_product(n): for (i,j,k) in product(range(n), repea...
Is virtualenv recommended for django production server?
9,337,149
66
2012-02-18T00:03:17Z
9,337,514
39
2012-02-18T01:00:22Z
[ "python", "django", "deployment" ]
I have always been using virtualenv for testing my app in localhost since I have isolated environment and can safely test new release of packages. Now It comes the time when I have to deploy my app to a production server. I am wondering if I should also use virtualenv for production server or just normal installation ...
I would do it that way if you ever think you'll run more than one project on the webserver. As soon as you have two projects you run the risk of a future upgrade of any python package breaking the other site.
Is virtualenv recommended for django production server?
9,337,149
66
2012-02-18T00:03:17Z
9,338,048
7
2012-02-18T02:43:29Z
[ "python", "django", "deployment" ]
I have always been using virtualenv for testing my app in localhost since I have isolated environment and can safely test new release of packages. Now It comes the time when I have to deploy my app to a production server. I am wondering if I should also use virtualenv for production server or just normal installation ...
Yes, I think you should use virtualenv to deploy it into production. It makes things a lot easier and cleaner for you, especially if you plan on deploying multiple services, e.g. django based websites or other python projects. You don't want each of them to be polluting the global python environment with their packages...
Is virtualenv recommended for django production server?
9,337,149
66
2012-02-18T00:03:17Z
9,339,816
11
2012-02-18T08:35:53Z
[ "python", "django", "deployment" ]
I have always been using virtualenv for testing my app in localhost since I have isolated environment and can safely test new release of packages. Now It comes the time when I have to deploy my app to a production server. I am wondering if I should also use virtualenv for production server or just normal installation ...
> Is virtualenv recommended for django production server? Yes, it makes your project not depend on certain aspects of the system environment and also it allows you to make the deployment process more clear and configurable. I use fabric, pip and virtualenv to deploy all my Django projects.
An efficiently stored dictionary. Does this data structure exist and what is it called?
9,337,205
11
2012-02-18T00:14:56Z
9,337,475
10
2012-02-18T00:53:48Z
[ "python", "data-structures", "bioinformatics" ]
I would like a data structure that stores lots of pieces of low-entropy data that are often similar to each other. I want to store them efficiently (compressed somehow) and retrieved by index or match. Quick retrieval is more important than compression, but it is not an option to store them uncompressed. The best exam...
As you already pointed, a suffix tree or a radix tree is probably the way to go. I'd suggest: 1. Creating a [radix tree](http://en.wikipedia.org/wiki/Radix_tree), storing the ids in the leaves. Check the links in [this answer](http://stackoverflow.com/a/4707555/520779) for a start, but I believe you'll have to fine tu...
How do you have shared log files under Windows?
9,337,415
6
2012-02-18T00:43:10Z
9,344,547
8
2012-02-18T22:03:55Z
[ "python", "windows", "logging", "batch-file", "locking" ]
I have several different processes and I would like them to all log to the same file. These processes are running on a Windows 7 system. Some are python scripts and others are `cmd` batch files. Under Unix you'd just have everybody open the file in append mode and write away. As long as each process wrote less than `P...
It is possible to have multiple batch processes safely write to a single log file. I know nothing about Python, but I imagine the concepts in this answer could be integrated with Python. Windows allows at most one process to have a specific file open for write access at any point in time. This can be used to implement...
How do I generate permutations of length LEN given a list of N Items?
9,338,052
4
2012-02-18T02:44:57Z
9,338,067
7
2012-02-18T02:47:44Z
[ "python", "permutation" ]
Note: I'm working in python on this. For example, given a list: ``` list = ['a','b','c','d','e','f','g','h','i','j'] ``` I want to generate a list of lists with all possible 3-item combinations: ``` ['a','b','c'], ['a','b','d'], ['a','b','e'] ``` The permutations should not use the same item twice in a permutation...
``` itertools.permutations(my_list, 3) ```
How do I generate permutations of length LEN given a list of N Items?
9,338,052
4
2012-02-18T02:44:57Z
9,338,075
10
2012-02-18T02:49:21Z
[ "python", "permutation" ]
Note: I'm working in python on this. For example, given a list: ``` list = ['a','b','c','d','e','f','g','h','i','j'] ``` I want to generate a list of lists with all possible 3-item combinations: ``` ['a','b','c'], ['a','b','d'], ['a','b','e'] ``` The permutations should not use the same item twice in a permutation...
Assuming you're in python 2.6 or newer: ``` from itertools import permutations for i in permutations(your_list, 3): print i ```
Converting a string (with scientific notation) to an int in Python
9,338,507
5
2012-02-18T04:20:26Z
9,338,516
13
2012-02-18T04:21:56Z
[ "python" ]
I'm trying to convert a set of strings from a txt file into int's within a list. I was able to find a nice snippet of code that returns each line and then I proceeded to try and convert it to an int. The problem is that the numbers are in scientific notation and I get this error: ValueError: invalid literal for int() w...
Use `float(i)` or `decimal.Decimal(i)` for floating point numbers, depending on how important maintaining precision is to you. `float` will store the numbers in machine-precision IEEE floating point, while `Decimal` will maintain full accuracy, at the cost of being slower. Also, you can iterate over an open file, y...
Is there a quick way to decrease the indentation of multiple lines in Python?
9,339,025
20
2012-02-18T06:00:02Z
9,339,040
44
2012-02-18T06:02:09Z
[ "python", "eclipse", "pydev", "edit", "indentation" ]
I am a newbie to python programming. I find that decreasing the indentation of a block of codes in python is quite annoying. For example, given the following code snippet ``` for i in range(density): if i < 5: x, y = rnd(0,shape[1]//2)*2, rnd(0,shape[0]//2)*2 Z[y,x] = 1 .... .... ``` If I ...
In vim, you select the block and then press the `<` key. In Eclipse you select it and then press `SHIFT` + `TAB`. Every code editor worth its salt has a one-key way to indent and dedent blocks.
pip install with wipe option by default
9,339,413
15
2012-02-18T07:17:50Z
9,362,082
9
2012-02-20T13:39:42Z
[ "python", "pip" ]
In a python (django) project, when I change the location of an existing dependency with pip, and I reinstall the updated requirements.txt file in another machine, I am being prompted with a message like this:- ``` Obtaining South from git+git://github.com/lambdafu/django-south.git@7bb081348d854d0b1aa82b87da5b446ad5d6f...
You could use the `yes` command: ``` yes w | pip install -r requirements.txt ```
pip install with wipe option by default
9,339,413
15
2012-02-18T07:17:50Z
14,644,866
24
2013-02-01T11:02:10Z
[ "python", "pip" ]
In a python (django) project, when I change the location of an existing dependency with pip, and I reinstall the updated requirements.txt file in another machine, I am being prompted with a message like this:- ``` Obtaining South from git+git://github.com/lambdafu/django-south.git@7bb081348d854d0b1aa82b87da5b446ad5d6f...
From PIP version 1.1 onwards you can also use: --exists-action=EXISTS\_ACTION Default action when a path already exists.Use this option more then one time to specify another action if a certain option is not available, choices: (s)witch, (i)gnore, (w)ipe, (b)ackup
Unescaping escaped characters in a string using Python 3.2
9,339,630
7
2012-02-18T07:58:23Z
9,340,191
10
2012-02-18T09:53:39Z
[ "python", "python-3.x" ]
Say I have a string in Python 3.2 like this: ``` '\n' ``` When I print() it to the console, it shows as a new line, obviously. What I want is to be able to print it literally as a backslash followed by an n. Further, I need to do this for all escaped characters, such as \t. So I'm looking for a function unescape() th...
To prevent special treatment of `\` in a literal string you could use `r` prefix: ``` s = r'\n' print(s) # -> \n ``` If you have a string that contains a newline symbol (`ord(s) == 10`) and you would like to convert it to a form suitable as a Python literal: ``` s = '\n' s = s.encode('unicode-escape').decode() print...
ImportError: cannot import name linsolve
9,340,331
5
2012-02-18T10:18:11Z
9,340,386
8
2012-02-18T10:27:47Z
[ "python", "scipy" ]
I am testing a piece of Python code that contains the line: ``` from scipy import sparse, linsolve ``` When I run the script, I get the error: ``` from scipy import sparse, linsolve ImportError: cannot import name linsolve ``` A quick google search shows the code for linsolve.py (hosted on Koders.com). My quest...
If the code in question is actually trying to import `scipy.linsolve`, that was deprecated a long time ago, and may well have been remove from the latest versions of scipy. For compatibility you could try this: ``` from scipy import sparse import scipy.sparse.linalg.dsolve as linsolve ``` that should give the code th...
Tkinter, executing functions over time
9,342,757
2
2012-02-18T16:12:33Z
9,343,402
11
2012-02-18T17:27:35Z
[ "python", "time", "tkinter" ]
I'm new to tkinter, and I'm trying to figure out how the control flow works. I want to display a rectangle and to make it blink three times. I wrote this code, but it doesn't work. I guess it's because `blink` is executed before `mainloop`, and it doesn't actually draw anything. If so, how can I swap the control flow ...
Event-driven programming requires a different mindset from procedural code. Your application is running in an infinite loop, pulling events off of a queue and processing them. To do animation, all you need to do is place items on that queue at an appropriate time. Tkinter widgets have a method named [after](http://eff...
Read CSV from within Zip File
9,343,880
13
2012-02-18T18:22:38Z
9,343,902
16
2012-02-18T18:25:39Z
[ "python", "csv", "zip" ]
I have a directory of zip files (approximately 10,000 small files), within each is a CSV file I am trying to read and split into a number of different CSV files. I managed to write the code to split the CSV files from a directory of CSVs, shown below, that reads the first atttribute of the CSV, and depending what it i...
Simple fix. You're overriding the `csv` module with your local `csv` variable. Just change the name of that variable: ``` import glob import os import csv import zipfile import StringIO for name in glob.glob('C:/Projects/abase/*.zip'): base = os.path.basename(name) filename = os.path.splitext(base)[0] d...
How do I expire keys in dynamoDB with Boto?
9,343,909
4
2012-02-18T18:26:27Z
21,323,698
7
2014-01-24T03:08:17Z
[ "python", "key-value", "boto", "amazon-dynamodb" ]
I'm trying to move from redis to dynamoDB and sofar everything is working great! The only thing I have yet to figure out is key expiration. Currently, I have my data setup with one primary key and no range key as so: ``` { "key" => string, "value" => ["string", "string"], "timestamp" => seconds since epoch } ```...
I'm also using DynamoDB like the way we used to use Redis. My suggestion is to **write the key into different time-sliced tables**. For example, say a type of record should last few minutes, at most less an hour, then you can 1. Create a new table every day for this type of record and store new records in today's ta...
How to stem words in python list?
9,343,929
7
2012-02-18T18:29:12Z
9,344,043
17
2012-02-18T18:41:42Z
[ "python", "nlp" ]
I have python list like below ``` documents = ["Human machine interface for lab abc computer applications", "A survey of user opinion of computer system response time", "The EPS user interface management system", "System and human system engineering testing of EPS", ...
``` from stemming.porter2 import stem documents = ["Human machine interface for lab abc computer applications", "A survey of user opinion of computer system response time", "The EPS user interface management system", "System and human system engineering testing of EPS", ...
How to retrieve the text entered in a text field using webdriver (python)?
9,344,148
3
2012-02-18T18:55:00Z
13,855,977
11
2012-12-13T08:40:57Z
[ "python", "webdriver" ]
This is a really basic question but I couldn't find an answer anywhere... How do I retrieve the text entered in a text field using webdriver under python? I have tried several `text` and `text()` neither works. ``` >>> driver.get("http://en.wikipedia.org/wiki/Main_Page") >>> el = driver.find_elements_by_xpath("//input...
As i have been using attribute action only. it was working fine to me.Use this code below. which text need to get from inputs ``` Description=driver.find_element_by_xpath("//*[@id='id_description']") Description.clear() Description.send_keys("xxx") Description.get_attribute("xxxx") print Description ```
Function failed: Raise Exception, or return FALSE? What's the better approach?
9,344,163
4
2012-02-18T18:57:08Z
9,344,193
7
2012-02-18T19:00:08Z
[ "python", "pep8" ]
I was wondering how you guys handle functions fails. Do you raise an exception, or do you return an error message? e.G. I have a function that is supposed to connect to an external com-object. If the com-object has not been initiated through another program, the connection cannot be established. What would be the pref...
python absolutely comes down on the side of exceptions here. i have always found [this article](http://eli.thegreenplace.net/2008/08/21/robust-exception-handling/) to be a great explanation.
A Python one liner? if x in y, do x
9,344,345
2
2012-02-18T21:42:31Z
9,344,394
9
2012-02-18T21:46:29Z
[ "python", "ruby" ]
``` numbers = [1,2,3,4,5,6,7,8,9] number = 1 ``` Can I write the following on one line? ``` if number in numbers: print number ``` Using the style of ruby: ``` puts number if numbers.include?(number) ``` I have tried: ``` print number if number in numbers ``` But the syntax is invalid.
Python is Python, Ruby is Ruby. My advice is not to try writing one in the other. Python does not have Ruby's / Perl's "postfix if", and the Pythonic way to write this is the one you've already got. But if you really must, this will work: ``` if number in numbers: print number ``` It is against the official style g...
Speed of Python Extensions in C vs. C
9,345,201
13
2012-02-18T23:35:52Z
9,345,231
13
2012-02-18T23:41:16Z
[ "python", "c" ]
Python extension modules written in C are faster than the equivalent programs written in pure Python. How do these extension modules compare (speed wise) to programs written in pure C? Are programs written in pure C even faster than the equivalent Python extension module?
> How do these extension modules compare (speed wise) to programs written in pure C? They are slightly slower due to the translation between Python data structures -> C types. Disregarding this translation the actual C code runs at exactly the same speed as a regular C function would. > Are programs written in pure C...
'Syntax Error' when returning True on Python 3.2
9,345,419
2
2012-02-19T00:13:27Z
9,345,447
10
2012-02-19T00:16:46Z
[ "python", "function", "return" ]
I have the following function in my script at the minute: ``` def _convert_time(p): """Converts a percentage into a date, based on current date.""" # This is the number of years that we subtract from # the current date. p_year = pow(math.e, (20.344 * pow(p, 3) + 3)) - pow(math.e, 3) # Returns...
You are missing a bracket. You need to change this line: ``` date_in_history = date.today() - timedelta(days=(p_year * 365) ``` with: ``` date_in_history = date.today() - timedelta(days=(p_year * 365)) ^ ...
What determines debugger run-time performance
9,346,622
6
2012-02-19T04:14:52Z
9,381,482
9
2012-02-21T16:44:03Z
[ "python", "performance", "debugging", "python-3.x" ]
I have tried debugging Python 3 with Wing IDE (v.4.1.3) and Komodo IDE (v.7.0.0). As, expected the debugger adds a lot of run-time overhead. But what surprised me is how different the debuggers can be between each other. Here are the run-times for the same program. No breakpoints or anything else, just a regular run w...
Doing an optimized Python debugger is as any other software: things can be really different performance-wise (I'm the PyDev author and I've done the PyDev debugger, so, I can comment on it, but not on the others, so, I'll just explain a bit on optimizing a Python debugger -- as I've spent a lot of time optimizing the P...
How do I redirect stdout to a file when using subprocess.call in python?
9,347,004
8
2012-02-19T05:29:07Z
9,347,016
20
2012-02-19T05:30:59Z
[ "python" ]
I'm calling a python script (B) from another python script (A). Using subprocess.call, how do I redirect the stdout of B to a file that specify? I'm using python 2.6.1.
Pass a file as the `stdout` parameter to `subprocess.call`: ``` with open('out-file.txt', 'w') as f: subprocess.call(['program'], stdout=f) ```
python: library for generalized suffix trees
9,347,078
12
2012-02-19T05:46:45Z
9,347,724
18
2012-02-19T08:17:38Z
[ "python", "suffix-tree" ]
I need python library that can construct suffix trees and especially generalised suffix trees. Could you suggest me some libraries. Thanks.
See the following libraries. * [suffixtree](http://code.google.com/p/suffixtree) * [Python-Suffix-Tree](https://github.com/kvh/Python-Suffix-Tree) * [SuffixTree](https://hkn.eecs.berkeley.edu/~dyoo/python/suffix_trees/) * [SuffixTree](http://www.daimi.au.dk/~mailund/suffix_tree.html) (same name different project, supp...
how to refer to a parent method in python?
9,347,406
12
2012-02-19T07:04:27Z
9,347,418
24
2012-02-19T07:07:21Z
[ "python", "inheritance", "polymorphism" ]
Suppose I have two classes (one a parent and one a subclass). How do I refer to a method in the parent class if the method is also defined in the subclass different? Here is the code: ``` class A: def __init__(self, num): self.value=num def f(self, num): return self.value+2 class B(A): def...
Use [`super`](http://docs.python.org/library/functions.html#super): ``` return 7 * super(B, self).f(num) ``` Or in python 3, it's just: ``` return 7 * super().f(num) ```
how to refer to a parent method in python?
9,347,406
12
2012-02-19T07:04:27Z
9,347,483
20
2012-02-19T07:24:54Z
[ "python", "inheritance", "polymorphism" ]
Suppose I have two classes (one a parent and one a subclass). How do I refer to a method in the parent class if the method is also defined in the subclass different? Here is the code: ``` class A: def __init__(self, num): self.value=num def f(self, num): return self.value+2 class B(A): def...
If you know you want to use A you can also explicitly refer to A in this way: ``` class B(A): def f(self,num): return 7 * A.f(self,num) ``` remember you have to explicitly give the self argument to the member function A.f()
Python strip with \n
9,347,419
8
2012-02-19T07:07:27Z
9,347,456
26
2012-02-19T07:17:59Z
[ "python", "strip" ]
This is my problem. I'm trying to read a text file and then convert the lines into floats. The text file has `\n` and `\t` in it though I don't know how to get rid of it. I tried using `line.strip()` but it didn't take it off and I got an error when I wanted to convert the stuff to floats. I then tried `line.strip("\...
You should be able to use `line.strip('\n')` and `line.strip('\t')`. But these don't modify the `line` variable...they just return the string with the `\n` and `\t` stripped. So you'll have to do something like ``` line = line.strip('\n') line = line.strip('\t') ``` That should work for removing from the start and en...
what's the difference between `groups` and `group` in Python's `re` module
9,347,950
4
2012-02-19T09:01:42Z
9,347,965
9
2012-02-19T09:04:09Z
[ "python", "regex" ]
Here it is: ``` import re >>>s = 'abc -j k -l m' >>>m = re.search('-\w+ \w+', s) >>>m.groups() () >>> m.group(0) '-j k' ``` Why `groups()` gives me nothing, but `group(0)` yields some? What is the difference? **Follow Up** Code is as follows ``` >>>re.findall('(-\w+ \w+)', s) ['-j k', '-l m', '-n o'] ``` `findall...
`groups()` only returns any explicitly-captured groups in your regex (denoted by `(` round brackets `)` in your regex), whereas `group(0)` returns the entire substring that's matched by your regex regardless of whether your expression has any capture groups. The first explicit capture in your regex is indicated by `gr...
Does Python have NO need for the Y-Combinator?
9,347,984
4
2012-02-19T09:08:23Z
9,348,058
8
2012-02-19T09:19:53Z
[ "python", "recursion", "lambda", "y-combinator", "self-reference" ]
After an hour of trying to understand the Y-Combinator... i finally got it, mostly but then i realized that the same thing can be achieved without it... although I'm not sure if i fully understand it's purpose. eg. Factorials with Y-Combinator ``` print (lambda h: (lambda f:f(f))(lambda f: h(lambda n: f(f)(n))))(lamb...
The purpose of the Y combinator is to demonstrate how to write an arbitrary recursive function using only anonymous functions. But almost every language ever invented allows named functions! In other words, it is mainly of academic interest. Of course, you can define factorials much more "naturally" in Python: ``` def...
QPixmap maintain aspect ratio python
9,348,201
2
2012-02-19T09:45:31Z
9,351,984
7
2012-02-19T18:38:21Z
[ "python", "aspect-ratio", "qpixmap", "qlabel" ]
I'm writing a program that will allow me to upload photos to TUMBLR via their API, I've got the uploading working (thanks to you guys). I've put a 'queueBox' on the side of the GUI, which displays the image names, and they are stored in a QListWidget. I've put this in my Main Class' constructor: ``` def __init__(...
Get rid of the ``` self.myLabel.setScaledContents(True) ``` call (or set it to False). It is filling your widget with the pixmap without caring about the aspect ratio. If you need to resize a `QPixmap`, as you have found, `scaled` is the required method. But you are invoking it wrong. Let's look at the definition: ...
Does tkinter have a table widget?
9,348,264
16
2012-02-19T09:59:15Z
9,348,306
14
2012-02-19T10:07:37Z
[ "python", "table", "tkinter" ]
I'm learning python, and I want to use it to create a simple GUI application. Since Tkinter is built-in, and it's very simple, I want to use it. My application will have a table to display some data loaded from database. I searched but not found any "table" examples built by Tkinter. Does it have "table" component? I...
Tkinter doesn't have a built-in table widget. The closest you can use is a `Listbox` or a `Treeview` of the tkinter's sub package [`ttk`](https://docs.python.org/3/library/tkinter.ttk.html). However, you can use [tktable](https://github.com/dossan/tktable), which is a wrapper around the `Tcl/Tk` [`TkTable`](http://wik...
Does tkinter have a table widget?
9,348,264
16
2012-02-19T09:59:15Z
9,349,794
12
2012-02-19T13:56:12Z
[ "python", "table", "tkinter" ]
I'm learning python, and I want to use it to create a simple GUI application. Since Tkinter is built-in, and it's very simple, I want to use it. My application will have a table to display some data loaded from database. I searched but not found any "table" examples built by Tkinter. Does it have "table" component? I...
If the table is read-only and you're using a sufficiently modern version of Tkinter you can use the [ttk.Treeview](http://www.tkdocs.com/tutorial/tree.html) widget.
Does tkinter have a table widget?
9,348,264
16
2012-02-19T09:59:15Z
9,952,181
7
2012-03-31T01:19:28Z
[ "python", "table", "tkinter" ]
I'm learning python, and I want to use it to create a simple GUI application. Since Tkinter is built-in, and it's very simple, I want to use it. My application will have a table to display some data loaded from database. I searched but not found any "table" examples built by Tkinter. Does it have "table" component? I...
You could use [tkintertable](http://code.google.com/p/tkintertable/). See [here](https://code.google.com/p/tkintertable/wiki/Usage) how to start using it.
How to install virtualenv without using sudo?
9,348,869
24
2012-02-19T11:47:58Z
9,348,877
14
2012-02-19T11:49:13Z
[ "python", "django", "virtualenv", "pip", "easy-install" ]
I have `easy_install` and `pip`. I had many errors on my **Linux Mint 12**, I just re-installed it and I want to install everything from scratch again. [This](http://stackoverflow.com/questions/9340637/is-this-a-linux-or-a-virtualenv-error/9341580#9341580) is one of the errors that I had. I received an interesting an...
The general idea is to install `virtualenv` itself globaly, i.e. `sudo easy_install virtualenv` or `sudo pip install virtualenv`, but then *create* the actual virtual environment ("run virtualenv") locally.
How to install virtualenv without using sudo?
9,348,869
24
2012-02-19T11:47:58Z
9,349,150
22
2012-02-19T12:30:16Z
[ "python", "django", "virtualenv", "pip", "easy-install" ]
I have `easy_install` and `pip`. I had many errors on my **Linux Mint 12**, I just re-installed it and I want to install everything from scratch again. [This](http://stackoverflow.com/questions/9340637/is-this-a-linux-or-a-virtualenv-error/9341580#9341580) is one of the errors that I had. I received an interesting an...
This solution is suitable in cases where no virtualenv is available system wide and you can not become root to install virtualenv. When I set up a debian for python development or deployment I always apt-get install python-virtualenv. It is more convenient to have it around than to do the bootstrap pointed out below. B...
How to install virtualenv without using sudo?
9,348,869
24
2012-02-19T11:47:58Z
15,555,989
8
2013-03-21T19:02:39Z
[ "python", "django", "virtualenv", "pip", "easy-install" ]
I have `easy_install` and `pip`. I had many errors on my **Linux Mint 12**, I just re-installed it and I want to install everything from scratch again. [This](http://stackoverflow.com/questions/9340637/is-this-a-linux-or-a-virtualenv-error/9341580#9341580) is one of the errors that I had. I received an interesting an...
<http://opensourcehacker.com/2012/09/16/recommended-way-for-sudo-free-installation-of-python-software-with-virtualenv/> suggests the following: ``` curl -L -o virtualenv.py https://raw.githubusercontent.com/pypa/virtualenv/master/virtualenv.py python virtualenv.py vvv-venv . vvv-venv/bin/activate pip install vvv ``` ...
Python _winreg woes
9,348,951
8
2012-02-19T12:00:53Z
16,803,506
8
2013-05-29T00:11:59Z
[ "python", "winreg" ]
I'm trying to access the windows registry (in Python) to query a key value using **\_winreg** and I can't get it to work. The following line returns a WindowsError saying that the "system cannot find the specified file": ``` key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Autodesk\Maya\2012\Setup\InstallP...
You need to combine the access key with one of the 64bit access keys. \_winreg.KEY\_WOW64\_64KEY Indicates that an application on 64-bit Windows should operate on the 64-bit registry view. \_winreg.KEY\_WOW64\_32KEY Indicates that an application on 64-bit Windows should operate on the 32-bit registry view. Try: ```...
How to set Python version by default in FreeBSD?
9,349,831
6
2012-02-19T14:02:14Z
9,350,147
18
2012-02-19T14:42:02Z
[ "python", "environment-variables", "freebsd" ]
I'm trying to install the application [node](https://github.com/joyent/node), but by default in my environment is *python 3*, and requires *python 2.6*. How can I change the default *python* version in *FreeBSD*? ``` # cd /usr/local/bin # ls -l | grep python -r-xr-xr-x 2 root wheel 1246256 Jul 12 2011 python -r-x...
You should remove the python meta-port `/usr/ports/lang/python`. Then set the following variable in `/etc/make.conf`: ``` PYTHON_DEFAULT_VERSION='python3.2' ``` (If you want the latest version. Alternatively you can also use `python3.1`. Currently, the default is `python2.7`.) Now install `/usr/ports/lang/python` ag...
Python tuples as keys slow?
9,350,002
7
2012-02-19T14:23:36Z
9,350,090
16
2012-02-19T14:34:17Z
[ "python", "dictionary", "tuples", "key" ]
I'm trying to implement an fast lookup for sorted tuples in a dictionary; something that answers the question "Does the tuple (3,8) have an associated value, and if yes, what is it?". Let the integers in the tuples be bound from below by 0 and from above by max\_int. I went ahead and used Python's dict but found that ...
Here are precise timing results with Python 2.7: ``` >>> %timeit (3, 8) in d.keys() # Slow, indeed 100000 loops, best of 3: 9.58 us per loop >>> %timeit 8 in t[3].keys() # Faster 1000000 loops, best of 3: 246 ns per loop >>> %timeit (3, 8) in d # Even faster! 10000000 loops, best of 3: 117 ns per loop >>> %time...
Python string representation of binary data
9,350,416
5
2012-02-19T15:18:41Z
9,350,449
10
2012-02-19T15:24:55Z
[ "python" ]
I'm trying to understand the way Python displays strings representing binary data. Here's an example using [os.urandom](http://docs.python.org/library/os.html#os.urandom) ``` In [1]: random_bytes = os.urandom(4) In [2]: random_bytes Out[2]: '\xfd\xa9\xbe\x87' In [3]: random_bytes = os.urandom(4) In [4]: random_byt...
It's only using the `\xHH` notation for characters that are (1) non-printable; and (2) don't have a shorter [escape sequence](http://docs.python.org/release/2.5.2/ref/strings.html). To examine the hex codes, you could use the [`binascii`](http://docs.python.org/library/binascii.html#binascii.hexlify) module: ``` In [...
How do you get PyPy, Django and PostgreSQL to work together?
9,350,422
86
2012-02-19T15:20:02Z
11,270,687
22
2012-06-30T01:07:07Z
[ "python", "django", "postgresql", "psycopg2", "pypy" ]
What fork, or combination of packages should one to use to make PyPy, Django and PostgreSQL play nice together? I know that PyPy and Django play nice together, but I am less certain about PyPy and PostgreSQL. I do see that Alex Gaynor has made a fork of PyPy called [pypy-postgresql](https://bitbucket.org/alex_gaynor/p...
## psycopg2cffi (Updated 2015) [psycopg2cffi](https://pypi.python.org/pypi/psycopg2cffi) is yet another psycopg2-compatible replacement and should provide the best PostgreSQL performance with PyPy. Add this to your `settings.py` to remain compatible with both: ``` try: import psycopg2 except ImportError: # Fa...
How do you get PyPy, Django and PostgreSQL to work together?
9,350,422
86
2012-02-19T15:20:02Z
13,663,976
13
2012-12-01T21:34:45Z
[ "python", "django", "postgresql", "psycopg2", "pypy" ]
What fork, or combination of packages should one to use to make PyPy, Django and PostgreSQL play nice together? I know that PyPy and Django play nice together, but I am less certain about PyPy and PostgreSQL. I do see that Alex Gaynor has made a fork of PyPy called [pypy-postgresql](https://bitbucket.org/alex_gaynor/p...
Some additional resources: * PyPy compatibility information: [DB adaptors](https://bitbucket.org/pypy/compatibility/wiki/Home#!db-adaptors) * [PostgreSQL page](http://wiki.python.org/moin/PostgreSQL) on the Python wiki * **psycopg2cffi** by Konstantin Lopuhin: cffi based implementation of psycopg2 for PyPy 2.0 and...
u'Georges Méliès' vs u'Georges M\xe9li\xe8s'
9,350,430
2
2012-02-19T15:21:06Z
9,350,510
7
2012-02-19T15:32:40Z
[ "python", "unicode" ]
I've read a dozen pages but im still not getting it. Where is the difference between these versions: `u'Georges Méliès'` and `u'Georges M\xe9li\xe8s'` and how do convert one to the other and vice-versa?
There is no difference after those strings have been parsed by the interpreter. One version simply puts the special characters, but it requires the source file to have a special encoding, such as UTF-8. The second version replaces those characters with their byte representation, so it's safe to have such strings in ...
GAE python threads not executing in parallel
9,351,719
8
2012-02-19T18:05:55Z
9,356,355
16
2012-02-20T04:54:47Z
[ "python", "google-app-engine", "python-2.7" ]
I am trying to create a simple web app using Python on GAE. The app needs to spawn some threads per request received. For this I am using python's threading library. I spawn all the threads and then wait on them. ``` t1.start() t2.start() t3.start() t1.join() t2.join() t3.join() ``` The application runs fine except ...
Are you experiencing this in the dev\_appserver or after uploading your app to the production service? From your mention of GoogleAppLauncher it sounds like you may be seeing this in the dev\_appserver; the dev\_appserver does not emulate the threading behavior of the production servers, and you'd be surprised to find ...
Initialise array of empty arrays
9,352,821
2
2012-02-19T20:15:03Z
9,352,840
12
2012-02-19T20:17:22Z
[ "python" ]
This is my code: ``` a = [[]] * 10 a[0].append(1) print a # Outputs [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]] ``` How can I get `a` to output ``` [[1], [], [], [], [], [], [], [], [], []] ``` ?
Try ``` a=[[] for i in xrange(10)] ``` In your code you're adding the same list 10 times. The following output should clarify this: ``` >>> a=[[]] * 5 >>> for i in a: print id(i) ... 155302636 155302636 155302636 155302636 155302636 >>> a=[[] for i in xrange(5)] >>> for i in a: print id(i) ... 155302668 155302732 ...
Could not import settings 'myproject.settings' (Is it on sys.path?): No module named pinax
9,353,092
5
2012-02-19T20:49:19Z
9,353,191
8
2012-02-19T21:00:25Z
[ "python", "django", "pinax" ]
I'm trying to get pinax working on WebFaction and having so many issues... ``` [Sun Feb 19 20:01:20 2012] [error] [client 127.0.0.1] mod_wsgi (pid=22796): Exception occurred processing WSGI script '/home/pawesome/webapps/qtsocial/myproject.wsgi'. [Sun Feb 19 20:01:20 2012] [error] [client 127.0.0.1] Traceback (most re...
Have you tried to add that folder to your PYTHONPATH explicitly? Also, you may need to add **both** the project folder and the parent one. Add these lines to your wsgi file, using the path of your project: ``` sys.path.append('/explicit/path/to/myproject') sys.path.append('/explicit/path/to') ``` P.S. do that before ...
Could not import settings 'myproject.settings' (Is it on sys.path?): No module named pinax
9,353,092
5
2012-02-19T20:49:19Z
9,353,250
8
2012-02-19T21:08:23Z
[ "python", "django", "pinax" ]
I'm trying to get pinax working on WebFaction and having so many issues... ``` [Sun Feb 19 20:01:20 2012] [error] [client 127.0.0.1] mod_wsgi (pid=22796): Exception occurred processing WSGI script '/home/pawesome/webapps/qtsocial/myproject.wsgi'. [Sun Feb 19 20:01:20 2012] [error] [client 127.0.0.1] Traceback (most re...
I think you need to add your stuff to the PYTHONPATH. I add my project and it's virtualenv. Here is a sample of what your wsgi could look like per project. ``` import sys import site import os envpath = '/development/myproject/env/lib/python2.7/site-packages' # we add currently directory to path and change to it pwd...