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 |
|---|---|---|---|---|---|---|---|---|---|
Choose list variable given probability of each variable | 4,437,250 | 6 | 2010-12-14T08:34:54Z | 4,442,687 | 7 | 2010-12-14T18:21:38Z | [
"python",
"probability"
] | I've been trying to code a program that uses the softmax activation function in the middle.
Right now, I have a list of probabilities like this:
```
P[0.10,0.25,0.60,0.05]
```
The sum of all the variables in P is always 1.
I wanted a way to pick the index of the list given the probability attached to it.
Or, in oth... | Basically, make a [cumulative probability distribution](http://en.wikipedia.org/wiki/Cumulative_distribution_function) (CDF) array. Basically, the value of the CDF for a given index is equal to the sum of all values in P equal to or less than that index. Then you generate a random number between 0 and 1 and do a binary... |
How to loop over form field choices and display associated model instance fields | 4,437,386 | 5 | 2010-12-14T08:55:14Z | 4,439,843 | 22 | 2010-12-14T13:51:52Z | [
"python",
"django",
"django-templates",
"django-forms"
] | I have a ModelForm with a multiple choice field. The choices are populated instances of Hikers belonging to a specific Club.
I want to customize the way my form displays, by displaying the choices in a table where the 1st column contains checkboxes, and a few more columns display the details of each hiker. So for exam... | Easiest would be if you define the whole form in a HTML template. You should be able to iterate over a field's values in a template like that:
```
{% for value, text in form.hikers.field.choices %}
{{ value }}: {{ text }}
{% endfor %}
``` |
how to start a python file while window starts? | 4,438,020 | 7 | 2010-12-14T10:12:41Z | 4,438,037 | 7 | 2010-12-14T10:15:27Z | [
"python",
"windows"
] | I have a python file and I am running the file.
If Windows is shutdown and booted up again, how I can run that file every time Windows starts? | In the following startup directory (at least this path exists on Windows XP):
```
C:\Documents and Settings\All Users\Start Menu\Programs\Startup
```
put a shortcut to your python program. It should be executed every time your system starts up. |
how to start a python file while window starts? | 4,438,020 | 7 | 2010-12-14T10:12:41Z | 4,439,204 | 14 | 2010-12-14T12:35:25Z | [
"python",
"windows"
] | I have a python file and I am running the file.
If Windows is shutdown and booted up again, how I can run that file every time Windows starts? | Depending on what the script is doing, you may:
1. package it into a service, that should then be installed
2. add it to the windows registry (HKCU\Software\Microsoft\Windows\CurrentVersion\Run)
3. add a shortcut to it to the startup folder of start menu - its location may change with OS version, but installers always... |
How to start a django cms project | 4,438,258 | 3 | 2010-12-14T10:39:20Z | 4,439,575 | 7 | 2010-12-14T13:19:08Z | [
"python",
"django",
"django-cms"
] | I decided to take a look to django-cms. After looking at the docs I cloned the repository using
```
git clone https://github.com/divio/django-cms.git
```
Then I installed it using
```
sudo python setup.py install
```
I already have django 1.2.3 installed. I moved to the `example` directory an ran `syncdb` which cre... | django-cms uses [South](http://south.aeracode.org/) for database migrations. Models handled by South are not synced to the database using `syncdb`. You have to use [`manage.py migrate`](http://south.aeracode.org/docs/commands.html#migrate).
Since you don't have any tables and data from django-cms to migrate, a faster ... |
Equivalent to GOTO in conditions, Python | 4,438,516 | 5 | 2010-12-14T11:11:10Z | 4,438,679 | 14 | 2010-12-14T11:33:20Z | [
"python",
"condition",
"goto"
] | Since there is no goto operator in Python, what technique can be used instead?
Condition
If it is true, go to thread 1, if is false, go to thread 2
In thread we do something small and after that we go to thread 2 where all other actions take place. | > Since there is no goto operator in Python, what technique can be used instead?
Constructing your code logically and semantically.
```
if condition:
perform_some_action()
perform_other_actions()
``` |
3D scatterplots in sage | 4,439,894 | 6 | 2010-12-14T13:55:49Z | 4,800,315 | 8 | 2011-01-26T00:17:47Z | [
"python",
"plot",
"sage"
] | Is it possible to create 3D scatterplots in [sage](http://sagemath.org/)?
By scatterplot I mean graph like this:
 | Absolutely. If you've got a list of tuples that represent your points, something like:
```
point_list=[(0.,1.,2.), (2.,2.,3.)]
point3d(point_list)
```
that will plot the two points given in point\_list, you can add axis labels with standard sage plotting options. |
Is there a Google Insights API? | 4,440,139 | 12 | 2010-12-14T14:23:39Z | 4,474,589 | 7 | 2010-12-17T20:40:49Z | [
"python",
"api"
] | I've been looking for an API to automatically retrieve Google Insights information for part of another algorithm, but have been unable to find anything. The first result on Google delivers a site with a python plugin which is now out of date.
Does such an API exist, or has anyone written a plugin, perhaps for python? | As far as I can tell, there is no API available as of yet, and neither is there a working implementation of a method for extracting data from Google Insights. However, I have found a solution to my (slightly more specific) problem, which could really just be solved by knowing how many times certain terms are searched f... |
In Python, is there an elegant way to print a list in a custom format without explicit looping? | 4,440,516 | 16 | 2010-12-14T15:04:55Z | 4,440,550 | 51 | 2010-12-14T15:08:11Z | [
"python",
"list"
] | I know you can do
```
print str(myList)
```
to get
```
[1, 2, 3]
```
and you can do
```
i = 0
for entry in myList:
print str(i) + ":", entry
i += 1
```
to get
```
0: 1
1: 2
2: 3
```
But is there a way similar to the first to get a result similar to the last?
With my limited knowledge of Python (and som... | ```
>>> lst = [1, 2, 3]
>>> print('\n'.join('{}: {}'.format(*k) for k in enumerate(lst)))
0: 1
1: 2
2: 3
```
Note: you just need to understand that list comprehension or iterating over a generator expression **is** explicit looping. |
Why doesn't django's model.save() call full_clean()? | 4,441,539 | 88 | 2010-12-14T16:32:35Z | 4,441,740 | 37 | 2010-12-14T16:47:58Z | [
"python",
"django",
"django-models",
"django-validation"
] | I'm just curious if anyone knows if there's good reason why django's orm doesn't call 'full\_clean' on a model unless it is being saved as part of a model form.
> Note that full\_clean() will not be called automatically when you call your modelâs save() method. Youâll need to call it manually when you want to run ... | AFAIK, this is because of backwards compatibility. There are also problems with ModelForms with excluded fields, models with default values, pre\_save() signals, etc.
Sources you might be intrested in:
* <http://code.djangoproject.com/ticket/13100>
* <http://groups.google.com/group/django-developers/browse_frm/thread... |
Why doesn't django's model.save() call full_clean()? | 4,441,539 | 88 | 2010-12-14T16:32:35Z | 32,431,937 | 12 | 2015-09-07T05:56:38Z | [
"python",
"django",
"django-models",
"django-validation"
] | I'm just curious if anyone knows if there's good reason why django's orm doesn't call 'full\_clean' on a model unless it is being saved as part of a model form.
> Note that full\_clean() will not be called automatically when you call your modelâs save() method. Youâll need to call it manually when you want to run ... | Because of the compatibility considering, the auto clean on save is not enabled in django kernel.
If we are starting a new project and want the default `save` method on Model could clean automatically, we can use the following signal to do clean before every model was saved.
```
from django.dispatch import receiver
f... |
Python logging configuration file | 4,441,842 | 17 | 2010-12-14T16:58:08Z | 4,442,026 | 9 | 2010-12-14T17:17:05Z | [
"python",
"logging"
] | I seem to be having some issues while attempting to implement logging into my python project.
I'm simply attempting to mimic the following configuration:
[Python Logging to Multiple Destinations](http://docs.python.org/library/logging.html#logging-to-multiple-destinations)
However instead of doing this inside of cod... | Adding the following line to the root logger took care of my problem:
```
level=NOTSET
``` |
Python logging configuration file | 4,441,842 | 17 | 2010-12-14T16:58:08Z | 6,744,560 | 13 | 2011-07-19T08:53:46Z | [
"python",
"logging"
] | I seem to be having some issues while attempting to implement logging into my python project.
I'm simply attempting to mimic the following configuration:
[Python Logging to Multiple Destinations](http://docs.python.org/library/logging.html#logging-to-multiple-destinations)
However instead of doing this inside of cod... | It looks like you've set the levels for your handlers, but not your logger. The logger's level filters every message before it can reach its handlers and the default is `WARNING` and above (as you can see). Setting the root logger's level to `NOTSET` as you have, as well as setting it to `DEBUG` (or whatever is the low... |
Why Python `Memory Error` with list `append()` lots of RAM left | 4,441,947 | 16 | 2010-12-14T17:07:43Z | 4,441,958 | 19 | 2010-12-14T17:09:00Z | [
"python",
"list",
"memory"
] | I am building a large data dictionary from a set of text files. As I read in the lines and process them, I `append(dataline)` to a list.
At some point the `append()` generates a `Memory Error` exception. However, watching the program run in the Windows Task Manager, at the point of the crash I see 4.3 GB available and... | If you're using a 32-bit build of Python, you might want to try a 64-bit version.
It is possible for a process to address at most 4GB of RAM using 32-bit addresses, but typically (depending on the OS), one gets much less. It sounds like your Python process may be hitting this limit. 64-bit addressing removes this limi... |
Python code genration with pyside-uic | 4,442,286 | 13 | 2010-12-14T17:42:21Z | 5,882,686 | 27 | 2011-05-04T11:33:14Z | [
"python",
"pyside"
] | How can I generate python code from a QtDesigner file ?
I found pyside-uic but I can't find an example for the syntax.
I run win7 and pythonxy with spyder.
Thanks
Arthur | pyside-uic is more or less identical to pyuic4, as such the man page specifies:
```
Usage:
pyside-uic [options] <ui-file>
Options:
--version
show program's version number and exit
-h,--help
show this help message and exit
-oFILE,--output=FILE
write generated code to FILE ... |
Python code genration with pyside-uic | 4,442,286 | 13 | 2010-12-14T17:42:21Z | 8,717,832 | 18 | 2012-01-03T19:52:36Z | [
"python",
"pyside"
] | How can I generate python code from a QtDesigner file ?
I found pyside-uic but I can't find an example for the syntax.
I run win7 and pythonxy with spyder.
Thanks
Arthur | Just tried Pyside's QUILoader, works fine:
```
from PySide import QtGui
from PySide import QtCore
from PySide import QtUiTools
class MyWidget(QtGui.QMainWindow):
def __init__(self, *args):
apply(QtGui.QMainWindow.__init__, (self,) + args)
loader = QtUiTools.QUiLoader()
file = QtCore.QFil... |
Python: Adding Fields to Objects Dynamically | 4,443,301 | 5 | 2010-12-14T19:28:28Z | 4,443,329 | 10 | 2010-12-14T19:30:24Z | [
"python",
"metaprogramming"
] | I am wondering whether it is possible to add fields to objects dynamically. For example, I want to be able to add something like:
```
user = object()
user.first_name = 'John'
user.last_name = 'Smith'
```
When I execute that in Python command line interpretor I get:
```
AttributeError: 'object' object has no attribut... | Try this:
```
class Object:
pass
obj = Object()
obj.x = 5
``` |
how to represent graphs /trees in python and how to detect cycles? | 4,443,734 | 9 | 2010-12-14T20:16:12Z | 4,443,841 | 11 | 2010-12-14T20:25:06Z | [
"python",
"algorithm"
] | i want to implement kruskal's algorithm in python how can i go about representing the tree/graph and what approach should i follow to detect the cycles ? | The simplest way of representing it (in my opinion) is by using a dict of ~~arrays~~ lists:
```
graph = {}
graph[node_id] = [other_node_id for other_node_id in neighbors(node_id)]
```
A simple way of finding cycles is by using a BF or DF search:
```
def df(node):
if visited(node):
pass # found a cycle he... |
How do I create a date picker in tkinter? | 4,443,786 | 13 | 2010-12-14T20:20:27Z | 4,443,945 | 7 | 2010-12-14T20:34:39Z | [
"python",
"tkinter"
] | Is there any standard way tkinter apps allow the user to choose a date? | Nope, Tk doesn't include a date picker widget. There are a couple of Python calendar widgets you could try:
<http://svn.python.org/projects/sandbox/trunk/ttk-gsoc/samples/ttkcalendar.py>
<http://effbot.org/zone/wcklib-calendar.htm> |
Python: building an LRU cache | 4,443,920 | 7 | 2010-12-14T20:32:29Z | 8,331,631 | 17 | 2011-11-30T19:20:06Z | [
"python",
"mongodb",
"lru"
] | I have around `6,00,000 entries in MongoDB` in the following format:
```
feature:category:count
```
where
* **feature** could be any word,
* **category** is positive or negative, and
* **count** tells how many times a feature occurred in a document for that category.
I want to cache the top 1000 tuples, let's say s... | The [LRU cache](http://docs.python.org/3.3/library/functools.html#functools.lru_cache) in Python3.3 has O(1) insertion, deletion, and search.
The design uses a circular doubly-linked list of entries (arranged oldest-to-newest) and a hash table to locate individual links. Cache hits use the hash table to find the relev... |
Get Filename Without Extension in Python | 4,444,923 | 66 | 2010-12-14T22:26:57Z | 4,444,952 | 151 | 2010-12-14T22:30:10Z | [
"python",
"regex"
] | If I have a filename like one of these:
```
1.1.1.1.1.jpg
1.1.jpg
1.jpg
```
How could I get only the filename, without the extension? Would a regex be appropriate? | In most cases, you shouldn't use a regex for that.
```
os.path.splitext(filename)[0]
```
This will also handle a filename like `.bashrc` correctly by keeping the whole name. |
Get Filename Without Extension in Python | 4,444,923 | 66 | 2010-12-14T22:26:57Z | 4,444,964 | 17 | 2010-12-14T22:32:29Z | [
"python",
"regex"
] | If I have a filename like one of these:
```
1.1.1.1.1.jpg
1.1.jpg
1.jpg
```
How could I get only the filename, without the extension? Would a regex be appropriate? | ```
>>> import os
>>> os.path.splitext("1.1.1.1.1.jpg")
('1.1.1.1.1', '.jpg')
``` |
Get Filename Without Extension in Python | 4,444,923 | 66 | 2010-12-14T22:26:57Z | 4,445,564 | 8 | 2010-12-15T00:10:20Z | [
"python",
"regex"
] | If I have a filename like one of these:
```
1.1.1.1.1.jpg
1.1.jpg
1.jpg
```
How could I get only the filename, without the extension? Would a regex be appropriate? | If I had to do this with a regex, I'd do it like this:
```
s = re.sub(r'\.jpg$', '', s)
``` |
Upper diagonal of a 2D numpy array | 4,445,109 | 9 | 2010-12-14T22:52:42Z | 4,445,251 | 8 | 2010-12-14T23:14:00Z | [
"python",
"numpy",
"slice"
] | This seems simple (and is trivial to write a three-line loop for), but how can I use numpy slicing make a list of the index locations of the upper diagonal of a numpy array? I.e.
Given a 4x4 array, I'd like the index locations at the X's:
```
[ X X X X ]
[ 0 X X X ]
[ 0 0 X X ]
[ 0 0 0 X ]
```
Giving:
```
[ (0,0), ... | carnieri beat me to the `numpy.triu_indices` answer, but there is also `numpy.triu_indices_from` which takes an array as input rather than the dimensions. |
Python compiler error, x takes no arguments (1 given) | 4,445,405 | 34 | 2010-12-14T23:40:01Z | 4,445,419 | 60 | 2010-12-14T23:42:21Z | [
"python",
"object",
"methods",
"arguments"
] | I'm writing a small piece of python as a homework assignment, and I'm not getting it to run! I don't have that much Python-experience, but I know quite a lot of Java.
I'm trying to implement a Particle Swarm Optimization algorithm, and here's what I have:
```
class Particle:
def __init__(self,domain,ID):
... | Python implicitly passes the object to method calls, but you need to explicitly declare the parameter for it. This is customarily named `self`:
```
def updateVelocity(self):
``` |
Why am I getting "IndentationError: expected an indented block"? | 4,446,366 | 22 | 2010-12-15T03:12:59Z | 4,446,372 | 30 | 2010-12-15T03:14:43Z | [
"python"
] | ```
if len(trashed_files) == 0 :
print "No files trashed from current dir ('%s')" % os.path.realpath(os.curdir)
else :
index=raw_input("What file to restore [0..%d]: " % (len(trashed_files)-1))
if index == "*" :
for tfile in trashed_files :
try:
tfile.restore()
... | Should be pretty self explanatory. You have an indentation error. Probably caused by a mix of tabs and spaces. |
Python: Check the occurrences in a list against a value | 4,446,380 | 3 | 2010-12-15T03:16:51Z | 4,446,385 | 17 | 2010-12-15T03:18:27Z | [
"python",
"list"
] | ```
lst = [1,2,3,4,1]
```
I want to know 1 occurs twice in this list, is there any efficient way to do? | `lst.count(1)` would return the number of times it occurs. If you're going to be counting items in a list, O(n) is what you're going to get.
The general function on the list is `list.count(x)`, and will return the number of times `x` occurs in a list. |
Python: Check the occurrences in a list against a value | 4,446,380 | 3 | 2010-12-15T03:16:51Z | 4,446,397 | 10 | 2010-12-15T03:21:32Z | [
"python",
"list"
] | ```
lst = [1,2,3,4,1]
```
I want to know 1 occurs twice in this list, is there any efficient way to do? | Are you asking whether every item in the list is unique?
```
len(set(lst)) == len(lst)
```
Whether `1` occurs more than once?
```
lst.count(1) > 1
```
Note that the above is not maximally efficient, because it won't short-circuit -- even if `1` occurs twice, it will still count the rest of the occurrences. If you w... |
how to send asynchronous email using django | 4,447,081 | 8 | 2010-12-15T05:48:21Z | 4,447,147 | 13 | 2010-12-15T06:01:08Z | [
"python",
"django",
"email",
"asynchronous"
] | This is my code:
```
class EmailThread(threading.Thread):
def __init__(self, subject, html_content, recipient_list):
self.subject = subject
self.recipient_list = recipient_list
self.html_content = html_content
threading.Thread.__init__(self)
def run (self):
msg = EmailM... | it is ok now ;
```
class EmailThread(threading.Thread):
def __init__(self, subject, html_content, recipient_list):
self.subject = subject
self.recipient_list = recipient_list
self.html_content = html_content
threading.Thread.__init__(self)
def run (self):
msg = EmailMes... |
how to send asynchronous email using django | 4,447,081 | 8 | 2010-12-15T05:48:21Z | 4,447,203 | 11 | 2010-12-15T06:10:04Z | [
"python",
"django",
"email",
"asynchronous"
] | This is my code:
```
class EmailThread(threading.Thread):
def __init__(self, subject, html_content, recipient_list):
self.subject = subject
self.recipient_list = recipient_list
self.html_content = html_content
threading.Thread.__init__(self)
def run (self):
msg = EmailM... | In the long run, it may prove to be a good decision to use a third-party Django application, such as [django-mailer](https://github.com/pinax/django-mailer/), to handle all sorts of asynchronous email sending/management requirements. |
How would I scale a 2-dimensional array in python? | 4,447,352 | 4 | 2010-12-15T06:37:36Z | 4,447,553 | 7 | 2010-12-15T07:13:33Z | [
"python",
"matrix"
] | I'm not sure how to go about scaling a 2-dimensional array. Given the array below, whose dimensions are 8x10, say I needed to scale it to 5x6 -- I've looked for concrete examples on wikipedia, but without much grounding in matrix math I'm a bit lost. If someone could point me in the right direction I'd really appreciat... | Since your array looks like it is a binary image of a lower case 'a' letter, I'm guessing that you mean scaling in the image sense.
To do that, I would recommend using the `imresize` function in scipy.misc (which is taken from PIL, I believe). Here's an example:
```
import numpy as np
from scipy.misc import imresize
... |
Force my scrapy spider to stop crawling | 4,448,724 | 19 | 2010-12-15T10:05:21Z | 7,073,313 | 7 | 2011-08-16T03:23:15Z | [
"python",
"scrapy"
] | is there a chance to stop crawling when specific if condition is true (like scrap\_item\_id == predefine\_value ). My problem is similar to [Scrapy - how to identify already scraped urls](http://stackoverflow.com/questions/3871613/scrapy-how-to-identify-already-scraped-urls) but I want to 'force' my scrapy spider to st... | This question was asked 8 months ago but I was wondering the same thing and have found another (not great) solution. Hopefully this can help the future readers.
I'm connecting to a database in my Pipeline file, if the database connection is unsuccessful, I wanted the Spider to stop crawling (no point in collecting dat... |
Force my scrapy spider to stop crawling | 4,448,724 | 19 | 2010-12-15T10:05:21Z | 7,969,243 | 18 | 2011-11-01T16:03:36Z | [
"python",
"scrapy"
] | is there a chance to stop crawling when specific if condition is true (like scrap\_item\_id == predefine\_value ). My problem is similar to [Scrapy - how to identify already scraped urls](http://stackoverflow.com/questions/3871613/scrapy-how-to-identify-already-scraped-urls) but I want to 'force' my scrapy spider to st... | In the latest version of Scrapy, available on GitHub, you can raise a CloseSpider exception to manually close a spider.
In the [0.14 release note doc](https://github.com/scrapy/scrapy/wiki/Scrapy-0.14-release-notes) is mentioned: "Added CloseSpider exception to manually close spiders (r2691)"
Example as per the docs:... |
Python solve equation for one variable | 4,449,110 | 3 | 2010-12-15T10:54:08Z | 4,449,230 | 7 | 2010-12-15T11:07:00Z | [
"python",
"solver",
"sympy",
"equations"
] | I'm trying to solve an equation in python using SymPy. I have a generated equation (something like `function = y(8.0-(y**3.0))` which I use with SymPy to create a new equation like this: `eq = sympy.Eq(function, 2)` which outputs `y(8.0-(y**3.0)) == 2`. but `sympy.solve(eq)` doesn't seem to work.
```
>>> from sympy im... | Yours is a non linear equation ... So you can use `optimize.fsolve` for it. For further details look for the function in this tutorial [scipy](http://www.tau.ac.il/~kineret/amit/scipy_tutorial/) |
Python solve equation for one variable | 4,449,110 | 3 | 2010-12-15T10:54:08Z | 5,129,085 | 7 | 2011-02-26T19:03:52Z | [
"python",
"solver",
"sympy",
"equations"
] | I'm trying to solve an equation in python using SymPy. I have a generated equation (something like `function = y(8.0-(y**3.0))` which I use with SymPy to create a new equation like this: `eq = sympy.Eq(function, 2)` which outputs `y(8.0-(y**3.0)) == 2`. but `sympy.solve(eq)` doesn't seem to work.
```
>>> from sympy im... | (I don't know why you mention scipy in your question when you use sympy in your code. I'll assume you are using sympy.)
Sympy can solve this equation if you specify an integer power for `y` (ie `y**3.0` changed to `y**3`).
The following works for me using Sympy 0.6.7.
```
from sympy import Eq, Symbol, solve
y = Sym... |
Why file read is faster on reading again? | 4,449,473 | 2 | 2010-12-15T11:39:57Z | 4,449,491 | 13 | 2010-12-15T11:41:47Z | [
"python",
"linux",
"file"
] | ```
SIZE = 1<<16
def justread(file):
with open(file, 'rb') as f:
while f.read(SIZE):
pass
```
The first time I run this function on a 700MB file it took 19 secs.
When I repeated
reading the same file again the time it took dropped to 0.5secs.
I repeated this with many files and the results ... | The operating system [caches](http://en.wikipedia.org/wiki/Page_cache) the file in memory upon the first read, and the second time it is read from memory instead of from hard disk. Of course memory is much faster. |
Relatively simple Python script using 100% cpu | 4,449,943 | 2 | 2010-12-15T12:38:37Z | 4,449,977 | 8 | 2010-12-15T12:42:37Z | [
"python",
"unix",
"cpu-usage"
] | I'm not going to provide the code because it's too long. The python script involves executing a lengthy number of commands run in a while loop.
Basic structure
```
while True:
The meat goes here
with the odd if:
and stuff
```
Now that I'm finished it, I'm noticing that upon running it, it uses 100% C... | Unless there is something to get in the way of the CPU being used (for example, waiting on disk IO or network IO, or pausing execution by sleeping), CPU usage will always be at around 100% while a program is running.
You might want to add in a time.sleep(numberOfSeconds) to your loop if you don't want it to be using 1... |
Cython Install GCC error | 4,450,111 | 15 | 2010-12-15T12:59:19Z | 4,450,201 | 31 | 2010-12-15T13:08:36Z | [
"python",
"gcc",
"install",
"cython"
] | Trying to install Cython on a small VPS running Ubuntu Server. Did
```
sudo apt-get install gcc
```
and then
```
python setup.py install
```
In the Cython directory, but I get this peculiar error.
```
running install
running build
running build_py
running build_ext
building 'Cython.Plex.Scanners' extension
gcc -pt... | You need the developer version of Python - i.e. the Python header files (Python.h)
```
sudo apt-get install python-dev
``` |
easy save/load of data in python | 4,450,144 | 4 | 2010-12-15T13:02:10Z | 4,450,248 | 15 | 2010-12-15T13:14:03Z | [
"python",
"io"
] | What is the easiest way to save and load data in python, preferably in a human-readable output format?
The data I am saving/loading consists of two vectors of floats. Ideally, these vectors would be named in the file (e.g. X and Y).
My current `save()` and `load()` functions use `file.readline()`, `file.write()` and ... | The most simple way to get a human-readable output is by using a serialisation format such a JSON. Python contains a [json](http://docs.python.org/library/json.html) library you can use to serialise data to and from a string. Like [pickle](http://docs.python.org/library/pickle.html), you can use this with an IO object ... |
Django search multiple filters | 4,450,447 | 5 | 2010-12-15T13:34:38Z | 4,450,817 | 7 | 2010-12-15T14:13:44Z | [
"python",
"django",
"django-forms"
] | Lets say I have a model
**models.py**
```
class user:
name = models.CharField(max_length=25)
class job:
job_name = models.CharField(max_length=25)
class user_job:
user = models.ForeignKey('user')
job = models.ForeignKey('job')
```
**forms.py**
```
jobs = (
('0', 'a'),
('1', 'b'),
... | You'll probably find it easier to search from the `User` model since what you want is a list of `Users`s who have both jobs. Django automatically sets up properties on your models that allow you to access related models both from model instances and in DB queries.
Assuming you set up your models like so:
```
from dja... |
String Interpolation in Python | 4,450,592 | 145 | 2010-12-15T13:50:57Z | 4,450,610 | 146 | 2010-12-15T13:52:28Z | [
"python",
"string-interpolation",
"language-comparisons"
] | Is there a Python equivalent to Ruby's string interpolation?
Ruby example:
```
name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
```
Whilst I could succeed using string concatenation in Python, it's seemingly verbose to me coming from Ruby. | Python 3.6 will add [literal string interpolation](https://www.python.org/dev/peps/pep-0498/) similar to Ruby's string interpolation. Starting with that version of Python (which is scheduled to be released by the end of 2016), you will be able to include expressions in "f-strings", e.g.
```
name = "Spongebob Squarepan... |
String Interpolation in Python | 4,450,592 | 145 | 2010-12-15T13:50:57Z | 4,450,740 | 13 | 2010-12-15T14:06:24Z | [
"python",
"string-interpolation",
"language-comparisons"
] | Is there a Python equivalent to Ruby's string interpolation?
Ruby example:
```
name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
```
Whilst I could succeed using string concatenation in Python, it's seemingly verbose to me coming from Ruby. | Python's string interpolation is similar to C's printf()
If you try:
```
name = "SpongeBob Squarepants"
print "Who lives in a Pineapple under the sea? %s" % name
```
The tag `%s` will be replaced with the `name` variable. You should take a look to the print function tags: <http://docs.python.org/library/functions.ht... |
String Interpolation in Python | 4,450,592 | 145 | 2010-12-15T13:50:57Z | 4,451,104 | 55 | 2010-12-15T14:44:50Z | [
"python",
"string-interpolation",
"language-comparisons"
] | Is there a Python equivalent to Ruby's string interpolation?
Ruby example:
```
name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
```
Whilst I could succeed using string concatenation in Python, it's seemingly verbose to me coming from Ruby. | Since Python 2.6.X you might want to use:
```
"my {0} string: {1}".format("cool", "Hello there!")
```
This goes double for Python 3.X, where the %-syntax is deprecated. |
String Interpolation in Python | 4,450,592 | 145 | 2010-12-15T13:50:57Z | 20,985,680 | 22 | 2014-01-08T02:03:04Z | [
"python",
"string-interpolation",
"language-comparisons"
] | Is there a Python equivalent to Ruby's string interpolation?
Ruby example:
```
name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
```
Whilst I could succeed using string concatenation in Python, it's seemingly verbose to me coming from Ruby. | I've developed the [interpy](https://github.com/SyrusAkbary/interpy) package, that **enables string interpolation in Python**.
Just install it via `pip install interpy`.
And then, add the line `# coding: interpy` at the beginning of your files!
Example:
```
#!/usr/bin/env python
# coding: interpy
name = "Spongebob ... |
String Interpolation in Python | 4,450,592 | 145 | 2010-12-15T13:50:57Z | 33,264,516 | 16 | 2015-10-21T16:25:35Z | [
"python",
"string-interpolation",
"language-comparisons"
] | Is there a Python equivalent to Ruby's string interpolation?
Ruby example:
```
name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
```
Whilst I could succeed using string concatenation in Python, it's seemingly verbose to me coming from Ruby. | String interpolation is going to be [included with Python 3.6 as specified in PEP 498](https://www.python.org/dev/peps/pep-0498/). You will be able to do this:
```
name = 'Spongebob Squarepants'
print(f'Who lives in a Pineapple under the sea? \n{name}')
```
Note that I hate Spongebob, so writing this was slightly pai... |
Python, find out that a list does not have specific item | 4,450,752 | 4 | 2010-12-15T14:07:39Z | 4,450,772 | 14 | 2010-12-15T14:08:45Z | [
"python",
"if-statement"
] | Let's say there is a list a that contains both numbers and letters. Is there quick way to find out that the list doesn't contain some specific element. I plan to use it in conditions. | Maybe
```
3 not in [1, 2, "a"]
# True
``` |
Recreating time series data using FFT results without using ifft | 4,451,591 | 5 | 2010-12-15T15:25:07Z | 4,452,499 | 11 | 2010-12-15T16:43:37Z | [
"python",
"math",
"signal-processing",
"fft"
] | I analyzed the sunspots.dat data (below) using fft which is a classic example in this area. I obtained results from fft in real and imaginery parts. Then I tried to use these coefficients (first 20) to recreate the data following the formula for Fourier transform. Thinking real parts correspond to a\_n and imaginery to... | When you called `fft(wolfer)`, you told the transform to assume a fundamental period equal to the length of the data. To reconstruct the data, you have to use basis functions of the same fundamental period = `2*pi/N`. By the same token, your time index `xs` has to range over the time samples of the original signal.
An... |
Python DocStrings & Pydev | 4,451,645 | 8 | 2010-12-15T15:30:42Z | 4,463,991 | 7 | 2010-12-16T18:12:55Z | [
"python",
"eclipse",
"pydev"
] | I've gotten Pydev up and running, and almost all is working well. However I'm having some trouble with docstrings.
Let's say for instance I have a function such as the following:
```
def _get_logging_statement(self):
"""Returns an easy to read string which separates items in the log file cleanly"""
result = "... | Doesn't look like it currently. Googled around for this issue and the top result pointed me to this [Pydev-users post](http://www.mail-archive.com/pydev-users@lists.sourceforge.net/msg03935.html):
> > > On Mon, May 3, 2010 at 5:45 AM, Janosch Peters wrote:
> > >
> > > Hi,
> > >
> > > when I hover over a function or cl... |
Common Lisp -- List unpacking? (similar to Python) | 4,451,854 | 10 | 2010-12-15T15:46:09Z | 4,451,864 | 9 | 2010-12-15T15:47:23Z | [
"python",
"list",
"lisp",
"common-lisp",
"iterable-unpacking"
] | In Python, assuming the following function is defined:
```
def function(a, b, c):
... do stuff with a, b, c ...
```
I am able to use the function using Python's sequence unpacking:
```
arguments = (1, 2, 3)
function(*arguments)
```
Does similar functionality exist in Common Lisp? So that if I have a function:
... | [`apply`](http://books.google.co.uk/books?id=Bby4FJy49QUC&lpg=PA61&ots=0tuzZ3zG1J&dq=lisp%20argument%20unpacking&pg=PA61#v=onepage&q&f=false) |
Common Lisp -- List unpacking? (similar to Python) | 4,451,854 | 10 | 2010-12-15T15:46:09Z | 4,451,888 | 17 | 2010-12-15T15:49:07Z | [
"python",
"list",
"lisp",
"common-lisp",
"iterable-unpacking"
] | In Python, assuming the following function is defined:
```
def function(a, b, c):
... do stuff with a, b, c ...
```
I am able to use the function using Python's sequence unpacking:
```
arguments = (1, 2, 3)
function(*arguments)
```
Does similar functionality exist in Common Lisp? So that if I have a function:
... | ```
(apply #'function arguments)
``` |
How to find the mountpoint a file resides on? | 4,453,602 | 12 | 2010-12-15T18:40:36Z | 4,453,715 | 13 | 2010-12-15T18:56:44Z | [
"python",
"linux",
"unix",
"filesystems"
] | For example, I've got a file with the following path:
```
/media/my_mountpoint/path/to/file.txt
```
I've got the whole path and want to get:
```
/media/my_mountpoint
```
How can I do this? Preferably in Python and without using external libraries / tools. (Both are not a requirement.) | You may either call the `mount` command and parse its output to find the longest common prefix with your path, or use the `stat` system call to get the device a file resides on and go up the tree until you get to a different device.
In Python, `stat` may be used as follows (untested and may have to be extended to hand... |
How do I modify the session in the Django test framework | 4,453,764 | 14 | 2010-12-15T19:01:59Z | 4,454,671 | 25 | 2010-12-15T20:42:47Z | [
"python",
"django",
"django-testing",
"django-sessions"
] | My site allows individuals to contribute content in the absence of being logged in by creating a User based on the current session\_key
I would like to setup a test for my view, but it seems that it is not possible to modify the request.session:
I'd like to do this:
```
from django.contrib.sessions.models import Ses... | The client object of the django testing framework makes possible to touch the session. Look at <http://docs.djangoproject.com/en/dev/topics/testing/?from=olddocs#django.test.client.Client.session> for details
Be careful : `To modify the session and then save it, it must be stored in a variable first (because a new Ses... |
How do I modify the session in the Django test framework | 4,453,764 | 14 | 2010-12-15T19:01:59Z | 7,722,483 | 23 | 2011-10-11T07:08:13Z | [
"python",
"django",
"django-testing",
"django-sessions"
] | My site allows individuals to contribute content in the absence of being logged in by creating a User based on the current session\_key
I would like to setup a test for my view, but it seems that it is not possible to modify the request.session:
I'd like to do this:
```
from django.contrib.sessions.models import Ses... | This is how I did it (inspired by a solution in <http://blog.mediaonfire.com/?p=36>).
```
from django.test import TestCase
from django.conf import settings
from django.utils.importlib import import_module
class SessionTestCase(TestCase):
def setUp(self):
# http://code.djangoproject.com/ticket/10899
... |
How do I modify the session in the Django test framework | 4,453,764 | 14 | 2010-12-15T19:01:59Z | 15,194,318 | 7 | 2013-03-04T03:55:39Z | [
"python",
"django",
"django-testing",
"django-sessions"
] | My site allows individuals to contribute content in the absence of being logged in by creating a User based on the current session\_key
I would like to setup a test for my view, but it seems that it is not possible to modify the request.session:
I'd like to do this:
```
from django.contrib.sessions.models import Ses... | As Andrew Austin already mentioned, it doesn't work because of this bug: <https://code.djangoproject.com/ticket/11475>
What you can do though is this (got it from <http://www.gregaker.net/2011/aug/29/testing-django-views-that-rely-on-session-variables/>):
```
from django.test import TestCase
from django.test.client i... |
Prepend a line to an existing file in Python | 4,454,298 | 38 | 2010-12-15T19:59:51Z | 4,454,470 | 12 | 2010-12-15T20:18:55Z | [
"python",
"prepend"
] | I need to add a single line to the first line of a text file and it looks like the only options available to me are more lines of code than I would expect from python. Something like this:
```
f = open('filename','r')
temp = f.read()
f.close()
f = open('filename', 'w')
f.write("#testfirstline")
f.write(temp)
f.close... | Other approach:
```
with open("infile") as f1:
with open("outfile", "w") as f2:
f2.write("#test firstline")
for line in f1:
f2.write(line)
```
or a one liner:
```
open("outfile", "w").write("#test firstline\n" + open("infile").read())
```
Thanks for the opportunity to think about thi... |
Prepend a line to an existing file in Python | 4,454,298 | 38 | 2010-12-15T19:59:51Z | 4,454,522 | 56 | 2010-12-15T20:24:30Z | [
"python",
"prepend"
] | I need to add a single line to the first line of a text file and it looks like the only options available to me are more lines of code than I would expect from python. Something like this:
```
f = open('filename','r')
temp = f.read()
f.close()
f = open('filename', 'w')
f.write("#testfirstline")
f.write(temp)
f.close... | Python makes a lot of things easy and contains libraries and wrappers for a lot of common operations, but the goal is not to hide fundamental truths.
The fundamental truth you are encountering here is that you generally can't prepend data to an existing flat structure without rewriting the entire structure. This is tr... |
Prepend a line to an existing file in Python | 4,454,298 | 38 | 2010-12-15T19:59:51Z | 4,454,598 | 24 | 2010-12-15T20:35:17Z | [
"python",
"prepend"
] | I need to add a single line to the first line of a text file and it looks like the only options available to me are more lines of code than I would expect from python. Something like this:
```
f = open('filename','r')
temp = f.read()
f.close()
f = open('filename', 'w')
f.write("#testfirstline")
f.write(temp)
f.close... | I would stick with separate reads and writes, but we certainly can express each more concisely:
Python2:
```
with file('filename', 'r') as original: data = original.read()
with file('filename', 'w') as modified: modified.write("new first line\n" + data)
```
Python3:
```
with open('filename', 'r') as original: dat... |
numpy: access an array by column | 4,455,076 | 147 | 2010-12-15T21:27:41Z | 4,455,154 | 241 | 2010-12-15T21:35:43Z | [
"python",
"arrays",
"numpy"
] | Suppose I have:
```
test = numpy.array([[1, 2], [3, 4], [5, 6]])
```
`test[i]` gets me *ith* line of the array (eg `[1, 2]`). How can I access the *ith* column? (eg `[1, 3, 5]`). Also, would this be an expensive operation? | ```
>>> test[:,0]
array([1, 3, 5])
```
Similarly,
```
>>> test[1,:]
array([3, 4])
```
lets you access rows. This is covered in Section 1.4 (Indexing) of the [NumPy reference](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html). This is quick, at least in my experience. It's certainly much quicker than ac... |
numpy: access an array by column | 4,455,076 | 147 | 2010-12-15T21:27:41Z | 16,121,210 | 26 | 2013-04-20T14:05:21Z | [
"python",
"arrays",
"numpy"
] | Suppose I have:
```
test = numpy.array([[1, 2], [3, 4], [5, 6]])
```
`test[i]` gets me *ith* line of the array (eg `[1, 2]`). How can I access the *ith* column? (eg `[1, 3, 5]`). Also, would this be an expensive operation? | And if you want to access more than one column at a time you could do:
```
>>> test = np.arange(9).reshape((3,3))
>>> test
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> test[:,[0,2]]
array([[0, 2],
[3, 5],
[6, 8]])
``` |
numpy: access an array by column | 4,455,076 | 147 | 2010-12-15T21:27:41Z | 22,990,906 | 17 | 2014-04-10T14:25:12Z | [
"python",
"arrays",
"numpy"
] | Suppose I have:
```
test = numpy.array([[1, 2], [3, 4], [5, 6]])
```
`test[i]` gets me *ith* line of the array (eg `[1, 2]`). How can I access the *ith* column? (eg `[1, 3, 5]`). Also, would this be an expensive operation? | ```
>>> test[:,0]
array([1, 3, 5])
```
this command gives you a row vector, if you just want to loop over it, it's fine, but if you want to hstack with some other array with dimension 3xN, you will have
ValueError: all the input arrays must have same number of dimensions
while
```
>>> test[:,[0]]
array([[1],
... |
Python3 sleep() problem | 4,456,581 | 8 | 2010-12-16T01:12:20Z | 4,456,612 | 19 | 2010-12-16T01:17:45Z | [
"python",
"python-3.x",
"sleep",
"flush"
] | I was writing a simple program on Python 3.1 and I stumbled upon this:
If I run this on the IDLE it works as intended - prints `"Initializing."` and then adds two dots, one after each second, and waits for input.
```
from time import sleep
def initialize():
print('Initializing.', end='')
sleep(1)
print("... | This is because the output is being buffered.
You should add a `sys.stdout.flush()` after each write |
How to get the list of all initialized objects and function definitions alive in python? | 4,458,701 | 15 | 2010-12-16T08:24:28Z | 4,458,733 | 23 | 2010-12-16T08:29:29Z | [
"python",
"memory",
"python-idle"
] | Say that in the python shell (IDLE) I have defined some classes, functions, variables. Also created objects of the classes. Then I deleted some of the objects and created some others. At a later point in time, how can I get to know what are the currently active objects, variables, and methods definitions active in the ... | Yes.
```
>>> import gc
>>> gc.get_objects()
```
Not that you'll find that useful. There is a *lot* of them. :-) Over 4000 just when you start Python.
Possibly a bit more useful is all the variables active locally:
```
>>> locals()
```
And the one active globally:
```
>>> globals()
```
(Note that "globally" in Py... |
get exception type in python 1.5.2 | 4,458,755 | 3 | 2010-12-16T08:33:08Z | 4,458,788 | 9 | 2010-12-16T08:35:20Z | [
"python",
"exception",
"syntax-error",
"raise"
] | How can I get the type of an Exception in python 1.5.2?
doing this:
```
try:
raise "ABC"
except Exception as e:
print str(e)
```
gives an SyntaxError:
```
except Exception as e:
^
SyntaxError: invalid syntax
```
**EDIT:**
this does not work:
```
try:
a = 3
b = not_existent_v... | It's
```
except Exception, e:
```
In Python 1 and 2. (Although `as` also works in Python 2.6 and 2.7).
(Why on earth are you using 1.5.2!?)
To then get the type of the error you use `type(e)`. To get the type name in Python 2 you use `type(e).__name__`, I have no idea if that works in 1.5.2, you'll have to check th... |
How to read class attributes in the same order as declared? | 4,459,531 | 22 | 2010-12-16T10:08:50Z | 4,460,034 | 11 | 2010-12-16T11:00:22Z | [
"python",
"class",
"metaclass"
] | I am writing a metaclass that reads class attributes and store them in a list, but I want the list (cls.columns) to respect the declaration order (that is : mycol2,mycol3,zut,cool,menfin,a in my exemple):
```
import inspect
import pprint
class Column(object):
pass
class ListingMeta(type):
def __new__(meta, cl... | Here is the workaround I juste developped :
```
import inspect
class Column(object):
creation_counter = 0
def __init__(self):
self.creation_order = Column.creation_counter
Column.creation_counter+=1
class ListingMeta(type):
def __new__(meta, classname, bases, classDict):
cls = typ... |
How to read class attributes in the same order as declared? | 4,459,531 | 22 | 2010-12-16T10:08:50Z | 27,113,652 | 21 | 2014-11-24T20:32:37Z | [
"python",
"class",
"metaclass"
] | I am writing a metaclass that reads class attributes and store them in a list, but I want the list (cls.columns) to respect the declaration order (that is : mycol2,mycol3,zut,cool,menfin,a in my exemple):
```
import inspect
import pprint
class Column(object):
pass
class ListingMeta(type):
def __new__(meta, cl... | In Python 3, just use an `OrderedDict` and store its `.keys()` before passing the whole dict to `type.__new__()`, like this:
```
import collections
class OrderedClassMembers(type):
@classmethod
def __prepare__(self, name, bases):
return collections.OrderedDict()
def __new__(self, name, bases, cl... |
How to make lists distinct? | 4,459,703 | 53 | 2010-12-16T10:27:13Z | 4,459,730 | 111 | 2010-12-16T10:29:27Z | [
"python"
] | I have a list in Python, how can I make it's values unique? | The simplest is to convert to a set then back to a list:
```
my_list = list(set(my_list))
```
One disadvantage with this is that it won't preserve the order. You may also want to consider if a set would be a better data structure to use in the first place, instead of a list. |
How to make lists distinct? | 4,459,703 | 53 | 2010-12-16T10:27:13Z | 4,459,748 | 8 | 2010-12-16T10:32:12Z | [
"python"
] | I have a list in Python, how can I make it's values unique? | To preserve the order:
```
l = [1, 1, 2, 2, 3]
result = list()
map(lambda x: not x in result and result.append(x), l)
result
# [1, 2, 3]
``` |
How to make lists distinct? | 4,459,703 | 53 | 2010-12-16T10:27:13Z | 4,463,433 | 17 | 2010-12-16T17:08:07Z | [
"python"
] | I have a list in Python, how can I make it's values unique? | Modified versions of <http://www.peterbe.com/plog/uniqifiers-benchmark>
To preserve the order:
```
def f(seq): # Order preserving
''' Modified version of Dave Kirby solution '''
seen = set()
return [x for x in seq if x not in seen and not seen.add(x)]
```
OK, now how does it work, because it's a little bit tri... |
How to make lists distinct? | 4,459,703 | 53 | 2010-12-16T10:27:13Z | 24,865,413 | 8 | 2014-07-21T12:44:05Z | [
"python"
] | I have a list in Python, how can I make it's values unique? | one-liner and preserve order
```
list(OrderedDict.fromkeys([2,1,1,3]))
```
although you'll need
```
from collections import OrderedDict
``` |
Linear Interpolation. How to implement this algorithm in C ? (Python version is given) | 4,459,930 | 4 | 2010-12-16T10:49:53Z | 4,536,541 | 8 | 2010-12-27T03:57:01Z | [
"python",
"c",
"algorithm",
"math",
"signal-processing"
] | There exists one very good linear interpolation method. It performs linear interpolation requiring **at most one multiply per output sample**. I found its description in a third edition of Understanding DSP by Lyons. This method involves a special hold buffer. Given a number of samples to be inserted between any two in... | ## Interpolation in the sense of "signal sample rate increase"
... or i call it, "upsampling" (wrong term, probably. disclaimer: i have not read Lyons'). I just had to understand what the code does and then re-write it for readability. As given it has couple of problems:
a) it is inefficient - two loops is ok but it ... |
running a python script with cron | 4,460,262 | 14 | 2010-12-16T11:26:04Z | 4,460,303 | 53 | 2010-12-16T11:31:11Z | [
"python",
"cron"
] | It might be very simple question, but how could I run a python script on my fedora dist every 2 days?
Thanks
Antonis | It is a question on cron.
First is add a SHEBANG line on top of your python script.
```
#!/usr/bin/env python
```
Make your script executable with `chmod +x`
And do a crontab -e and add `0 0 */2 * * /path/to/your/pythonscript.py` |
Install Python 2.7.1 side-by-side with Apple-supplied Python | 4,460,367 | 12 | 2010-12-16T11:38:41Z | 4,464,015 | 24 | 2010-12-16T18:15:32Z | [
"python",
"osx",
"osx-snow-leopard"
] | I have just downloaded the Python 2.7.1 DMG from [Python.org](http://www.python.org/download/releases/2.7.1/). I have seen suggestions to get ActivePython, but I would prefer the one from Python.org.
1. If I just run the `mpkg` installer inside the DMG, accepting all defaults, will it live peacefully with the Apple-su... | If you did not change the default set of packages when using the python.org installer, typing `python` from a command line should run the newly-installed Python 2.7. (You will need to start a new terminal session after running the installer to see this.) The current python.org installers for OS X create a folder in you... |
Hadoop Streaming Job failed error in python | 4,460,522 | 8 | 2010-12-16T11:58:09Z | 4,465,333 | 14 | 2010-12-16T21:00:42Z | [
"python",
"hadoop",
"mapreduce"
] | From [this guide](http://www.michael-noll.com/tutorials/writing-an-hadoop-mapreduce-program-in-python/#running-the-python-code-on-hadoop), I have successfully run the sample exercise. But on running my mapreduce job, I am getting the following error
`ERROR streaming.StreamJob: Job not Successful!
10/12/16 17:13:38 ... | Your -mapper and -reducer should just be the script name.
```
hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop jar contrib/streaming/hadoop-0.20.0-streaming.jar -file /home/hadoop/mapper.py -mapper mapper.py -file /home/hadoop/reducer.py -reducer reducer.py -input my-input/* -output my-output
```
When your scripts are in ... |
Python: Getting the error message of an exception | 4,460,669 | 28 | 2010-12-16T12:19:16Z | 4,460,784 | 25 | 2010-12-16T12:32:58Z | [
"python",
"django",
"exception-handling"
] | In python 2.6.6, how can I capture the error message of an exception.
IE:
```
response_dict = {} # contains info to response under a django view.
try:
plan.save()
response_dict.update({'plan_id': plan.id})
except IntegrityError, e: #contains my own custom exception raising with custom messages.
response_d... | Pass it through `str()` first.
```
response_dict.update({'error': str(e)})
```
Also note that certain exception classes may have specific attributes that give the exact error. |
Python - Convert date to ISO 8601 | 4,460,698 | 17 | 2010-12-16T12:22:36Z | 4,460,765 | 36 | 2010-12-16T12:30:21Z | [
"python",
"datetime",
"iso8601"
] | In Python, how can I convert a string like this:
> Thu, 16 Dec 2010 12:14:05 +0000
to ISO 8601 format, while keeping the timezone?
Please note that the orginal date is string, and the output should be string too, not `datetime` or something like that.
I have no problem to use third parties libraries, though. | Using [dateutil](http://niemeyer.net/python-dateutil):
```
import dateutil.parser as parser
text = 'Thu, 16 Dec 2010 12:14:05 +0000'
date = (parser.parse(text))
print(date.isoformat())
# 2010-12-16T12:14:05+00:00
``` |
Enhance SQLAlchemy syntax for polymorphic identity | 4,460,830 | 5 | 2010-12-16T12:40:08Z | 4,462,796 | 7 | 2010-12-16T16:09:05Z | [
"python",
"sqlalchemy",
"metaclass"
] | I have a declarative base class `Entity` which defines the column `name` as polymorphic, e.g.
```
class Entity(DeclarativeBase):
name = Column('name', String(40))
__mapper_args__ = {'polymorphic_on':name}
```
In subclasses, I could now say
```
class Experiment(Entity):
__mapper_args__ = {'polymorphic_ide... | Shame on me but the problem could easily be solved by not using the `dict_` but by setting the attribute directly on `cls`.
```
class Meta(DeclarativeMeta):
def __init__(cls, *args, **kw):
if getattr(cls, '_decl_class_registry', None) is None:
return # they use this in the docs, so maybe its no... |
Extract the first paragraph from a Wikipedia article (Python) | 4,460,921 | 26 | 2010-12-16T12:49:22Z | 4,461,624 | 36 | 2010-12-16T14:12:21Z | [
"python",
"wikipedia"
] | How can I extract the first paragraph from a Wikipedia article, using Python?
For example, for **Albert Einstein**, that would be:
> Albert Einstein (pronounced /ËælbÉrt
> Ëaɪnstaɪn/; German: [ËalbÉt ËaɪnÊtaɪn]
> ( listen); 14 March 1879 â 18 April
> 1955) was a theoretical physicist,
> philosopher and ... | Some time ago I made two classes for get Wikipedia articles in plain text. I know that they aren't the best solution, but you can adapt it to your needs:
[wikipedia.py](http://pastebin.com/FVDxLWNG)
[wiki2plain.py](http://pastebin.com/idw8vQQK)
You can use it like this:
```
from wikipedia import Wikipedia
from... |
Extract the first paragraph from a Wikipedia article (Python) | 4,460,921 | 26 | 2010-12-16T12:49:22Z | 6,082,536 | 9 | 2011-05-21T14:57:55Z | [
"python",
"wikipedia"
] | How can I extract the first paragraph from a Wikipedia article, using Python?
For example, for **Albert Einstein**, that would be:
> Albert Einstein (pronounced /ËælbÉrt
> Ëaɪnstaɪn/; German: [ËalbÉt ËaɪnÊtaɪn]
> ( listen); 14 March 1879 â 18 April
> 1955) was a theoretical physicist,
> philosopher and ... | What I did is this:
```
import urllib
import urllib2
from BeautifulSoup import BeautifulSoup
article= "Albert Einstein"
article = urllib.quote(article)
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')] #wikipedia needs this
resource = opener.open("http://en.wikipedia.org/wiki/" + a... |
Extract the first paragraph from a Wikipedia article (Python) | 4,460,921 | 26 | 2010-12-16T12:49:22Z | 19,506,740 | 25 | 2013-10-21T23:50:20Z | [
"python",
"wikipedia"
] | How can I extract the first paragraph from a Wikipedia article, using Python?
For example, for **Albert Einstein**, that would be:
> Albert Einstein (pronounced /ËælbÉrt
> Ëaɪnstaɪn/; German: [ËalbÉt ËaɪnÊtaɪn]
> ( listen); 14 March 1879 â 18 April
> 1955) was a theoretical physicist,
> philosopher and ... | I wrote a Python library that aims to make this very easy. Check it out at [Github](https://github.com/goldsmith/Wikipedia).
To install it, run
```
$ pip install wikipedia
```
Then to get the first paragraph of an article, just use the `wikipedia.summary` function.
```
>>> import wikipedia
>>> print wikipedia.summa... |
Why does Learn Python The Hard Way suggest to "Read your .py file backwards."? | 4,461,540 | 2 | 2010-12-16T14:02:15Z | 4,461,622 | 12 | 2010-12-16T14:12:02Z | [
"python"
] | I am reading [Learn Python The Hard Way](http://learnpythonthehardway.org/wiki?name=Learn+Python+The+Hard+Way) and I am really curious what he means by
> Read your .py file backwards | Exercise 41 (page 117) explains it better. This snippet:
```
cities['_find']=find_city
city_found=cities['_find'](cities,state)
```
reads like this when read backwards:
> 1. `state` and `city` are...
> 2. passed as parameters to...
> 3. a function at...
> 4. `_find` inside...
> 5. the dict `cities`...
> 6. and ï¬na... |
Beautiful Soup to parse url to get another urls data | 4,462,061 | 16 | 2010-12-16T14:55:22Z | 4,462,877 | 43 | 2010-12-16T16:18:49Z | [
"python",
"html",
"parsing",
"beautifulsoup"
] | I need to parse a url to get a list of urls that link to a detail page. Then from that page I need to get all the details from that page. I need to do it this way because the detail page url is not regularly incremented and changes, but the event list page stays the same.
Basically:
```
example.com/events/
<a hre... | ```
import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen('http://yahoo.com').read()
soup = BeautifulSoup(page)
soup.prettify()
for anchor in soup.findAll('a', href=True):
print anchor['href']
```
It will give you the list of urls. Now You can iterate over those urls and parse the data.
*... |
How to run Python nose tests with a different version of Python | 4,463,240 | 12 | 2010-12-16T16:49:33Z | 4,463,489 | 14 | 2010-12-16T17:14:54Z | [
"python",
"unit-testing",
"centos",
"nose"
] | We have CentOS with the ancient Python 2.4 interpreter.
But we would like to write out tests with a newer 2.5/2.6 syntax.
Assuming we have a second Python interpreter installed (e.g. python2.6) is there any way
to run the 'nosetests' shell command and tell it to use a specific python interpreter instead of the defaul... | The nosetests file is in Python, so it should just be a matter of running it in your new version. Find where the file is:
```
which nosetests
```
Then:
```
python2.6 /usr/bin/nosetests
```
Adjusting the name and path to match your system. I've not tested, but that should work. |
Python multiprocessing a function with several inputs | 4,463,275 | 6 | 2010-12-16T16:53:46Z | 4,463,341 | 11 | 2010-12-16T16:59:27Z | [
"python",
"multiprocessing"
] | In Python the `multiprocessing` module can be used to run a function over a range of values in parallel. For example, this produces a list of the first 100000 evaluations of f.
```
def f(i):
return i * i
def main():
import multiprocessing
pool = multiprocessing.Pool(2)
ans = pool.map(f, range(100000))... | There are several ways to do this. In the example given in the question, you could just define a wrapper function
```
def g(i):
return f(i, 20)
```
and pass this wrapper to `map()`. A more general approach is to have a wrapper that takes a single tuple argument and unpacks the tuple to multiple arguments
```
def... |
Python multiprocessing a function with several inputs | 4,463,275 | 6 | 2010-12-16T16:53:46Z | 4,463,621 | 9 | 2010-12-16T17:26:42Z | [
"python",
"multiprocessing"
] | In Python the `multiprocessing` module can be used to run a function over a range of values in parallel. For example, this produces a list of the first 100000 evaluations of f.
```
def f(i):
return i * i
def main():
import multiprocessing
pool = multiprocessing.Pool(2)
ans = pool.map(f, range(100000))... | You can use [functools.partial](http://docs.python.org/library/functools.html#functools.partial)
```
def f(i, n):
return i * i + 2*n
def main():
import multiprocessing
pool = multiprocessing.Pool(2)
ans = pool.map(functools.partial(f, n=20), range(100000))
return ans
``` |
Python: Combine "if 'x' in dict" and "for i in dict['x']" | 4,464,274 | 6 | 2010-12-16T18:45:40Z | 4,464,282 | 7 | 2010-12-16T18:47:07Z | [
"python",
"json",
"design"
] | Really two questions: If I have a dictionary (that originally came from parsing a json message) that has an optional array in it:
```
dict_with = {'name':'bob','city':'san francisco','kids': {'name': 'alice'} }
dict_without = {'name':'bob','city':'san francisco' }
```
I would normally have code like:
```
if 'kids' i... | An empty sequence results in no iteration.
```
for k in D.get('kids', ()):
``` |
Python: Combine "if 'x' in dict" and "for i in dict['x']" | 4,464,274 | 6 | 2010-12-16T18:45:40Z | 4,464,286 | 10 | 2010-12-16T18:47:26Z | [
"python",
"json",
"design"
] | Really two questions: If I have a dictionary (that originally came from parsing a json message) that has an optional array in it:
```
dict_with = {'name':'bob','city':'san francisco','kids': {'name': 'alice'} }
dict_without = {'name':'bob','city':'san francisco' }
```
I would normally have code like:
```
if 'kids' i... | ```
for x in d.get("kids", ()):
print "kid:", x
``` |
How to convert regexp to python from perl | 4,464,470 | 2 | 2010-12-16T19:09:07Z | 4,464,511 | 15 | 2010-12-16T19:13:31Z | [
"python",
"regex",
"perl"
] | in Perl:
```
if ($test =~ /^id\:(.*)$/ ) {
print $1;
}
``` | In Python:
```
import re
test = 'id:foo'
match = re.search(r'^id:(.*)$', test)
if match:
print match.group(1)
```
In Python, regular expressions are available through the [`re` library](http://docs.python.org/library/re.html).
The `r` before the string indicates that it is a [raw string literal](http://docs.py... |
Why is the return value of an empty python regexp search a match? | 4,464,955 | 2 | 2010-12-16T20:16:14Z | 4,464,969 | 10 | 2010-12-16T20:18:22Z | [
"python",
"regex"
] | When passing an empty string to a regular expression object, the result of a search is a match object an not None. Should it be None since there is nothing to match?
```
import re
m = re.search("", "some text")
if m is None:
print "Returned None"
else:
print "Return a match"
```
Incidentally, using the speci... | Empty pattern matches any part of the string.
Check this:
```
import re
re.search("", "ffff")
<_sre.SRE_Match object at 0xb7166410>
re.search("", "ffff").start()
0
re.search("$", "ffff").start()
4
```
Adding $ doesn't yield the same result. Match is at the end, because it is the only place it can be. |
Don't understand python pop altering multiple variables | 4,465,496 | 2 | 2010-12-16T21:22:28Z | 4,465,508 | 7 | 2010-12-16T21:23:37Z | [
"python",
"list",
"pop"
] | I'm sure this is something simple that I've overlooked, but I'm hoping someone can explain the following to me:
```
origList = [1, 2, 3, 4, 5, 6, 7, 8]
def test(inputList):
while range(len(inputList)):
inputList.pop()
altList = origList
test(altList)
print 'origList:', origList # prints origList: []
print ... | Everything in Python is a reference. They're the same list.
```
altList = origList[:]
``` |
Does Django have a template tag that can detect URLs and turn them into hyperlinks? | 4,465,636 | 4 | 2010-12-16T21:41:26Z | 4,465,706 | 11 | 2010-12-16T21:50:54Z | [
"python",
"django",
"http",
"templates",
"url"
] | When someone writes a post and copies and pastes a url in it, can Django detect it and render it as a hyperlink rather than plain text? | Django has the [urlize template filter](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#urlize) which will automatically detect both URLs and email addresses and turn them into the appropriate hyperlinks.
The docs there are actually a little thin, so I recommend also reading the [docstring in the source f... |
Python [Errno 98] Address already in use | 4,465,959 | 53 | 2010-12-16T22:24:24Z | 4,466,035 | 76 | 2010-12-16T22:33:22Z | [
"python",
"sockets",
"connection",
"errno"
] | In my Python socket program, I sometimes need to interrupt it with ctrl-c. When I do this, it does close the connection using socket.close() however when I try to reopen it I have to wait what seems like a minute before I can connect again. How does one correctly close a socket? Or is this intended? | Yes, it is intended. Here you can read [detailed explanation](http://stackoverflow.com/questions/337115/setting-time-wait-tcp). It is possible to override this behavior by setting SO\_REUSEADDR option on a socket. For example:
```
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
``` |
Python [Errno 98] Address already in use | 4,465,959 | 53 | 2010-12-16T22:24:24Z | 25,529,620 | 7 | 2014-08-27T14:17:40Z | [
"python",
"sockets",
"connection",
"errno"
] | In my Python socket program, I sometimes need to interrupt it with ctrl-c. When I do this, it does close the connection using socket.close() however when I try to reopen it I have to wait what seems like a minute before I can connect again. How does one correctly close a socket? Or is this intended? | If you use a TCPServer, UDPServer or their subclasses in the SocketServer module, you can set this class variable (before instanciating a server):
```
SocketServer.TCPServer.allow_reuse_address = True
```
(via [SocketServer.ThreadingTCPServer - Cannot bind to address after program restart](http://stackoverflow.com/qu... |
python argparse with dependencies | 4,466,197 | 11 | 2010-12-16T22:57:33Z | 4,466,258 | 7 | 2010-12-16T23:09:21Z | [
"python",
"argparse"
] | I'm writing a script which has 2 arguments which are mutually exclusive, and an option that only makes sense with one of those arguments. I'm trying to set up argparse to fail if you call it with the argument that makes no sense.
To be clear:
`-m -f` makes sense
`-s` makes sense
`-s -f` should throw errors
no argu... | You just have the argument groups mixed up. In your code, you only assign one option to the mutually exclusive group. I think what you want is:
```
parser = argparse.ArgumentParser(description='Lookup servers by ip address from host file')
parser.add_argument('host', nargs=1,
help="ip address to lookup")
m... |
Scrapy Newbie Question - can't get tutorial file working | 4,466,474 | 3 | 2010-12-16T23:47:04Z | 12,188,985 | 7 | 2012-08-30T02:11:38Z | [
"python",
"scrapy"
] | I am a complete newbie to Python and Scrapy so I started by trying to replicate the tutorial. I am trying to scrape the www.dmoz.org website as per the tutorial.
I compose the dmoz\_spider.py as indicated below
```
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from dmoz.items imp... | I had this problem. Make sure you made the below change as it says to do in the tutorial.
Open items.py and see if you changed class
```
class TutorialItem(Item):
title=Field()
link=Field()
desc=Field()
```
into:
```
class DmozItem(Item):
title=Field()
link=Field()
desc=Field()
``` |
In Django, how do i change "This field is required." to "Name is required"? | 4,466,499 | 10 | 2010-12-16T23:52:20Z | 4,466,904 | 21 | 2010-12-17T01:13:15Z | [
"python",
"django",
"forms",
"frameworks"
] | I'm using the forms framework. And when I set required=True, this error shows. What if I don't want it to say "This field", but instead, say the label?
Since i'm not going to be displaying it beneath the form input. I"m going to display all the errors at the top of the page. | An easy way to specify simple "required" validation messages is to pass the field the error\_messages argument.
```
name = forms.CharField(error_messages={'required': 'Your Name is Required'})
```
Check the docs for which keys can be specified per field:
<http://docs.djangoproject.com/en/dev/ref/forms/fields/#django.... |
Trying to use MEGAM as an NLTK ClassifierBasedPOSTagger? | 4,467,193 | 5 | 2010-12-17T02:29:41Z | 4,473,022 | 8 | 2010-12-17T17:14:32Z | [
"python",
"nlp",
"nltk",
"pos-tagger"
] | I am currently trying to build a general purpose (or as general as is practical) POS tagger with NLTK. I have dabbled with the brown and treebank corpora for training, but will probably be settling on the treebank corpus.
Learning as I go, I am finding the classifier POS taggers are the most accurate. The Maximum Enti... | This one liner should work for training a MEGAM MaxentClassifier for the ClassifierBasedPOSTagger. Of course, that assumes MEGAM is already installed (go [here](http://www.umiacs.umd.edu/~hal/megam/) to download)
```
maxent_tagger = ClassifierBasedPOSTagger(train=train_sents, classifier_builder=lambda train_feats: Max... |
Play simple beep with python without external library | 4,467,240 | 14 | 2010-12-17T02:44:39Z | 4,467,299 | 23 | 2010-12-17T03:01:14Z | [
"python",
"playback",
"noise"
] | Using only the modules that come with a standard python 2.6 installation, would it be possible to play a simple beeping noise? | If you're on a Unix terminal, you can print "\a" to get a terminal bell:
```
>>> def beep():
... print "\a"
>>> beep()
```
Of course, that will print a newline too⦠So `sys.stdout.write("\a")` might be better. But you get the idea. |
Play simple beep with python without external library | 4,467,240 | 14 | 2010-12-17T02:44:39Z | 22,264,121 | 7 | 2014-03-08T02:14:37Z | [
"python",
"playback",
"noise"
] | Using only the modules that come with a standard python 2.6 installation, would it be possible to play a simple beeping noise? | On windows:
```
import winsound # for sound
import time # for sleep
winsound.Beep(440, 250) # frequency, duration
time.sleep(0.25) # in seconds (0.25 is 250ms)
winsound.Beep(600, 250)
time.sleep(0.25)
```
34.4. winsound â Sound-playing interface for Windows:
<http://docs.python.org/2... |
Python Sharing a network socket with multiprocessing.Manager | 4,467,626 | 2 | 2010-12-17T04:11:35Z | 8,686,107 | 7 | 2011-12-31T03:33:52Z | [
"python",
"sockets",
"networking",
"process",
"share"
] | I am currently writing a nginx proxy server module with a Request queue in front, so the requests are not dropped when the servers behind the nginx can't handle the requests (nginx is configured as a load balancer).
I am using
```
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
```
The idea is to put t... | U can use multiprocessing.reduction to transfer the connection and socket objects between processes
Example Code
```
# Main process
from multiprocessing.reduction import reduce_handle
h = reduce_handle(client_socket.fileno())
pipe_to_worker.send(h)
# Worker process
from multiprocessing.reduction import rebuild_handl... |
Generating 3D noise quickly in python | 4,467,638 | 9 | 2010-12-17T04:14:20Z | 4,467,770 | 10 | 2010-12-17T04:47:27Z | [
"python",
"noise"
] | I need a method to generate 3D simplex noise in python rather quickly. What methods are there out there to solve this problem? | ```
$ pip install noise
```
* <http://pypi.python.org/pypi/noise/>
> This package is designed to give you simple to use, fast functions for
> generating Perlin noise in your Python programs. Perlin noise is famously
> called the "salt" of procedural generation, as it adds considerable flavor in
> its application. Noi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.