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 |
|---|---|---|---|---|---|---|---|---|---|
Finding Memory Usage, CPU utilization, Execution time for running a python script | 13,507,205 | 3 | 2012-11-22T06:47:23Z | 13,507,805 | 8 | 2012-11-22T07:34:51Z | [
"python",
"memory",
"cpu-usage",
"execution-time"
] | I am using python, and suppose i had some code as below
**example.py**
```
import os, psutil
import MySQLdb as mdb
conn = mdb.connect(user='root', passwd='redhat', db='File_Data', host='localhost', charset="utf8")
file_path = "/home/local/user/Module/File_processing/part-file.txt"
p = psutil.Process(os.getpid())
cur... | **For time profiling**
1. `cd` into the dir that contains `example.py` (lets call this `exampledir`).
2. run `python -m cProfile -o example.profile example.py`
3. [download RunSnake](http://pypi.python.org/pypi/RunSnakeRun/2.0.2b1) and unpack it anywhere
4. `cd` into the dir where you unpacked RunSnake
5. run `python ... |
Expression evaluating to None when substr is not found | 13,508,677 | 9 | 2012-11-22T08:39:23Z | 13,508,726 | 7 | 2012-11-22T08:43:15Z | [
"python",
"string"
] | `str.find()` always returns `-1` if not found.
Can I write an expression instead of `str.find()` and `return None` if not found? | Do you mean something like this?
```
def find2(str, substr):
result = str.find(substr)
return result if result != -1 else None
```
In Python 2.4, change the last line to
```
if result != -1:
return result
else:
return None
``` |
Is there a way to set all values of a dictionary to zero? | 13,508,829 | 3 | 2012-11-22T08:50:21Z | 13,508,846 | 9 | 2012-11-22T08:51:53Z | [
"python"
] | For example, I have a list of ASCII characters and want to zip them with a list of zeroes equal to the number of characters in the ASCII list,
like:
```
import string
a = string.printable
#Gives all ASCII characters as a list ^
b = zeroes * len(a)
c = zip(a,b)
```
Something like that? | You can use a dict comprehension:
```
{ x:0 for x in string.printable}
``` |
Is there a way to set all values of a dictionary to zero? | 13,508,829 | 3 | 2012-11-22T08:50:21Z | 13,508,866 | 8 | 2012-11-22T08:53:05Z | [
"python"
] | For example, I have a list of ASCII characters and want to zip them with a list of zeroes equal to the number of characters in the ASCII list,
like:
```
import string
a = string.printable
#Gives all ASCII characters as a list ^
b = zeroes * len(a)
c = zip(a,b)
```
Something like that? | There is a standard method for that:
```
mydict = dict.fromkeys(string.printable, 0)
```
or, if you need a list of tuples (to be quite honest, Martijn's version of that is more pythonic, but just for variety):
```
import itertools
tuples = zip(string.printable, itertools.repeat(0))
``` |
key value pairs from tuple in python | 13,509,165 | 2 | 2012-11-22T09:12:19Z | 13,509,229 | 13 | 2012-11-22T09:15:15Z | [
"python",
"django",
"web.py"
] | how can I convert a tuple into a key value pairs dynamically?
Let's say I have:
```
tuple = ('name1','value1','name2','value2','name3','value3')
```
I want to put it into a dictionary:
```
dictionary = { name1 : value1, name2 : value2, name3 : value3 )
``` | Convert the tuple to key-value pairs and let the `dict` constructor build a dictionary:
```
it = iter(tuple_)
dictionary = dict(zip(it, it))
```
The `zip(it, it)` idiom produces pairs of items from an otherwise flat iterable, providing a sequence of pairs that can be passed to the `dict` constructor. A generalization... |
MS Word r/w in python, Python-docx issue and win32com references? | 13,509,207 | 2 | 2012-11-22T09:14:30Z | 13,509,702 | 8 | 2012-11-22T09:40:12Z | [
"python",
"ms-word",
"win32com"
] | Recently I'am experimenting with different API's for MS Word file management (writing for now). At this point I need just a simple writing python API. I tried win32com module which prove to be very robust with lack of examples for python online (very little knowledge of VB and C to be able to translate examples from MS... | When using `win32com`, bear in mind that you are talking to the Word object model. You don't need to know a lot of VBA or other languages to apply the samples to using Python; you just need to figure out which parts of the object model are being used.
Let's take the following sample (in VBA) which will create a new in... |
Python: How can I define a class in a doctest? | 13,510,698 | 6 | 2012-11-22T10:31:33Z | 13,510,788 | 11 | 2012-11-22T10:35:55Z | [
"python",
"unit-testing",
"class",
"documentation",
"doctest"
] | I would like to use a doctest comment block to demonstrate the usage of a particular base class, but either this cannot be done with doctest or I am doing something wrong.
Here is my simple demo code.
```
class MyClass(object):
'''
>>> m = MyClass()
>>> print m.x
1
>>> class A(MyClass):
>>> de... | Try it out in the interpreter; it uses `...` to show continuation lines. `>>>` is only for a *new* statement or expression, while a `class` in incomplete until you've had an empty `...` continuation line:
```
>>> class A(MyClass):
... def __init__(self):
... super(A, self).__init__()
...
``... |
How to compile all py file to pyc file in a folder by writing a python script? | 13,511,997 | 5 | 2012-11-22T11:38:44Z | 13,512,060 | 16 | 2012-11-22T11:42:54Z | [
"python"
] | I work on win system, and I wonder a way that I can use a python script which could run in cmd lines to mass compile the py files.
I have write a simple python code.
```
import py_compile, os, glob
dir = 'D:\\FAS\\config'
for f in glob.glob(dir + '\\*.py'):
py_compile.compile(f)
print "Success compile the file... | ```
import compileall
compileall.compile_dir('D:/FAS/config', force=True)
``` |
Python 2.7 UnicodeDecodeError: 'ascii' codec can't decode byte | 13,512,443 | 3 | 2012-11-22T12:07:02Z | 13,512,521 | 10 | 2012-11-22T12:13:41Z | [
"python",
"unicode"
] | I've been parsing some docx files (UTF-8 encoded XML) with special characters (Czech alphabet). When I try to output to stdout, everything goes smoothly, but I'm unable to output data to the file,
> Traceback (most recent call last):
> File "./test.py", line 360, in
> ofile.write(u'\t\t\t\t\t\n')
> UnicodeEncod... | `ofile` is a bytestream, which you are writing a character string to. Therefore, it tries to handle your mistake by encoding to a byte string. This is only generally safe with ASCII characters. Since `word` contains non-ASCII characters, it fails:
```
>>> open('/dev/null', 'wb').write(u'ä')
Traceback (most recent cal... |
Drawing a graph or a network from a distance matrix? | 13,513,455 | 12 | 2012-11-22T13:11:18Z | 13,513,976 | 11 | 2012-11-22T13:41:25Z | [
"python",
"graph",
"plot",
"social-networking"
] | I'm trying to plot/sketch (matplotlib or other python library) a 2D network of a big distance matrix where distances would be the edges of the sketched network and the line and column its nodes.
```
DistMatrix =
[ 'a', 'b', 'c', 'd'],
['a', 0, 0.3, 0.4, 0.7],
['b', 0.3, 0, 0.9, ... | You can use the networkx package, that work perfectly with this kind of problems.
Adjust your matrix to remove a simple numpy array like this:
```
DistMatrix =array([[0, 0.3, 0.4, 0.7],
[0.3, 0, 0.9, 0.2],
[0.4, 0.9, 0, 0.1],
[0.7, 0.2, 0.1, 0] ])
```
then import networkx and... |
Drawing a graph or a network from a distance matrix? | 13,513,455 | 12 | 2012-11-22T13:11:18Z | 13,514,416 | 17 | 2012-11-22T14:05:51Z | [
"python",
"graph",
"plot",
"social-networking"
] | I'm trying to plot/sketch (matplotlib or other python library) a 2D network of a big distance matrix where distances would be the edges of the sketched network and the line and column its nodes.
```
DistMatrix =
[ 'a', 'b', 'c', 'd'],
['a', 0, 0.3, 0.4, 0.7],
['b', 0.3, 0, 0.9, ... | The [graphviz](http://www.graphviz.org/) program `neato` *tries* to respect edge lengths. [doug shows a way](http://stackoverflow.com/a/1898456/190597) to harness `neato` using [networkx](http://networkx.lanl.gov) like this:
```
import networkx as nx
import numpy as np
import string
dt = [('len', float)]
A = np.array... |
Does an in-thread uncaught exception kill only the thread or the whole process? | 13,513,627 | 5 | 2012-11-22T13:21:44Z | 13,513,766 | 9 | 2012-11-22T13:29:21Z | [
"python",
"multithreading",
"exception"
] | When an exception is raised inside a thread without catching it anywhere else, will it then kill the whole application/interpreter/process? Or will it only kill the thread? | Let's try it:
```
import threading
import time
class ThreadWorker(threading.Thread):
def run(self):
print "Statement from a thread!"
raise Dead
class Main:
def __init__(self):
print "initializing the thread"
t = ThreadWorker()
t.start()
time.sleep(2)
... |
python's round() function not working? | 13,514,706 | 2 | 2012-11-22T14:24:12Z | 13,514,788 | 7 | 2012-11-22T14:28:40Z | [
"python"
] | below is my program for finding approximate root for a some 5000th-degree polynomial that is given as a series:
```
def s(r, z):
sm = 0
for k in range(1, z+1):
sm += (900-3*k) * r ** (k-1)
return sm
target = -600000000000
n = 1
dr = .125
curr = 0
while abs(curr - target) > 1:
curr = s(n, 5000... | By deafault python's print rounds numbers to 11 digits when printing.
Try instead
```
print '%0.12f'%n
```
To be a little more clear, when you are in the interactive console and do:
```
>>> x = 1.123456789012345
>>> x
1.123456789012345
>>> print x
1.12345678901
```
Remember that the the first call is actually a cal... |
Overriding Python's Hashing Function in Dictionary | 13,514,716 | 5 | 2012-11-22T14:24:39Z | 13,514,743 | 10 | 2012-11-22T14:26:12Z | [
"python",
"hash",
"dictionary",
"hashtable"
] | I am trying to create a custom hash function for some object that I'll be hashing into a dictionary. The hashing function is unique (not the standard Python one). This is very important to me: to use the unique function. Each key's value is a list.
Assuming I override `__hash__` and end up coming up with the right has... | The python `dict` implementation uses the hash value to both sparsely store values based on the key and to avoid collisions in that storage. It uses the result of `hash()` as a *starting point*, it is not the definitive position.
Thus, although `hash(4)` returns `4`, the exact 'position' in the underlying C structure ... |
matplotlib: how to prevent x-axis labels from overlapping each other | 13,515,471 | 18 | 2012-11-22T15:05:57Z | 13,521,621 | 21 | 2012-11-23T00:10:30Z | [
"python",
"matplotlib",
"bar-chart"
] | I'm generating a bar-chart with matplotlib. It all works well but I can't figure out how to prevent the labels of the x-axis from overlapping each other. Here an example:

Here is some sample SQL for a postgres 9.1 database:
```
drop table if exists... | I think you're confused on a few points about how matplotlib handles dates.
You're not actually plotting dates, at the moment. You're plotting things on the x-axis with `[0,1,2,...]` and then manually labeling every point with a string representation of the date.
Matplotlib will automatically position ticks. However,... |
matplotlib: how to prevent x-axis labels from overlapping each other | 13,515,471 | 18 | 2012-11-22T15:05:57Z | 13,534,891 | 10 | 2012-11-23T19:37:18Z | [
"python",
"matplotlib",
"bar-chart"
] | I'm generating a bar-chart with matplotlib. It all works well but I can't figure out how to prevent the labels of the x-axis from overlapping each other. Here an example:

Here is some sample SQL for a postgres 9.1 database:
```
drop table if exists... | ### Edit 2014-09-30
pandas now has a `read_sql` function. You definitely want to use that instead.
### Original Answer
Here's how you should convert your date string into real datetime objects:
```
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
data_tuples = [
('4084036', '... |
Why doesn't NotImplemented raise a TypeError? | 13,516,357 | 3 | 2012-11-22T15:59:43Z | 13,516,497 | 8 | 2012-11-22T16:08:53Z | [
"python",
"python-3.x",
"comparison-operators"
] | Suppose I define a class `A` and I don't want anyone to write an inequality of that class without getting away.
```
class A():
def __ne__(self, other):
return NotImplemented
print(A() != A())
```
But this prints out `True` and doesn't raise a `TypeError` although I have deliberately "turned off" the `!=` ... | When you return `NotImplemented` you indicate that you do not *know* if `__ne__` should return `True` or `False`.
Normally, Python will then swap the operands; if `a != b` results in `NotImplemented`, it'll try `b != a` instead. That'll fail here too, since you use the same type on both sides of the operator. For the ... |
Using scikit-learn classifier inside nltk, multiclass case | 13,516,364 | 5 | 2012-11-22T16:00:18Z | 13,516,794 | 14 | 2012-11-22T16:28:16Z | [
"python",
"nltk",
"scikit-learn"
] | Classification of text documents is a [simple task with scikit-learn](http://stackoverflow.com/questions/10526579/use-scikit-learn-to-classify-into-multiple-categories) but there isn't a clean support of that in NLTK, also there are samples for doing that in hard way like [this](https://github.com/japerk/nltk-trainer/b... | The NLTK wrapper for scikit-learn doesn't know about multilabel classification, and it shouldn't because it doesn't implement [`MultiClassifierI`](http://nltk.org/api/nltk.classify.html#nltk.classify.api.MultiClassifierI). Implementing that would require a separate class.
You can either implement the missing functiona... |
SQLAlchemy how to filter by children in many to many | 13,517,141 | 7 | 2012-11-22T16:54:36Z | 13,517,142 | 11 | 2012-11-22T16:54:36Z | [
"python",
"orm",
"sqlalchemy",
"many-to-many",
"filtering"
] | I was asking for a problem I had in SQLAlchemy and found the solution while writing. I post it anyway just in case it helps somebody :)
Let's say I have a many to many relationship that seems to work (at least I can fetch children) Three tables: posts, tags and post\_tags.
```
import sqlalchemy as alc
class Tag(Base... | ```
query = (
session.query(Post)
.join(Post.tags) # It's necessary to join the "children" of Post
.filter(Post.date_out.between(start_date, end_date))
# here comes the magic:
# you can filter with Tag, even though it was not directly joined)
.filter(Tag.a... |
How to create new PyQt4 windows from an existing window? | 13,517,568 | 5 | 2012-11-22T17:28:02Z | 13,519,181 | 8 | 2012-11-22T19:47:56Z | [
"python",
"window",
"pyqt",
"qt-designer",
"pyuic"
] | I've been trying to call a new window from an existing one using python3 and Qt4.
I've created two windows using Qt Designer (the main application and another one), and I've converted the .ui files generated by Qt Designer into .py scripts - but I can't seem to create new windows from the main application.
I tried do... | Although `pyuic` can create executable scripts with the `-x, --execute` option, it is mainly intended for testing.
The main purpose of `pyuic` is to create *static* python modules from Qt Desgner `ui` files that allow you to *import* the contained GUI classes into your application.
Let's say you've created two `ui` f... |
Draw different color for nodes in networkx based on their node value | 13,517,614 | 16 | 2012-11-22T17:32:06Z | 13,517,947 | 35 | 2012-11-22T17:57:32Z | [
"python",
"graph",
"visualization",
"networkx"
] | I have a large graph of nodes and directed edges. Furthermore, I have an additional list of values assigned to each node.
I now want to change the color of each node according to their node value. So e.g., drawing nodes with a very high value red and those with a low value blue (similar to a heatmap). Is this somehow ... | ```
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edges_from(
[('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])
val_map = {'A': 1.0,
'D': 0.5714285714285714,
'H': 0.0}
values = [... |
No handlers could be found for logger "pika.adapters.blocking_connection" | 13,517,955 | 15 | 2012-11-22T17:58:51Z | 13,518,256 | 29 | 2012-11-22T18:24:19Z | [
"python",
"amqp",
"pika"
] | Similar questions all seem to be based around using a custom logger, I'm happy to just use the default / none at all. My pika python app runs and receives messages but after a few seconds crashes with `No handlers could be found for logger "pika.adapters.blocking_connection"`, any ideas?
```
import pika
credentials =... | Fixed by adding:
```
import logging
logging.basicConfig()
``` |
python regex: get end digits from a string | 13,518,874 | 8 | 2012-11-22T19:18:08Z | 13,518,902 | 14 | 2012-11-22T19:21:20Z | [
"python",
"regex"
] | I am quite new to python and regex (regex newbie here), and I have the following simple string:
```
s=r"""99-my-name-is-John-Smith-6376827-%^-1-2-767980716"""
```
I would like to extract only the last digits in the above string i.e 767980716 and I was wondering how I could achieve this using python regex.
I wanted t... | You can use [`re.match`](http://docs.python.org/3/library/re.html#re.match) to find only the characters:
```
>>> import re
>>> s=r"""99-my-name-is-John-Smith-6376827-%^-1-2-767980716"""
>>> re.match('.*?([0-9]+)$', s).group(1)
'767980716'
```
Alternatively, [`re.finditer`](http://docs.python.org/3/library/re.html#re.... |
Python Unit Testing | 13,520,279 | 4 | 2012-11-22T21:34:22Z | 13,520,411 | 14 | 2012-11-22T21:48:07Z | [
"python",
"unit-testing"
] | I've written a script that opens up a file, reads the content and does some operations and calculations and stores them in sets and dictionaries.
How would I write a unit test for such a thing? My questions specifically are:
1. Would I test that the file opened?
2. The file is huge (it's the unix dictionary file). Ho... | That's not what unit-testing is about!
1. Your file doesn't represent an UNIT, so no you don't test the file or WITH the file!
2. your unit-test should test every single method of your functions/methods which deals with the a)file-processing b) calculations
3. it's not seldom that your unit-tests exceeds the line of c... |
python script to show progress | 13,520,622 | 8 | 2012-11-22T22:09:12Z | 13,520,665 | 12 | 2012-11-22T22:13:14Z | [
"python",
"progress-bar"
] | I would like show progress to user when my python script processing a big file.
I have seen script printings `'\', "|', '/'` in the same cursor in the shell to show progress.
How can I do that in python? | You should use [python-progressbar](http://code.google.com/p/python-progressbar/)
It's as simple to use as:
```
import progressbar as pb
progress = pb.ProgressBar(widgets=_widgets, maxval = 500000).start()
progvar = 0
for i in range(500000):
# Your code here
progress.update(progvar + 1)
progvar += 1
`... |
python script to show progress | 13,520,622 | 8 | 2012-11-22T22:09:12Z | 13,520,860 | 8 | 2012-11-22T22:32:44Z | [
"python",
"progress-bar"
] | I would like show progress to user when my python script processing a big file.
I have seen script printings `'\', "|', '/'` in the same cursor in the shell to show progress.
How can I do that in python? | A simple "infinite spinner" implementation:
```
import sys
import time
import itertools
for c in itertools.cycle('/-\|'):
sys.stdout.write('\r' + c)
sys.stdout.flush()
time.sleep(0.2)
``` |
How can I make multiple empty arrays in python? | 13,520,876 | 5 | 2012-11-22T22:35:01Z | 13,520,887 | 7 | 2012-11-22T22:36:50Z | [
"python",
"arrays",
"list",
"empty-list"
] | How can I make many empty arrays without manually typing
```
list1=[] , list2=[], list3=[]
```
Is there a for loop that will make me 'n' number of such empty arrays? | Lookup [list comprehensions](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions)
```
listOfLists = [[] for i in range(N)]
```
Now, `listOfLists` has N empty lists in it
More links on list comprehensions:
[1](http://stackoverflow.com/questions/9418389/list-comprehension)
[2](http://stackoverfl... |
How can I make multiple empty arrays in python? | 13,520,876 | 5 | 2012-11-22T22:35:01Z | 13,520,888 | 21 | 2012-11-22T22:36:50Z | [
"python",
"arrays",
"list",
"empty-list"
] | How can I make many empty arrays without manually typing
```
list1=[] , list2=[], list3=[]
```
Is there a for loop that will make me 'n' number of such empty arrays? | A list comprehension is easiest here:
```
>>> n = 5
>>> lists = [[] for _ in range(n)]
>>> lists
[[], [], [], [], []]
```
Be wary not to fall into the trap that is:
```
>>> lists = [[]] * 5
>>> lists
[[], [], [], [], []]
>>> lists[0].append(1)
>>> lists
[[1], [1], [1], [1], [1]]
``` |
How can I make multiple empty arrays in python? | 13,520,876 | 5 | 2012-11-22T22:35:01Z | 13,520,920 | 11 | 2012-11-22T22:40:44Z | [
"python",
"arrays",
"list",
"empty-list"
] | How can I make many empty arrays without manually typing
```
list1=[] , list2=[], list3=[]
```
Is there a for loop that will make me 'n' number of such empty arrays? | If you want to create different lists without a "list of lists", try this:
```
list1, list2, list3, list4 = ([] for i in range(4))
``` |
Get only one field from django forms in template | 13,521,634 | 3 | 2012-11-23T00:12:15Z | 13,521,775 | 7 | 2012-11-23T00:32:37Z | [
"python",
"django",
"django-forms",
"django-templates"
] | I have one form :
```
class FormLogin(forms.Form):
email = forms.EmailField(max_length=150)
name = forms.CharField(max_length=20)
```
How can I put just email field in my template ?
I tried this :
```
{{ form.fields.email }}
```
But it returns `<django.forms.fields.CharField object at 0x00000000043BCEB8>`. | You can just use:
```
{{ form.email }}
``` |
How to do multiclass classification properly with NLTK? | 13,521,898 | 5 | 2012-11-23T00:50:33Z | 13,522,156 | 8 | 2012-11-23T01:39:50Z | [
"python",
"machine-learning",
"nltk"
] | So, I'm trying to do text multiclass classification. I have been reading a lot of old questions and blog posts, but I still can't fully understand the concept of that.
I tried some example from this blog post as well. <http://www.laurentluce.com/posts/twitter-sentiment-analysis-using-python-and-nltk/>
But when it com... | There's no need for a one-vs-all scheme with Naive Bayes -- it's a multiclass model out of the box. Just feed a list of `(sample, label)` pairs to the classifier learner where `label` denotes the language. |
In Flask convert form POST object into a representation suitable for mongodb | 13,522,137 | 4 | 2012-11-23T01:35:41Z | 18,422,573 | 12 | 2013-08-24T19:56:31Z | [
"python",
"mongodb",
"post",
"flask",
"pymongo"
] | I am using Flask and MongoDB. I am trying to convert the content of request.form into something suitable for saving via PyMongo. It seems like something that should come up often enough to have a ready-made solution.
So what Flask give me is something like:
```
ImmutableMultiDict([('default', u''), ('required': u'on'... | You can use werkzeug's [getlist](http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.MultiDict.getlist) to write code like this
```
data = dict((key, request.form.getlist(key)) for key in request.form.keys())
```
Now each key of `data` would be a list which would contain 1 more element. To get resu... |
Convert an integer to binary without using the built-in bin function | 13,522,773 | 7 | 2012-11-23T03:36:22Z | 13,522,788 | 8 | 2012-11-23T03:39:28Z | [
"python",
"list",
"binary",
"converter",
"bit"
] | This function receives as a parameter an integer and should return a list representing the same value expressed in binary as a list of bits, where the first element in the list is the most significant (leftmost) bit.
My function currently outputs `'1011'` for the number 11, I need `[1,0,1,1]` instead.
For example,
`... | ```
def trans(x):
if x == 0: return [0]
bit = []
while x:
bit.append(x % 2)
x >>= 1
return bit[::-1]
``` |
How can I solve multivariable linear equation in python? | 13,523,026 | 2 | 2012-11-23T04:17:53Z | 13,523,288 | 7 | 2012-11-23T04:52:15Z | [
"python",
"linear-algebra"
] | I have 10,000 variables. for 100 of them, I do know the exact value.
others are given like:
```
a = 0.x_1 * b + 0.y_2 * c+ 0.z_1 * d + (1 - 0.x_1 - 0.y_1 - 0.z_1) * a
b = 0.x_2 * c + 0.y_2 * d+ 0.z_2 * e + (1 - 0.x_2 - 0.y_2 - 0.z_2) * b
...
q = 0.x_10000 * p + 0.y_10000 * r+ 0.z_10000 * s + (1 - 0.x_10000 - 0.y_10... | (Using [numpy](http://numpy.scipy.org/)) If we rewrite the system of linear equations
```
x - y + 2z = 5
y - z = -1
z = 3
```
as the matrix equation
```
A x = b
```
with
```
A = np.array([[ 1, -1, 2],
[ 0, 1, -1],
[ 0, 0, 1]])
```
and
```
b = np.array([5,-1,3])
```... |
Python complex dictionary keys | 13,523,070 | 15 | 2012-11-23T04:23:01Z | 13,523,098 | 10 | 2012-11-23T04:26:30Z | [
"python",
"dictionary",
"key"
] | My question pertains to dictionary keys. I want to set up a dictionary that has 3 keys for any single object. The keys must be in order and can have a wide range of values. For instance,
```
dictionary = {(key1,key2,key3) : object}
```
key1 can be any value between 1 and 10
key2 can be any value between 11 and 20
key... | Sure you can, as well as to create single string key for this - just merge string results for your keys like ','.join([k1,k2,k3])
[Read more about dictionaries.](http://docs.python.org/2/tutorial/datastructures.html#dictionaries)
> dictionaries are indexed by keys, which can be any immutable type;
> strings and numbe... |
Python: calling a function as a method of a class | 13,524,370 | 4 | 2012-11-23T06:55:22Z | 13,524,523 | 8 | 2012-11-23T07:09:29Z | [
"python"
] | Let's start with some code:
```
def func(*x):
print('func:', x)
class ABC:
def __init__(self, f):
self.f1 = f
def f2(*x):
print('f2:', x)
```
Now we do some tests:
```
>>> a = ABC(func)
>>> a.f1(10)
func: (10,)
>>> a.f2(10)
f2: (<__main__.ABC object at 0xb75381cc>, 10)
>>> a.f3 = func
... | You kind of partially answered your own question inspecting the object. In Python, objects behave like namespaces, so the first attribute points to a function and the second points to a method.
This is how you can add a method dynamically:
```
from types import MethodType
def func(*x):
print('func:', x)
class ... |
Validation of dependant inlines in django admin | 13,526,792 | 8 | 2012-11-23T10:04:33Z | 14,031,135 | 16 | 2012-12-25T13:40:20Z | [
"python",
"django",
"django-admin"
] | I am using Django 1.4 and I want to set validation rules that compare values of different inlines.
I have three simple classes
In models.py:
```
class Shopping(models.Model):
shop_name = models.CharField(max_length=200)
class Item(models.Model):
item_name = models.CharField(max_length=200)
cost = models... | You could override your Inline formset to achieve what you want. In the clean method of the formset you have access to your Shopping instance through the 'instance' member. Therefore you could use the Shopping model to store the calculated total temporarily and make your formsets communicate. In models.py:
```
class S... |
Accessing Primary Key from URL in Django View Class | 13,527,843 | 7 | 2012-11-23T11:07:56Z | 13,528,732 | 22 | 2012-11-23T12:00:23Z | [
"python",
"django",
"url-routing"
] | I have a URL pattern mapped to a custom view class in my Django App, like so:
```
url( r'^run/(?P<pk>\d+)/$', views.PerfRunView.as_view( ))
```
The problem is, I cannot figure out how I can access 'pk' from the URL pattern string in my view class so that I can retrieve a specific model object based on its database id... | In a class-based view, all of the elements from the URL are placed into `self.args` (if they're non-named groups) or `self.kwargs` (for named groups). So, for your view, you can use `self.kwargs['pk']`. |
Scrapy - Silently drop an item | 13,527,921 | 7 | 2012-11-23T11:13:06Z | 22,333,187 | 13 | 2014-03-11T18:14:16Z | [
"python",
"scrapy"
] | I am using Scrapy to crawl several websites, which may share redundant information.
For each page I scrape, I store the url of the page, its title and its html code, into mongoDB.
I want to avoid duplication in database, thus, I implement a pipeline in order to check if a similar item is already stored. In such a case... | The proper way to do this looks to be to implement a custom LogFormatter for your project, and change the logging level of dropped items.
Example:
```
from scrapy import log
from scrapy import logformatter
class PoliteLogFormatter(logformatter.LogFormatter):
def dropped(self, item, exception, response, spider):
... |
'P 0' < 'P! ' in python and postgresql | 13,530,048 | 9 | 2012-11-23T13:24:17Z | 13,530,653 | 7 | 2012-11-23T14:02:37Z | [
"python",
"postgresql"
] | A script in Python didn't work, and I reduced the problem to what follows.
In PostgreSQL 9.1 I tried:
```
SELECT 'P 0' < 'P! '
f
```
And in Python 2.7.3:
```
>>> 'P 0' < 'P! '
True
```
Why is `' '` not lower than `'!'` in PostgreSQL? What is happening? | PostgreSQL is using your locale's collation rules for string comparison. Python is using a different locale (possibly "C") for collation.
It's hard to say more without knowing what your database `LC_COLLATE` is (from `\l+` in `psql`) and what your runtime environment for Python is. Try showing the database locale and ... |
How to know bytes size of python object like arrays and dictionaries? - The simple way | 13,530,762 | 14 | 2012-11-23T14:10:07Z | 13,530,819 | 22 | 2012-11-23T14:13:11Z | [
"python",
"object",
"memory",
"size",
"byte"
] | I was looking for a easy way to know bytes size of arrays and dictionaries object, like
```
[ [1,2,3], [4,5,6] ] or { 1:{2:2} }
```
Many topics say to use pylab, for example:
```
from pylab import *
A = array( [ [1,2,3], [4,5,6] ] )
A.nbytes
24
```
But, what about dictionaries?
I saw lot of answers proposing to us... | There's:
```
>>> import sys
>>> sys.getsizeof([1,2, 3])
96
>>> a = []
>>> sys.getsizeof(a)
72
>>> a = [1]
>>> sys.getsizeof(a)
80
```
But I wouldn't say it's that reliable, as Python has overhead for each object, and there are objects that contain nothing but references to other objects, so it's not quite the same as... |
How to know bytes size of python object like arrays and dictionaries? - The simple way | 13,530,762 | 14 | 2012-11-23T14:10:07Z | 16,573,658 | 11 | 2013-05-15T19:42:24Z | [
"python",
"object",
"memory",
"size",
"byte"
] | I was looking for a easy way to know bytes size of arrays and dictionaries object, like
```
[ [1,2,3], [4,5,6] ] or { 1:{2:2} }
```
Many topics say to use pylab, for example:
```
from pylab import *
A = array( [ [1,2,3], [4,5,6] ] )
A.nbytes
24
```
But, what about dictionaries?
I saw lot of answers proposing to us... | a bit late to the party but an easy way to get size of dict is to pickle it first.
Using sys.getsizeof on python object (including dictionary) may not be exact since it does not count referenced objects.
The way to handle it is to serialize it into a string and use sys.getsizeof on the string. Result will be much clo... |
Parsing data to create a json data object with Python | 13,530,967 | 6 | 2012-11-23T14:21:52Z | 13,531,261 | 21 | 2012-11-23T14:41:13Z | [
"python",
"json",
"parsing",
"google-bigquery"
] | Here is my data from google bigquery to parse:
```
{
u'kind': u'bigquery#queryResponse',
u'rows': [
{
u'f': [
{
u'v': u'the'
},
{
u'v': u'995'
},
{
u'v... | If 'Z' is your big dictionary, on 'response' you will get the structure you need.
```
import json
response = []
for row in z['rows']:
for key, dict_list in row.iteritems():
count = dict_list[1]
year = dict_list[2]
response.append({'count': count['v'], 'year' : year['v']})
print json.dump... |
python variables are pointers? | 13,530,998 | 27 | 2012-11-23T14:23:39Z | 13,531,014 | 18 | 2012-11-23T14:25:06Z | [
"python",
"variables",
"pointers"
] | Variables in Python are just pointers, as far as I know.
Based on this rule, I can assume that the result for this code snippet:
```
i = 5
j = i
j = 3
print(i)
```
would be `3`.
But I got an unexpected result for me, it was `5`.
Moreover, my Python book does cover this example:
```
i = [1,2,3]
j = i
i[0] = 5
prin... | Variables are not pointers. When you assign to a variable you are *binding* the name to an object. From that point onwards you can refer to the object by using the name, until that name is rebound.
In your first example the name `i` is bound to the value `5`. Binding different values to the name `j` does not have any ... |
python variables are pointers? | 13,530,998 | 27 | 2012-11-23T14:23:39Z | 13,531,087 | 41 | 2012-11-23T14:29:18Z | [
"python",
"variables",
"pointers"
] | Variables in Python are just pointers, as far as I know.
Based on this rule, I can assume that the result for this code snippet:
```
i = 5
j = i
j = 3
print(i)
```
would be `3`.
But I got an unexpected result for me, it was `5`.
Moreover, my Python book does cover this example:
```
i = [1,2,3]
j = i
i[0] = 5
prin... | We call them references. They work like this
```
i = 5 # create int(5) instance, bind it to i
j = i # bind j to the same int as i
j = 3 # create int(3) instance, bind it to j
print i # i still bound to the int(5), j bound to the int(3)
```
Small ints are interned, but that isn't important to this explan... |
Check for a cookie with Python Flask | 13,531,149 | 9 | 2012-11-23T14:33:08Z | 13,531,185 | 21 | 2012-11-23T14:35:56Z | [
"python",
"session",
"cookies",
"flask"
] | I would like to get a cookie (e.g. `country`) with this Flask call.
```
data = request.cookies.get("country")
```
How can I tell if the cookie exists? | `request.cookies` is a `dict`, so:
```
if 'country' in request.cookies:
# do something
else:
# do something else
``` |
Python: Catching specific exception | 13,531,247 | 15 | 2012-11-23T14:40:19Z | 13,531,310 | 20 | 2012-11-23T14:43:51Z | [
"python"
] | I want to catch a specific ValueError, not just any ValueError.
I tried somthing like this:
```
try: maquina['WPF'] = macdat(ibus, id, 'WPF')
except: ValueError, 'For STRING = âWPFâ, this machine is not a wind machine.':
pass
```
But it raises a SyntaxError: can't assign to literal.
Then I tried:
```
try... | in `except ValueError,e`, `e` is an instance of the exception, not a string. So when you test if `e` is not equal to a particular string, that test is always False. Try:
```
if e.message != "...""
```
instead.
Example:
```
def catch(msg):
try:
raise ValueError(msg)
except ValueError as e:
if... |
Python script to generate JUnit report from another testing result | 13,531,364 | 11 | 2012-11-23T14:47:49Z | 15,435,447 | 10 | 2013-03-15T14:52:02Z | [
"python",
"junit",
"jenkins"
] | I have an acceptance test case, the result is plain text. I want to use Jenkins to show the result, and the JUnit format is suitable for me.
So I want to check whether there is existing python code to generate JUnit-format XML, so that I can easily just add my parsing code.
[Related question](http://stackoverflow.com... | Corey above suggested junitxml, but I was in the same boat as larrycai in that I'm not writing unit tests to test Python code. I'm writing Python scripts to do black box system testing and just wanted to output results in JUnit XML without reinventing the wheel.
I briefly looked at David Black's "python junit xml outp... |
Python stats: how do I write it to a (human readable) file | 13,532,531 | 14 | 2012-11-23T16:09:42Z | 16,446,824 | 23 | 2013-05-08T17:34:25Z | [
"python",
"file-io",
"profiling"
] | I am using Python's hotshot profiler: <http://docs.python.org/2/library/hotshot.html>
It shows how to print the stats:
```
stats.print_stats(20)
```
But how do I get that into a file? I'm not sure how to get at the information so I can write it to a file using write().
EDIT:
I'd like the same easily readable resul... | Stats takes an optional 'stream' argument. Simply open a file and pass the open file object to the Stats constructor as shown below. From that point any call to print\_stats() will output to the stream you passed into the constructor. Hope this helps. :)
```
stream = open('path/to/output', 'w');
stats = pstats.Stats('... |
python: httplib.CannotSendRequest when nesting threaded SimpleXMLRPCServers | 13,534,251 | 4 | 2012-11-23T18:34:33Z | 13,544,439 | 7 | 2012-11-24T18:52:25Z | [
"python",
"python-2.7",
"httplib",
"xmlrpclib",
"simplexmlrpcserver"
] | I am intermittently receiving a httplib.CannotSendRequest exception when using a chain of SimpleXMLRPCServers that use the SocketServer.ThreadingMixin.
What I mean by 'chain' is the following:
I have a client script which uses xmlrpclib to call a function on a SimpleXMLRPCServer. That server, in turn, calls another S... | Okay, I'm a bit stupid. I think I was staring at the code for to protracted a period of time that I missed the obvious solution staring me in the face (quite literally, because the answer is actually in the actual question.)
Basically, the CannotSendRequest occurs when an httplib.HTTPConnection is interrupted by an in... |
How to store a hashtable of lists in Python (hashed by identity)? | 13,536,223 | 4 | 2012-11-23T22:02:48Z | 13,536,241 | 14 | 2012-11-23T22:05:33Z | [
"python",
"python-2.7",
"set",
"hashtable",
"python-2.x"
] | I need to store a `set` of `list`s hashed by **identity**: two lists are equal iff they are the same object.
Not only does using `tuple`s [not make much sense semantically](http://news.e-scribe.com/397), but I also need to mutate the lists sometimes (append a few elements to the end every once in a while), so I can't ... | Use `dict` instead of set, and let the `id` of the list be the key:
```
dct[id(lst)] = lst
```
Test for existence of list in the "set" using `id(lst) in dct`. |
Adding line breaks in ipython | 13,536,370 | 26 | 2012-11-23T22:24:12Z | 13,536,468 | 31 | 2012-11-23T22:35:48Z | [
"python",
"ipython"
] | If introduce a for loop in iPython, or any multi-line command, how do I go back and add lines to it? I ran this:
```
for row in table.find_all('tr'):
cells = row.find_all('td')
for c,cell in enumerate(cells):
print c,":",cell.get_text().strip()
try:
this = cells[0]
that = cells[1]
... | The `%edit` magic function in iPython lets you edit code in your favorite editor and will then execute it as if it was typed directly. You can also edit code you've already typed into the repl since it's stored in a special variable, for example:
```
In [1]: def foo(x):
...: print x
...:
In [2]: %edit _... |
Adding line breaks in ipython | 13,536,370 | 26 | 2012-11-23T22:24:12Z | 19,101,631 | 39 | 2013-09-30T18:52:30Z | [
"python",
"ipython"
] | If introduce a for loop in iPython, or any multi-line command, how do I go back and add lines to it? I ran this:
```
for row in table.find_all('tr'):
cells = row.find_all('td')
for c,cell in enumerate(cells):
print c,":",cell.get_text().strip()
try:
this = cells[0]
that = cells[1]
... | There is also a way to add a newline directly in the repl: ctrl-v, ctrl-j
The ctrl-v basically lets you send a control code and then the ctrl-j is the code for a newline (line-feed). It's a bit awkward to type but has the advantage of also working in the regular Python shell as well as in Bash itself.
Edit: At least ... |
Embedding Python with C | 13,536,669 | 5 | 2012-11-23T23:03:53Z | 13,536,912 | 9 | 2012-11-23T23:35:04Z | [
"python",
"c",
"python-2.7"
] | I want to use an event based Python library in a C application. I use the offical C-API for embedding Python: <http://docs.python.org/2/c-api/index.html#c-api-index>
It is no problem to call methods from C and collect return values. However, I don't know how to do the following:
Several of the python library function... | This is harder than one would expect, but it can be done.
If you have a single C function that you want to provide as a callback, you can use `PyCFunction_New` to convert it into a Python callable:
```
#include <python.h>
static PyObject *my_callback(PyObject *ignore, PyObject *args)
{
/* ... */
}
static struct P... |
Why am I getting a NameError? | 13,537,472 | 3 | 2012-11-24T01:25:44Z | 13,537,484 | 10 | 2012-11-24T01:26:53Z | [
"python"
] | I have the following code:
```
from crypt import crypt
from itertools import product
from string import ascii_letters, digits
def decrypt(all_hashes, salt, charset=ascii_letters + digits + "-"):
products = (product(charset, repeat=r) for r in range(8))
chain = itertools.chain.from_iterable(products)
fo... | It doesn't look like you imported `itertools`...
```
from itertools import product
```
doesn't count as that will only pull `product` directly into your module's namespace (your module still doesn't know anything about the rest of `itertools`. Just add:
```
import itertools
```
at the top of your script and that er... |
Optional URL variables | 13,537,606 | 6 | 2012-11-24T01:58:28Z | 13,537,726 | 8 | 2012-11-24T02:29:21Z | [
"python",
"url-routing",
"flask"
] | Is there a way to define URLs with optional URL params in Flask? Essentially, what I'd like to do is define rules that allow for optionally specified languages:
```
/
/de -> matches / (but doesn't collide with /profile)
/profile
/de/profile
```
I think I've figured out a way to do it, but it involves either making a... | Just in case you didn't know, you can register multiple routes for a view. Might be a pain to do it for every view, but it's doable...
```
DEFAULT_LANG = 'en'
@app.route('/profile')
@app.route('/<lang>/profile')
def profile(lang=DEFAULT_LANG):
pass
```
Or, perhaps you could implement your own `route` decorator th... |
Python equivalent of npm or rubygems | 13,537,901 | 15 | 2012-11-24T03:10:41Z | 13,537,980 | 20 | 2012-11-24T03:28:38Z | [
"python",
"rubygems",
"npm"
] | I've been looking around for a package manager that can be used with python. I want to list project dependencies in a file. For example ruby uses Gemfile where you can use bundle install.
How can I achieve this in python? | The `pip` tool is becoming the standard in equivalent of Ruby's gems. Like `distribute`, `pip` uses the [PyPI](http://pypi.python.org/pypi) package repository (by default) for resolving and downloading dependencies. `pip` can install dependencies from a file listing project dependencies (called `requirements.txt` by co... |
Python: copy of a variable | 13,538,266 | 6 | 2012-11-24T04:27:28Z | 13,538,309 | 9 | 2012-11-24T04:35:42Z | [
"python",
"variables",
"copy"
] | Is there a way in to make copy of a variable so that when the value changes of variable 'a' it copies itself to variable 'b'?
Example
```
a='hello'
b=a #.copy() or a function that will make a copy
a='bye'
# Is there a way to make
# 'b' equal 'a' without
# doing 'b=a'
print a
print b
```
I am having a prob... | You're exploring how Python deals with references. Assignment is simply binding a reference to an object on the right hand side. So, this is somewhat trivial:
```
a = 'foo'
b = a
print b is a #True -- They *are the same object*
```
However, as soon as you do:
```
b = 'bar'
b is a #False -- they're not longer the s... |
Python: avoiding infinite loops in __getattribute__ | 13,538,324 | 17 | 2012-11-24T04:39:05Z | 13,538,355 | 8 | 2012-11-24T04:45:02Z | [
"python",
"python-3.x"
] | The method `__getattribute__` needs to be written carefully in order to avoid the infinite loop. For example:
```
class A:
def __init__(self):
self.x = 100
def __getattribute__(self, x):
return self.x
>>> a = A()
>>> a.x # infinite looop
RuntimeError: maximum recursion depth exceeded while... | When you do this:
```
return object.__getattribute__(self, x)
```
you are calling a specific function -- the one defined in the object class, and not the one defined in A, so there is no recursion.
When you do this:
```
return self.x
```
you are letting python choose which function to call, and it calls th... |
Python: avoiding infinite loops in __getattribute__ | 13,538,324 | 17 | 2012-11-24T04:39:05Z | 13,538,433 | 18 | 2012-11-24T05:03:58Z | [
"python",
"python-3.x"
] | The method `__getattribute__` needs to be written carefully in order to avoid the infinite loop. For example:
```
class A:
def __init__(self):
self.x = 100
def __getattribute__(self, x):
return self.x
>>> a = A()
>>> a.x # infinite looop
RuntimeError: maximum recursion depth exceeded while... | You seem to be under the impression that your implementation of `__getattribute__` is merely a hook, that if you provide it Python will call it, and otherwise the interpreter will do it's normal magic directly.
That is not correct. When python looks up attributes on instances, `__getattribute__` is the main entry for ... |
what happen b=a[:] in python? | 13,539,242 | 8 | 2012-11-24T07:24:36Z | 13,539,266 | 11 | 2012-11-24T07:27:46Z | [
"python",
"python-3.x",
"python-2.7"
] | ```
>>>a=[999999,2,3]
>>>b=[999999,2,3]
>>>print(a[0] is b[0])
False#because it works for numbers -5 through 256
>>>a=[1,2,3]
>>>b=a[:]
>>>print(a[0] is b[0])
True#because it works for numbers -5 through 256
>>>a=[999999,2,3]
>>>b=a[:]
>>>print(a[0] is b[0])
True#why not ... | The -5 to 256 range has to do with the [following](http://docs.python.org/2/c-api/int.html):
> The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an `int` in that range you actually just get back a reference to the existing object.
To demonstrate this, no... |
Plotting dates with sharex=True leads to ValueError: ordinal must be >= 1 | 13,539,868 | 6 | 2012-11-24T09:14:34Z | 13,540,368 | 8 | 2012-11-24T10:33:30Z | [
"python",
"numpy",
"matplotlib"
] | When doing some analysis, I stumbled upon a ValueError and I could boil it down to the following simple example which can reproduce the error I got:
```
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
x = np.array([dt.datetime(2012, 10, 19, 10, 0, 0),
dt.datetime(2012, 10, 19, 1... | The error is avoided if you plot something on the second axis:
```
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
x = np.array([dt.datetime(2012, 10, 19, 10, 0, 0),
dt.datetime(2012, 10, 19, 10, 0, 1),
dt.datetime(2012, 10, 19, 10, 0, 2),
dt.datetime... |
What is faster for searching items in list, in operator or index()? | 13,540,330 | 3 | 2012-11-24T10:28:42Z | 13,540,396 | 11 | 2012-11-24T10:37:46Z | [
"python",
"performance",
"list",
"search"
] | From this [site](http://effbot.org/zone/python-list.htm), it says that list.index() is a linear search through the list.
And it also seems like `in` is also linear.
Is there any advantage to using one over the other? | If you want to compare different python approaches, such as the `in` operator versus `.index()`, use the [`timeit` module](http://docs.python.org/2/library/timeit.html) to test the speed differences. Python data type complexities are documented on <http://wiki.python.org/moin/TimeComplexity>.
Do note that there is a b... |
Different behaviour between python console and python script | 13,541,862 | 5 | 2012-11-24T13:51:51Z | 13,541,957 | 8 | 2012-11-24T14:04:25Z | [
"python",
"console",
"gtk",
"pydev"
] | I am experiencing different behaviour on the same code using the python console and a python script.
The code is as follows:
```
import gtk
import webkit
win = gtk.Window()
win.show()
web = webkit.WebView()
win.add(web)
web.show()
web.open("http://www.google.com")
```
When running the code in the python console, the... | Add
```
gtk.main()
```
to the end of your script. This starts the `gtk` event loop.
---
```
import gtk
import webkit
class App(object):
def __init__(self):
win = gtk.Window()
win.connect("destroy", self.destroy)
web = webkit.WebView()
web.open("http://www.google.com")
wi... |
python: Help to implement an algorithm to find the minimum-area-rectangle for given points in order to compute the major and minor axis length | 13,542,855 | 11 | 2012-11-24T15:59:37Z | 13,545,089 | 7 | 2012-11-24T20:06:33Z | [
"python",
"geometry"
] | I have a set of points (black dots in geographic coordinate value) derived from the convex hull (blue) of a polygon (red). see Figure:
```
[(560023.44957588764,6362057.3904932579),
(560023.44957588764,6362060.3904932579),
(560024.44957588764,636206... | Given a clockwise-ordered list of n points in the convex hull of a set of points, it is an O(n) operation to find the minimum-area enclosing rectangle. (For convex-hull finding, in O(n log n) time, see [activestate.com recipe 66527](http://code.activestate.com/recipes/66527-finding-the-convex-hull-of-a-set-of-2d-points... |
python: Help to implement an algorithm to find the minimum-area-rectangle for given points in order to compute the major and minor axis length | 13,542,855 | 11 | 2012-11-24T15:59:37Z | 33,619,018 | 7 | 2015-11-09T21:57:19Z | [
"python",
"geometry"
] | I have a set of points (black dots in geographic coordinate value) derived from the convex hull (blue) of a polygon (red). see Figure:
```
[(560023.44957588764,6362057.3904932579),
(560023.44957588764,6362060.3904932579),
(560024.44957588764,636206... | I just implemented this myself, so I figured I'd drop my version here for others to view:
```
import numpy as np
from scipy.spatial import ConvexHull
def minimum_bounding_rectangle(points):
"""
Find the smallest bounding rectangle for a set of points.
Returns a set of points representing the corners of th... |
Why is recursion in python so slow? | 13,543,019 | 8 | 2012-11-24T16:18:18Z | 13,543,259 | 13 | 2012-11-24T16:48:05Z | [
"python",
"performance",
"recursion",
"python-2.7"
] | So I was messing around in idle with recursion, and I noticed that a loop using recursion was much slower then a regular while loop, and I was wondering if anyone knew why. I have included the tests that I had done below:
```
>>> import timeit
>>> setu="""def test(x):
x=x-1
if x==0:
return x
else:
... | You've written your function to be tail recursive. In many imperative and functional languages, this would trigger tail recursion elimination, where the compiler replaces the CALL/RETURN sequence of instructions with a simple JUMP, making the process more or less the same thing as iteration, as opposed to the normal st... |
Adding to numpy.nextafter() float returns unexpected result | 13,543,291 | 3 | 2012-11-24T16:50:55Z | 13,543,966 | 8 | 2012-11-24T17:58:49Z | [
"python",
"numpy",
"python-2.7",
"ieee-754"
] | According to Wolfram Alpha, this is true for `x > 2`.
```
6.0/(x+16) > 2.0/(x+4)
```
To get the smallest possible `x`, I'm using `numpy.nextafter()`.
```
>>> from numpy import nextafter
>>> x = nextafter(2,2+1)
>>> x
2.0000000000000004
```
However.
```
>>> 6.0/(x+16) > 2.0/(x+4)
False
```
Curiously.
```
>>> x+1
... | ```
import numpy as np
x = 2.0
while True:
if 6.0/(x+16) > 2.0/(x+4): break
x = np.nextafter(x, x+1)
print(repr(x))
```
yields
```
2.0000000000000009
```
---
How floats are handled in CPython depends on the underlying C library. Most C libraries implement the [IEEE 754 Standard for Floating-Point Arithm... |
django form got multiple values for keyword argument | 13,544,504 | 15 | 2012-11-24T18:59:10Z | 13,544,661 | 59 | 2012-11-24T19:17:32Z | [
"python",
"django",
"django-forms",
"django-views",
"django-urls"
] | I have a simple model as follows:
```
RATING_CHOICES = zip(range(1, 6), range(1, 6))
class Rating(models.Model):
value = models.IntegerField(choices=RATING_CHOICES)
additional_note = models.TextField(null=True, blank=True)
from_user = models.ForeignKey(User, related_name='from_user')
to_user = models.... | the first argument to your view should be `request` |
How to check if an array is 2D | 13,544,639 | 7 | 2012-11-24T19:15:14Z | 13,544,650 | 11 | 2012-11-24T19:16:29Z | [
"python",
"numpy"
] | I read from a file with `loadtxt` like this
```
data = loadtxt(filename) # id x1 y1 x2 y2
```
`data` could look like
```
array([[ 4. , 104.442848, -130.422137, 104.442848, 130.422137],
[ 5. , 1. , 2. , 3. , 4. ]])
```
I can then reduce `data` to the lines belongin... | [data.ndim](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.ndim.html) gives the dimension (what numpy calls the number of `axes`) of the array.
---
As you already have observed, when a data file only has one line, `np.loadtxt`
returns a 1D-array. When the data file has more than one line, `np.loadt... |
plot data from CSV file with matplotlib | 13,545,388 | 14 | 2012-11-24T20:42:09Z | 13,550,615 | 17 | 2012-11-25T11:32:57Z | [
"python",
"numpy",
"matplotlib"
] | I have a CSV file at `e:\dir1\datafile.csv`.
It contains three columns and 10 heading and trailing lines need to be skipped.
I would like to plot it with numpy.loadtxt(), for which I haven't found any rigorous documentation.
Here is what I started to write from the several tries I found on the web.
```
import matplot... | According to the [docs](http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html) `numpy.loadtxt` is
> a fast reader for simply formatted files. The genfromtxt function provides more sophisticated handling of, e.g., lines with missing values.
so there are only a few options to handle more complicated fi... |
python passlib: what is the best value for "rounds" | 13,545,677 | 7 | 2012-11-24T21:14:00Z | 13,572,232 | 15 | 2012-11-26T20:03:06Z | [
"python",
"encryption",
"pbkdf2"
] | from the [passlib documentation](http://packages.python.org/passlib/password_hash_api.html#choosing-the-right-rounds-value)
> For most public facing services, you can generally have signin take upwards of 250ms - 400ms before users start getting annoyed.
so what is the best value for `rounds` in a **login/registratio... | *(passlib developer here)*
The amount of time pbkdf2\_sha512 takes is linearly proportional to it's rounds parameter (`elapsed_time = rounds * native_speed`). Using the data for your system, `native_speed = 12000 / .143 = 83916 iterations/second`, which means you'll need around `83916 * .350 = 29575 rounds` to get ~35... |
How do I strtotime in python? | 13,546,936 | 8 | 2012-11-25T00:02:40Z | 13,546,960 | 9 | 2012-11-25T00:05:18Z | [
"python",
"datetime"
] | I'm scraping a a page that includes among other things, date information. So I have a variable named `warrant_issued` that contains `u'11/5/2003'` -- I want to store this as a machine readable date. PHP has a handy `strtotime` function that works fabulously. I was hoping that [datetime](http://docs.python.org/2.7/libra... | [`strptime()`](http://docs.python.org/2.7/library/datetime.html#datetime.datetime.strptime) is definitely the right approach, it's just a class method for the [`datetime` class](http://docs.python.org/2.7/library/datetime.html#datetime.datetime) (confusingly part of the `datetime` module).
That is, `datetime.datetime.... |
from import statements in Python | 13,547,088 | 2 | 2012-11-25T00:23:17Z | 13,547,094 | 7 | 2012-11-25T00:24:06Z | [
"python",
"import"
] | I'm a little confused by the from import statements in Python. In particular, how I can import a class from a module that is within a package. For example, if I have a package named my package that has two modules (module 1 and module 2), how can I import a specific class from module 1 within module 2?
What I'm findin... | You were on the right track:
```
from package.module1 import class1
```
If as you say you're importing from within the same package, you can also do
```
from .module1 import class1
```
The `.` means "the position in the package hierarchy of the module doing the importing". See [the documentation](http://docs.python... |
Is Python set more space efficient than list? | 13,547,883 | 4 | 2012-11-25T02:59:27Z | 13,547,897 | 9 | 2012-11-25T03:04:05Z | [
"python"
] | `list` is known to initialize with a big chunk of space to optimize the time needed to expand the list (on average we don't have to keep making new list like an array).
What about `set`?
The following construction makes it space wasted because of `list`. I understand `tuple` is more space saving because it is immutab... | ```
>>> from sys import getsizeof as size
>>> s = set(xrange(100))
>>> l = list(xrange(100))
>>> size(s)
8424
>>> size(l)
1016
```
`set`s take up *more* memory than `list`s. Some of the functionality that `set`s offer requires more memory (e.g. quick membership tests). |
Replace CentralWidget in MainWindow | 13,550,076 | 3 | 2012-11-25T10:16:23Z | 13,551,018 | 8 | 2012-11-25T12:30:48Z | [
"python",
"user-interface",
"pyqt",
"pyside"
] | I'm kinda new to PySide.I have a main window object which shows one widget at a time. I've been trying to change the central widget of the `QMainWindow` class in order to replace the visible Widget in the window when pressing a button. The problem is that the button pressed is in the Widget class, not in the main windo... | You may use a [`QStackedWidget`](http://doc.qt.digia.com/qt/qstackedwidget.html) as central widget and add both the log-in screen and "logged-in" screen to it.
An example usage:
```
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, se... |
PIL image to array (numpy array to array) - Python | 13,550,376 | 2 | 2012-11-25T10:57:52Z | 13,550,527 | 7 | 2012-11-25T11:18:52Z | [
"python",
"arrays",
"image",
"numpy",
"python-imaging-library"
] | I have a .jpg image that I would like to convert to Python array, because I implemented treatment routines handling plain Python arrays.
It seems that PIL images support conversion to numpy array, and according to the documentation I have written this:
```
from PIL import Image
im = Image.open("D:\Prototype\Bikesgray... | I think what you are looking for is:
```
list(im.getdata())
```
or, if the image is too big to load entirely into memory, so something like that:
```
for pixel in iter(im.getdata()):
print pixel
```
from [PIL documentation](http://effbot.org/imagingbook/image.htm#tag-Image.Image.getdata):
> getdata
>
> im.getd... |
Python printing without commas | 13,550,423 | 5 | 2012-11-25T11:03:36Z | 13,550,428 | 18 | 2012-11-25T11:04:43Z | [
"python"
] | How I can print lists without brackets and commas?
I have a list of permutations like this:
```
[1, 2, 3]
[1, 3, 2] etc..
```
I want to print them like this: `1 2 3` | ```
blah = [ [1,2,3], [1,3,2] ]
for bla in blah:
print ' '.join(map(str, bla))
```
It's worth noting that `map` is a bit old-fashioned and is better written as either a generator or list-comp depending on requirements. This also has the advantage that it'll be portable across Python 2.x & 3.x as it'll generate a ... |
Creating a multiple phone vCard using vObject | 13,552,836 | 5 | 2012-11-25T16:13:30Z | 14,740,339 | 8 | 2013-02-06T22:45:20Z | [
"python",
"vcard",
"vobject"
] | im using vObject to create a vCard. Everything works well except I can't add multiple phone numbers.
Right now i'm doing this:
```
v.add('tel')
v.tel.type_param = 'WORK'
v.tel.value = employee.office_phone
v.add('tel')
v.tel.type_param = 'FAX'
v.tel.value = employee.fax
```
As it's working as a key value, the work ... | The `add()` method returns a specific object which can be used to fill in more data:
```
import vobject
j = vobject.vCard()
o = j.add('fn')
o.value = "Meiner Einer"
o = j.add('n')
o.value = vobject.vcard.Name( family='Einer', given='Meiner' )
o = j.add('tel')
o.type_param = "cell"
o.value = '+321 987 654321'
o = j... |
Get current route instead of route_path in Pyramid | 13,552,992 | 3 | 2012-11-25T16:29:16Z | 13,553,585 | 24 | 2012-11-25T17:37:43Z | [
"python",
"pyramid"
] | I have navigation bar, such as :
```
<div id="nav">
<ul>
<li
% if request.current_route_path == "somepath":
class="current"
% endif
> <a href='/page1"> 1 </a></li>
<li
% if request.current_route_path == "another_test":
class="current"
%endif
> <a href="/page2"> 2 </a> <li>
</ul>
</div>
```
I wa... | What you want is to use the [`matched_route`](http://docs.pylonsproject.org/projects/pyramid/en/1.4-branch/narr/urldispatch.html#matched-route).
```
if request.matched_route.name == 'my_route_name':
``` |
This character - ã - raises a UnicodeEncodeError | 13,553,185 | 4 | 2012-11-25T16:54:15Z | 13,553,483 | 11 | 2012-11-25T17:26:07Z | [
"python",
"unicode",
"encoding",
"python-3.x",
"gb2312"
] | I am using a Python script to convert files from `gb2312` to `utf-8`. This character messes everything: `ã` (it is one symbol, not "mm").
```
text = 'ã'
text.encode(encoding='gb2312')
```
raises this error:
> UnicodeEncodeError: 'gb2312' codec can't encode character '\u040b' in position 1: illegal multibyte sequ... | OK, so, I downloaded the file `1.php` and ran your *original* script on it and I get a *different* error mesage:
```
UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 99-100:
illegal multibyte sequence
```
The bytes in the file at offsets 99 and 100 are A9 4C in that order. That is neither a valid G... |
Django Circular Model Dependency | 13,554,211 | 7 | 2012-11-25T18:45:48Z | 13,554,254 | 9 | 2012-11-25T18:49:56Z | [
"python",
"database",
"django",
"database-design",
"django-models"
] | I have a circular dependency in my Django models, such that model A has a foreign key reference to B, while B has a many-to-many reference to A. I've consulted other SO posts and have used the string model names instead of the actual classes, but to no avail. Here are abbreviated versions of my two classes:
**User mod... | * `'listings.models.Listing'` should be `'listings.Listing'`
* `'users.models.User'` should be `'users.User'` (or `'auth.User'` if you were to use `django.contrib.auth.models.User`)
Refer to [official documentation](https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey) for more. |
How to get the option text using BeautifulSoup | 13,555,307 | 4 | 2012-11-25T20:42:27Z | 13,555,350 | 9 | 2012-11-25T20:48:20Z | [
"python",
"html-parsing",
"beautifulsoup"
] | I want to using BeautifulSoup to get the option text in the following html. For example: I'd like to get 2002/12 , 2003/12 etc.
```
<select id="start_dateid">
<option value="0">2002/12</option>
<option value="1">2003/12</option>
<option value="2">2004/12</option>
<option value="3">2005/12</option>
<option value="4">20... | You don't have to use `lxml` here. I have trouble installing it on my machine, so my answer does not make use of it.
```
from bs4 import BeautifulSoup as BS
import urllib2
soup = BS(urllib2.urlopen("./test.html").read())
contents = [str(x.text) for x in soup.find(id="start_dateid").find_all('option')]
```
With this,... |
Starting Celery: AttributeError: 'module' object has no attribute 'celery' | 13,555,386 | 8 | 2012-11-25T20:52:25Z | 13,568,512 | 7 | 2012-11-26T16:01:56Z | [
"python",
"django",
"celery",
"django-celery"
] | I try to start a Celery worker server from a command line:
```
celery -A tasks worker --loglevel=info
```
The code in tasks.py:
```
import os
os.environ[ 'DJANGO_SETTINGS_MODULE' ] = "proj.settings"
from celery import task
@task()
def add_photos_task( lad_id ):
...
```
I get the next error:
```
Traceback (most r... | Celery uses `celery` file for storing configuration of your app, you can't just give a python file with tasks and start celery.
You should define `celery` file ( for Celery>3.0; previously it was `celeryconfig.py`)..
> celeryd --app app.celery -l info
This example how to start celery with config file at `app/celery.p... |
Starting Celery: AttributeError: 'module' object has no attribute 'celery' | 13,555,386 | 8 | 2012-11-25T20:52:25Z | 13,569,129 | 10 | 2012-11-26T16:36:41Z | [
"python",
"django",
"celery",
"django-celery"
] | I try to start a Celery worker server from a command line:
```
celery -A tasks worker --loglevel=info
```
The code in tasks.py:
```
import os
os.environ[ 'DJANGO_SETTINGS_MODULE' ] = "proj.settings"
from celery import task
@task()
def add_photos_task( lad_id ):
...
```
I get the next error:
```
Traceback (most r... | I forgot to create a celery object in tasks.py:
```
from celery import Celery
from celery import task
celery = Celery('tasks', broker='amqp://guest@localhost//') #!
import os
os.environ[ 'DJANGO_SETTINGS_MODULE' ] = "proj.settings"
@task()
def add_photos_task( lad_id ):
...
```
After that we could normally star... |
AttributeError: 'NoneType' object has no attribute 'append' | 13,555,551 | 2 | 2012-11-25T21:13:28Z | 13,555,564 | 9 | 2012-11-25T21:15:48Z | [
"python"
] | I have a weird problem with python passing a list as parameter to a function. Here is the code:
```
def foobar(depth, top, bottom, n=len(listTop)):
print dir(top)
print top.append("hi")
if depth > 0:
exit()
foobar(depth+1, top.append(listTop[i]), bottom.append(listBottom[i]))
top = bottom = []... | You pass in the *result* of `top.append()` to your function. `top.append()` returns None:
```
>>> [].append(0) is None
True
```
You need to call `.append()` separately, then pass in just `top`:
```
top.append(listTop[i])
bottom.append(listBottom[i])
foobar(depth+1, top, bottom)
```
Note that the `n=len(listTop)` ar... |
Python not recognizing unicode | 13,556,587 | 3 | 2012-11-25T23:12:20Z | 13,556,619 | 8 | 2012-11-25T23:16:21Z | [
"python",
"unicode"
] | I'm trying to make a script that converts japanese katakana to romaji ("ã·" to "shi"). Here's what I'm trying:
```
x = u''
x = raw_input('Enter katakana: ')
x = x.replace(u'\u30B7', u'shi')
```
> Enter Katakana: ã·
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128)... | `raw_input` returns the entered string in a byte-encoded form that varies depending on the terminal used. Try decoding the input explicitly to Unicode first with:
```
import sys
x = raw_input('Enter katakana: ').decode(sys.stdin.encoding)
```
The error you get is from replace trying to naively convert the byte-encode... |
Array elementwise operations | 13,556,703 | 7 | 2012-11-25T23:29:10Z | 13,556,834 | 9 | 2012-11-25T23:45:10Z | [
"python",
"arrays",
"numpy",
"elementwise-operations"
] | I have two input arrays x and y of the same shape. I need to run each of their elements with matching indices through a function, then store the result at those indices in a third array z. What is the most pythonic way to accomplish this? Right now I have four four loops - I'm sure there is an easier way.
```
x = [[2,... | One "easier way" is to create a NumPy-aware function using [`numpy.vectorize`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html). A "ufunc" is NumPy terminology for an elementwise function (see documentation [here](http://docs.scipy.org/doc/numpy/reference/ufuncs.html)). Using `numpy.vectorize` ... |
How can I make a list from a list of tuples ? | 13,557,613 | 2 | 2012-11-26T01:45:14Z | 13,557,641 | 9 | 2012-11-26T01:50:09Z | [
"python",
"list",
"tuples"
] | if I have a list of tuple like:
```
L=[(('a','b','c','d'),2),(('f','e','d','a'),3)]
```
I want to make a list that like:
```
L1=[['a','b','c','d'],['f','e','d','a']]
```
this is what I did:
```
L1=[]
for item in L:
for(letter,integer) in item:
L1.append(list(letter))
print(L1)
```
but it come... | What's useful here is a list comprehension:
```
L1 = [list(letters) for (letters, number) in L]
```
This iterates over each pair in your list, taking the letters tuple of each pair and converting it to a list. It then stores each result as the element of a new list. |
Flask App Using WTForms with SelectMultipleField | 13,558,345 | 4 | 2012-11-26T03:35:33Z | 13,559,448 | 7 | 2012-11-26T06:01:49Z | [
"python",
"flask",
"jinja2",
"wtforms"
] | I have a Flask application that uses WTForms for user input. It uses a `SelectMultipleField` in a form. I can't seem to get the app to POST all items in the field when selected; it only sends the first item selected regardless of how many the user selects.
The [Flask documentation](http://wtforms.simplecodes.com/docs/... | Flask returns request.form as a werkzeug MultiDict object. This is kind of like a dictionary, only with traps for the unwary.
<http://flask.pocoo.org/docs/api/#flask.request>
http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.MultiDict
> MultiDict implements all standard dictionary methods. Intern... |
Can I write italics to the Python shell? | 13,559,276 | 7 | 2012-11-26T05:45:33Z | 13,559,470 | 10 | 2012-11-26T06:04:23Z | [
"python",
"italics"
] | Is it possible to write something like this:
```
>>> text_output = "Hello World."
>>> print text_output
```
...where if the text\_output is printed to the Python Shell, it is printed in italics? | If your console supports italics. Eg [rxvt-unicode](http://software.schmorp.de/pkg/rxvt-unicode.html) using [ansi escape code](http://en.wikipedia.org/wiki/ANSI_escape_code)
```
>>> print "\x1B[3mHello World\x1B[23m"
```
 |
pip: how to install a git pull request | 13,561,618 | 5 | 2012-11-26T09:06:50Z | 13,561,621 | 11 | 2012-11-26T09:06:50Z | [
"python",
"pip"
] | I want to install a git pull request with pip for testing in my local virtualenv. I want to install it directly from github, without creating a local git repository. | You can add the exact commit to the URL by appending the hash:
```
pip install git+https://github.com/other-repository/project.git@remote_branch_name
```
example:
```
pip install --user git+https://github.com/d1b/pip.git@fix_pip_build_directory
```
Or to a single commit. But this does not get updated, if the pull r... |
python tar file how to extract file into stream | 13,562,037 | 3 | 2012-11-26T09:36:18Z | 13,562,203 | 10 | 2012-11-26T09:46:37Z | [
"python",
"stream",
"tar"
] | I am trying to extract a zipped folder but instead of directly using `.extractall()`, I want to extract the file into stream so that I can handle the stream myself. Is it possible to do it using `tarfile`? Or is there any suggestions? | You can obtain each file from a tar file as a python `file` object using the `.extractfile()` method. Loop over the `tarfile.TarFile()` instance to list all entries:
```
import tarfile
with tarfile.open(path) as tf:
for entry in tf: # list each entry one by one
fileobj = tf.extractfile(entry)
# f... |
Jinja2 inline comments | 13,562,222 | 10 | 2012-11-26T09:47:53Z | 13,562,327 | 25 | 2012-11-26T09:53:53Z | [
"python",
"macros",
"comments",
"jinja2"
] | How can I put comments inside Jinja2 argument list declaration ?
Everything I have tried gives an error:
**jinja2.exceptions.TemplateSyntaxError: unexpected char u'#'**
```
{{ Switch('var',
[('1', 'foo'), # comment 1
('2', 'bar'), ## comment 2
('3', 'rum'), {# comment 3 #}
]) }}
{% macr... | Jinja2 has no support for comments within a `{{ ... }}` statement. You can only use comments *outside* of such statements, and then only with `{# .. #}` or `## comment`.
* `{# .. #}` is only meant for *disabling* part of a template
* `# statement` is the equivalent of `{% statement %}`, if [line statements are enabled... |
Why I get "QTimer can only be used with threads started with QThread" messages if I have no QTimer in my code? | 13,562,501 | 9 | 2012-11-26T10:04:40Z | 13,632,460 | 9 | 2012-11-29T18:38:20Z | [
"python",
"pyqt4",
"multiplatform",
"qtimer"
] | When (and only when) I quit my application, these (and only these) repeated message appear on the command prompt:
```
QObject::startTimer: QTimer can only be used with threads started with QThread
QObject::startTimer: QTimer can only be used with threads started with QThread
QObject::startTimer: QTimer can only be use... | I've had similar problems in the past.
The `QFileSystemModel`[documentation page](http://www.riverbankcomputing.com/static/Docs/PyQt4/html/qfilesystemmodel.html) says the following:
> QFileSystemModel.**init** (self, QObject parent = None)
>
> The parent argument, if not None, causes self to be owned by Qt
> instead ... |
Editing django-rest-framework serializer object before save | 13,563,020 | 28 | 2012-11-26T10:35:38Z | 13,564,519 | 35 | 2012-11-26T12:05:25Z | [
"python",
"django",
"serialization",
"django-rest-framework",
"django-serializer"
] | I want to edit a `django-rest-framwork` serializer object before it is saved. This is how I currently do it -
```
def upload(request):
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid(): # All validation rules pass
obj = form.save(commit=False... | **Now edited for REST framework 3**
With REST framework 3 the pattern is now:
```
if serializer.is_valid():
serializer.save(user_id=15)
```
Note that the serializers do *not* now ever expose an unsaved object instance as `serializer.object`, however you *can* inspect the raw validated data as `serializer.validat... |
Editing django-rest-framework serializer object before save | 13,563,020 | 28 | 2012-11-26T10:35:38Z | 15,146,107 | 14 | 2013-02-28T21:35:58Z | [
"python",
"django",
"serialization",
"django-rest-framework",
"django-serializer"
] | I want to edit a `django-rest-framwork` serializer object before it is saved. This is how I currently do it -
```
def upload(request):
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid(): # All validation rules pass
obj = form.save(commit=False... | You can edit the serializer's object before save the serializer:
```
if serializer.is_valid():
serializer.object.user_id = 15 # <----- this line
serializer.save()
``` |
Generate keyboard events | 13,564,851 | 31 | 2012-11-26T12:27:50Z | 13,615,802 | 53 | 2012-11-28T22:47:25Z | [
"python",
"keyboard-events"
] | **short summary:**
I am trying to create a program that will send keyboard events to the computer that for all purposes the simulated events should be treated as actual keystrokes on the keyboard.
**original post:**
I am looking for a way to generate keyboard events using python.
Assume that the function receives a... | It can be done using ctypes:
```
import ctypes
from ctypes import wintypes
import time
user32 = ctypes.WinDLL('user32', use_last_error=True)
INPUT_MOUSE = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARE = 2
KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP = 0x0002
KEYEVENTF_UNICODE = 0x0004
KEYEVENTF_SCANCODE = 0... |
How can I install from a git subdirectory with pip? | 13,566,200 | 19 | 2012-11-26T13:49:53Z | 19,516,714 | 28 | 2013-10-22T11:33:43Z | [
"python",
"git",
"pip"
] | I have a git repository with many folders, one of them being a python module installable with pip, like this:
```
repo.git/
repo.git/folder1/
repo.git/folder2/
repo.git/mymodule/
repo.git/mymodule/__init__.py
repo.git/mymodule/setup.py
repo.git/mymodule/...
```
Right now I have to do the following to install:
```
gi... | There is a [pull request](https://github.com/pypa/pip/pull/1215) regarding this feature, and it seems to have been merged to develop branch a month ago. The syntax is the [following](https://github.com/pnasrat/pip/commit/abf27b5bd207024b35885fd1fddd7803b488a3d4):
```
pip install -e git+https://git.repo/some_repo.git#e... |
Scale the real part of complex numpy array | 13,567,089 | 4 | 2012-11-26T14:41:11Z | 13,567,150 | 8 | 2012-11-26T14:44:02Z | [
"python",
"numpy",
"complex-numbers"
] | I have a vector of complex numbers (the result of a FFT) and I would like to scale only the real part of the complex numbers by factors in another vector.
### Example
```
cplxarr= np.array([1+2j, 3+1j, 7-2j])
factarr= np.array([.5, .6, .2])
# desired result of cplxarr * factarr :
# np.array([.5+2j 1.8+1j 1.4-2j])
```... | This'll do it:
```
>>> factarr*cplxarr.real + (1j)*cplxarr.imag
array([ 0.5+2.j, 1.8+1.j, 1.4-2.j])
```
Not sure if it's the best way though.
---
It turns out that for me at least (OS-X 10.5.8, python 2.7.3, numpy 1.6.2) This version is about twice as fast as the other version which uses `np.vectorize`:
```
>>> ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.