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 |
|---|---|---|---|---|---|---|---|---|---|
python: how to have a dictionary which can be accessed from all the app | 11,013,911 | 3 | 2012-06-13T11:28:11Z | 11,014,019 | 7 | 2012-06-13T11:35:17Z | [
"python",
"google-app-engine",
"python-2.7"
] | I am new to Python and have been studying its fundementals for 3 months now, learning types, functions and algorithms. Now I started practiciging web app development with GAE framework.
Goal: have a very large dictionary, which can be accessed from all .py files throughout the web app without having it stored more tha... | Use the [memcache](https://developers.google.com/appengine/docs/python/memcache/usingmemcache). You can store a pickled dict in the memcache, but you could also just store the keys/values directly in memcache. Write a wrapper class that ensures loading of the values from the data store if they are not already in memcac... |
Django models and Python properties | 11,014,138 | 7 | 2012-06-13T11:43:44Z | 11,025,419 | 11 | 2012-06-14T01:00:16Z | [
"python",
"django",
"django-models"
] | I've tried to set up a Django model with a python property, like so:
```
class Post(models.Model):
_summary = models.TextField(blank=True)
body = models.TextField()
@property
def summary(self):
if self._summary:
return self._summary
else:
return self.body
@... | Unfortunately, Django models don't play very nice with Python properties. The way it works, the ORM only recognizes the names of field instances in QuerySet filters.
You won't be able to refer to `summary` in your filters, instead you'll have to use `_summary`. This gets messy real quick, for example to refer to this ... |
How to create a TRIE in Python | 11,015,320 | 59 | 2012-06-13T12:56:13Z | 11,016,430 | 77 | 2012-06-13T13:56:08Z | [
"python",
"python-2.7",
"trie"
] | I am new to Python and trying to learn and advance. I am interested in TRIEs and DAWGs and I have been reading a lot about it but I don't understand what should the output TRIE or DAWG file look like.
* Should a TRIE be an object of nested dictionaries? Where each letter
is divided in to letters and so on?
* Would a... | [Unwind](http://stackoverflow.com/a/11015381/577088) is essentially correct that there are many different ways to implement a trie; and for a large, scalable trie, nested dictionaries might become cumbersome -- or at least space inefficient. But since you're just getting started, I think that's the easiest approach; yo... |
How to create a TRIE in Python | 11,015,320 | 59 | 2012-06-13T12:56:13Z | 12,913,605 | 16 | 2012-10-16T11:22:37Z | [
"python",
"python-2.7",
"trie"
] | I am new to Python and trying to learn and advance. I am interested in TRIEs and DAWGs and I have been reading a lot about it but I don't understand what should the output TRIE or DAWG file look like.
* Should a TRIE be an object of nested dictionaries? Where each letter
is divided in to letters and so on?
* Would a... | Have a look at this:
<https://github.com/kmike/marisa-trie>
> Static memory-efficient Trie structures for Python (2.x and 3.x).
>
> String data in a MARISA-trie may take up to 50x-100x less memory than
> in a standard Python dict; the raw lookup speed is comparable; trie
> also provides fast advanced methods like pre... |
How to create a TRIE in Python | 11,015,320 | 59 | 2012-06-13T12:56:13Z | 21,303,098 | 9 | 2014-01-23T08:36:11Z | [
"python",
"python-2.7",
"trie"
] | I am new to Python and trying to learn and advance. I am interested in TRIEs and DAWGs and I have been reading a lot about it but I don't understand what should the output TRIE or DAWG file look like.
* Should a TRIE be an object of nested dictionaries? Where each letter
is divided in to letters and so on?
* Would a... | Here is a list of python packages that implement Trie:
* [marisa-trie](https://pypi.python.org/pypi/marisa-trie/) - a C++ based implementation.
* [python-trie](https://github.com/bdimmick/python-trie) - a simple pure python implementation.
* [PyTrie](https://pypi.python.org/pypi/PyTrie) - a more advanced pure python i... |
pip fails to install packages from requirements.txt | 11,015,692 | 14 | 2012-06-13T13:17:39Z | 11,015,904 | 13 | 2012-06-13T13:29:10Z | [
"python",
"package",
"pip"
] | I am trying to install a python software using the requirements file.
```
>> cat requirements.txt
Cython==0.15.1
numpy==1.6.1
distribute==0.6.24
logilab-astng==0.23.1logilab-common==0.57.1
netaddr==0.7.6
numexpr==2.0.1
ply==2.5
pycallgraph==0.5.1
pyflowtools==0.3.4.1
pylint==0.25.1
tables==2.3.1
wsgiref==0.1.2
```
So... | It looks like the `numexpr` package has an install-time dependency on numpy. Pip makes two passes through your requirements: first it downloads all packages and runs each one's `setup.py` to get its metadata, and then it installs them all in a second pass.
So, numexpr is trying to import from numpy in its setup.py, bu... |
Push an element to an array if it is not present (no duplicates) | 11,016,767 | 4 | 2012-06-13T14:13:52Z | 11,016,979 | 9 | 2012-06-13T14:25:03Z | [
"python",
"mongodb"
] | I have an event collection which I'm going through to find a category to the specific event and then I'm updating my other collection using a $push statement. The problem is that when two events have the same category it'll create a duplicate, which I don't want.
I know about upserts but I am unsure if they are the be... | Send through the third argument on your update as true as per the [MongoDB Docs](http://www.mongodb.org/display/DOCS/Updating) and [PyMongo Docs](http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update).
```
self.users.update({"user_id": event['userid']}, {'$push': {'camp... |
Push an element to an array if it is not present (no duplicates) | 11,016,767 | 4 | 2012-06-13T14:13:52Z | 11,080,804 | 8 | 2012-06-18T10:14:17Z | [
"python",
"mongodb"
] | I have an event collection which I'm going through to find a category to the specific event and then I'm updating my other collection using a $push statement. The problem is that when two events have the same category it'll create a duplicate, which I don't want.
I know about upserts but I am unsure if they are the be... | Found a better answer to my problem:
By using $addToSet it didn't create duplicates (I also made sure no duplicates where made before by adding all dictionaries to a list):
```
self.users.update({"user_id": event['userid']}, {'$addToSet': {'campaigns': UserCampaigns[i]}})
```
If I just had used $push it would always... |
Should internal class methods returnvalues or just modify instance variables in python? | 11,017,364 | 13 | 2012-06-13T14:42:43Z | 11,017,501 | 8 | 2012-06-13T14:49:10Z | [
"python",
"oop",
"design",
"instance-variables"
] | I am creating a query builder class that will help in constructing a query for mongodb from URL params. I have never done much object oriented programming, or designed classes for consumption by people other than myself, besides using basic language constructs and using django's built in Models.
So I have this `QueryB... | It's perfectly fine to modify `self.query_dict` as the whole idea of object-oriented programming is that methods can modify an object's state. As long as an object is in a consistent state after a method has finished, you're fine. The fact that `_build_query` is an internal method does not matter. You can choose to cal... |
flask return image created from database | 11,017,466 | 26 | 2012-06-13T14:47:09Z | 11,017,839 | 47 | 2012-06-13T15:05:04Z | [
"python",
"binary",
"flask"
] | my images are stored in MongoDB, I'd like to return them to the client, here is how the code is like:
```
@app.route("/images/<int:pid>.jpg")
def getImage(pid):
# get image binary from MongoDB, which is bson.Binary type
return image_binary
```
However, it seems that I can't return binary directly in Flask?
H... | Setting the correct headers should do the trick:
```
@app.route("/images/<int:pid>.jpg")
def getImage(pid):
response = make_response(image_binary)
response.headers['Content-Type'] = 'image/jpeg'
response.headers['Content-Disposition'] = 'attachment; filename=img.jpg'
return response
```
Relevant: [wer... |
flask return image created from database | 11,017,466 | 26 | 2012-06-13T14:47:09Z | 25,150,805 | 17 | 2014-08-06T01:10:09Z | [
"python",
"binary",
"flask"
] | my images are stored in MongoDB, I'd like to return them to the client, here is how the code is like:
```
@app.route("/images/<int:pid>.jpg")
def getImage(pid):
# get image binary from MongoDB, which is bson.Binary type
return image_binary
```
However, it seems that I can't return binary directly in Flask?
H... | Just wanted to confirm that dav1d's second suggestion is correct - I tested this (where obj.logo is a mongoengine ImageField), works fine for me:
```
import io
from flask import current_app as app
from flask import send_file
from myproject import Obj
@app.route('/logo.png')
def logo():
"""Serves the logo image.... |
How to run gevent in production | 11,017,699 | 15 | 2012-06-13T14:58:26Z | 11,755,083 | 20 | 2012-08-01T08:07:09Z | [
"python",
"gevent",
"gunicorn"
] | I am making use of gevent in my Python application (Django based). However, I am now wondering how to run it in production. What server should I use? During development, I use gevent.pywsgi, but is that production-ready? I have also heard about gunicorn, but I've seen some pretty [bad benchmarks](http://nichol.as/bench... | [Gunicorn](http://gunicorn.org/) is really the best option. It's fast, it's written in pure python (which makes it easy to deploy on hosted services like [Heroku](http://www.heroku.com/)), and it's well maintained and used for a large amount of Python web applications.
By default, Gunicorn uses a synchronous worker cl... |
python: print using carriage return and comma not working | 11,018,188 | 10 | 2012-06-13T15:24:03Z | 11,018,255 | 12 | 2012-06-13T15:27:15Z | [
"python",
"newline",
"carriage-return"
] | I need to print over one line in a loop (Python 3.x). Looking around on SO already, I put this line in my code:
```
print('{0} imported\r'.format(tot),)
```
However, it still prints multiple lines when looped through. I have also tried
```
sys.stdout.write('{0} imported\r'.format(tot))
```
but this doesn't print **... | In the first case, some systems will treat `\r` as a newline. In the second case, you didn't `flush` the line. Try this:
```
sys.stdout.write('{0} imported\r'.format(tot))
sys.stdout.flush()
```
Flushing the line isn't necessary on all systems either, as Levon reminds me -- but it's generally a good idea when using `... |
Plotting a masked surface plot using python, numpy and matplotlib | 11,020,160 | 8 | 2012-06-13T17:25:28Z | 11,038,838 | 12 | 2012-06-14T18:06:52Z | [
"python",
"numpy",
"matplotlib"
] | I'm plotting a surface using matplotlib 1.1.0.
The plot Z axis is masked like so:
```
Zm = ma.masked_where((abs(z_grid) < 1.09) & (abs(z_grid) > 0.91), (z_surface))
surf = ax.plot_surface(X, Y,Zm, rstride=2, cstride=2, cmap=colors,linewidth=0, antialiased=False)
```
But I'm not seeing the mask applied on the plot. I... | Fraxel mentioned that surface\_plot doesn't support masking. In order to get around the issue, this is what I did:
I basically manually masked the z axis data by setting every masked value to numpy.nan like so:
```
Zm = ma.masked_where((abs(z_grid) < 1.02) & (abs(z_grid) > 0.98), (z_surface))
z_surface[where(ma.getma... |
Using flask extensions in flask blueprints | 11,020,170 | 7 | 2012-06-13T17:25:47Z | 11,027,030 | 24 | 2012-06-14T05:15:10Z | [
"python",
"flask"
] | I want to create a blueprint; not an issue with the current blueprint I have. I can do this.
But, say I wanted to use a flask extension in my application (for my case I want to integrate flask-Cache)?
Everything I've done so far has errored:
* cache = Cache(my\_blueprint)
* importing Cache and various parts of Cache... | In order to avoid circular imports you will want to create your cache instance separate from your application instance (you may want to consider switching to the app factory module if you are building something more complex).
**cache.py**
```
from flask.ext.cache import Cache
cache = Cache()
```
**foo.py**
```
fro... |
Initializing empty Python data structures | 11,020,657 | 12 | 2012-06-13T18:00:08Z | 11,020,698 | 20 | 2012-06-13T18:03:00Z | [
"python",
"list",
"dictionary"
] | Is there any tangible difference between the two forms of syntax available for creating empty Python lists/dictionaries, i.e.
```
l = list()
l = []
```
and:
```
d = dict()
d = {}
```
I'm wondering if using one is preferable over the other. | The function form calls the constructor at runtime to return a new instance, whereas the literal form causes the compiler to "create" it (really, to emit bytecode that results in a new object) at compile time. The former can be useful if (for some reason) the classes have been locally rebound to different types.
```
>... |
How do I get a "debug" variable in my Django template context? | 11,020,663 | 12 | 2012-06-13T18:00:31Z | 11,020,825 | 18 | 2012-06-13T18:10:19Z | [
"python",
"django",
"django-templates"
] | According to this SO post:
[How to check the TEMPLATE\_DEBUG flag in a django template?](http://stackoverflow.com/questions/1271631/how-to-check-the-template-debug-flag-in-a-django-template)
if:
* A) my settings.py file has:
`TEMPLATE_CONTEXT_PROCESSORS = ['django.core.context_processors.debug',...`
* and B) I use... | You also need to ensure the request's IP address is in the `INTERNAL_IPS` in your settings (which you probably don't have set): <https://docs.djangoproject.com/en/1.4/ref/templates/api/#django-core-context-processors-debug> |
Webcam stream and OpenCV - python | 11,021,047 | 8 | 2012-06-13T18:24:49Z | 11,022,050 | 21 | 2012-06-13T19:32:04Z | [
"python",
"opencv",
"webcam"
] | I want to get the video stream from my webcam using python and OpenCV, for that task i've implemented this simple code:
```
import cv
cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)
capture = cv.CaptureFromCAM(0)
def repeat():
frame = cv.QueryFrame(capture)
cv.ShowImage("w1", frame)
while True:
repeat()
```
whe... | You need to add `waitkey` function at end.
Below piece of code works fine for me.
```
import cv
cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)
capture = cv.CaptureFromCAM(0)
def repeat():
frame = cv.QueryFrame(capture)
cv.ShowImage("w1", frame)
while True:
repeat()
if cv.WaitKey(33)==27:
break
... |
Parallel Pip install | 11,021,130 | 11 | 2012-06-13T18:30:39Z | 11,021,329 | 7 | 2012-06-13T18:43:37Z | [
"python",
"parallel-processing",
"pip"
] | Our Django project is getting huge. We have hundreds of apps and use a ton of 3rd party python packages, many of which need to have C compiled. Our deployments are taking a long time when we need to create a new virtual environment for major releases. With that said, I'm looking to speed things up, starting with Pip. D... | Have you analyzed the deployment process to see where the time really goes? It surprises me that running multiple parallel pip processes does not speed it up much.
If the time goes to querying PyPI and finding the packages (in particular when you also download from Github and other sources) then it may be beneficial t... |
Tuple unpack in assignment | 11,021,185 | 3 | 2012-06-13T18:34:01Z | 11,021,215 | 8 | 2012-06-13T18:36:17Z | [
"python",
"tuples",
"iterable-unpacking"
] | I would like to unpack a tuple in a python statement like so:
```
a = 5, *(6,7)
```
but this raises a `SyntaxError`. What is the cleanest way to achieve something like this?
The best I've come up with so far is:
```
a = tuple([5]+list((6,7)))
``` | You can just concatenate the tuples directly:
```
>>> a = (5,)+(6, 7)
>>> a
(5, 6, 7)
``` |
SSL error after python/django fork | 11,021,560 | 3 | 2012-06-13T18:58:26Z | 11,021,637 | 7 | 2012-06-13T19:04:15Z | [
"python",
"database",
"django",
"postgresql",
"fork"
] | I've got a python django app where part of it is parsing a large file. This takes forever, so I put a fork in to deal with the processing, allowing the user to continue to browse the site. Within the fork code, there's a bunch of calls to our postgres database, hosted on amazon.
I'm getting the following error:
```
S... | Forking while holding a socket open (such as a database connection) is generally not safe, as both processes will end up trying to use the same socket at once.
You will need, at a minimum, to close and reopen the database connection after forking.
Ideally, though, this is probably better suited for a task queueing sy... |
Multiple directories and/or subdirectories in IPython Notebook session? | 11,021,853 | 30 | 2012-06-13T19:19:51Z | 11,025,306 | 20 | 2012-06-14T00:37:53Z | [
"python",
"ipython",
"directory",
"subdirectories"
] | The IPython documentation pages suggest that opening several different sessions of IPython notebook is the only way to interact with saved notebooks in different directories or subdirectories, but this is not explicitly confirmed anywhere.
I am facing a situation where I might need to interact with hundreds of differe... | > The IPython documentation pages suggest that opening several different sessions of IPython notebook is the only way to interact with saved notebooks in different directories or subdirectories, but this is not explicitly confirmed anywhere.
Yes, this is a current (*temporary*) limitation of the Notebook server. Multi... |
string.format() with optional placeholders | 11,022,655 | 9 | 2012-06-13T20:15:48Z | 11,022,717 | 10 | 2012-06-13T20:20:32Z | [
"python",
"string-formatting"
] | I have the following Python code (I'm using Python 2.7.X):
```
my_csv = '{first},{middle},{last}'
print( my_csv.format( first='John', last='Doe' ) )
```
I get a `KeyError` exception because 'middle' is not specified (this is expected). However, I want all of those placeholders to be optional. If those named parameter... | Here is one option:
```
from collections import defaultdict
my_csv = '{d[first]},{d[middle]},{d[last]}'
print( my_csv.format( d=defaultdict(str, first='John', last='Doe') ) )
``` |
How to import csv data file into scikit-learn? | 11,023,411 | 12 | 2012-06-13T21:15:30Z | 11,035,992 | 27 | 2012-06-14T15:04:49Z | [
"python",
"scikit-learn"
] | From my understanding, the scikit-learn accepts data in (n-sample, n-feature) format which is a 2D array. Assuming I have data in the form ...
```
Stock prices indicator1 indicator2
2.0 123 1252
1.0 .. ..
.. . .
.
```
How do I import this? | This is not a CSV file; this is just a space separated file. Assuming there are no missing values, you can easily load this into a Numpy array called `data` with
```
import numpy as np
f = open("filename.txt")
f.readline() # skip the header
data = np.loadtxt(f)
```
If the stock price is what you want to predict (yo... |
How to import csv data file into scikit-learn? | 11,023,411 | 12 | 2012-06-13T21:15:30Z | 24,902,227 | 12 | 2014-07-23T05:02:10Z | [
"python",
"scikit-learn"
] | From my understanding, the scikit-learn accepts data in (n-sample, n-feature) format which is a 2D array. Assuming I have data in the form ...
```
Stock prices indicator1 indicator2
2.0 123 1252
1.0 .. ..
.. . .
.
```
How do I import this? | You can look up the loadtxt function in [numpy](http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html).
To get the optional inputs into the loadtxt method.
A simple change for csv is
```
data = np.loadtxt(fname = f, delimiter = ',')
``` |
How to import csv data file into scikit-learn? | 11,023,411 | 12 | 2012-06-13T21:15:30Z | 30,813,195 | 19 | 2015-06-12T22:42:28Z | [
"python",
"scikit-learn"
] | From my understanding, the scikit-learn accepts data in (n-sample, n-feature) format which is a 2D array. Assuming I have data in the form ...
```
Stock prices indicator1 indicator2
2.0 123 1252
1.0 .. ..
.. . .
.
```
How do I import this? | A very good alternative to [numpy loadtxt](http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html) is [read\_csv from Pandas](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html). The data is loaded into a Pandas dataframe with the big advantage that it can handle mixed data types... |
Python name mangling function | 11,024,344 | 6 | 2012-06-13T22:37:37Z | 11,024,578 | 10 | 2012-06-13T23:05:04Z | [
"python",
"oop",
"name-mangling"
] | Is there a function in the Python standard library to reproduce Python's name mangling scheme with a "private" attribute name? It seems like there would be, but I can't find it for the life of me.
I wrote this, but if there's a better way I'm all ears.
```
def mangle_name (cls, attrname) :
prefix = '_' + cls.__na... | It looks like the [compiler](http://docs.python.org/library/compiler.html) module has a Python implementation for this, the signature is `mangle(name, klass)` where `klass` is the class name, not the object itself.
Here is how you can access and use it:
```
>>> from compiler.misc import mangle
>>> mangle('__some_such... |
Why am I getting 404 error in Flask? | 11,024,374 | 2 | 2012-06-13T22:41:28Z | 11,024,402 | 9 | 2012-06-13T22:43:43Z | [
"python",
"http-status-code-404",
"flask"
] | I'm a Django developer learning Flask. I'm pretty new to how things work in Flask. I'm getting a 404 with the following code when I visit `localhost:5000`. Could someone explain why I'm getting this:
*The requested URL was not found on the server.
If you entered the URL manually please check your spelling and try agai... | You're calling `app.run()` before registering your handler. You should move the whole `if __name__ == '__main__'` block to the bottom of the script. |
Is it possible to overload Python assignment? | 11,024,646 | 31 | 2012-06-13T23:13:33Z | 11,024,711 | 24 | 2012-06-13T23:20:26Z | [
"python",
"class",
"methods",
"assignment-operator",
"magic-methods"
] | Is there a magic method that can overload the assignment operator, like `__assign__(self, new_value)`?
I'd like to forbid a re-bind for an instance:
```
class Protect():
def __assign__(self, value):
raise Exception("This is an ex-parrot")
var = Protect() # once assigned...
var = 1 # this should raise... | No, as assignment is a [language intrinsic](http://docs.python.org/reference/simple_stmts.html#grammar-token-assignment_stmt) which doesn't have a modification hook. |
Is it possible to overload Python assignment? | 11,024,646 | 31 | 2012-06-13T23:13:33Z | 11,024,909 | 26 | 2012-06-13T23:41:14Z | [
"python",
"class",
"methods",
"assignment-operator",
"magic-methods"
] | Is there a magic method that can overload the assignment operator, like `__assign__(self, new_value)`?
I'd like to forbid a re-bind for an instance:
```
class Protect():
def __assign__(self, value):
raise Exception("This is an ex-parrot")
var = Protect() # once assigned...
var = 1 # this should raise... | The way you describe it is absolutely not possible. Assignment to a name is a fundamental feature of Python and no hooks have been provided to change its behavior.
However, assignment to a member in a class instance *can* be controlled as you want, by overriding `.__setattr__()`.
```
class MyClass(object):
def __... |
Run Python in cmd | 11,024,993 | 8 | 2012-06-13T23:49:41Z | 11,025,010 | 15 | 2012-06-13T23:51:20Z | [
"python",
"windows-7",
"path",
"cmd",
"python-2.7"
] | I am running python 2.7, I can run a program fine when I open the `*.py` file.
But when I go to cmd and type "`python *.py any other args`", it doesn't work, it says that python is not recognised. This is hard because I am trying to do things like `sys.argv[]`, any help is great.
Thanks | You probably don't have the Python executable on your `PATH`. The [PATH variable](http://en.wikipedia.org/wiki/PATH_%28variable%29) tells the command interpreter where to find the commands you are issuing.
If you are on a **Unix/Linux** system try
```
/usr/bin/python
```
Under **Windows** it may vary, so find where ... |
Read/Write NetworkX Graph Object | 11,025,126 | 7 | 2012-06-14T00:08:18Z | 11,354,723 | 15 | 2012-07-06T01:26:46Z | [
"python",
"file-io",
"networkx"
] | I am trying to deal with a super-massive NetworkX Graph object with hundreds of millions of nodes. I'd like to be able to write it to file as to not consume all my computer memory. However, I need to constantly be searching across existing nodes, updating edges, etc.
Is there a good solution for this? I'm not sure how... | First try `pickle`; it's designed to serialize general objects.
**An example of creating a DiGraph and serializing to a file:**
```
import networkx as nx
import pickle
dg = nx.DiGraph()
dg.add_edge('a','b')
dg.add_edge('a','c')
pickle.dump(dg, open('/tmp/graph.txt', 'w'))
```
**An example of loading a DiGraph from a... |
Problems with Jinja2: TemplateNotFound: index.html | 11,025,321 | 8 | 2012-06-14T00:40:47Z | 11,071,186 | 10 | 2012-06-17T12:11:08Z | [
"python",
"google-app-engine",
"templates",
"jinja2"
] | I'm trying to build my first GAE app with jinja2. After overcoming a dozen small errors, now I'm stuck with this:
```
Traceback (most recent call last):
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1536, in __call__
rv = self.handle_exception(request, response, e)
File "C:\... | Try to use
```
loader=jinja2.FileSystemLoader('templates')
```
instead of
```
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))
```
It works for me. |
Python MySQLdb slow in updating values | 11,025,475 | 4 | 2012-06-14T01:11:29Z | 11,025,516 | 8 | 2012-06-14T01:20:56Z | [
"python",
"mysql"
] | I am trying to update a database with values from a csv file, the following is my code:
```
import MySQLdb as mdb
import sys
import csv
con = None
command = ''
new_name_list = []
old_name_list = []
duplicates = []
update_list = []
file = 'csv_file.csv'
listReader = csv.reader(open(file, 'r'))
for row in listReader:
... | You could try using `executemany`:
```
data = [(n, d[n]) for n in old_name_list]
cur.executemany("UPDATE file SET fil_name='%s' WHERE fil_name='%s'", data)
```
Additionally, you may want to consider indexing fil\_name (assuming fil\_name is read-mostly) |
If I have a list of words, how can I check if string does not contain any of the words in the list, and efficiently? | 11,025,748 | 4 | 2012-06-14T02:02:29Z | 11,025,763 | 8 | 2012-06-14T02:05:06Z | [
"python",
"search",
"loops",
"filter",
"stop-words"
] | As title says, I have a list of words, Like `stopWords = ["the", "and", "with", etc...]` and I'm receiving text like "Kill the fox and dog". I want the output like "Kill fox dog" very efficiently and fast. How can I do this (I know I can iterate using a for loop, but thats not very efficient) | The most imporant improvement is to **make stopWords a `set`**. This means the lookups will be very fast
```
stopWords = set(["the", "and", "with", etc...])
" ".join(word for word in msg.split() if word not in stopWords)
```
If you just want to know if any of the stopWords are in the text
```
if any(word in stopWord... |
Calling rm from subprocess using wildcards does not remove the files | 11,025,784 | 8 | 2012-06-14T02:09:58Z | 11,025,795 | 13 | 2012-06-14T02:12:29Z | [
"python",
"django",
"shell",
"rm"
] | I'm trying to build a function that will remove all the files that start with 'prepend' from the root of my project. Here's what I have so far
```
def cleanup(prepend):
prepend = str(prepend)
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
end = "%s*" % prepend
cmd = 'rm'
args = "%s/%s" %... | Would you consider this approach using [os.remove()](http://docs.python.org/library/os.html?highlight=os.remove#os.remove) to deleting files instead of `rm`:
```
import os
os.remove('Path/To/filename.ext')
```
**Update** (basically moving my comment from below into my answer)**:**
As `os.remove()` can't handle wildc... |
Calling rm from subprocess using wildcards does not remove the files | 11,025,784 | 8 | 2012-06-14T02:09:58Z | 11,025,857 | 8 | 2012-06-14T02:23:34Z | [
"python",
"django",
"shell",
"rm"
] | I'm trying to build a function that will remove all the files that start with 'prepend' from the root of my project. Here's what I have so far
```
def cleanup(prepend):
prepend = str(prepend)
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
end = "%s*" % prepend
cmd = 'rm'
args = "%s/%s" %... | The problem is that you are passing two arguments to `subprocess.Popen`: `rm` and a path, such as `/home/user/t*` (if prefix is `t`). `Popen` then will try to remove a file named *exactly this way*: t followed by an asterisk at the end.
If you want to use `Popen` with the wildcard, you should pass the `shell` paramete... |
Why does the content of a tuple changes when I append to a list inside of it but does not change when I update a variable? | 11,026,011 | 7 | 2012-06-14T02:49:55Z | 11,026,323 | 7 | 2012-06-14T03:36:54Z | [
"python",
"list",
"append",
"tuples",
"variable-assignment"
] | ```
myVar = ["jhhj", "hgc"]
myTuple = ([1,2,3], [4,5,6], myVar)
myVar.append('lololol')
print myTuple
```
Why and how can this tuple be modified by appending after construction?
```
myVar = "lol"
myTuple = ([1,2,3], [4,5,6], myVar)
myVar = "lolol"
print myTuple
```
Why is this going to print out `([1,2,3], [4,5,6], ... | Well, let me try to explain with some images.
In Python, everything is an object. Those objects are *referenced* by variables. Some kinds of objects, such as lists and tuples, just store references to other objects.
That said, when you execute
```
myVar = ["jhhj", "hgc"]
myTuple = ([1,2,3], [4,5,6], myVar)
```
You ... |
I'm using excel to build websites - Looking for an alternative | 11,026,205 | 4 | 2012-06-14T03:19:24Z | 11,026,241 | 7 | 2012-06-14T03:23:28Z | [
"python",
"mysql",
"html"
] | I'm currently concatenating adjacent cells in excel to repeat common HTML elements and divs - it feels like I've gone down a strange excel path in developing my webpage, and I was wondering if an experienced web designer could let me know how I might accomplish my goals for the site with a more conventional method (aim... | Wow, that sounds really painful.
If all you have is 40 images that you want to generate HTML for, and the rest of your site is static, it may be simplest just to have a single text file with each line containing an image file path. Then, use Python to look at each line, generate the appropriate HTML, and concatenate i... |
Building a Mac and Windows GUI Application | 11,026,541 | 10 | 2012-06-14T04:10:52Z | 11,026,789 | 9 | 2012-06-14T04:44:27Z | [
"c++",
"python",
"cross-platform",
"wxpython",
"py2app"
] | I am planning to build a GUI application for Mac and Windows. I've been doing some research in the technology choices, as in the language, libraries, and build tools, so that I can share as much code as possible between the two platforms.
**The main requirements are:**
1. Meets the Mac App Store requirements.
2. Nati... | I think you might be ruling out Qt too quickly. This [guy](http://stackoverflow.com/a/5430867/245265) has reported that he publishd a Qt-based app on the Mac App Store.
According to this related [answer](http://stackoverflow.com/a/10767009/245265), you can specify the Qt build target to use Cocoa instead of the deprec... |
Python writing dict to txt file and reading dict from txt file | 11,026,959 | 48 | 2012-06-14T05:07:15Z | 11,027,016 | 38 | 2012-06-14T05:14:09Z | [
"python"
] | I am new to Python and am trying to write a dictionary to a txt file. Then read the dict values by typing the keys with raw\_input. I feel like I am just missing one step but I have been looking for awhile now so any help would be appreciated.
EDIT: I get this error
File "name.py", line 24, in reading
print whip[name... | To store Python objects in files, use the [`pickle`](http://docs.python.org/library/pickle.html) module:
```
import pickle
a = {
'a': 1,
'b': 2
}
with open('file.txt', 'wb') as handle:
pickle.dump(a, handle)
with open('file.txt', 'rb') as handle:
b = pickle.loads(handle.read())
print a == b # True
```
Not... |
Python writing dict to txt file and reading dict from txt file | 11,026,959 | 48 | 2012-06-14T05:07:15Z | 11,027,021 | 85 | 2012-06-14T05:14:27Z | [
"python"
] | I am new to Python and am trying to write a dictionary to a txt file. Then read the dict values by typing the keys with raw\_input. I feel like I am just missing one step but I have been looking for awhile now so any help would be appreciated.
EDIT: I get this error
File "name.py", line 24, in reading
print whip[name... | Have you tried [the json module](http://docs.python.org/library/json.html)? JSON format is very similar to python dictionary. And it's human readable/writable:
```
>>> import json
>>> d = {"one":1, "two":2}
>>> json.dump(d, open("text.txt",'w'))
```
This code dumps to a text file
```
$ cat text.txt
{"two": 2, "one"... |
Python writing dict to txt file and reading dict from txt file | 11,026,959 | 48 | 2012-06-14T05:07:15Z | 11,027,069 | 38 | 2012-06-14T05:20:12Z | [
"python"
] | I am new to Python and am trying to write a dictionary to a txt file. Then read the dict values by typing the keys with raw\_input. I feel like I am just missing one step but I have been looking for awhile now so any help would be appreciated.
EDIT: I get this error
File "name.py", line 24, in reading
print whip[name... | Your code is *almost right*! You are right, you are just missing one step. When you read in the file, you are reading it as a string; but you want to turn the string back into a dictionary.
The error message you saw was because `self.whip` was a string, not a dictionary.
I first wrote that you could just feed the str... |
Will Python io stream get automatically closed in list comprehension? | 11,027,307 | 8 | 2012-06-14T05:45:55Z | 11,027,437 | 17 | 2012-06-14T05:55:16Z | [
"python",
"io"
] | For example I have the following code:
```
d = [l for l in open('a.txt', 'r')]
```
After `d` is created, will the stream opened in the list comprehension get closed automatically ? | "Maybe".
In cPython, which uses refcounting, the file will be closed as soon as the list comprehension finishes (and all references to the `file` object are lost).
But the Python standard does not *require* that it be closed. For example, the file will not be closed immediately in jython, which uses the JVM garbage c... |
Virtualenv ". venv/bin/activate" vs "source venv/bin/activate" | 11,027,782 | 7 | 2012-06-14T06:27:52Z | 11,028,680 | 12 | 2012-06-14T07:36:45Z | [
"python",
"virtualenv"
] | lets say i created a virtualenv called venv (virtualenv venv)
From reading tutorials, i read there are 2 ways to activate virtual env:
1. `. venv/bin/activate`
2. `source venv/bin/activate`
I think they both accomplish the same thing, but i dont understand whats going on.
Also for number 1, doesnt the "." just mean... | `.` and `source` does exactly the same thing, with the only difference being that while `source` is more readable, it may not be available in all shells.
The command runs the contents of the script within the current shell, and this is important in the case of `activate` because one of the things that the script does ... |
How do I disable log messages from the Requests library? | 11,029,717 | 194 | 2012-06-14T08:52:12Z | 11,029,841 | 274 | 2012-06-14T08:59:53Z | [
"python",
"logging",
"python-requests"
] | By default, the [Requests](http://docs.python-requests.org/en/master/) library writes log messages to the console, along the lines of Starting new HTTP connection (1): example.com etc. I'm usually not interested in these messages, how do I disable them? | I found out how to configure *requests*'s logging level, it's done via the standard [logging](http://docs.python.org/library/logging.html) module. I decided to configure it to not log messages unless they are at least warnings:
```
import logging
logging.getLogger("requests").setLevel(logging.WARNING)
```
If you wis... |
How do I disable log messages from the Requests library? | 11,029,717 | 194 | 2012-06-14T08:52:12Z | 16,043,023 | 9 | 2013-04-16T17:08:46Z | [
"python",
"logging",
"python-requests"
] | By default, the [Requests](http://docs.python-requests.org/en/master/) library writes log messages to the console, along the lines of Starting new HTTP connection (1): example.com etc. I'm usually not interested in these messages, how do I disable them? | Let me copy/paste the documentation section which it I wrote about week or two ago, after having a problem similar to yours:
```
import requests
import logging
# these two lines enable debugging at httplib level (requests->urllib3->httplib)
# you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEA... |
How do I disable log messages from the Requests library? | 11,029,717 | 194 | 2012-06-14T08:52:12Z | 21,725,878 | 21 | 2014-02-12T10:55:25Z | [
"python",
"logging",
"python-requests"
] | By default, the [Requests](http://docs.python-requests.org/en/master/) library writes log messages to the console, along the lines of Starting new HTTP connection (1): example.com etc. I'm usually not interested in these messages, how do I disable them? | ```
import logging
urllib3_logger = logging.getLogger('urllib3')
urllib3_logger.setLevel(logging.CRITICAL)
```
In this way all the messages of level=INFO from urllib3 won't be present in the logfile.
So you can continue to use the level=INFO for your log messages...just modify this for the library you are using. |
How do I disable log messages from the Requests library? | 11,029,717 | 194 | 2012-06-14T08:52:12Z | 36,208,664 | 12 | 2016-03-24T19:37:45Z | [
"python",
"logging",
"python-requests"
] | By default, the [Requests](http://docs.python-requests.org/en/master/) library writes log messages to the console, along the lines of Starting new HTTP connection (1): example.com etc. I'm usually not interested in these messages, how do I disable them? | In case you came here looking for a way to modify logging of any (possibly deeply nested) module, use `logging.Logger.manager.loggerDict` to get a dictionary of all of the logger objects, which you can then use as the argument to `logging.getLogger`:
```
import requests
import logging
for key in logging.Logger.manager... |
Should I write dict or {} in Python when constructing a dictionary with string keys? | 11,031,039 | 6 | 2012-06-14T10:17:33Z | 11,031,395 | 8 | 2012-06-14T10:41:34Z | [
"python",
"coding-style"
] | This is just a trivial question of what convention you suggest. Recently, I have seen many examples of people writing `dict(key1=val1, key2=val2)` instead of what I think is the more idiomatic `{"key1": val1, "key2": val2}`. I think the reason is to avoid using `""` for the keys, but I am not sure. Perhaps the `dict()`... | `{"key1": val1, "key2": val2}` is more idiomatic; I hardly ever encounter `dict` with keyword arguments and I've certainly never been tempted to write it. It's also more general, because keyword arguments have to be Python identifiers:
```
>>> {"foo bar": 1}
{'foo bar': 1}
>>> dict(foo bar=1)
-------------------------... |
How can I make setuptools install a package from another source that's also available on pypi with the same version number? | 11,032,125 | 19 | 2012-06-14T11:28:57Z | 11,036,019 | 9 | 2012-06-14T15:06:00Z | [
"python",
"pip",
"setuptools",
"distutils",
"easy-install"
] | It's a similar question to [How can I make setuptools install a package that's not on PyPI?](http://stackoverflow.com/questions/3472430/how-can-i-make-setuptools-install-a-package-thats-not-on-pypi) but not the same.
As I would like to use the forked version of some package, setuptools ignore the dependency link (as i... | I believe you can just use `dependency_links` as described in that question:
```
from setuptools import setup
setup(name = 'mypkg',
version = '0.0.1',
description = 'Foo',
author = 'bar',
author_email = 'bar@example.com',
install_requires = ['pyScss==1.1.3'],
dependency_links = [
'ht... |
convert microseconds into a human readable time | 11,032,799 | 5 | 2012-06-14T12:11:38Z | 11,032,832 | 17 | 2012-06-14T12:13:54Z | [
"python",
"time"
] | I need to convert a time difference (diff) between two actions into a human readable time.
How can I do this with python?
I tried something like
```
diff = 49503757
datetime.time(0,0,0,diff)
```
but the diff value was too long, the datetime expects a value of microseconds in between 0 and 999999 and my diff ... | ```
>>> from datetime import timedelta
>>> str(timedelta(microseconds=49503757))
'0:00:49.503757'
``` |
difference between numpy dot() and inner() | 11,033,573 | 20 | 2012-06-14T12:59:21Z | 11,033,895 | 22 | 2012-06-14T13:16:03Z | [
"python",
"matrix",
"numpy"
] | What is the difference between
```
import numpy as np
np.dot(a,b)
```
and
```
import numpy as np
np.inner(a,b)
```
all examples I tried returned the same result. [Wikipedia](http://en.wikipedia.org/wiki/Dot_product) has the same article for both?! In [the description](http://docs.scipy.org/doc/numpy/reference/gener... | [`numpy.dot`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html#numpy.dot):
> For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation). For N dimensions it is a sum product over the **last axis** of a and the **second-to-las... |
Change specific value in CSV file via Python | 11,033,590 | 8 | 2012-06-14T13:00:07Z | 11,033,883 | 7 | 2012-06-14T13:15:39Z | [
"python",
"csv",
"filereader"
] | I need the way to change specific value of the column of csv file. For example I have csv file:
```
"Ip","Sites"
"127.0.0.1",10
"127.0.0.2",23
"127.0.0.3",50
```
and I need to change value 23 to 30 of the "127.0.0.2".
I use csv library: import csv
Appreciate any help as I'm new in Python. Thanks! | You can't really replace values in the existing file. Instead, you need to:
1. read in existing file
2. alter file in memory
3. write out new file (overwriting existing file)
What you can also do is read in the existing file line by line, writing it out to a new file, while replacing values on the fly. When done, clo... |
Change specific value in CSV file via Python | 11,033,590 | 8 | 2012-06-14T13:00:07Z | 11,033,891 | 20 | 2012-06-14T13:15:59Z | [
"python",
"csv",
"filereader"
] | I need the way to change specific value of the column of csv file. For example I have csv file:
```
"Ip","Sites"
"127.0.0.1",10
"127.0.0.2",23
"127.0.0.3",50
```
and I need to change value 23 to 30 of the "127.0.0.2".
I use csv library: import csv
Appreciate any help as I'm new in Python. Thanks! | This is the solution opening the csv file, changing the values in memory and then writing back the changes to disk.
```
r = csv.reader(open('/tmp/test.csv')) # Here your csv file
lines = [l for l in r]
```
Content of lines:
```
[['Ip', 'Sites'],
['127.0.0.1', '10'],
['127.0.0.2', '23'],
['127.0.0.3', '50']]
```
... |
Transfer Python setup accross different PC | 11,033,753 | 7 | 2012-06-14T13:09:14Z | 11,034,515 | 10 | 2012-06-14T13:47:15Z | [
"python"
] | My scenario is I have two laptops with `fresh installation` of `windows`. Now I use both of them for programming.
So, lets suppose I install various python modules/packages in one of the laptop. So is there a way I can `clone` this complete python setup on my other laptop. The reason for this is my internet connection... | Here is a completely different suggestion, this is recommended if you want to synchronize the packages between the two PCs and not cloning everything just once.
It only works if you install packages with [`pip`](http://www.pip-installer.org). It does not work for packages which are not installable/installed with pip.
... |
Boost Python Hello World example not working in Python | 11,036,319 | 6 | 2012-06-14T15:22:48Z | 11,036,958 | 10 | 2012-06-14T16:01:21Z | [
"python",
"c++",
"boost",
"boost-python"
] | I'm having a great deal of trouble using my c++ code from Visual C++ (wrapped by boost) in Python.
Alright, so the tools I'm using are: Visual Studio 2010, BoostPro 1\_47, Windows 7, and Python 2.7 (32-bit).
I have the following code which compiles nicely in Visual Studio 2010:
```
#define BOOST_PYTHON_STATIC_LIB
#i... | AFAIK you have to change the extension of the DLL to `.pyd` or otherwise Python will not be able to load it. I think you can set a build option to automatically set the extension in VS, but I don't know for sure.
Also, make sure that the created extension is somewhere on the [`PYTHONPATH`](http://docs.python.org/using... |
Pythonic way to iterate over a collections.Counter() instance in descending order? | 11,037,005 | 9 | 2012-06-14T16:03:53Z | 11,037,033 | 12 | 2012-06-14T16:06:17Z | [
"collections",
"iteration",
"python-2.7",
"python"
] | In Python 2 (2.7, to be more precise), I want to iterate over a collections.Counter instance in descending count order.
```
>>> import collections
>>> c = collections.Counter()
>>> c['a'] = 1
>>> c['b'] = 999
>>> c
Counter({'b': 999, 'a': 1})
>>> for x in c:
print x
a
b
```
In the example above, it appears th... | You can iterate over `c.most_common()` to get the items in the desired order. See also the [documentation of `Counter.most_common()`](http://docs.python.org/library/collections.html#collections.Counter.most_common).
Example:
```
>>> c = collections.Counter(a=1, b=999)
>>> c.most_common()
[('b', 999), ('a', 1)]
``` |
Getting a python traceback without an exception | 11,037,109 | 11 | 2012-06-14T16:11:20Z | 11,038,685 | 11 | 2012-06-14T17:56:34Z | [
"python",
"stack-trace",
"pretty-print"
] | Suppose you have these modules:
## module1.py
```
import module2
def a():
module1.b()
def c():
print "Hi guys!"
```
## module2.py
```
import module1
def b():
module1.c()
```
I want a function `func(a())` that produces a similar output to this: (=a traceback ?)
```
/usr/local/lib/python2.7/dist-pac... | [traceback.print\_stack](http://docs.python.org/library/traceback.html#traceback.print_stack) works nicely for me:
```
>>> import traceback
>>> def what():
... traceback.print_stack()
...
>>> def hey():
... what()
...
>>> hey()
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in hey
File "<std... |
How can I generalize my pandas data grouping to more than 3 dimensions? | 11,037,895 | 9 | 2012-06-14T16:58:42Z | 11,038,086 | 9 | 2012-06-14T17:11:45Z | [
"python",
"pandas"
] | I'm using the excellent `pandas` package to deal with a large amount of varied meteorological diagnostic data and I'm quickly running out of dimensions as I stitch the data together. Looking at the documentation, it may be that using the `MultiIndex` may solve my problem, but I'm not sure how to apply it to my situatio... | I might suggest using `pandas.concat` along with its `keys` argument to glue together Series DataFrames to create a MultiIndex in the columns:
```
In [20]: data
Out[20]:
{'a': 2012-04-16 0
2012-04-17 1
2012-04-18 2
2012-04-19 3
2012-04-20 4
2012-04-21 5
2012-04-22 6
2012-04-23 7
2012-04-24 ... |
python datetime: Round/trim number of digits in microseconds | 11,040,177 | 16 | 2012-06-14T19:38:57Z | 11,040,248 | 17 | 2012-06-14T19:42:57Z | [
"python",
"datetime",
"formatter"
] | Currently I am logging stuff and I am using my own formatter with a custom formatTime():
```
def formatTime(self, _record, _datefmt):
t = datetime.datetime.now()
return t.strftime('%Y-%m-%d %H:%M:%S.%f')
```
My issue is that the microseconds, %f, are six digits. Is there anyway to spit out less di... | The simplest way would be to use slicing to just chop off the last three digits of the microseconds:
```
def format_time():
t = datetime.datetime.now()
s = t.strftime('%Y-%m-%d %H:%M:%S.%f')
return s[:-3]
```
If you want to actually round the number rather than just chopping, it's a little more work but n... |
class variables is shared across all instances in python? | 11,040,438 | 9 | 2012-06-14T19:56:41Z | 11,040,485 | 9 | 2012-06-14T19:59:32Z | [
"python",
"class",
"global-variables",
"instance-variables",
"member"
] | I started coding in python a week ago, it is my mistake i started coding using oops,classes and objects that soon. I assumed my C++ proficiency will help.... I got bit by the following code
```
class A:
var=0
list=[]
def __init__(self):
pass
```
Here to my surprise, var and list are kinda g... | These are basically like static variables in Java:
```
// Example equivalent Java
class A {
static int var = 0;
static String[] list;
}
```
This is the intended behavior: Class variables are *for the class*.
For normal instance variables, declare them in the constructor:
```
class A:
def __init__(self):... |
class variables is shared across all instances in python? | 11,040,438 | 9 | 2012-06-14T19:56:41Z | 11,040,513 | 12 | 2012-06-14T20:01:20Z | [
"python",
"class",
"global-variables",
"instance-variables",
"member"
] | I started coding in python a week ago, it is my mistake i started coding using oops,classes and objects that soon. I assumed my C++ proficiency will help.... I got bit by the following code
```
class A:
var=0
list=[]
def __init__(self):
pass
```
Here to my surprise, var and list are kinda g... | `var` should definitely not be shared as long as you access it by `instance.var` or `self.var`. With the list however, what your statement does is when the class gets evaluated, one list instance is created and bound to the class dict, hence all instances will have the same list. Whenever you set `instance.list = somet... |
Pandas DataFrame Add column to index without resetting | 11,040,626 | 7 | 2012-06-14T20:09:38Z | 11,856,979 | 14 | 2012-08-08T02:50:06Z | [
"python",
"dataframe",
"pandas"
] | how do I add 'd' to the index below without having to reset it first?
```
from pandas import DataFrame
df = DataFrame( {'a': range(6), 'b': range(6), 'c': range(6)} )
df.set_index(['a','b'], inplace=True)
df['d'] = range(6)
# how do I set index to 'a b d' without having to reset it first?
df.reset_index(['a','b','d']... | We added an `append` option to `set_index`. Try that.
The command is:
```
df.set_index(['d'], append=True)
```
(we don't need to specify ['a', 'b'], as they already are in the index and we're appending to them) |
find permutations of items in a python list, with an added complexity | 11,040,749 | 2 | 2012-06-14T20:17:57Z | 11,040,828 | 8 | 2012-06-14T20:24:07Z | [
"python",
"list",
"permutation"
] | Please bear with me while I struggle to explain this; my math is rusty and I just started computer programming, sorry!
Say I have a list of 3 items. I want to find all possible arrangements of the items in this list where each arrangement consists of 3 items.
Next, still using my original list, I want to find all the... | Just [`itertools.permutations`](http://docs.python.org/library/itertools.html#itertools.permutations). You can inspect its sources if you want exact algo. |
Python.h: No such file or directory | 11,041,299 | 14 | 2012-06-14T21:02:37Z | 11,041,388 | 9 | 2012-06-14T21:09:16Z | [
"c++",
"python",
"include",
"cmake",
"kdevelop"
] | I recently installed KDevelop 4 for C++ development on my Macbook Pro running Ubuntu 12.04 LTS.
I want to embed Python application in my C++ code. To do that, one needs to include the Python.h header file. So, I did that.
```
#include <iostream>
#include <Python.h>
int main(int argc, char **argv) {
Py_Initialize... | You want to include the following on the compile line:
```
`python-config --cflags`
```
and this on the link line:
```
`python-config --ldflags`
``` |
Python.h: No such file or directory | 11,041,299 | 14 | 2012-06-14T21:02:37Z | 11,055,816 | 16 | 2012-06-15T17:53:29Z | [
"c++",
"python",
"include",
"cmake",
"kdevelop"
] | I recently installed KDevelop 4 for C++ development on my Macbook Pro running Ubuntu 12.04 LTS.
I want to embed Python application in my C++ code. To do that, one needs to include the Python.h header file. So, I did that.
```
#include <iostream>
#include <Python.h>
int main(int argc, char **argv) {
Py_Initialize... | In your CMakeLists.txt, try adding the following:
```
find_package(PythonLibs REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
target_link_libraries(<your exe or lib> ${PYTHON_LIBRARIES})
```
For details of the commands, run:
```
cmake --help-module FindPythonLibs
cmake --help-command find_package
cmake --help-... |
Python.h: No such file or directory | 11,041,299 | 14 | 2012-06-14T21:02:37Z | 14,811,099 | 24 | 2013-02-11T11:13:26Z | [
"c++",
"python",
"include",
"cmake",
"kdevelop"
] | I recently installed KDevelop 4 for C++ development on my Macbook Pro running Ubuntu 12.04 LTS.
I want to embed Python application in my C++ code. To do that, one needs to include the Python.h header file. So, I did that.
```
#include <iostream>
#include <Python.h>
int main(int argc, char **argv) {
Py_Initialize... | ```
sudo apt-get install python2.7-dev
```
worked for me on a "Python.h: No such file or directory" issue |
Why dict.get(key) instead of dict[key]? | 11,041,405 | 130 | 2012-06-14T21:10:39Z | 11,041,421 | 238 | 2012-06-14T21:12:12Z | [
"python",
"dictionary"
] | Today, I came across the `dict` method `get` which, given a key in the dictionary, returns the associated value.
For what purpose is this function useful? If I wanted to find a value associated with a key in a dictionary, I can just do `dict[key]`, and it returns the same thing:
```
dictionary = {"Name": "Harry", "Ag... | It allows you to provide a default value if the key is missing:
```
dictionary.get("bogus", None)
```
returns `None`, whereas
```
dictionary["bogus"]
```
would raise a `KeyError`. |
Why dict.get(key) instead of dict[key]? | 11,041,405 | 130 | 2012-06-14T21:10:39Z | 11,041,428 | 9 | 2012-06-14T21:12:27Z | [
"python",
"dictionary"
] | Today, I came across the `dict` method `get` which, given a key in the dictionary, returns the associated value.
For what purpose is this function useful? If I wanted to find a value associated with a key in a dictionary, I can just do `dict[key]`, and it returns the same thing:
```
dictionary = {"Name": "Harry", "Ag... | The purpose is you can give a default value if the key is not found which is very useful
```
dictionary.get("Name",'harry')
``` |
Why dict.get(key) instead of dict[key]? | 11,041,405 | 130 | 2012-06-14T21:10:39Z | 11,041,485 | 18 | 2012-06-14T21:16:38Z | [
"python",
"dictionary"
] | Today, I came across the `dict` method `get` which, given a key in the dictionary, returns the associated value.
For what purpose is this function useful? If I wanted to find a value associated with a key in a dictionary, I can just do `dict[key]`, and it returns the same thing:
```
dictionary = {"Name": "Harry", "Ag... | `get` takes a second optional value. If the specified key does not exist in your dictionary, then this value will be returned.
```
dictionary = {"Name": "Harry", "Age": 17}
dictionary.get('Year', 'No available data')
>> 'No available data'
```
If you do not give the second parameter, `None` will be returned.
If you ... |
Why dict.get(key) instead of dict[key]? | 11,041,405 | 130 | 2012-06-14T21:10:39Z | 37,968,524 | 7 | 2016-06-22T12:48:42Z | [
"python",
"dictionary"
] | Today, I came across the `dict` method `get` which, given a key in the dictionary, returns the associated value.
For what purpose is this function useful? If I wanted to find a value associated with a key in a dictionary, I can just do `dict[key]`, and it returns the same thing:
```
dictionary = {"Name": "Harry", "Ag... | > **What is the `dict.get()` method?**
As already mentioned the `get` method contains an additional parameter which indicates the missing value. [From the documentation](https://docs.python.org/3/library/stdtypes.html#dict.get)
> ```
> get(key[, default])
> ```
>
> Return the value for key if key is in the dictionary... |
How to write/read a Pandas DataFrame with MultiIndex from/to an ASCII file? | 11,041,411 | 9 | 2012-06-14T21:11:12Z | 11,042,986 | 11 | 2012-06-15T00:00:13Z | [
"python",
"pandas"
] | I want to be able to create a Pandas DataFrame with MultiIndexes for the rows and the columns index and read it from an ASCII text file. My data looks like:
```
col_indx = MultiIndex.from_tuples([('A', 'B', 'C'), ('A', 'B', 'C2'), ('A', 'B', 'C3'),
('A', 'B2', 'C'), ('A', 'B... | Not sure which version of pandas you are using but with `0.7.3` you can export your `DataFrame` to a TSV file and retain the indices by doing this:
```
df.to_csv('mydf.tsv', sep='\t')
```
The reason you need to export to TSV versus CSV is since the column headers have `,` characters in them. This should solve the fir... |
Python multiprocess profiling | 11,041,683 | 24 | 2012-06-14T21:33:19Z | 11,041,719 | 13 | 2012-06-14T21:36:31Z | [
"python",
"multiprocessing",
"cprofile"
] | I'm struggling to figure out how to profile a simple multiprocess python script
```
import multiprocessing
import cProfile
import time
def worker(num):
time.sleep(3)
print 'Worker:', num
if __name__ == '__main__':
for i in range(5):
p = multiprocessing.Process(target=worker, args=(i,))
cPr... | You're profiling the process startup, which is why you're only seeing what happens in `p.start()` as you sayâand `p.start()` returns once the subprocess is kicked off. You need to profile inside the `worker` method, which will get called in the subprocesses. |
How to split string with 2 arguments? | 11,041,996 | 3 | 2012-06-14T22:04:02Z | 11,042,004 | 9 | 2012-06-14T22:05:04Z | [
"python",
"string",
"split"
] | If I have a string thats `'asdf foo\nHi\nBar thing'`, I want it to split the string, so the output is `['asdf', 'foo', 'hi', 'bar', thing']`. Thats essentially `x.split(' ')` and `x.split('\n')`. How can I do this efficiently? I want it to be about one line long, instead of having a for loop to split again... | Omit the parameter to `split()`: `x.split()` will split on both, spaces and newline characters (and also tabs).
Example:
```
>>> x = 'asdf foo\nHi\nBar thing'
>>> x.split()
['asdf', 'foo', 'Hi', 'Bar', 'thing']
``` |
Django formwizard: passing data between forms | 11,042,084 | 4 | 2012-06-14T22:12:57Z | 11,266,066 | 8 | 2012-06-29T17:09:31Z | [
"python",
"django"
] | I have a form wizard that contains 3 forms. Basically, what I am trying to do is to pass data from first and second forms to the third one. What I tried is to add a dictionary attribute to wizard class and update that dictionary every time the method `process_step` is called. [Django 1.4 documentation](https://docs.dja... | What I would do is the following:
```
class MyWizard(SessionWizardView):
def get_context_data(self, form, **kwargs):
context = super(MyWizard, self).get_context_data(form=form, **kwargs)
if self.steps.step1 == 3:
data_from_step_1 = self.get_cleaned_data_for_step('0') # zero indexed
... |
How can i use xaxis_date() with barh()? | 11,042,290 | 6 | 2012-06-14T22:36:01Z | 11,056,898 | 8 | 2012-06-15T19:19:46Z | [
"python",
"datetime",
"matplotlib",
"bar-chart"
] | in the code below, bdate and edate are both datetime.datetime() objects:
```
pylab.barh(ypos, edate - bdate, left=bdate, height=TRMWidth )
```
but this throws an AttributeError way down in dates.py.\_to\_ordinalf() :
> File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/pyp... | What's happening is that matplotlib doesn't actually use datetime objects for plotting.
Dates are first converted into an internal floating point format. The conversion isn't set up to handle timedeltas (which is arguably an oversight).
You can basically do exactly what you wanted, you just need to explictly convert ... |
Adding base class to existing object in python | 11,042,424 | 6 | 2012-06-14T22:52:18Z | 11,050,571 | 8 | 2012-06-15T12:23:18Z | [
"python",
"inheritance",
"metaclass",
"monkeypatching"
] | I have several objects of different kinds (different function names, different signatures) and I monkey patch them to have a common way to access them from different functions. Briefly, there is a dispatcher that takes the objects that I want to patch and depending on the object type it calls different patcher. A patch... | Dynamically modifying an object's type is reasonably safe, as long as the extra base class is compatible (and you'll get an exception if it isn't). The simplest way to add a base class is with the 3-argument `type` constructor:
```
cls = object.__class__
object.__class__ = cls.__class__(cls.__name__ + "WithExtraBase",... |
How to use Python's tempfile.NamedTemporaryFile()? | 11,043,372 | 14 | 2012-06-15T01:00:35Z | 11,043,390 | 24 | 2012-06-15T01:03:02Z | [
"python",
"temporary-files"
] | I'm working on a Python script that needs to create about 50 distinct temporary files, which are all appended frequently during the course of the script and merged at the end. I'm sure that the `tempfile` module can do what I need, but I haven't been able to figure out how from reading the documentation.
I want to use... | > "That name can be retrieved from the name member of the file object."
means that you can get the name of the temporary file created like so:
```
In [4]: import tempfile
In [5]: tf = tempfile.NamedTemporaryFile()
In [6]: tf.name # retrieve the name of the temp file just created
Out[6]: 'c:\\blabla\\locals~1\\tem... |
Checking for Errors | 11,043,434 | 2 | 2012-06-15T01:08:45Z | 11,043,478 | 11 | 2012-06-15T01:15:20Z | [
"python"
] | How do I set a value to **only accept certain data in Python**? Like I am making a code for a colour identifier. I want my variable to only accept up to `FFFFFF` any nothing greater than that. The base-16 characters pretty much...**hex code**.
The reason I am trying to do this is because if a user enters in a value li... | ```
try:
val = int(hex_val, 16)
except ValueError:
# Not a valid hex value
if val > int("FFFFFF", 16):
# Value is too large
``` |
Whether eval() better than self-analysis? | 11,047,480 | 4 | 2012-06-15T08:53:52Z | 11,047,530 | 10 | 2012-06-15T08:57:53Z | [
"python",
"eval"
] | Here is my situation, I have a string as follows
```
'a':1 'b':2 'c':3
```
I want to turn this to a dict, so I have two options:
1. Split the string by `' '` and then by `':'` then put the pairs to a `dict`.
2. Replace `' '` with `','`, append `'{'`, and `'}'` to string and use `eval()` to get a `dict`.
So my quest... | I would do it like this:
```
import ast
result = ast.literal_eval(''.join(["{", s.replace(" ", ", "), "}"]))
```
You can also do this (although the difference may be negligible):
```
import ast
result = ast.literal_eval("{" + s.replace(" ", ", ") + "}")
```
It's better to use `ast.literal_eval` as [it's safer](http... |
Is it safe to use os.environ.setdefault? | 11,047,621 | 8 | 2012-06-15T09:04:36Z | 11,048,314 | 10 | 2012-06-15T09:46:37Z | [
"python"
] | From my ipython shell, I see a method setdefault in os.environ but it is not documented. <http://docs.python.org/library/os.html#os.environ>. Is it documented somewhere else?
```
def setdefault(self, key, failobj=None):
if key not in self:
self[key] = failobj
return self[key]
```
Can I use this functi... | The [`os.environ` documentation](http://docs.python.org/library/os.html#os.environ) does state it's a mapping:
> A mapping object representing the string environment.
As such it behaves according to the python [mapping documentation](http://docs.python.org/library/stdtypes.html#mapping-types-dict) of which `dict` is ... |
Creating a table look-a-like Tkinter | 11,047,803 | 3 | 2012-06-15T09:14:59Z | 11,049,650 | 24 | 2012-06-15T11:15:29Z | [
"python",
"tkinter"
] | I am looking to create something that resembles a table in Tkinter but it doesn't necessarily have to be one.
I would like to create headers 'Name1', 'Name2', 'Value' for example and beneath each one I wish to have several blank rows.
These rows I then wish to fill in later (therefore a Label) with values I have calc... | What problem are you having? The simple solution is to lay out widgets using `grid`. You can put whatever type of widget you want in each cell. And yes, labels can have borders. Though, a simple way to do grid lines is to use a padding around each cell, so that the color of the frame will show through the gaps.
Do thi... |
On adjusting margins in matplotlib | 11,049,038 | 4 | 2012-06-15T10:33:50Z | 11,051,531 | 9 | 2012-06-15T13:24:33Z | [
"python",
"matplotlib"
] | I am trying to minimize margins around a 1X2 figure, a figure which are two stacked subplots. I searched a lot and came up with commands like:
```
self.figure.subplots_adjust(left=0.01, bottom=0.01, top=0.99, right=0.99)
```
Which leaves a **large gap** on top and between the subplots. Playing with these parameters, ... | They're in figure coordinates: <http://matplotlib.sourceforge.net/users/transforms_tutorial.html>
To remove gaps between subplots, [use the `wspace` and `hspace` keywords](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.subplots_adjust) to `subplots_adjust`.
If you want to have things adjusted... |
How do I create an alias for a variable in Python? | 11,049,942 | 5 | 2012-06-15T11:35:24Z | 11,050,226 | 11 | 2012-06-15T11:58:28Z | [
"python",
"variables",
"alias"
] | ## Normal way
```
class A:
__init__():
self.a.b.c = 10
anotherMethod():
self.a.b.c = self.a.b.c * 10
```
## Aliased approach
```
class A:
__init__():
self.a.b.c = 10
alias self.aliased = self.a.b.c # Creates an alias
anotherMethod():
self.aliased = self.aliased ... | The solution to this is to use getter and setter methods - fortunately Python has [the `property()` builtin](http://docs.python.org/library/functions.html#property) to hide the ugliness of this.
```
class A:
def __init__():
self.a.b.c = 10
@property
def aliased(self):
return self.a.b.c
@... |
Prevent encoding errors in Python | 11,050,292 | 5 | 2012-06-15T12:04:10Z | 11,050,550 | 8 | 2012-06-15T12:22:00Z | [
"python",
"windows",
"encoding",
"console"
] | I have scripts which print out messages by the logging system or sometimes print commands. On the Windows console I get error messages like
```
Traceback (most recent call last):
File "C:\Python32\lib\logging\__init__.py", line 939, in emit
stream.write(msg)
File "C:\Python32\lib\encodings\cp850.py", line 19, ... | The problem is that your terminal/shell (cmd as your are on Windows) cannot print every Unicode character.
You can fail-safe encode your strings with the `errors` argument of the `str.encode` method. For example you can replace not supported chars with `?` by setting `errors='replace'`.
```
>>> s = u'\u2019'
>>> prin... |
Equivalent for pop on strings | 11,050,591 | 5 | 2012-06-15T12:24:40Z | 11,050,657 | 14 | 2012-06-15T12:29:31Z | [
"python",
"string",
"pop"
] | Given a very large string. I would like to process parts of the string in a loop like this:
```
large_string = "foobar..."
while large_string:
process(large_string.pop(200))
```
What is a nice and efficient way of doing this? | You can wrap the string in a `StringIO` or `BytesIO` and pretend it's a file. That should be pretty fast.
```
from cStringIO import StringIO
# or, in Py3/Py2.6+:
#from io import BytesIO, StringIO
s = StringIO(large_string)
while True:
chunk = s.read(200)
if len(chunk) > 0:
process(chunk)
if len(ch... |
python default parameter value using datetime | 11,050,714 | 2 | 2012-06-15T12:33:09Z | 11,050,761 | 19 | 2012-06-15T12:36:21Z | [
"python",
"datetime"
] | I have a simple Python script that uses a signal handler for Ctl-C. If the program completes normally, the end time is passed into the "print\_results" function. I wanted the print\_results function to have an optional parameter that, if not passed, simply gets the current "now" time. But when I call it from the signal... | The problem you are having is that you are evaluating the function in the parameter. This means that `ended=datetime.datetime.now()` takes the value of the time when this is being parsed, not when it is called. What you should do is something like this:
```
def print_results(ended=None):
if ended is None:
... |
No has_key() method for Python 3 dictionaries | 11,051,652 | 3 | 2012-06-15T13:31:31Z | 11,051,669 | 14 | 2012-06-15T13:32:48Z | [
"python",
"python-3.x"
] | I read "Python Cookbook" and see what in a recipe "Finding the Intersection of Two Dictionaries" authors recommend using such one-liner:
```
filter(another_dict.has_key, some_dict.keys())
```
But since Python 3 dictionaries don't have has\_key() method how should I modify suggested code? I suppose there could be some... | Python 3 has dictionary key views instead, a much more powerful concept. Your code can be written as
```
some_dict.keys() & another_dict.keys()
```
in Python 3.x. This returns the common keys of the two dictionaries as a set.
This is also available in Python 2.7, using the method `dict.viewkeys()`.
As a closer matc... |
Is there a faster way of converting a number to a name? | 11,052,808 | 8 | 2012-06-15T14:37:03Z | 11,053,813 | 7 | 2012-06-15T15:32:15Z | [
"python",
"namespaces",
"converter"
] | The following code defines a sequence of names that are mapped to numbers. It is designed to take a number and retrieve a specific name. The class operates by ensuring the name exists in its cache, and then returns the name by indexing into its cache. The question in this: **how can the name be calculated based on the ... | This is a fun little problem full of off by 1 errors.
Without loops:
```
import string
first_digits = sorted(string.ascii_letters + '_')
rest_digits = sorted(string.digits + string.ascii_letters + '_')
def convert(number):
if number < len(first_digits):
return first_digits[number]
current_base = le... |
How to read in floats from a file? | 11,053,318 | 2 | 2012-06-15T15:05:40Z | 11,053,403 | 9 | 2012-06-15T15:09:47Z | [
"python",
"string",
"file",
"floating-point"
] | How can I open a file and read in the floats from the file, when it is in string format, in Python? I would also like to change the values of the each float and rewrite the file over with the new values. | Assuming there's one float per line:
```
with open("myfile") as f:
floats = map(float, f)
# change floats
with open("myfile", "w") as f:
f.write("\n".join(map(str, floats)))
```
If you want more control with formatting, use the [`format` method](http://docs.python.org/library/string.html#formatstrings) of s... |
"for num in [1,4,5]" Python equivalent in C++? | 11,054,444 | 2 | 2012-06-15T16:08:59Z | 11,054,490 | 9 | 2012-06-15T16:11:42Z | [
"c++",
"python",
"for-loop"
] | Is there a direct analog to this in C++?
```
for num in [1,4,5] :
```
iterates through a loop using `num=1`, then `4`, then `5`. If I call continue within this loop it goes to the next number wherever I may call it.
Is there a similar structure in C++? | In C++11, the following is legal:
```
for (auto num : {1,4,5})
{
// loop body
}
```
`{1,4,5}` here is an instance of `std::initializer_list<int>`. |
Homebrew install libxml2 with python modules | 11,054,972 | 7 | 2012-06-15T16:46:37Z | 11,370,367 | 13 | 2012-07-06T22:17:12Z | [
"python",
"osx",
"libxml2",
"homebrew"
] | Good morning,
I'm trying to install libxml2 with python modules. I have tried the following:
```
brew install --with-python libxml2
==> Downloading ftp://xmlsoft.org/libxml2/libxml2-2.8.0.tar.gz
Already downloaded: /Users/brandon/Library/Caches/Homebre... | First, you cannot install libxml2 because you already successfully installed it, so you will first need to uninstall it.
`brew uninstall libxml2`
Next you will need to edit the brew formula - which is simple enough to do --
type
`brew edit libxml2` and change the line
```
system "./configure", "--prefix=#{prefix}",... |
Python multiprocessing global variable updates not returned to parent | 11,055,303 | 11 | 2012-06-15T17:13:18Z | 11,056,415 | 12 | 2012-06-15T18:39:33Z | [
"python",
"multiprocessing"
] | I am trying to return values from subprocesses but these values are unfortunately unpicklable. So I used global variables in threads module with success but have not been able to retrieve updates done in subprocesses when using multiprocessing module. I hope I'm missing something.
The results printed at the end are al... | When you use `multiprocessing` to open a second process, an *entirely new instance* of Python, with its own global state, is created. That global state is not shared, so changes made by child processes to global variables will be invisible to the parent process.
Additionally, most of the abstractions that `multiproces... |
python checking strings in a list? | 11,055,809 | 2 | 2012-06-15T17:53:05Z | 11,055,881 | 11 | 2012-06-15T17:58:26Z | [
"python",
"list"
] | I am trying to iterate through a list checking every string in the list for a character.
```
test = [str(i) for i in range(100)]
for i in test:
if '0' or '4' or '6' or '8' in str(i):
test.remove(i)
```
I thought this would be fine but, the list is this after:
```
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, ... | There are two issues with your code. The first is that you are modifying the list while iterating over it. The second is that you are using the `or` operator in the wrong way â the condition in the `if` statement will always be `True`.
Here's a fixed version:
```
test = [i for i in range(100) if set("0468").isdisjo... |
Huge memory usage of Python's json module? | 11,057,712 | 5 | 2012-06-15T20:23:47Z | 11,058,050 | 11 | 2012-06-15T20:53:08Z | [
"python",
"json",
"memory-leaks"
] | When I load the file into json, pythons memory usage spikes to about 1.8GB and I can't seem to get that memory to be released. I put together a test case that's very simple:
```
with open("test_file.json", 'r') as f:
j = json.load(f)
```
I'm sorry that I can't provide a sample json file, my test file has a lot of... | I think these two links address some interesting points about this not necessarily being a json issue, but rather just a "large object" issue and how memory works with python vs the operating system
See [Why doesn't Python release the memory when I delete a large object?](http://effbot.org/pyfaq/why-doesnt-python-rele... |
Python - Group by and sum a list of tuples | 11,058,001 | 7 | 2012-06-15T20:48:38Z | 11,058,060 | 8 | 2012-06-15T20:54:17Z | [
"python",
"group-by",
"list-comprehension"
] | Given the following list:
```
[
('A', '', Decimal('4.0000000000'), 1330, datetime.datetime(2012, 6, 8, 0, 0)),
('B', '', Decimal('31.0000000000'), 1330, datetime.datetime(2012, 6, 4, 0, 0)),
('AA', 'C', Decimal('31.0000000000'), 1330, datetime.datetime(2012, 5, 31, 0, 0)),
('B', '', Decimal('7.00000000... | You want [`itertools.groupby`](http://docs.python.org/library/itertools.html#itertools.groupby).
Note that `groupby` expects the input to be sorted, so you may need to do that before hand:
```
keyfunc = lambda t: (t[0], t[1], t[3], t[4])
data.sort(key=keyfunc)
for key, rows in itertools.groupby(data, keyfunc):
pr... |
python string syntax error += operator | 11,058,482 | 2 | 2012-06-15T21:32:19Z | 11,058,499 | 7 | 2012-06-15T21:34:26Z | [
"python",
"string"
] | I get a syntax error in Python 2.7.3 like so:
```
[s += 'Orig' for s in strs]
File "<stdin>", line 1
[s += 'Orig' for s in strs]
^
SyntaxError: invalid syntax
```
where strs is just a list of strings, like `['a', 'b', 'c', 'd']`
if I change the code to:
```
[s + 'Orig' for s in strs]
```
Then it work... | Assignment in Python (including `+=`) is a statement, not an expression. You can only use expressions in a list comprehension.
What does your example with `+` not do that you want it to do? |
python string syntax error += operator | 11,058,482 | 2 | 2012-06-15T21:32:19Z | 11,058,530 | 7 | 2012-06-15T21:36:53Z | [
"python",
"string"
] | I get a syntax error in Python 2.7.3 like so:
```
[s += 'Orig' for s in strs]
File "<stdin>", line 1
[s += 'Orig' for s in strs]
^
SyntaxError: invalid syntax
```
where strs is just a list of strings, like `['a', 'b', 'c', 'd']`
if I change the code to:
```
[s + 'Orig' for s in strs]
```
Then it work... | You can't do this. `s += 'Orig'` is shorthand for `s = s + Orig`, which is an assignment. For clarity reasons, python does not allow you place assignment statements inside other statements. See the [Why canât I use an assignment in an expression?](http://docs.python.org/faq/design.html#why-can-t-i-use-an-assignment-i... |
Django guests vote only once poll | 11,059,191 | 5 | 2012-06-15T23:02:33Z | 11,059,221 | 7 | 2012-06-15T23:06:21Z | [
"python",
"django"
] | I'm new to Django but am working on the tutorial on the Django website for creating a poll.
What is the best way to make it so guests (no registration / login) can only vote once on a poll?
* IP (Don't want IP because people sharing a network can only vote once).
* Cookie (User can delete the cookie but seems like th... | There is one solution independent on the server framework you use:
[Evercookie](http://samy.pl/evercookie/) gives you **virtually irrevokable cookies**. Use them, if you want that level of data persistence.
Evercookie is a solution for storing data in cookies and various other places (such as memory used by Flash "*c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.