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 |
|---|---|---|---|---|---|---|---|---|---|
What's perfect counterpart in Python for "while not eof" | 15,599,639 | 41 | 2013-03-24T14:25:31Z | 15,599,648 | 86 | 2013-03-24T14:26:23Z | [
"python",
"file",
"iteration",
"eof"
] | To read some text file, in C or Pascal, I always use the following snippets to read the data until EOF:
```
while not eof do begin
readline(a);
do_something;
end;
```
Thus, I wonder how can I do this simple and fast in Python? | Loop over the file to read lines:
```
with open('somefile') as openfileobject:
for line in openfileobject:
do_something()
```
File objects are iterable and yield lines until EOF. Using the file object as an iterable uses a buffer to ensure performant reads.
You can do the same with the stdin (no need to ... |
What's perfect counterpart in Python for "while not eof" | 15,599,639 | 41 | 2013-03-24T14:25:31Z | 15,599,657 | 12 | 2013-03-24T14:27:04Z | [
"python",
"file",
"iteration",
"eof"
] | To read some text file, in C or Pascal, I always use the following snippets to read the data until EOF:
```
while not eof do begin
readline(a);
do_something;
end;
```
Thus, I wonder how can I do this simple and fast in Python? | The Python idiom for opening a file and reading it line-by-line is:
```
with open('filename') as f:
for line in f:
do_something(line)
```
The file will be automatically closed at the end of the above code (the `with` construct takes care of that).
Finally, it is worth noting that `line` will preserve the... |
What's perfect counterpart in Python for "while not eof" | 15,599,639 | 41 | 2013-03-24T14:25:31Z | 15,599,780 | 31 | 2013-03-24T14:40:18Z | [
"python",
"file",
"iteration",
"eof"
] | To read some text file, in C or Pascal, I always use the following snippets to read the data until EOF:
```
while not eof do begin
readline(a);
do_something;
end;
```
Thus, I wonder how can I do this simple and fast in Python? | You can imitate the C idiom in Python.
To read a buffer up to `max_size` number of bytes, you can do this:
```
with open(filename,'rb') as f:
while True:
buf=f.read(max_size)
if not buf: break
process(buf)
```
Or, a text file line by line:
```
# warning -- not idiomatic Python! See below... |
How to find all occurrences of a pattern and their indices in Python | 15,599,726 | 4 | 2013-03-24T14:33:30Z | 15,599,760 | 13 | 2013-03-24T14:37:50Z | [
"python",
"regex",
"string",
"shortcut"
] | Is there a pythonian or shorthand way to get all pattern occurrences from a string and their indices? I can write a method that does it, I'm just wondering if there's a super short one-liner or something :) | python [`re`](http://docs.python.org/2/library/re.html) module to the rescue.
```
>>> import re
>>> [x.start() for x in re.finditer('foo', 'foo foo foo foo')]
[0, 4, 8, 12]
```
[`re.finditer`](http://docs.python.org/library/re.html#re.finditer) returns a [generator](http://wiki.python.org/moin/Generators), what this ... |
pyqt disconnect slots. New style | 15,600,014 | 4 | 2013-03-24T15:02:59Z | 15,600,458 | 9 | 2013-03-24T15:40:28Z | [
"python",
"pyqt",
"signals",
"disconnect",
"slot"
] | I asign slot with this.
```
...
self.query = QtGui.QLineEdit(self)
self.query.textChanged.connect(lambda: self.makeThread(self.googleSearch()))
self.query.returnPressed.connect(lambda: self.launchNavigator(1))
...
```
but how i can disconnect? I tried with this b... | The lambda expressions return *different* functions that (more or less by chance ;) ) will do the same thing. Therefore, what you connected your signal to is not the same thing as the second lambda you're using when trying to disconnect it; see this example:
```
>>> f = lambda x: x
>>> g = lambda x: x
>>> f is g
False... |
python exception not recognized; how to handle with except? | 15,600,707 | 11 | 2013-03-24T16:02:38Z | 15,600,736 | 16 | 2013-03-24T16:04:52Z | [
"python",
"exception",
"global-variables"
] | I have a command in a try clause which I know throws an exception. I'm trying to catch it in an "except" clause, but the except clause seems to not recognize the existence of the exception. The exception, when unhandled (i.e. not enclosed in a try clause), looks like this in the interactive window:
```
Traceback (most... | You probably just need to import the `HTTPError` class before using it. Try inserting at the top of your actions.py file:
```
from urllib2 import HTTPError
```
and then you should be able to use your code as is. |
python exception not recognized; how to handle with except? | 15,600,707 | 11 | 2013-03-24T16:02:38Z | 15,600,753 | 8 | 2013-03-24T16:06:09Z | [
"python",
"exception",
"global-variables"
] | I have a command in a try clause which I know throws an exception. I'm trying to catch it in an "except" clause, but the except clause seems to not recognize the existence of the exception. The exception, when unhandled (i.e. not enclosed in a try clause), looks like this in the interactive window:
```
Traceback (most... | You need to check for urllib2.HTTPError:
```
except urllib2.HTTPError:
``` |
Contour graph in python | 15,601,096 | 8 | 2013-03-24T16:39:36Z | 15,601,481 | 21 | 2013-03-24T17:13:30Z | [
"python",
"matplotlib",
"contour"
] | How would I make a countour grid in python using `matplotlib.pyplot`, where the grid is one colour where the `z` variable is below zero and another when `z` is equal to or larger than zero? I'm not very familiar with `matplotlib` so if anyone can give me a simple way of doing this, that would be great.
So far I have:
... | You can do this using the `levels` keyword in contourf.

```
import numpy as np
import matplotlib.pyplot as plt
fig, axs = plt.subplots(1,2)
x = np.linspace(0, 1, 100)
X, Y = np.meshgrid(x, x)
Z = np.sin(X)*np.sin(Y)
levels = np.linspace(-1, 1, 40)... |
Using git-remote-hg on windows | 15,601,246 | 5 | 2013-03-24T16:53:23Z | 17,198,467 | 8 | 2013-06-19T18:18:40Z | [
"python",
"git",
"mercurial",
"hg-git"
] | According to this answer <http://stackoverflow.com/a/13354944/867294> it should be fairly easy to set up git to work with mercurial "no dependencies or anything".
This doesn't seem to work all that smooth on Windows tough.
I tried to follow this guide
<https://github.com/msysgit/msysgit/wiki/Guide-to-git-remote-hg>
... | I got this to work today on Windows. Basically, since the msysgit distributions have no Python support, I took Felipe's git-remote-hg.py file and used py2exe to package it up as an executable. Afterwards, I put all of the py2exe output into the 'libexec' folder under my Git installation directory, and it works.
For it... |
Copying data from S3 to AWS redshift using python and psycopg2 | 15,601,704 | 9 | 2013-03-24T17:32:08Z | 15,650,392 | 11 | 2013-03-27T01:19:26Z | [
"python",
"psycopg2",
"amazon-redshift"
] | I'm having issues executing the copy command to load data from S3 to Amazon's Redshift from python.
I have the following copy command:
```
copy moves from 's3://<my_bucket_name>/moves_data/2013-03-24/18/moves'
credentials 'aws_access_key_id=<key_id>;aws_secret_access_key=<key_secret>'
removequotes
delimiter ',';
```... | I have used this exact setup (psycopg2 + redshift + COPY) successfully. Did you commit afterwards? SQL Workbench defaults to auto-commit while psycopg2 defaults to opening a transaction, so the data won't be visible until you call commit() on your connection.
The full workflow is:
```
conn = psycopg2.connect(...)
cur... |
Copying data from S3 to AWS redshift using python and psycopg2 | 15,601,704 | 9 | 2013-03-24T17:32:08Z | 20,389,306 | 7 | 2013-12-05T00:53:20Z | [
"python",
"psycopg2",
"amazon-redshift"
] | I'm having issues executing the copy command to load data from S3 to Amazon's Redshift from python.
I have the following copy command:
```
copy moves from 's3://<my_bucket_name>/moves_data/2013-03-24/18/moves'
credentials 'aws_access_key_id=<key_id>;aws_secret_access_key=<key_secret>'
removequotes
delimiter ',';
```... | First, make sure the transaction is *committed*.
```
conn = psycopg2.connect(conn_string)
cur = conn.cursor()
cur.execute(copy_cmd_str)
conn.commit()
```
you can ensure a transaction-commit with following way as well (ensuring releasing the resources),
```
with psycopg2.connect(conn_string) as conn:
with conn.cu... |
is the newline "\n" 2 characters or 1 character | 15,601,824 | 7 | 2013-03-24T17:41:51Z | 15,601,846 | 10 | 2013-03-24T17:44:16Z | [
"python",
"io"
] | So i have a file.txt:
```
>>012345
>> (new line)
```
when I call:
```
b=a.read(7)
print b
```
this will give me
```
012345
(with a newline here)
```
So I see that it has read the next 7 characters, counting the "\n" as a single character.
But when I use seek, it seems that it treats "\n" as two characters:
```... | Python opens files in *text mode* by default. Files open in text mode have platform-native newline conventions translated to `\n` automatically.
You opened a file using the `\r\n` newline convention, on Windows most probably.
Open the file in binary mode if you do not want this translation to take place. See the docu... |
Flask: How to manage different environment databases? | 15,603,240 | 5 | 2013-03-24T19:55:04Z | 15,648,619 | 7 | 2013-03-26T22:28:45Z | [
"python",
"flask",
"flask-sqlalchemy"
] | I am working on an app which looks similar to
```
facebook/
__init__.py
feed/
__init__.py
business.py
views.py
models/
persistence.py
user.py
chat/
__init__.py
models.py
... | Solution I use:
```
#__init__.py
app = Flask(__name__)
app.config.from_object('settings')
app.config.from_envvar('MYCOOLAPP_CONFIG',silent=True)
```
On the same level from which application loads:
```
#settings.py
SERVER_NAME="dev.app.com"
DEBUG=True
SECRET_KEY='xxxxxxxxxx'
#settings_production.py
SERVER_NAME="app... |
Replacing = with '\x' and then decoding in python | 15,604,597 | 6 | 2013-03-24T22:05:50Z | 15,604,659 | 7 | 2013-03-24T22:12:30Z | [
"python",
"utf-8",
"decode",
"backslash"
] | I fetched the subject of an email message using python modules and received string
```
'=D8=B3=D9=84=D8=A7=D9=85_=DA=A9=D8=AC=D8=A7=D8=A6=DB=8C?='
```
I know the string is encoded in 'utf-8'. Python has a method called on strings to decode such strings. But to use the method I needed to replace `=` sign with `\x` str... | Just decode it from quoted-printable to get utf8-encoded bytestring:
```
In [35]: s = '=D8=B3=D9=84=D8=A7=D9=85_=DA=A9=D8=AC=D8=A7=D8=A6=DB=8C?='
In [36]: s.decode('quoted-printable')
Out[36]: '\xd8\xb3\xd9\x84\xd8\xa7\xd9\x85_\xda\xa9\xd8\xac\xd8\xa7\xd8\xa6\xdb\x8c?'
```
Then, if needed, from utf-8 to unicode:
```... |
How to get the last exception object after an error is raised at a Python prompt? | 15,605,925 | 26 | 2013-03-25T00:34:32Z | 15,606,149 | 33 | 2013-03-25T01:06:42Z | [
"python",
"exception",
"try-catch",
"read-eval-print-loop"
] | When debugging Python code at the interactive prompt (REPL), often I'll write some code which raises an exception, but I haven't wrapped it in a `try`/`except`, so once the error is raised, I've forever lost the exception object.
Often the traceback and error message Python prints out isn't enough. For example, when f... | The `sys` module provides some functions for post-hoc examining of exceptions: [`sys.last_type`](http://docs.python.org/2/library/sys.html#sys.last_type), [`sys.last_value`](http://docs.python.org/2/library/sys.html#sys.last_value), and [`sys.last_traceback`](http://docs.python.org/2/library/sys.html#sys.last_traceback... |
Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx---- | 15,607,903 | 51 | 2013-03-25T04:54:33Z | 15,607,971 | 51 | 2013-03-25T05:01:14Z | [
"python",
"file",
"permissions",
"chmod"
] | Recently I am using Python module os, when I tried to change the permission of a file, I did not get the expected result. For example, I intended to change the permission to rw-rw-r--,
```
os.chmod("/tmp/test_file", 664)
```
The ownership permission is actually -w--wx--- (230)
```
--w--wx--- 1 ag ag 0 Mar 25 05:45 t... | Found this on a [different forum](http://ubuntuforums.org/showthread.php?t=889326)
> If you're wondering why that leading zero is important, it's because
> permissions are set as an octal integer, and Python automagically
> treats any integer with a leading zero as octal. So os.chmod("file",
> 484) (in decimal) would ... |
Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx---- | 15,607,903 | 51 | 2013-03-25T04:54:33Z | 17,776,766 | 55 | 2013-07-21T20:50:14Z | [
"python",
"file",
"permissions",
"chmod"
] | Recently I am using Python module os, when I tried to change the permission of a file, I did not get the expected result. For example, I intended to change the permission to rw-rw-r--,
```
os.chmod("/tmp/test_file", 664)
```
The ownership permission is actually -w--wx--- (230)
```
--w--wx--- 1 ag ag 0 Mar 25 05:45 t... | So for people who want symantics similar to:
```
$ chmod 755 somefile
```
In python2:
```
$ python -c "import os; os.chmod('somefile', 0755)"
```
But in python3:
```
$ python3 -c "import os; os.chmod('somefile', 0o755)"
``` |
What does print()'s `flush` do? | 15,608,229 | 4 | 2013-03-25T05:27:08Z | 15,608,332 | 7 | 2013-03-25T05:37:45Z | [
"python",
"python-3.x"
] | There is a boolean optional argument to the `print()` function `flush` which defaults to False.
The documentation says it is to forcibly flush the stream.
I don't understand the concept of flushing. What is flushing here? What is flushing of stream? | There are a couple of things to understand here. One is the difference between buffered I/O and unbuffered I/O. The concept is fairly simple - for buffered I/O, there is an internal buffer which is kept. Only when that buffer is full (or some other event happens, such as it reaches a newline) is the output "flushed". W... |
Eclipse and Google App Engine: ImportError: No module named _sysconfigdata_nd; unrecognized arguments: --high_replication | 15,608,236 | 40 | 2013-03-25T05:27:54Z | 16,224,441 | 94 | 2013-04-25T20:49:16Z | [
"python",
"eclipse",
"google-app-engine"
] | Just upgraded to Ubuntu 13.04 and Eclipse complained with the following 2 errors:
```
1. ImportError: No module named _sysconfigdata_nd
ERROR 2013-03-25 07:26:43,559 http_runtime.py:221] unexpected port response from runtime ['']; exiting the development server
ERROR 2013-03-25 07:26:43,561 server.py:576] Reque... | The "No module named \_sysconfigdata\_nd" is [a bug in the Ubuntu package](https://bugs.launchpad.net/ubuntu/+source/python2.7/+bug/1115466).
You can create a softlink as a workaround:
```
sudo ln -s /usr/lib/python2.7/plat-*/_sysconfigdata_nd.py /usr/lib/python2.7/
``` |
Eclipse and Google App Engine: ImportError: No module named _sysconfigdata_nd; unrecognized arguments: --high_replication | 15,608,236 | 40 | 2013-03-25T05:27:54Z | 20,991,008 | 23 | 2014-01-08T09:00:40Z | [
"python",
"eclipse",
"google-app-engine"
] | Just upgraded to Ubuntu 13.04 and Eclipse complained with the following 2 errors:
```
1. ImportError: No module named _sysconfigdata_nd
ERROR 2013-03-25 07:26:43,559 http_runtime.py:221] unexpected port response from runtime ['']; exiting the development server
ERROR 2013-03-25 07:26:43,561 server.py:576] Reque... | Depending on different conditions, updating `virtualenv` may actually be a better idea instead of [this walkaround](http://stackoverflow.com/a/16224441/548696), as mentioned on [linked bug reports](https://bugs.launchpad.net/ubuntu/+source/python2.7/+bug/1115466). To update `virtualenv` you could use the following comm... |
Python convert html to text and mimic formatting | 15,608,555 | 7 | 2013-03-25T05:57:37Z | 15,608,928 | 7 | 2013-03-25T06:29:03Z | [
"python",
"html",
"beautifulsoup"
] | I'm learning BeautifulSoup, and found many "html2text" solutions, but the one i'm looking for should mimic the formatting:
```
<ul>
<li>One</li>
<li>Two</li>
</ul>
```
Would become
```
* One
* Two
```
and
```
Some text
<blockquote>
More magnificent text here
</blockquote>
Final text
```
to
```
Some text
Mor... | Take a look at Aaron Swartz's [html2text](https://github.com/aaronsw/html2text) script (can be installed with `pip install html2text`). Note that the output is valid [Markdown](http://en.wikipedia.org/wiki/Markdown). If for some reason that doesn't fully suit you, some rather trivial tweaks should get you the exact out... |
sorting multiple lists in python based on sorting of a single list | 15,610,724 | 3 | 2013-03-25T08:45:47Z | 15,611,016 | 7 | 2013-03-25T09:03:10Z | [
"python",
"itertools"
] | I am a python newbie here, and I have been struck on a rather simple problem - and I am looking for the most efficient way to solve this. So, I have 5 lists as follows:
```
a,b,c,d,score
```
where the above lists all have the same size (500 in my case). `a,b,c,d` are string lists and `score` is an `int` list.
What I... | ```
sorted_lists = sorted(izip(a, b, c, d, score), reverse=True, key=lambda x: x[4])
a, b, c, d, score = [[x[i] for x in sorted_lists] for i in range(5)]
```
In this first step, `zip` the lists together. This takes the first element from every list and puts them into a tuple, appends that tuple to a new list, then doe... |
Convert Image ( png ) To Matrix And Then To 1D Array | 15,612,373 | 2 | 2013-03-25T10:12:43Z | 15,613,103 | 9 | 2013-03-25T10:50:53Z | [
"python",
"image-processing",
"numpy"
] | I have 5 pictures and i want to convert each image to 1d array and put it in a matrix as vector.
I want to be able to convert each vector to image again.
```
img = Image.open('orig.png').convert('RGBA')
a = np.array(img)
```
I'm not familiar with all the features of numpy and wondered if there other tools I can us... | ```
import numpy as np
import Image
img = Image.open('orig.png').convert('RGBA')
arr = np.array(img)
# record the original shape
shape = arr.shape
# make a 1-dimensional view of arr
flat_arr = arr.ravel()
# convert it to a matrix
vector = np.matrix(flat_arr)
# do something to the vector
vector[:,::10] = 128
# ref... |
How to fetch json argument in handler (json is in body of post request with no key to json) | 15,614,021 | 2 | 2013-03-25T11:40:10Z | 15,618,041 | 10 | 2013-03-25T14:57:10Z | [
"python",
"python-2.7",
"tornado"
] | From client I generate post request and in body I have simlpe JSON like
```
{
"action": "copy_all",
"id": "aabbababab",
"factory_id": 12297829382473034000
}
```
How to fetch this argument this in handler (post function) ?
I know how to parse when I send like key/value pair and get argument by key, but her... | use:
```
data = tornado.escape.json_decode(self.request.body)
``` |
How Can You Create an Admin User with Factory_Boy? | 15,616,277 | 11 | 2013-03-25T13:34:18Z | 17,980,414 | 19 | 2013-07-31T20:32:50Z | [
"python",
"django",
"selenium",
"factory-boy"
] | I'm a relative Django beginner and just started doing some testing for my projects. What I want to do is build a functional test with selenium that logs into the Django Admin site.
I first followed this tutorial <http://www.tdd-django-tutorial.com/tutorial/1/> and used fixtures and dumpdata to make the admin account i... | If you subclass factory.DjangoModelFactory it should save the user object for you. See the note section under [PostGenerationMethodCall](https://factoryboy.readthedocs.org/en/latest/reference.html#factory.PostGenerationMethodCall). Then you only need to do the following:
```
class UserFactory(factory.DjangoModelFactor... |
Line colour of 3D parametric curve in python's matplotlib.pyplot | 15,617,207 | 12 | 2013-03-25T14:18:14Z | 15,617,576 | 12 | 2013-03-25T14:34:52Z | [
"python",
"matplotlib"
] | I've been googling quite some time with no success ... maybe my keywords are just lousy. Anyway, suppose I have three 1D `numpy.ndarray`s of the same length I'd like to plot them in 3D as a trajectory. Moreover, I'd like to be able to do either of the following things:
1. Change the colour of the line as a function of... | As with normal 2d plots, you cannot have a gradient of color along an ordinary line. However, you can do it with `scatter`:
```
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * ... |
Line colour of 3D parametric curve in python's matplotlib.pyplot | 15,617,207 | 12 | 2013-03-25T14:18:14Z | 15,617,860 | 9 | 2013-03-25T14:48:06Z | [
"python",
"matplotlib"
] | I've been googling quite some time with no success ... maybe my keywords are just lousy. Anyway, suppose I have three 1D `numpy.ndarray`s of the same length I'd like to plot them in 3D as a trajectory. Moreover, I'd like to be able to do either of the following things:
1. Change the colour of the line as a function of... | You can plot every line segment separately, as shown below. This just loops over 6 predefined colors, since @askewchan's answer already demonstrates well how to use a colormap.
```
cols = 'rgbcmy'
for i in range(len(x)-1):
ax.plot(x[i:i+2], y[i:i+2], z[i:i+2], color=cols[i%6])
```
![enter image description here]... |
Resampling a multi-index DataFrame | 15,617,496 | 5 | 2013-03-25T14:31:05Z | 15,621,178 | 7 | 2013-03-25T17:34:55Z | [
"python",
"pandas"
] | I want to resample a DataFrame with a multi-index containing both a datetime column and some other key. The Dataframe looks like:
```
import pandas as pd
from StringIO import StringIO
csv = StringIO("""ID,NAME,DATE,VAR1
1,a,03-JAN-2013,69
1,a,04-JAN-2013,77
1,a,05-JAN-2013,75
2,b,03-JAN-2013,69
2,b,04-JAN-2013,75
2,b... | The example unstacks a non-numerical column 'NAME' which is silently dropped but causes problems during re-stacking. The code below worked for me
```
print df[['VAR1']].unstack('ID').resample('W-THU').stack('ID')
Params VAR1
DATE ID
2013-01-03 A 69.0
B 69.0
2013-01-10 A 76.0
B... |
Gevent multicore usage | 15,617,553 | 16 | 2013-03-25T14:33:43Z | 15,617,665 | 39 | 2013-03-25T14:39:05Z | [
"python",
"multiprocessing",
"gevent"
] | I'm just started with python gevent and I was wondering about the cpu / mulitcore usage of the library.
Trying some examples doing many requests via the monkeypatched urllib I noticed, that they were running just on one core using 99% load.
How can I use all cores with gevent using python?
Is there best practice? Or ... | Gevent gives you the ability to deal with blocking requests. It does not give you the ability to run on multi-core.
There's only one greenlet (gevent's coroutine) running in a python process at any time. The real benefit of gevent is that it is very powerful when it deals with I/O bottlenecks (which is usually the cas... |
How can I satisfy an import of direct_to_template? | 15,621,048 | 22 | 2013-03-25T17:26:20Z | 15,621,222 | 46 | 2013-03-25T17:37:24Z | [
"python",
"django",
"social-networking",
"pinax"
] | I am getting an error page from an originally Pinax 0.7 project:
```
ImportError at /
No module named simple
Request Method: GET
Request URL: http://stornge.com:8000/
Django Version: 1.5
Exception Type: ImportError
Exception Value:
No module named simple
Exception Location: /home/jonathan/clay/../clay/urls.py i... | `direct_to_template` has been deprecated. In django 1.5 try using a Class based view in `urls.py`
```
from django.views.generic import TemplateView
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name='homepage.html'), name="home"),
)
```
There's some information on migrating to version 1.4 (... |
Python Fabric - No hosts found. Please specify (single) host string for connection: | 15,621,174 | 9 | 2013-03-25T17:34:50Z | 15,621,751 | 9 | 2013-03-25T18:08:25Z | [
"python",
"fabric"
] | How do I get No hosts found. Please specify (single) host string for connection: ?
How to a resolve with fabric?
```
def bootstrap():
host = 'ec2-54-xxx.xxx.xxx.compute-1.amazonaws.com'
env.hosts = [host]
env.user = "ubuntu"
env.key_filename = "/home/ubuntu/omg.pem"
fab boostrap
No hosts found. Pleas... | Instead of setting hosts inside your task, do it before it gets called with a decorator:
```
from fabric.api import hosts, env
@hosts(['ec2-54-xxx.xxx.xxx.compute-1.amazonaws.com'])
def bootstrap():
env.user = "ubuntu"
env.key_filename = "/home/ubuntu/omg.pem"
```
For more information on this, check out [Def... |
Python Fabric - No hosts found. Please specify (single) host string for connection: | 15,621,174 | 9 | 2013-03-25T17:34:50Z | 24,107,686 | 13 | 2014-06-08T15:28:06Z | [
"python",
"fabric"
] | How do I get No hosts found. Please specify (single) host string for connection: ?
How to a resolve with fabric?
```
def bootstrap():
host = 'ec2-54-xxx.xxx.xxx.compute-1.amazonaws.com'
env.hosts = [host]
env.user = "ubuntu"
env.key_filename = "/home/ubuntu/omg.pem"
fab boostrap
No hosts found. Pleas... | Also you can use env.host\_string instead of env.hosts:
```
def bootstrap():
env.host_string # 'ec2-54-xxx.xxx.xxx.compute-1.amazonaws.com'
env.user = "ubuntu"
env.key_filename = "/home/ubuntu/omg.pem"
``` |
How to understand the equal sign '=' symbol in IMAP email text? | 15,621,510 | 13 | 2013-03-25T17:54:37Z | 15,621,614 | 14 | 2013-03-25T18:01:02Z | [
"python",
"html",
"imap",
"gmail-imap",
"imaplib"
] | I am currently using Python imaplib to process email text.
I use fetch command to fetch the raw data email from GMail server. However, I found one thing really tricky - the equal sign '='. It is not a normal equal sign but a special symbol.
For example:
1. '=' sometimes acts as the hyphenation mark at the end of tex... | In a nutshell, an equal sign at the end of a line indicates a soft line break. An equal sign followed by two hexadecimal characters (0-9, A-F) encodes a single octet (byte).
This encoding scheme is called "quoted printable" and is defined in section 6.7 of [RFC 2045](http://www.faqs.org/rfcs/rfc2045.html). See items (... |
parsing XML file gets UnicodeEncodeError (ElementTree) / ValueError (lxml) | 15,622,027 | 5 | 2013-03-25T18:24:46Z | 15,622,069 | 13 | 2013-03-25T18:27:00Z | [
"python",
"encoding",
"lxml",
"elementtree",
"python-requests"
] | I send a GET request to the [CareerBuilder API](http://api.careerbuilder.com/) :
```
import requests
url = "http://api.careerbuilder.com/v1/jobsearch"
payload = {'DeveloperKey': 'MY_DEVLOPER_KEY',
'JobTitle': 'Biologist'}
r = requests.get(url, params=payload)
xml = r.text
```
And get back an XML that look... | You are using the *decoded* unicode value. Use [`r.raw` raw response data](http://docs.python-requests.org/en/latest/user/quickstart/#raw-response-content) instead:
```
r = requests.get(url, params=payload, stream=True)
r.raw.decode_content = True
etree.parse(r.raw)
```
which will read the data from the response dire... |
What is the recommended size of indentation in Python? | 15,623,229 | 3 | 2013-03-25T19:37:14Z | 15,623,246 | 15 | 2013-03-25T19:37:56Z | [
"python",
"indentation"
] | Is there any **official** rule/proposal on how should the Python code be indented? | From [PEP 8](http://www.python.org/dev/peps/pep-0008/#indentation) (Python's official style guide):
> Use 4 spaces per indentation level. |
Better syntax for re-raising an exception only if an exception occurred? | 15,623,971 | 2 | 2013-03-25T20:19:16Z | 15,623,999 | 9 | 2013-03-25T20:21:00Z | [
"python",
"exception"
] | I find myself doing this when I want to catch an exception, always run some specific code, then re-raise the original exception:
```
try:
error = False
# do something that *might* raise an exception
except Exception:
error = True
finally:
# something I *always* want to run
if error:
raise
`... | Raise the exception in the except handler:
```
try:
# do something that *might* raise an exception
except Exception:
raise
finally:
# something I *always* want to run
```
The `finally` suite is *always* going to be executed wether or not you re-raised the exception.
From the [documentation](http://docs.p... |
Why does scipy.optimize.curve_fit not fit to the data? | 15,624,070 | 11 | 2013-03-25T20:24:40Z | 15,624,303 | 22 | 2013-03-25T20:38:42Z | [
"python",
"matplotlib",
"scipy",
"curve-fitting",
"data-fitting"
] | I've been trying to fit an exponential to some data for a while using scipy.optimize.curve\_fit but i'm having real difficulty. I really can't see any reason why this wouldn't work but it just produces a strait line, no idea why!
Any help would be much appreciated
```
from __future__ import division
import numpy
from... | Numerical algorithms tend to work better when not fed extremely small (or large) numbers.
In this case, the graph shows your data has extremely small x and y values. If you scale them, the fit is remarkable better:
```
xData = np.load('xData.npy')*10**5
yData = np.load('yData.npy')*10**5
```
---
```
from __future__... |
Why does scipy.optimize.curve_fit not fit to the data? | 15,624,070 | 11 | 2013-03-25T20:24:40Z | 17,238,290 | 16 | 2013-06-21T14:54:23Z | [
"python",
"matplotlib",
"scipy",
"curve-fitting",
"data-fitting"
] | I've been trying to fit an exponential to some data for a while using scipy.optimize.curve\_fit but i'm having real difficulty. I really can't see any reason why this wouldn't work but it just produces a strait line, no idea why!
Any help would be much appreciated
```
from __future__ import division
import numpy
from... | A (slight) improvement to this solution, not accounting for a priori knowledge of the data might be the following: Take the inverse-mean of the data set and use that as the "scale factor" to be passed to the underlying leastsq() called by curve\_fit(). This allows the fitter to work and returns the parameters on the or... |
Passing a parameter to the decorator in python | 15,624,801 | 5 | 2013-03-25T21:08:38Z | 15,624,856 | 10 | 2013-03-25T21:11:53Z | [
"python",
"parameters",
"decorator"
] | Why is this decorator with a parameter not working?
```
def decAny( f0 ):
def wrapper( s0 ):
return "<%s> %s </%s>" % ( any, f0(), any )
return wrapper
@decAny( 'xxx' )
def test2():
return 'test1XML'
print( test2() )
```
always gives me an error saying "str is not callable"
it is trying to execu... | Decorators are functions that return functions. When "passing a parameter to the decorator" what you are actually doing is calling a function that returns a decorator. So `decAny()` should be a function that returns a function that returns a function.
It would look something like this:
```
import functools
def decAn... |
SQLAlchemy can't connect to an mssql database | 15,626,467 | 14 | 2013-03-25T23:04:17Z | 15,627,017 | 18 | 2013-03-25T23:58:17Z | [
"python",
"sql-server",
"sqlalchemy"
] | Here's my simple test script. Just trying to do a basic select statement. Found the basic bits on a tutorial.
```
from sqlalchemy import *
db = create_engine('mssql+pyodbc://user:pass@ip_address/database_name')
db.echo = True
metadata = MetaData(db)
users = Table('member', metadata, autoload=True)
def run(stm... | If not specified in the URL, the default driver for the `mssql+pyodbc` dialect would be "SQL Server" [1]. That means you need to have a section that reads like this in /etc/unixODBC/odbcinst.ini:
```
[SQL Server]
Driver=/path/to/library.so
```
It works "automatically" on Windows, because if you open *Administrator To... |
What value do I use in a slicing range to include the last value in a numpy array? | 15,627,312 | 8 | 2013-03-26T00:31:17Z | 15,627,479 | 8 | 2013-03-26T00:49:47Z | [
"python",
"numpy",
"scipy"
] | Imagine some numpy array, e.g. `x = np.linspace(1,10)`.
`x[i:j]` gives me a view into `x` for the range `[i,j)`.
I love that I can also do `x[i:-k]` which excludes the last `k` elements.
However, in order to include the last element I need to do `x[i:]`.
My question is this: How do I combine these two notations if I... | You can't, because -0 doesn't slice that way in python (it becomes 0)
You could just do the old school:
```
l = list()
for k in [5,4,3,2,1,0]:
l.append(x[:len(x)-k])
``` |
why is pip so SLOW to download? (how to troubleshoot?) | 15,629,061 | 10 | 2013-03-26T03:47:41Z | 15,720,189 | 10 | 2013-03-30T15:28:39Z | [
"python",
"download",
"pip"
] | I can wget e.g. [python coverage](https://pypi.python.org/packages/source/c/coverage/coverage-3.6.tar.gz#md5=67d4e393f4c6a5ffc18605409d2aa1ac) and pip install the package locally quickly and without any problem, but `pip install coverage` takes *forever*. Using pip 1.3.1 in a virtual env on Ubuntu 12.04. Any idea what ... | As Donald Stufft answered in [pip issue 864](https://github.com/pypa/pip/issues/864), it happens because `pip` crawls a lot of pages looking for package sdists, and this behavior was inherited from `easy_install`. Some packages do not work if you remove that feature, and some guys started a new PEP to remove this exter... |
How to remove Create and Edit... from many2one field.? | 15,630,054 | 5 | 2013-03-26T05:33:28Z | 15,630,138 | 12 | 2013-03-26T05:42:02Z | [
"python",
"xml",
"one-to-many",
"openerp",
"many-to-one"
] | Please advice me How to remove "Create and Edit..." from many2one field.?
that item shows below in the many2one fields which I filtered with domain option.
OpenERP version 7 | I don't have much idea. Maybe for that you have to make changes in web addons.
But an alternative solution is that you can make that **many2one** field **selection**. Add `widget="selection"` attribute in your xml.
`<field name="Your_many2one_field" widget="selection">` |
Python.h missing from Ubuntu 12.04 | 15,631,135 | 55 | 2013-03-26T06:58:18Z | 15,631,179 | 7 | 2013-03-26T07:01:24Z | [
"python",
"ubuntu-12.04"
] | I am very new to python.I installed an openflow controller on my Linux PC (Ubunutu 12.04) called RYU using:
```
sudo pip install ryu
```
I was trying to run a python file using ryu-manager as shown below.
```
sudo ryu-manager simple_switch.py
Traceback (most recent call last):
File "/usr/local/bin/ryu-manager",... | Install `gevent` directly - `sudo apt-get install python-gevent`. |
Python.h missing from Ubuntu 12.04 | 15,631,135 | 55 | 2013-03-26T06:58:18Z | 15,631,332 | 31 | 2013-03-26T07:11:37Z | [
"python",
"ubuntu-12.04"
] | I am very new to python.I installed an openflow controller on my Linux PC (Ubunutu 12.04) called RYU using:
```
sudo pip install ryu
```
I was trying to run a python file using ryu-manager as shown below.
```
sudo ryu-manager simple_switch.py
Traceback (most recent call last):
File "/usr/local/bin/ryu-manager",... | Even if you have Python installed, the header file and the library usually aren't installed by default. On Ubuntu, they come in a separate package called [`python-dev`](http://packages.ubuntu.com/search?keywords=python-dev). |
Python.h missing from Ubuntu 12.04 | 15,631,135 | 55 | 2013-03-26T06:58:18Z | 15,631,703 | 148 | 2013-03-26T07:34:13Z | [
"python",
"ubuntu-12.04"
] | I am very new to python.I installed an openflow controller on my Linux PC (Ubunutu 12.04) called RYU using:
```
sudo pip install ryu
```
I was trying to run a python file using ryu-manager as shown below.
```
sudo ryu-manager simple_switch.py
Traceback (most recent call last):
File "/usr/local/bin/ryu-manager",... | This should do it:
`sudo apt-get update; sudo apt-get install python-dev -y`
It will install any missing headers. It helped me a lot. |
Launch IPython notebook with selected browser | 15,632,663 | 20 | 2013-03-26T08:43:25Z | 15,633,541 | 7 | 2013-03-26T09:32:26Z | [
"python",
"windows",
"subprocess",
"ipython"
] | I am trying to start IPython with a non default browser (in my case Firefox)
and thought I could replicate the replicate the script given [in this blog](http://www.libertypages.com/clarktech/?p=3357)
**I am on Windows 7**
I put the following code in a file say "module.py"
```
import subprocess
subprocess.call("ipyth... | Why not use
```
--browser=<Unicode> (NotebookApp.browser)
Specify what command to use to invoke a web browser when opening the
notebook. If not specified, the default browser will be determined by the
`webbrowser` standard library module, which allows setting of the BROWSER
``` |
Launch IPython notebook with selected browser | 15,632,663 | 20 | 2013-03-26T08:43:25Z | 15,748,692 | 30 | 2013-04-01T17:54:31Z | [
"python",
"windows",
"subprocess",
"ipython"
] | I am trying to start IPython with a non default browser (in my case Firefox)
and thought I could replicate the replicate the script given [in this blog](http://www.libertypages.com/clarktech/?p=3357)
**I am on Windows 7**
I put the following code in a file say "module.py"
```
import subprocess
subprocess.call("ipyth... | I had the same problem on windows and got it work this way:
* Create a config file with command
`ipython profile create default`
* Edit ipython\_notebook\_config.py file, search for line
`#c.NotebookApp.browser =''`
and replace it with
```
import webbrowser
webbrowser.register('firefox', None, webbrowser.GenericB... |
Connect to an URI in postgres | 15,634,092 | 11 | 2013-03-26T09:58:20Z | 15,636,665 | 16 | 2013-03-26T12:05:05Z | [
"python",
"psycopg2"
] | I'm guessing this is a pretty basic question, but I can't figure out why:
```
import psycopg2
psycopg2.connect("postgresql://postgres:postgres@localhost/postgres")
```
Is giving the following error:
```
psycopg2.OperationalError: missing "=" after
"postgresql://postgres:postgres@localhost/postgres" in connection inf... | I would use the `urlparse` module to parse the url and then use the result in the connection method. This way it's possible to overcome the psycop2 problem.
```
import urlparse # import urllib.parse for python 3+
result = urlparse.urlparse("postgresql://postgres:postgres@localhost/postgres")
username = result.username... |
Python Groupby statement | 15,636,008 | 3 | 2013-03-26T11:33:15Z | 15,636,027 | 7 | 2013-03-26T11:33:56Z | [
"python",
"itertools"
] | I mam trying to group the following details list:
```
details = [('20130325','B'), ('20130320','A'), ('20130325','B'), ('20130320','A')]
>>for k,v in itertools.groupby(details,key=operator.itemgetter(0)):
>> print k,list(v)
```
And this is the output with the above groupby statement:
```
20130325 [('20130325', 'B'... | You have to sort your details first:
```
details.sort(key=operator.itemgetter(0))
```
or
```
fst = operator.itemgetter(0)
itertools.groupby(sorted(details, key=fst), key=fst)
```
Groupby groups consecutive matching records together.
[Documentation:](http://docs.python.org/2/library/itertools.html#itertools.groupby... |
django model object filter | 15,636,527 | 2 | 2013-03-26T11:57:37Z | 15,636,844 | 7 | 2013-03-26T12:14:44Z | [
"python",
"database",
"django",
"django-forms"
] | I have tables called 'has\_location' and 'locations'. 'has\_location' has `user_has` and `location_id` and its own `id` which is given by django itself.
'locations' have more columns.
Now I want to get all locations of some certain user. What I did is..(user.id is known):
```
users_locations_id = has_location.object... | Using `__in` for this kind of query is a common anti-pattern in Django: it's tempting because of its simplicity, but it scales poorly in most databases. See slides 66ff in [this presentation by Christophe Pettus](http://www.slideshare.net/OReillyOSCON/unbreaking-your-django-application).
You have a many-to-many relati... |
numpy.unique with order preserved | 15,637,336 | 15 | 2013-03-26T12:41:00Z | 15,637,489 | 12 | 2013-03-26T12:49:35Z | [
"python",
"numpy"
] | ```
['b','b','b','a','a','c','c']
```
numpy.unique gives
```
['a','b','c']
```
How can I get the original order preserved
```
['b','a','c']
```
---
Great answers. Bonus question. Why do none of these methods work with this dataset? <http://www.uploadmb.com/dw.php?id=1364341573> Here's the question [numpy sort wie... | Use the `return_index` functionality of `np.unique`. That returns the indices at which the elements first occurred in the input. Then `argsort` those indices.
```
>>> u, ind = np.unique(['b','b','b','a','a','c','c'], return_index=True)
>>> u[np.argsort(ind)]
array(['b', 'a', 'c'],
dtype='|S1')
``` |
numpy.unique with order preserved | 15,637,336 | 15 | 2013-03-26T12:41:00Z | 15,637,512 | 18 | 2013-03-26T12:50:33Z | [
"python",
"numpy"
] | ```
['b','b','b','a','a','c','c']
```
numpy.unique gives
```
['a','b','c']
```
How can I get the original order preserved
```
['b','a','c']
```
---
Great answers. Bonus question. Why do none of these methods work with this dataset? <http://www.uploadmb.com/dw.php?id=1364341573> Here's the question [numpy sort wie... | `unique()` is slow, O(Nlog(N)), but you can do this by following code:
```
import numpy as np
a = np.array(['b','a','b','b','d','a','a','c','c'])
_, idx = np.unique(a, return_index=True)
print a[np.sort(idx)]
```
output:
['b' 'a' 'd' 'c']
`Pandas.unique()` is much faster for big array O(N):
```
import pandas as pd... |
Unicode encoding/decoding | 15,637,419 | 3 | 2013-03-26T12:45:38Z | 15,637,448 | 11 | 2013-03-26T12:47:25Z | [
"python",
"unicode",
"utf-8"
] | I have a string that looks like this.
```
st = '/M\xe4rzen'
```
I would like to covert this to unicode. How can I do this? I've tried:
```
st.decode('utf-8')
unicode(t, 'utf-8')
```
The original file is utf-8 encoded, but I can't seem to get the unicode representation of the string. | Your data is not UTF8 encoded; more likely it is using the Latin-1 encoding:
```
>>> print st.decode('latin1')
/Märzen
```
Calling `.decode()` is enough, no need to *also* call `unicode()`. |
Socket.error: Invalid Argument supplied | 15,638,214 | 8 | 2013-03-26T13:26:20Z | 15,645,894 | 7 | 2013-03-26T19:35:50Z | [
"python",
"sockets"
] | I am learning networking programming and trying to grasp the basics of sockets through this example.
```
import socket,sys
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
MAX = 65535
PORT = 1060
if sys.argv[1:] == ['server']:
s.bind(('127.0.0.1',PORT))
print 'Listening at ' , s.getsockname()
while ... | Well I got the problem.The socket doesn't have an address untill its either binded or data is sent.
Just had to comment it out.
```
elif sys.argv[1:] == ['client']:
## print ' Address before sending ' ,s.getsockname()
```
Thanks |
Django forms.DateInput does not apply the attributes given in attrs field | 15,638,325 | 4 | 2013-03-26T13:31:34Z | 15,639,994 | 9 | 2013-03-26T14:46:23Z | [
"python",
"django",
"django-forms",
"django-1.4"
] | Placeholder, class not getting set when tried to apply through the django's attrs specifier for [forms.DateInput](https://docs.djangoproject.com/en/dev/ref/forms/widgets/#dateinput)
The form is a [ModelForm](https://docs.djangoproject.com/en/dev/topics/forms/modelforms/).
And according to the [docs](https://docs.djan... | Since you ~~didn't post your form code, my best guess is that you explicitly instantiated a form field like this~~ confirmed my guess by posting the code that looks roughly like this:
```
class MyForm(forms.ModelForm):
my_date_field = forms.DateField()
class Meta:
model = MyModel
widgets = {
... |
Is there a standard solution for Gauss elimination in Python? | 15,638,650 | 15 | 2013-03-26T13:46:04Z | 15,678,524 | 16 | 2013-03-28T09:43:44Z | [
"python",
"matrix",
"numpy"
] | Is there somewhere in the cosmos of `scipy/numpy/...` a standard method for Gauss-elimination of a matrix?
One finds many snippets via google, but I would prefer to use "trusted" modules if possible. | I finally found, that it can be done using **LU decomposition**. Here the **U** matrix represents the reduced form of the linear system.
```
from numpy import array
from scipy.linalg import lu
a = array([[2.,4.,4.,4.],[1.,2.,3.,3.],[1.,2.,2.,2.],[1.,4.,3.,4.]])
pl, u = lu(a, permute_l=True)
```
Then `u` reads
```
... |
Listing variables expected by a function in Python? | 15,638,706 | 2 | 2013-03-26T13:48:15Z | 15,638,720 | 9 | 2013-03-26T13:49:07Z | [
"python",
"function",
"variables",
"metaprogramming"
] | I am wondering if it is possible to list the variables expected by a Python function, prior to calling it, in order to pass the expected variables from a bigger dict containing a lot of variables.
I have searched the net but couldn't find anything. However, the python interpreter can show the list of expected variable... | You can use the [`inspect.getargspec()` function](http://docs.python.org/2/library/inspect.html#inspect.getargspec):
```
import inspect
argspec = inspect.getargspec(somefunction)
```
`argspec` is a named tuple with 4 elements:
* A list with the argument names
* The name of the catchall `*args` parameter, if defined... |
Is there a convention to distinguish Python integration tests from unit tests? | 15,639,265 | 23 | 2013-03-26T14:14:07Z | 15,881,638 | 16 | 2013-04-08T14:22:50Z | [
"python",
"unit-testing",
"integration-testing"
] | The most common way of structuring a Python package with unit tests is as follows:
```
package/
__init__.py
module_1.py
module_2.py
module_n.py
test/
__init__.py
test_module_1.py
test_module_2.py
test_module_n.py
```
I would like to distinguish between unit tests (o... | In our project we have unit tests inside each package, same as your case, and integration tests ,system tests, as a separate package on top level, i.e:
```
package_1/
__init__.py
module_1.py
module_n.py
test/
__init__.py
test_module_1.py
test_module_n.py
package_n/
__init__.py
module_1.py
mod... |
Why does multiprocessing use only a single core after I import numpy? | 15,639,779 | 81 | 2013-03-26T14:37:34Z | 15,641,148 | 87 | 2013-03-26T15:36:46Z | [
"python",
"linux",
"numpy",
"multiprocessing",
"blas"
] | I am not sure whether this counts more as an OS issue, but I thought I would ask here in case anyone has some insight from the Python end of things.
I've been trying to parallelise a CPU-heavy `for` loop using `joblib`, but I find that instead of each worker process being assigned to a different core, I end up with al... | After some more googling I found the answer [here](http://bugs.python.org/issue17038).
It turns out that certain Python modules (`numpy`, `scipy`, `tables`, `pandas`, `skimage`...) mess with core affinity on import. As far as I can tell, this problem seems to be specifically caused by them linking against multithreade... |
Why does multiprocessing use only a single core after I import numpy? | 15,639,779 | 81 | 2013-03-26T14:37:34Z | 31,370,840 | 8 | 2015-07-12T17:56:27Z | [
"python",
"linux",
"numpy",
"multiprocessing",
"blas"
] | I am not sure whether this counts more as an OS issue, but I thought I would ask here in case anyone has some insight from the Python end of things.
I've been trying to parallelise a CPU-heavy `for` loop using `joblib`, but I find that instead of each worker process being assigned to a different core, I end up with al... | Python 3 now exposes the [methods](https://docs.python.org/dev/library/os.html#os.sched_setaffinity) to directly set the affinity
```
>>> import os
>>> os.sched_getaffinity(0)
{0, 1, 2, 3}
>>> os.sched_setaffinity(0, {1, 3})
>>> os.sched_getaffinity(0)
{1, 3}
>>> x = {i for i in range(10)}
>>> x
{0, 1, 2, 3, 4, 5, 6, ... |
Python memory consumption: dict VS list of tuples | 15,641,344 | 14 | 2013-03-26T15:45:36Z | 15,641,471 | 16 | 2013-03-26T15:50:53Z | [
"python",
"list",
"dictionary",
"memory",
"tuples"
] | There are plenty of questions and discussion about memory consumption of different python data types. Yet few of them (if any) come to a very specific scenario. When you want to store LOTS of key-value data in memory, which data structure is more memory-efficient, a dict or a list of tuples?
At beginning I thought dic... | Your `list` of `tuple`s adds an extra layer. You have *3* layers of items:
* The outer list of length 1 million, so 1 million pointers
+ 1 million 2-slot tuples, so 2 million pointers
- 2 million references to 1 million integer values
while your `dict` only holds:
* The dict (including 1 million cached hashes)... |
How can I get a SQLAlchemy ORM object's previous state after a db update? | 15,642,286 | 3 | 2013-03-26T16:25:56Z | 15,671,586 | 8 | 2013-03-27T23:37:26Z | [
"python",
"orm",
"sqlalchemy",
"crud"
] | The issue is that I can't figure out how to use SQLAlchemy to notify me when an object goes into a new state.
I'm using SQLAlchemy ORM (Declarative) to update an object:
```
class Customer(declarative_base()):
__table_name__ = "customer"
id = Column(Integer, primary_key=True)
status = Column(String)
```... | My solution was to use 'after\_flush' SessionEvent instead of 'set' AttributeEvent.
Many thanks to [agronholm](http://stackoverflow.com/users/242021/agronholm) who provided [this example SessionEvent code](http://pastebin.com/CSxrpL64) that specifically checked an object's value and oldvalue.
The solution below is a ... |
reverse() argument after ** must be a mapping | 15,642,559 | 9 | 2013-03-26T16:38:03Z | 25,672,259 | 9 | 2014-09-04T18:07:44Z | [
"python",
"django",
"django-1.2"
] | I have an inscription form that doesnt work when submitting
I get this error :
**reverse() argument after \*\* must be a mapping, not str**
This is my view :
```
def inscription(request, seance_id):
seance = get_object_or_404(Variant, id=seance_id)
inscription_config = {'form_class': InscriptionForm,
... | I try to answer, since I had the same problem but didn't find an answer online.
I think the origin of this problem is a wrong `get_absolute_url(...)` method. For example, if you write it like this:
```
@models.permalink
def get_absolute_url(self):
return reverse('my_named_url', kwargs={ "pk": self.pk })
```
Then... |
Pythonic way of sorting a list | 15,643,865 | 3 | 2013-03-26T17:40:40Z | 15,643,892 | 13 | 2013-03-26T17:42:08Z | [
"python",
"sorting"
] | For example i would have a list of of
```
lists = ['jack 20', 'ben 10', 'alisdar 50', 'ollie 35']
```
and I would need to sort it so based on the number,
```
lists.sort() = ['ben 10', 'jack 20', 'ollie 35', 'alisdar 50']
```
Possible somehow use formatting with split()? | Use a `key` function:
```
lists.sort(key=lambda s: int(s.rsplit(None, 1)[-1]))
```
The `key` callable is passed each and every element in `lists` and that element is sorted according to the return value. In this case we
* split once on whitespace, starting on the right
* take the last element of the split
* turn tha... |
Best practices for Querying graphs by edge and node attributes in NetworkX | 15,644,684 | 8 | 2013-03-26T18:26:53Z | 15,651,795 | 16 | 2013-03-27T04:14:36Z | [
"python",
"networkx",
"igraph"
] | Using NetworkX, and new to the library, for a social network analysis query. By Query, I mean select/create subgraphs by attributes of both edges nodes where the edges create a path, and nodes contain attributes. The graph is using a MultiDiGraph of the form
```
G2 = nx.MultiDiGraph()
G2.add_node( "UserA", { "type" :"... | It's pretty straightforward to write a one-liner to make a list or generator of nodes with a specific property (generators shown here)
```
import networkx as nx
G = nx.Graph()
G.add_node(1, label='one')
G.add_node(2, label='fish')
G.add_node(3, label='two')
G.add_node(4, label='fish')
# method 1
fish = (n for n in G... |
How to read specific part of large file in Python | 15,644,859 | 5 | 2013-03-26T18:36:57Z | 15,644,885 | 10 | 2013-03-26T18:38:56Z | [
"python",
"parsing"
] | Given a large file (hundreds of MB) how would I use Python to quickly read the content between a specific start and end index within the file?
Essentially, I'm looking for a more efficient way of doing:
```
open(filename).read()[start_index:end_index]
``` | You can `seek` into the file the file and then read a certain amount from there. Seek allows you to get to a specific offset within a file, and then you can limit your read to only the number of bytes in that range.
```
with open(filename) as fin:
fin.seek(start_index)
data = fin.read(end_index - start_index)
... |
Python progress bar and downloads | 15,644,964 | 15 | 2013-03-26T18:43:06Z | 15,645,088 | 33 | 2013-03-26T18:50:52Z | [
"python",
"python-2.7"
] | I have a python script that launches a URL that is a downloadable file. Is there some way to have python use commandline to display the download progress as oppose to launching the browser? | Updated for your sample url:
I've just written a super simple (slightly hacky) approach to this for scraping pdfs off a certain site. Note, it only works correctly on unix based systems (linux, mac os) as powershell does not handle "\r"
```
link = "http://indy/abcde1245"
file_name = "download.data"
with open(file_nam... |
Python progress bar and downloads | 15,644,964 | 15 | 2013-03-26T18:43:06Z | 20,943,461 | 27 | 2014-01-06T05:19:15Z | [
"python",
"python-2.7"
] | I have a python script that launches a URL that is a downloadable file. Is there some way to have python use commandline to display the download progress as oppose to launching the browser? | You can use the '[clint](https://github.com/kennethreitz/clint)' package (written by the same author as 'requests') to add a simple progress bar to your downloads like this:
```
from clint.textui import progress
r = requests.get(url, stream=True)
path = '/some/path/for/file.txt'
with open(path, 'wb') as f:
total_... |
Copy the last three lines of a text file in python? | 15,647,467 | 3 | 2013-03-26T21:09:19Z | 15,647,823 | 7 | 2013-03-26T21:33:21Z | [
"python",
"list",
"text"
] | I'm new to python and the way it handles variables and arrays of variables in lists is quite alien to me. I would normally read a text file into a vector and then copy the last three into a new array/vector by determining the size of the vector and then looping with a for loop a copy function for the last size-three in... | To get the last three lines of a file efficiently, use `deque`:
```
from collections import deque
with open('somefile') as fin:
last3 = deque(fin, 3)
```
This saves reading the whole file into memory to slice off what you didn't actually want.
To reflect your comment - your complete code would be:
```
from col... |
"Flattening" a list of dictionaries | 15,647,690 | 12 | 2013-03-26T21:24:07Z | 15,647,716 | 17 | 2013-03-26T21:26:06Z | [
"python",
"dictionary"
] | So my aim is to go from:
```
fruitColourMapping = [{'apple': 'red'}, {'banana': 'yellow'}]
```
to
```
finalMap = {'apple': 'red', 'banana': 'yellow'}
```
A way I got is:
```
from itertools import chain
fruits = list(chain.from_iterable([d.keys() for d in fruitColourMapping]))
colour = list(chain.from_iterable([... | ```
finalMap = {}
for d in fruitColourMapping:
finalMap.update(d)
``` |
"Flattening" a list of dictionaries | 15,647,690 | 12 | 2013-03-26T21:24:07Z | 15,647,719 | 10 | 2013-03-26T21:26:15Z | [
"python",
"dictionary"
] | So my aim is to go from:
```
fruitColourMapping = [{'apple': 'red'}, {'banana': 'yellow'}]
```
to
```
finalMap = {'apple': 'red', 'banana': 'yellow'}
```
A way I got is:
```
from itertools import chain
fruits = list(chain.from_iterable([d.keys() for d in fruitColourMapping]))
colour = list(chain.from_iterable([... | Rather than deconstructing and reconstructing, just copy and update:
```
final_map = {}
for fruit_color_definition in fruit_color_mapping:
final_map.update(fruit_color_definition)
``` |
"Flattening" a list of dictionaries | 15,647,690 | 12 | 2013-03-26T21:24:07Z | 15,647,755 | 12 | 2013-03-26T21:28:41Z | [
"python",
"dictionary"
] | So my aim is to go from:
```
fruitColourMapping = [{'apple': 'red'}, {'banana': 'yellow'}]
```
to
```
finalMap = {'apple': 'red', 'banana': 'yellow'}
```
A way I got is:
```
from itertools import chain
fruits = list(chain.from_iterable([d.keys() for d in fruitColourMapping]))
colour = list(chain.from_iterable([... | ```
{k: v for d in fruitColourMapping for k, v in d.items()}
``` |
"Flattening" a list of dictionaries | 15,647,690 | 12 | 2013-03-26T21:24:07Z | 15,704,200 | 9 | 2013-03-29T13:25:58Z | [
"python",
"dictionary"
] | So my aim is to go from:
```
fruitColourMapping = [{'apple': 'red'}, {'banana': 'yellow'}]
```
to
```
finalMap = {'apple': 'red', 'banana': 'yellow'}
```
A way I got is:
```
from itertools import chain
fruits = list(chain.from_iterable([d.keys() for d in fruitColourMapping]))
colour = list(chain.from_iterable([... | ## Why copy at all?
In Python 3, you can use the new [`ChainMap`](http://docs.python.org/3.3/library/collections#collections.ChainMap):
> **A ChainMap groups multiple dicts (or other mappings) together to create a single, updateable view.**
> The underlying mappings are stored in a list. That list is public and
> c... |
How do you view the request headers that mechanize is using? | 15,648,272 | 3 | 2013-03-26T22:05:28Z | 15,663,033 | 9 | 2013-03-27T15:43:16Z | [
"python",
"web-scraping",
"mechanize"
] | I am attempting to submit some data to a form programatically. I'm having a small issue whereby the server is "not liking" what I'm sending it. Frustratingly, there is no error messages, or anything that could help diagnose the issue, all it does is spit me back to the same page I started on when I hit `br.submit()`.
... | Are you asking how to see what headers your browser or mechanize is sending?
---
**Browser**
Like the other commentators say you can check the headers sent by the browsers with a plugin like [Firebug](http://getfirebug.com) (Firefox), Developer tools (IE ['F12'](http://msdn.microsoft.com/en-gb/library/ie/gg589507%28... |
Alembic: alembic revision says Import Error | 15,648,284 | 9 | 2013-03-26T22:06:02Z | 15,769,215 | 12 | 2013-04-02T16:22:59Z | [
"python",
"flask",
"flask-sqlalchemy",
"alembic"
] | I am trying to integrate my `Flask` project with `Alembic`
My application structure looks like
```
project/
configuration/
__init__.py
dev.py
test.py
core/
# all source code
db/
migrations/
__init... | I did `export PYTHONPATH=<path_to_project>` and ran the command again and it ran successfully |
sqlalchemy.exc.ArgumentError: Can't load plugin: sqlalchemy.dialects:driver | 15,648,814 | 12 | 2013-03-26T22:44:13Z | 15,664,644 | 21 | 2013-03-27T16:51:56Z | [
"python",
"sqlalchemy",
"psycopg2",
"alembic"
] | I am trying to run `alembic` migration and when I run
```
alembic revision --autogenerate -m "Added initial tables"
```
It fails saying
```
sqlalchemy.exc.ArgumentError: Can't load plugin: sqlalchemy.dialects:driver
```
the database url is
```
postgresql+psycopg2://dev:passwd@localhost/db
```
and I even have `psy... | Here's how to produce an error like that:
```
>>> from sqlalchemy import *
>>> create_engine("driver://")
Traceback (most recent call last):
... etc
sqlalchemy.exc.ArgumentError: Can't load plugin: sqlalchemy.dialects:driver
```
so I'd say you aren't actually using the postgresql URL you think you are - you probably ... |
xlwt write excel sheet on the fly | 15,649,034 | 7 | 2013-03-26T23:02:57Z | 15,649,139 | 13 | 2013-03-26T23:13:17Z | [
"python",
"xlwt"
] | I am used to creating a spreadsheet in the following way:
```
wbk = xlwt.Workbook()
earnings_tab = wbk.add_sheet('EARNINGS')
wbk.save(filepath)
```
Is there any way to not save to file to a filepath, and instead write it on-the-fly to a user who downloads the file? Or do I need to save it as a tmp file an... | To quote [the documentation for the `.save()` method of `xlwt`](https://xlwt.readthedocs.org/en/latest/api.html?highlight=save#xlwt.Workbook.Workbook.save):
> It can also be a stream object with a write method, such as a
> `StringIO`, in which case the data for the excel file is written to the
> stream.
Modified exam... |
Sub matrix of a list of lists (without numpy) | 15,650,538 | 6 | 2013-03-27T01:36:52Z | 15,650,623 | 9 | 2013-03-27T01:46:15Z | [
"python",
"matrix",
"python-3.x"
] | Suppose I have a matrix composed of a list of lists like so:
```
>>> LoL=[list(range(10)) for i in range(10)]
>>> LoL
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2... | ```
In [74]: [row[2:5] for row in LoL[1:4]]
Out[74]: [[2, 3, 4], [2, 3, 4], [2, 3, 4]]
```
---
You could also mimic NumPy's syntax by defining a subclass of `list`:
```
class LoL(list):
def __init__(self, *args):
list.__init__(self, *args)
def __getitem__(self, item):
try:
return ... |
Returning from __len__() when >64 bits | 15,650,878 | 12 | 2013-03-27T02:20:01Z | 15,651,299 | 13 | 2013-03-27T03:12:48Z | [
"python",
"ipv6",
"long-integer"
] | In this problem, I'm dealing with IPv6 network address spaces, so the length is `2^(128-subnet)`.
It appears that python (at least on this machine), will cope with up to a 64 bit signed number as the return value from `__len__()`. So `len(IP('2001::/66'))` works, but `len(IP('2001::/65'))` fails.
```
from IPy import ... | The issue you're hitting is that Python's C API has a system-dependent limit on the lengths of containers. That is, the C function `PyObject_Size` returns a `Py_ssize_t` value, which is a signed version of the standard C `size_t` type. It's size is system dependent, but probably 32-bits on 32-bit systems and 64-bits on... |
Put a gap/break in a line plot | 15,652,503 | 8 | 2013-03-27T05:32:05Z | 15,663,252 | 10 | 2013-03-27T15:53:00Z | [
"python",
"matplotlib"
] | I have a data set with effectively "continuous" sensor readings, with the occasional gap.
However there are several periods in which no data was recorded. These gaps are significantly longer than the sample period.
By default, pyplot connects each data point to the next (if I have a line style set), however I feel th... | Masked arrays work well for this. You just need to mask the first of the points you don't want to connect:
```
import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt
t1 = np.arange(0, 8, 0.05)
mask_start = len(t1)
t2 = np.arange(10, 14, 0.05)
t = np.concatenate([t1, t2])
c = np.cos(t) # an aside... |
how to create a python socket listner deamon | 15,652,791 | 2 | 2013-03-27T06:03:13Z | 15,652,969 | 7 | 2013-03-27T06:21:25Z | [
"python",
"network-programming",
"daemon"
] | i would like to know how to create a deamon that listens for a post request. i found this code to create a deamon on this [link](http://code.activestate.com/recipes/278731/) but i didn't know how to fill it.
im sending commandes from an android phone to a php server over json that redirects it to python that can commun... | If you have to write a daemon, you definitely want to use [`python-daemon`](https://pypi.python.org/pypi/python-daemon/), as it's the reference implementation of [PEP 3143](http://www.python.org/dev/peps/pep-3143). There are a ton of little things you have to get right.
If you have to write a server, and have never do... |
Ignore KeyError and continue program | 15,653,966 | 4 | 2013-03-27T07:48:34Z | 15,653,995 | 11 | 2013-03-27T07:50:35Z | [
"python",
"dictionary",
"python-3.x"
] | In Python 3 I have a program coded as below. It basically takes an input from a user and checks it against a dictionary (EXCHANGE\_DATA) and outputs a list of information.
```
from shares import EXCHANGE_DATA
portfolio_str=input("Please list portfolio: ")
portfolio_str= portfolio_str.replace(' ','')
portfolio_str= por... | Why not:
```
for code in portfolio_list:
try:
share_name, share_value = EXCHANGE_DATA[code]
print('{:<6} {:<20} {:>8.2f}'.format(code, share_name, share_value)
except KeyError:
continue
```
OR check dict.get method:
```
for code in portfolio_list:
res = EXCHANGE_DATA.ge... |
I am using Python3 and I want to use RabbitMQ | 15,655,189 | 8 | 2013-03-27T09:13:06Z | 16,738,270 | 7 | 2013-05-24T15:13:21Z | [
"python",
"python-3.x",
"rabbitmq"
] | I am using Python3 and I want to use RabbitMQ. I already tried to use Pika, and txAMQP but they do not support Python 3. Have anybody an idea how I can use RabbitMQ. | Check this page <https://github.com/hollobon/pika-python3>
May be it can help you. |
Performance between "from package import *" and "import package" | 15,655,224 | 6 | 2013-03-27T09:14:46Z | 15,655,265 | 14 | 2013-03-27T09:17:34Z | [
"python",
"performance",
"import"
] | Is there any performance difference between "from package import \*" and "import package"? | No, the difference is not a question of performance. In both cases, the entire module must be parsed, and any module-level code will be executed. The only difference is in namespaces: in the first, all the names in the imported module will become names in the current module; in the second, only the package name is defi... |
Replace all words from word list with another string in python | 15,658,187 | 4 | 2013-03-27T11:56:13Z | 15,658,331 | 10 | 2013-03-27T12:03:13Z | [
"python",
"text",
"for-loop",
"replace"
] | I have a user entered string and I want to search it and replace any occurrences of a list of words with my replacement string.
```
import re
prohibitedWords = ["MVGame","Kappa","DatSheffy","DansGame","BrainSlug","SwiftRage","Kreygasm","ArsonNoSexy","GingerPower","Poooound","TooSpicy"]
# word[1] contains the user e... | You can do that with a single call to `sub`:
```
big_regex = re.compile('|'.join(map(re.escape, prohibitedWords)))
the_message = big_regex.sub("repl-string", str(word[1]))
```
Example:
```
>>> import re
>>> prohibitedWords = ['Some', 'Random', 'Words']
>>> big_regex = re.compile('|'.join(map(re.escape, prohibitedWor... |
universal method for working with currency with no rounding, two decimal places, and thousands separators | 15,658,925 | 3 | 2013-03-27T12:35:28Z | 15,661,699 | 8 | 2013-03-27T14:42:17Z | [
"python",
"python-2.7",
"currency-formatting"
] | i am a newbie learning python (2.7.3) and was given a simple exercise calculating costs but soon became interested in really being able to control or understand the 'exactness' of the results that were being produced. if i use the calculator on my computer i get the results i think i am after (ie they seem very specifi... | Use the [`format()` function](http://docs.python.org/2/library/functions.html#format) to format `float` or `Decimal` types:
```
format(value, ',.2f')
```
which results in:
```
>>> format(12345.678, ',.2f')
'12,345.68'
```
The `,` adds a comma as a thousands separator in the output.
You generally do *not* want to i... |
Alembic --autogenerate producing empty migration | 15,660,676 | 12 | 2013-03-27T13:57:08Z | 15,668,175 | 11 | 2013-03-27T19:53:25Z | [
"python",
"migration",
"flask",
"flask-sqlalchemy",
"alembic"
] | I am trying to use `Alembic` for the first time and want to use `--autogenerate` feature described [here](http://alembic.readthedocs.org/en/latest/tutorial.html#auto-generating-migrations)
My project structure looks like
```
project/
configuration/
__init__.py
dev.py
... | As per @zzzeek, after I included the following in my `env.py`, I was able to work with `--autogenerate` option
in `env.py` under `run_migrations_online()`
```
from configuration import app
from core.expense.models import user # added my model here
alembic_config = config.get_section(config.config_ini_section)
alembi... |
Python: most efficient way to convert date to datetime | 15,661,013 | 5 | 2013-03-27T14:11:25Z | 15,661,036 | 11 | 2013-03-27T14:12:12Z | [
"python",
"datetime",
"python-datetime"
] | In Python, I convert a `date` to `datetime` by:
1. converting from `date` to `string`
2. converting from `string` to `datetime`
Code:
```
import datetime
dt_format="%d%m%Y"
my_date = datetime.date.today()
datetime.datetime.strptime(my_date.strftime(dt_format), dt_format)
```
I suspect this is far from the most effi... | Use [`datetime.datetime.combine()`](http://docs.python.org/2/library/datetime.html#datetime.datetime.combine) with a time object, `datetime.time.min` represents `00:00` and would match the output of your date-string-datetime path:
```
datetime.datetime.combine(my_date, datetime.time.min)
```
Demo:
```
>>> import dat... |
Python does not see pygraphviz | 15,661,384 | 16 | 2013-03-27T14:28:21Z | 15,667,958 | 52 | 2013-03-27T19:40:52Z | [
"python",
"install",
"pygraphviz"
] | I have installed pygraphviz using easy\_install
But when i launch python i have an error:
```
>>>import pygraphviz as pgv
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named pygraphviz
>>>
```
Using Ubuntu 12.04 and gnome-terminal. | Assuming that you're on Ubuntu please look at following steps
1. `sudo apt-get install graphviz libgraphviz-dev pkg-config`
2. Create and activate [virtualenv](http://www.clemesha.org/blog/modern-python-hacker-tools-virtualenv-fabric-pip/) if needed. The commands looks something like `sudo apt-get install python-pip p... |
Python does not see pygraphviz | 15,661,384 | 16 | 2013-03-27T14:28:21Z | 17,456,678 | 7 | 2013-07-03T19:35:48Z | [
"python",
"install",
"pygraphviz"
] | I have installed pygraphviz using easy\_install
But when i launch python i have an error:
```
>>>import pygraphviz as pgv
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named pygraphviz
>>>
```
Using Ubuntu 12.04 and gnome-terminal. | The quick and easy solution is:
```
sudo apt-get install -y python-pygraphviz
```
using pip will also work, but make sure you have graphviz, libgraphviz-dev, and pkg-config already installed.
```
sudo apt-get install -y graphviz libgraphviz-dev pkg-config python-pip
sudo pip install pygraphviz
``` |
How to cleanly keep below 80-char width with long strings? | 15,664,101 | 20 | 2013-03-27T16:28:04Z | 15,664,124 | 36 | 2013-03-27T16:28:54Z | [
"python",
"coding-style",
"readability",
"code-readability"
] | I'm attempting to keep my code to 80 chars or less nowadays as I think it looks more aesthetically pleasing, for the most part. Sometimes, though, the code ends up looking worse if I have to put line breaks in weird places.
One thing I haven't figured out how to handle very nicely yet is long strings. For example:
``... | You can split the string into two:
```
def foo():
if conditional():
logger.info("<Conditional's meaning> happened, so we're not "
"setting up the interface.")
```
Multiple consecutive strings within the same expression are automatically [concatenated into one, at compile time](http://d... |
subprocess.Popen in Threads | 15,665,582 | 3 | 2013-03-27T17:34:51Z | 15,665,726 | 7 | 2013-03-27T17:42:22Z | [
"python",
"multithreading",
"subprocess"
] | I have a number of files (over 4000) that I want to simultaneously load into PostgreSQL. I have separated them into 4 different file lists and I want a thread to iterate through each list loading the data.
The problem I have is that is I use os.system to call the loading program but this prevents the other threads fro... | * [Don't repeat yourself](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself). One `threadLoad` method suffices. That way, if you need to modify something in the method you do not need to make the same modification in 4 different places.
* Use `run.communicate()` to block until the subprocess is done.
* This starts o... |
Adding to the end of a line in Python | 15,665,880 | 3 | 2013-03-27T17:50:32Z | 15,665,908 | 7 | 2013-03-27T17:51:53Z | [
"python",
"line",
"add"
] | I want to add some letters to the beginning and end of each line using python.
I found various methods of doing this, however, whichever method I use the letters I want to add to then end are always added to the beginning.
```
input = open("input_file",'r')
output = open("output_file",'w')
for line in input:
new... | When reading lines from a file, python leaves the `\n` on the end. You could `.rstrip` it off however.
```
yourstring = 'L{0}LL\n'.format(yourstring.rstrip('\n'))
``` |
Komodo Edit disable autocomple | 15,666,599 | 7 | 2013-03-27T18:27:22Z | 15,666,887 | 13 | 2013-03-27T18:42:20Z | [
"python",
"autocomplete",
"komodo"
] | I am using Komodo Edit 8 and its autocomplete feature is totally annoying.
As soon as I type **"for i"** , it autofills in this:
```
for i in range:
code
```
Now i have to delete it manually to continue typing. I tried to turn off **"Enable automatic autocomplete and calltips triggering when you type"** from **Edit... | Try this:
> Edit > Preferences > Smart Editing > Auto-Abbreviation > **Uncheck** "Enable Auto-Abbreviation with Trigger Characters" |
sys.stdin does not close on ctrl-d | 15,666,923 | 4 | 2013-03-27T18:44:30Z | 15,668,800 | 11 | 2013-03-27T20:29:44Z | [
"python",
"linux",
"command-line",
"eof"
] | I have the following code in program.py:
```
from sys import stdin
for line in stdin:
print line
```
I run, enter lines, and then press `Ctrl`+`D`, but the program does not exit.
This does work:
```
$ printf "echo" | python program.py
```
Why does the program not exit when I press `Ctrl`+`d`?
I am using the Fe... | `Ctrl`+`D` has a strange effect. It doesn't close the input stream, but only causes a C-level `fread()` to return an empty result. For regular files such a result means that the file is now at its end, but it's acceptable to read more, e.g. to check if someone else wrote more data to the file in the meantime.
In addit... |
What does id( ) function used for? | 15,667,189 | 29 | 2013-03-27T18:58:15Z | 15,667,224 | 16 | 2013-03-27T18:59:55Z | [
"python"
] | I read the [doc](http://docs.python.org/2/library/functions.html#id) and saw this `id( )` function.
What the doc said:
> Return the âidentityâ of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping life... | That's the identity of the **location** of the object in memory...
This example might help you understand the concept a little more.
```
foo = 1
bar = foo
baz = bar
fii = 1
print id(foo)
print id(bar)
print id(baz)
print id(fii)
> 1532352
> 1532352
> 1532352
> 1532352
```
These all point to the same location in me... |
What does id( ) function used for? | 15,667,189 | 29 | 2013-03-27T18:58:15Z | 15,667,328 | 48 | 2013-03-27T19:05:37Z | [
"python"
] | I read the [doc](http://docs.python.org/2/library/functions.html#id) and saw this `id( )` function.
What the doc said:
> Return the âidentityâ of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping life... | Your post asks several questions:
> What is the number returned from the function ?
It is "*an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime.*" [(Python Standard Library - Built-in Functions)](https://docs.python.org/2/library/functions.html#id) A unique n... |
How do I install Mezzanine as a Django app? | 15,667,578 | 12 | 2013-03-27T19:19:41Z | 27,972,009 | 7 | 2015-01-15T20:02:41Z | [
"python",
"django",
"mezzanine"
] | I already have an existing Django website. I have added a new url route '/blog/' where I would like to have a Mezzanine blog. If it possible to installed Mezzanine as an app in an existing Django site as opposed to a standalone blog application. | If youre like me, you'll find that the FAQ is sorely lacking in it's description of how to get Mezzanine working as an app. So here's what I did (after a painful half day of hacking) to get it integrated (somewhat):
1. Download the repo and copy it into your project
2. Run setup.py for the package
3. `cd` to the packa... |
TypeError - Classes in Python | 15,668,246 | 4 | 2013-03-27T19:58:14Z | 15,668,277 | 7 | 2013-03-27T20:00:10Z | [
"python",
"class",
"typeerror"
] | I'm a beginner at Python just getting to grips with classes. I'm sure it's probably something very basic, but why does this code:
```
class Television():
def __init__(self):
print('Welcome your TV.')
self.volume = 10
self.channel = 1
def channel(self, channel):
self.channel = in... | You assign a `channel` attribute in your `__init__`:
```
self.channel = 1
```
This shadows the `channel()` method on the class. Rename the attribute or the method.
Attributes on the instance trump those on the class (except for data descriptors; think `property`s). From the [Class definitions documentation](http://d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.