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, remove all occurrences of string in list | 10,563,288 | 5 | 2012-05-12T11:25:45Z | 10,563,308 | 11 | 2012-05-12T11:28:15Z | [
"python",
"string",
"list"
] | Say i have a list:
```
main_list = ['bacon', 'cheese', 'milk', 'cake', 'tomato']
```
and another list:
```
second_list = ['cheese', 'tomato']
```
and I want to remove all elements that are found in the second list, from the main list?
Thank you in advance
Adam | ```
new_array = [x for x in main_array if x not in second_array]
```
However, this is not very performant for large lists. You can optimize by using a set for `second_array`:
```
second_array = set(second_array)
new_array = [x for x in main_array if x not in second_array]
```
If the order of the items does not matte... |
Does python officially support reusing a loop-variable after the loop? | 10,563,613 | 10 | 2012-05-12T12:12:54Z | 10,563,724 | 10 | 2012-05-12T12:27:09Z | [
"python"
] | Is the following code bad practice?
```
for i in some_values:
do_whatever(i)
do_more_things(i)
```
Somehow, it feels to me like the variable `i` should remain in the scope to the block inside the for-loop. However python 2.7 lets me reuse it after the loop.
Does python officially supports that feature, or am I a... | Yes, it's official:
```
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
> The target list is not deleted when the loop is finished
```
<http://docs.python.org/reference/compound_stmts.html#for>
Note that a [target list](http://docs.python.org/reference/simple_stmts.ht... |
How to unpack multiple tuples in function call | 10,564,801 | 18 | 2012-05-12T14:58:04Z | 10,564,819 | 20 | 2012-05-12T15:00:46Z | [
"python",
"tuples"
] | If I have a function `def f(a, b, c, d)` and two tuples, each with two elements, is there any way to unpack these tuples so that I can send their values to the function?
```
f(*tup1, *tup2)
``` | As of [the release of Python 3.5.0](https://www.python.org/downloads/release/python-350/), [PEP 448 "Additional Unpacking Generalizations"](http://www.python.org/dev/peps/pep-0448/) makes the natural syntax for this valid Python:
```
>>> f(*tup1, *tup2)
1 2 2 3
```
In older versions of Python, you can need to concate... |
How to unpack multiple tuples in function call | 10,564,801 | 18 | 2012-05-12T14:58:04Z | 10,564,833 | 10 | 2012-05-12T15:02:50Z | [
"python",
"tuples"
] | If I have a function `def f(a, b, c, d)` and two tuples, each with two elements, is there any way to unpack these tuples so that I can send their values to the function?
```
f(*tup1, *tup2)
``` | Another approach using `chain`
```
>>> from itertools import chain
>>> def foo(a,b,c,d):
print a,b,c,d
>>> tup1 = (1,2)
>>> tup2 = (3,4)
>>> foo(*chain(tup1,tup2))
1 2 3 4
``` |
pandas, python - how to select specific times in timeseries | 10,565,282 | 13 | 2012-05-12T16:05:17Z | 10,567,298 | 20 | 2012-05-12T20:46:40Z | [
"python",
"indexing",
"time-series",
"pandas"
] | I worked now for quite some time using python and pandas for analysing a set of hourly data and find it quite nice (Coming from Matlab.)
Now I am kind of stuck. I created my DataFrame like that:
```
SamplingRateMinutes=60
index = DateRange(initialTime,finalTime, offset=datetools.Minute(SamplingRateMinutes))
ts=DataFr... | In upcoming pandas 0.8.0, you'll be able to write
```
hour = ts.index.hour
selector = ((10 <= hour) & (hour <= 13)) | ((20 <= hour) & (hour <= 23))
data = ts[selector]
``` |
How can I access variables set in the python nosetests setup function | 10,565,523 | 16 | 2012-05-12T16:35:15Z | 10,573,740 | 11 | 2012-05-13T17:27:37Z | [
"python",
"nose"
] | I think what I'm trying to do is fairly simple. I want to initialize a couple of variables in a test setup function, and then use them in the test functions that are decorated with that setup. The following trivial example illustrates what I mean:
```
from nose.tools import *
def setup():
foo = 10
def teardown()... | As the comments to your question already suggested, simply switch to classes and use instance variables like `self.foo`. That's the way it should be done.
If you insist on not using classes, try `global` variables. You didn't hear this from me, though.
```
from nose.tools import *
foo = None
def setup():
global... |
Numpy: How to check if array contains certain numbers? | 10,565,598 | 8 | 2012-05-12T16:44:35Z | 10,565,640 | 9 | 2012-05-12T16:50:03Z | [
"python",
"numpy"
] | For example: I have `a = np.array([123, 412, 444])`
and `b = np.array([123, 321])`
I want to know if `a` contains **all** the elements in `b`. Is there a simple operation for this? In this case that would not be true. | You can use set difference to determine what you are looking for. Numpy has a built-in function called [numpy.setdiff1d(ar1, ar2)](http://docs.scipy.org/doc/numpy/reference/generated/numpy.setdiff1d.html):
> Return the sorted, unique values in ar1 that are not in ar2.
Example for your case:
```
>>> a = np.array([123... |
Numpy: How to check if array contains certain numbers? | 10,565,598 | 8 | 2012-05-12T16:44:35Z | 10,565,697 | 9 | 2012-05-12T16:56:13Z | [
"python",
"numpy"
] | For example: I have `a = np.array([123, 412, 444])`
and `b = np.array([123, 321])`
I want to know if `a` contains **all** the elements in `b`. Is there a simple operation for this? In this case that would not be true. | You could alway use a set:
```
>>> a = numpy.array([123, 412, 444])
>>> b = numpy.array([123, 321])
>>> set(b) in set(a)
False
```
Or with newer versions of numpy:
```
>>> numpy.in1d(b,a)
array([ True, False], dtype=bool)
```
If you want just 'the answer' rather than an array:
```
>>> numpy.in1d(b,a).all()
False
`... |
Decrypting in Python an string encrypted using .NET | 10,565,896 | 8 | 2012-05-12T17:21:47Z | 10,565,933 | 8 | 2012-05-12T17:25:40Z | [
"c#",
".net",
"python",
"string",
"encryption"
] | I am trying to encrypt a string using C# and decrypt it using Python. The encryption/decryption part works as expected (i.e. I am able to decrypt the string I originally encrypted). However the string returned by Python has 2 extra bytes at the beginning and each character is separated by a space.
```
**Original strin... | The string is encoded to bytes using the UTF-16 encoding. The first two bytes are a BOM. Then each character is encoded to two bytes.
From the documentation for [`Encoding.Unicode`](http://msdn.microsoft.com/en-us/library/system.text.encoding.unicode.aspx):
> Gets an encoding for the UTF-16 format using the little en... |
python: read lines from compressed text files | 10,566,558 | 24 | 2012-05-12T19:02:49Z | 10,566,577 | 11 | 2012-05-12T19:04:55Z | [
"python",
"large-files",
"decompression"
] | Is it easy to read a line from a gz-compressed text file using python without extracting the file completely? I have a text.gz file which is aroud 200mb. When I extract it, it becomes 7.4gb. And this is not the only file I have to read. For the total process, I have to read 10 files. Although this will be a sequential ... | Have you tried using [gzip.GzipFile](http://docs.python.org/library/gzip.html#gzip.GzipFile)? Arguments are similar to `open`. |
python: read lines from compressed text files | 10,566,558 | 24 | 2012-05-12T19:02:49Z | 10,566,609 | 32 | 2012-05-12T19:10:21Z | [
"python",
"large-files",
"decompression"
] | Is it easy to read a line from a gz-compressed text file using python without extracting the file completely? I have a text.gz file which is aroud 200mb. When I extract it, it becomes 7.4gb. And this is not the only file I have to read. For the total process, I have to read 10 files. Although this will be a sequential ... | You could use the standard gzip module in python. Just use:
```
gzip.open('myfile.gz')
```
to open the file as any other file and read its lines.
More information here: [Python gzip module](http://docs.python.org/library/gzip.html) |
python: read lines from compressed text files | 10,566,558 | 24 | 2012-05-12T19:02:49Z | 30,868,178 | 8 | 2015-06-16T12:54:05Z | [
"python",
"large-files",
"decompression"
] | Is it easy to read a line from a gz-compressed text file using python without extracting the file completely? I have a text.gz file which is aroud 200mb. When I extract it, it becomes 7.4gb. And this is not the only file I have to read. For the total process, I have to read 10 files. Although this will be a sequential ... | Using [gzip.GzipFile](http://docs.python.org/library/gzip.html#gzip.GzipFile):
```
import gzip
with gzip.open('input.gz','r') as fin:
for line in fin:
print('got line', line)
```
Note that `gzip.open(filename, mode)` is an alias for `gzip.GzipFile(filename, mode)` |
If else based on existence of python function optional arguments | 10,567,644 | 3 | 2012-05-12T21:48:18Z | 10,567,668 | 12 | 2012-05-12T21:54:14Z | [
"python",
"arguments"
] | I have written a function as follows, with optional argument 'b'.
url depends on the existence of b.
```
def something(a, b=None)
if len(b) >= 1:
url = 'http://www.xyz.com/%sand%s' % (a, b)
else:
url = 'http://www.xyz.com/%s' (a)
```
This raises an error when `b=None`, saying *"object of type... | You can simply use `if b:` - this will require the value to be both not `None` and not an empty string/list/whatever. |
Is it safe to use the python word "type" in my code? | 10,568,087 | 12 | 2012-05-12T23:08:15Z | 10,568,115 | 21 | 2012-05-12T23:12:27Z | [
"python",
"python-2.7",
"reserved-words"
] | Can I use the word "type" in my own code or is it reserved? My function header:
```
def get(
self,
region='Delhi',
city='Delhi',
category='Apartments',
type='For sale',
limit = 60,
PAGESIZE=5,
year=2012,
month=1,
day=1,
next_page=None,
threetapspage=0,
):
```
Thank you | Using `type` as a keyword argument to a function will mask the [built-in function "type"](http://docs.python.org/library/functions.html#type) within the scope of the function. So while doing so does not raise a `SyntaxError`, it is not considered good practice, and I would avoid doing so. |
Merge multiple zip files into a single zip file in Python | 10,568,468 | 8 | 2012-05-13T00:28:46Z | 10,568,688 | 9 | 2012-05-13T01:30:55Z | [
"python",
"zip"
] | I have multiple zip files that have the same structure -- they contain XML files at the root level. All files in each zip file are unique (no duplicates across the zip files). I need to combine all of the XML files from all of the zip files into a single zip file (with the same structure as the original zip files). Sug... | This is the shortest version I could come up with:
```
>>> import zipfile as z
>>> z1 = z.ZipFile('z1.zip', 'a')
>>> z2 = z.ZipFile('z2.zip', 'r')
>>> z1.namelist()
['a.xml', 'b.xml']
>>> z2.namelist()
['c.xml', 'd.xml']
>>> [z1.writestr(t[0], t[1].read()) for t in ((n, z2.open(n)) for n in z2.namelist())]
[None, None... |
Two arguments in django-admin custom command | 10,568,864 | 7 | 2012-05-13T02:25:22Z | 10,568,955 | 12 | 2012-05-13T02:49:15Z | [
"python",
"django",
"django-admin",
"arguments"
] | I have a **working** django-admin custom command that I use to populate my database with new information. Again, everything works.
However, I have now changed my models and function slightly to accept two arguments as a tuple - first name **and** last name, instead of just "name".
Previous code below - working. Run u... | It's entirely possible, although `django.core.management` does not provide a specific tool to do so. You can parse the arguments passed via the `args` keyword argument. You'll have to come up with a syntax for doing so (defining the syntax in the `help` attribute of the command would probably be a good idea).
Assuming... |
How to read a RSA public key in PEM + PKCS#1 format | 10,569,189 | 22 | 2012-05-13T03:47:27Z | 10,574,723 | 18 | 2012-05-13T19:53:19Z | [
"python",
"cryptography",
"x509",
"pycrypto",
"key-management"
] | I have a RSA public key in PEM format + PKCS#1(I guess):
```
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBAJNrHWRFgWLqgzSmLBq2G89exgi/Jk1NWhbFB9gHc9MLORmP3BOCJS9k
onzT/+Dk1hdZf00JGgZeuJGoXK9PX3CIKQKRQRHpi5e1vmOCrmHN5VMOxGO4d+zn
JDEbNHODZR4HzsSdpQ9SGMSx7raJJedEIbr0IP6DgnWgiA7R1mUdAgMBAAE=
-----END RSA PUBLIC KEY-----
```
I ... | PyCrypto supports *PKCS#1* in the sense that it can read in X.509 `SubjectPublicKeyInfo` objects that *contain* an RSA public key encoded in *PKCS#1*.
Instead, the data encoded in your key is a pure `RSAPublicKey` object (that is, an ASN.1 SEQUENCE with two INTEGERs, modulus and public exponent).
You can still read i... |
Django-Pinax : How do you use a pinax app apart from what you get with a pinax base project? | 10,569,310 | 14 | 2012-05-13T04:26:34Z | 10,908,828 | 8 | 2012-06-06T05:54:05Z | [
"python",
"django",
"pinax",
"django-1.3"
] | I am trying to understand **Pinax** and plan to use it in my next project.
I have started with a **pinax basic project**, and now I have something to go with **runserver**.
Now, I understand that I can customize the initial setup that I got from pinax and customize the profiles, themes, etc as per my requirements.
*... | You seem to be assuming that unless *all* of Pinax is useful, Pinax as a project isn't useful. It was never the intention that Pinax be a single thing, all of which you use on a given project.
If all you find helpful is the project layout, that's fine. Pinax suggests a standard project layout (which you can use alone ... |
How to print Unicode character in Python? | 10,569,438 | 42 | 2012-05-13T05:00:57Z | 10,569,468 | 10 | 2012-05-13T05:07:50Z | [
"python",
"python-unicode"
] | I want to make a dictionary where English words point to Russian and French translations.
How do I print out unicode characters in Python? Also, how do you store unicode chars in a variable? | In Python 2, you declare unicode strings with a `u`, as in `u"ç«"` and use `decode()` and `encode()` to translate to and from unicode, respectively.
It's quite a bit easier in Python 3. A very good overview can be found [here](http://pyvideo.org/video/948/pragmatic-unicode-or-how-do-i-stop-the-pain). That presentatio... |
How to print Unicode character in Python? | 10,569,438 | 42 | 2012-05-13T05:00:57Z | 10,569,477 | 43 | 2012-05-13T05:10:04Z | [
"python",
"python-unicode"
] | I want to make a dictionary where English words point to Russian and French translations.
How do I print out unicode characters in Python? Also, how do you store unicode chars in a variable? | To include Unicode characters in your Python source code, you can use [Unicode escape characters](http://docs.python.org/howto/unicode.html#unicode-literals-in-python-source-code) in the form `\u0123` in your string, and prefix the string literal with 'u'.
Here's an example running in the Python interactive console:
... |
How to print Unicode character in Python? | 10,569,438 | 42 | 2012-05-13T05:00:57Z | 20,447,935 | 23 | 2013-12-07T23:20:41Z | [
"python",
"python-unicode"
] | I want to make a dictionary where English words point to Russian and French translations.
How do I print out unicode characters in Python? Also, how do you store unicode chars in a variable? | ## Print a unicode character in Python:
**Print a unicode character directly from python interpreter:**
```
el@apollo:~$ python
Python 2.7.3
>>> print u'\u2713'
â
```
Unicode character `u'\u2713'` is a checkmark. The interpreter prints the checkmark on the screen.
**Print a unicode character from a python script:... |
how to get all keys&values in nested dict of list-of-dicts and dicts? | 10,569,636 | 10 | 2012-05-13T05:57:23Z | 10,569,687 | 7 | 2012-05-13T06:08:26Z | [
"python",
"list",
"dictionary"
] | ```
{'action_name':'mobile signup',
'functions':[{'name':'test_signUp',
'parameters':{'username':'max@getappcard.com',
'password':'12345',
'mobileLater':'123454231',
'mobile':'1e2w1e2w',
... | You might want to use a recursive function to extract all the `key, value` pairs.
```
def extract(dict_in, dict_out):
for key, value in dict_in.iteritems():
if isinstance(value, dict): # If value itself is dictionary
extract(value, dict_out)
elif isinstance(value, unicode):
... |
How to make a redirect and keep the query string? | 10,569,768 | 10 | 2012-05-13T06:26:14Z | 10,590,179 | 13 | 2012-05-14T19:57:44Z | [
"python",
"google-app-engine",
"python-2.7",
"wsgi",
"webapp2"
] | I want to make a redirect and keep what is the query string. Something like `self.redirect` plus the query parameters that was sent. Is that possible? | ```
newurl = '/my/new/route?' + urllib.urlencode(self.request.params)
self.redirect(newurl)
``` |
How to make a redirect and keep the query string? | 10,569,768 | 10 | 2012-05-13T06:26:14Z | 10,594,001 | 7 | 2012-05-15T04:03:26Z | [
"python",
"google-app-engine",
"python-2.7",
"wsgi",
"webapp2"
] | I want to make a redirect and keep what is the query string. Something like `self.redirect` plus the query parameters that was sent. Is that possible? | You can fetch the query string to the current request with `self.request.query_string`; thus you can redirect to a new URL with `self.redirect('/new/url?' + self.request.query_string)`. |
self.attr resets between tests in unittest.TestCase | 10,570,307 | 6 | 2012-05-13T08:24:04Z | 10,570,433 | 7 | 2012-05-13T08:46:37Z | [
"python",
"unit-testing"
] | I'd like to use a `self.attr` of a `unittest.TestCase` class, however it seems it is not persistent between tests:
```
import unittest
class TestNightlife(unittest.TestCase):
_my_param = 0
def test_a(self):
print 'test A = %d' % self._my_param
self._my_param = 1
def test_b(self):
... | It works that way because unittest.main() create separate object for every test (in this case two objects are created).
About your motivation: test should not change global state. You should revert global state to state before test in tearDown or test itself. It's very problematic if tests are changing global state, y... |
Scrapy: ImportError: No module named items | 10,570,635 | 11 | 2012-05-13T09:22:36Z | 10,570,868 | 20 | 2012-05-13T10:01:45Z | [
"python",
"scrapy"
] | When I try to run scrapy I get this error ImportError: No module named items
I just added in items.py the list of things I want to scrape and in the spider.py I have imported the class with from spider.items import SpiderItem
Dont know why its not loading it...
Package layout is...
```
./spider
./spider/pipelines.p... | From [this message on google groups](http://groups.google.com/group/scrapy-users/msg/13e4127878714417) (which 1 minute of searching would have found)
Your spider module is named the same as your scrapy project module, so
python is trying to import items relative to byub.py spider.
You are facing a common regret of py... |
imaplib - What is the correct folder name for Archive/All Mail in Gmail? | 10,570,889 | 4 | 2012-05-13T10:04:49Z | 10,574,029 | 7 | 2012-05-13T18:07:18Z | [
"python",
"email",
"gmail",
"imaplib"
] | I have a script which exports all the email in Gmail as text files.
It works fine with this line where you select the folder:
```
mail.select("inbox")
```
But I am not sure what the name is for Gmail's archive, where all of the email is stored. I've tried archive and all mail and stuff, but no luck.
Anyone know the... | Solved it.
It is `[Gmail]/All Mail` or, if you are a Gmail UK user like me, it may be `[Google Mail]/All Mail`, because Gmail used to be called Google Mail in the UK due to trademark issues.
If you're doing this for general use, I'd recommend testing to see if `[Gmail]/All Mail` works (most common), and if not testin... |
How can I disable the Django Celery admin modules? | 10,571,960 | 6 | 2012-05-13T13:03:01Z | 10,573,827 | 16 | 2012-05-13T17:41:38Z | [
"python",
"django",
"django-admin",
"celery",
"django-celery"
] | I have no need to the celery modules in my Django admin. Is there a way I could remove it? | To be more specific, in `admin.py` of any app inside `INSTALLED_APPS` after `'djcelery'`
```
from django.contrib import admin
from djcelery.models import (TaskState, WorkerState,
PeriodicTask, IntervalSchedule, CrontabSchedule)
admin.site.unregister(TaskState)
admin.site.unregister(WorkerState)
admin... |
find position of a substring in a string | 10,572,199 | 10 | 2012-05-13T13:37:23Z | 10,572,235 | 11 | 2012-05-13T13:43:25Z | [
"python",
"string",
"find",
"position"
] | i am having a python string of format
```
mystr = "hi.this(is?my*string+"
```
here i need to get the position of 'is' that is surrounded by special characters or non-alphabetic characters (i.e. second 'is' in this example). however, using
```
mystr.find('is')
```
will return the position if 'is' that is associated ... | Here the best option is to use a regular expression. Python has [the `re` module](http://docs.python.org/library/re.html) for working with regular expressions.
We use a simple search to find the position of the `"is"`:
```
>>> match = re.search(r"[^a-zA-Z](is)[^a-zA-Z]", mystr)
```
This returns the first match as a ... |
Halftone Images In Python | 10,572,274 | 5 | 2012-05-13T13:47:38Z | 10,575,940 | 16 | 2012-05-13T23:11:26Z | [
"python",
"image",
"processing",
"cmyk"
] | I am working on a project that requires me to separate out each color in a CYMK image and generate a halftone image that will be printed on a special halftone printer. The method used is analogues to silk screening in that the process is almost identical. Take a photo and break out each color channel. Then produce a sc... | I used to run a screen printing studio (it was a fairly small one), and although I have never actually done colour separation printing, I am reasonably familiar with the principles. This is how I would approach it:
1. Split the image into C, M, Y, K.
2. Rotate each separated image by 0, 15, 30, and 45 degrees respecti... |
ImportError: No module named sqlalchemy | 10,572,498 | 19 | 2012-05-13T14:22:42Z | 10,572,551 | 47 | 2012-05-13T14:32:54Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy"
] | I'm unable to find a module in python ,though easy\_install says its already installed.
Any idea how to resolve this isseue?
```
$ python -c "from flaskext.sqlalchemy import SQLAlchemy"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named sqlalchemy
$ python -V
Pytho... | Did you install [`flaskext.sqlalchemy`](http://packages.python.org/Flask-SQLAlchemy/)? It looks like you have the SQLAlchemy package installed but not the flask Extension. Try `pip install Flask-SQLAlchemy` or `easy_install Flask-SQLAlchemy`. It is [available in the cheeseshop](http://pypi.python.org/pypi/Flask-SQLAlch... |
ImportError: No module named sqlalchemy | 10,572,498 | 19 | 2012-05-13T14:22:42Z | 10,593,364 | 7 | 2012-05-15T02:12:50Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy"
] | I'm unable to find a module in python ,though easy\_install says its already installed.
Any idea how to resolve this isseue?
```
$ python -c "from flaskext.sqlalchemy import SQLAlchemy"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named sqlalchemy
$ python -V
Pytho... | Okay,I have re-installed the package via pip even that didn't help. And then I rsync'ed the entire /usr/lib/python-2.7 directory from other working machine with similar configuration to
the current machine.It started working. I don't have any idea ,what was wrong with my setup. I see some difference "print sys.path" ou... |
ImportError: No module named sqlalchemy | 10,572,498 | 19 | 2012-05-13T14:22:42Z | 10,775,143 | 26 | 2012-05-27T15:33:42Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy"
] | I'm unable to find a module in python ,though easy\_install says its already installed.
Any idea how to resolve this isseue?
```
$ python -c "from flaskext.sqlalchemy import SQLAlchemy"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named sqlalchemy
$ python -V
Pytho... | I just experienced the same problem. Apparently, there is a new distribution method, the extension code is no longer stored under `flaskext`.
**Source:** Flask [CHANGELOG](https://github.com/mitsuhiko/flask-sqlalchemy/blob/master/CHANGES)
This worked for me:
```
from flask_sqlalchemy import SQLAlchemy
``` |
Specifying optional dependencies in pypi python setup.py | 10,572,603 | 11 | 2012-05-13T14:41:21Z | 10,572,833 | 15 | 2012-05-13T15:11:27Z | [
"python",
"setup.py",
"pypi"
] | How do I specify optional dependencies in python's `setup.py` ?
Here's my stab at specifying an optional dependency for an open source library of mine but it doesn't seem to do much.
<https://github.com/od-eon/django-cherrypy/blob/master/setup.py>
Specifically `extra_requires` in this snippet:
```
setup(
name='... | You've got an incorrect keyword. It's `extras_require`, and [it's supposed to be a dict.](http://peak.telecommunity.com/DevCenter/setuptools#declaring-extras-optional-features-with-their-own-dependencies)
```
setup(
name="django-cherrypy",
...
extras_require = {
'mysterious_feature_x': ["newrelic"... |
Mutable strings in Python | 10,572,624 | 20 | 2012-05-13T14:45:10Z | 10,572,745 | 13 | 2012-05-13T15:01:07Z | [
"python",
"string",
"mutable"
] | Please, do you know of a Python library which provides mutable strings? Google returned surprisingly few results. The only usable library I found is <http://code.google.com/p/gapbuffer/> which is in C but I would prefer it to be written in pure Python.
Edit: Thanks for the responses but I'm after an *efficient* librar... | In Python mutable sequence type is **bytearray\*** see [this link](http://docs.python.org/library/stdtypes.html#typesseq-mutable) |
Mutable strings in Python | 10,572,624 | 20 | 2012-05-13T14:45:10Z | 10,572,792 | 11 | 2012-05-13T15:06:55Z | [
"python",
"string",
"mutable"
] | Please, do you know of a Python library which provides mutable strings? Google returned surprisingly few results. The only usable library I found is <http://code.google.com/p/gapbuffer/> which is in C but I would prefer it to be written in pure Python.
Edit: Thanks for the responses but I'm after an *efficient* librar... | ```
class MutableString(object):
def __init__(self, data):
self.data = list(data)
def __repr__(self):
return "".join(self.data)
def __setitem__(self, index, value):
self.data[index] = value
def __getitem__(self, index):
if type(index) == slice:
return "".join(... |
Mutable strings in Python | 10,572,624 | 20 | 2012-05-13T14:45:10Z | 26,172,377 | 12 | 2014-10-03T02:14:49Z | [
"python",
"string",
"mutable"
] | Please, do you know of a Python library which provides mutable strings? Google returned surprisingly few results. The only usable library I found is <http://code.google.com/p/gapbuffer/> which is in C but I would prefer it to be written in pure Python.
Edit: Thanks for the responses but I'm after an *efficient* librar... | This will allow you to efficiently change characters in a string. Although you can't change the string length.
```
>>> import ctypes
>>> a = 'abcdefghijklmn'
>>> mutable = ctypes.create_string_buffer(a)
>>> mutable[5:10] = ''.join( reversed(list(mutable[5:10].upper())) )
>>> a = mutable.value
>>> print `a, type(a)`
(... |
Connecting two points in a 3D scatter plot in Python and matplotlib | 10,572,939 | 9 | 2012-05-13T15:29:00Z | 10,573,237 | 12 | 2012-05-13T16:15:45Z | [
"python",
"matplotlib",
"mplot3d"
] | In the code below, how do I create lines connecting each pair of scatter plots (i.e. linking the green circle to the yellow arrowhead) created by the two lines of code towards the end just before the .show() instruction?
```
import matplotlib.pyplot
from mpl_toolkits.mplot3d import Axes3D
dates = [20020514, 200... | Draw a line segment between those points:
```
import matplotlib.pyplot
from mpl_toolkits.mplot3d import Axes3D
dates = [20020514, 20020515, 20020516, 20020517, 20020520]
highs = [1135, 1158, 1152, 1158, 1163]
lows = [1257, 1253, 1259, 1264, 1252]
upperLimits = [1125.0, 1125.0, 1093.75, 1125.0, 1125... |
Slicing a list using a variable, in Python | 10,573,485 | 11 | 2012-05-13T16:52:02Z | 10,573,523 | 27 | 2012-05-13T16:56:48Z | [
"python",
"list",
"slice"
] | Given a list
```
a = range(10)
```
You can slice it using statements such as
```
a[1]
a[2:4]
```
However, I want to do this based on a variable set elsewhere in the code. I can easily do this for the first one
```
i = 1
a[i]
```
But how do I do this for the other one? I've tried indexing with a list:
```
i = [2,... | that's what [`slice()`](http://docs.python.org/library/functions.html#slice) is for:
```
a = range(10)
s = slice(2,4)
print a[s]
```
but that's not really so much different then using `a[2:4]`. |
Python, transposing a list and writing to a CSV file | 10,573,915 | 10 | 2012-05-13T17:52:30Z | 10,573,941 | 8 | 2012-05-13T17:55:34Z | [
"python",
"list",
"csv"
] | I need to write into a csv file using python and each iterator item should start in a new line.
So delimiter I am using is "\n".
After each list has been written,next list should write from next cell.
like below:
```
lol = [[1,2,3],[4,5,6]]
```
The csv will be like:
```
1 4
2 5
3 6
```
What I have tried:
```
file... | first transpose your input by using `zip()`
```
>>> zip(*lol)
[(1, 4), (2, 5), (3, 6)]
```
and after that just pass it to `csw.writer` e.g.
```
with open("test.csv", "wb") as f:
fileWriter = csv.writer(f, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)
for row in zip(*lol):
fileWriter.writero... |
Python, transposing a list and writing to a CSV file | 10,573,915 | 10 | 2012-05-13T17:52:30Z | 10,574,198 | 11 | 2012-05-13T18:32:44Z | [
"python",
"list",
"csv"
] | I need to write into a csv file using python and each iterator item should start in a new line.
So delimiter I am using is "\n".
After each list has been written,next list should write from next cell.
like below:
```
lol = [[1,2,3],[4,5,6]]
```
The csv will be like:
```
1 4
2 5
3 6
```
What I have tried:
```
file... | Without using zip, you could do this:
```
import csv
lol = [[1,2,3],[4,5,6],[7,8,9]]
item_length = len(lol[0])
with open('test.csv', 'wb') as test_file:
file_writer = csv.writer(test_file)
for i in range(item_length):
file_writer.writerow([x[i] for x in lol])
```
This will output into test.csv:
```
1,4,7
2... |
Python: wrapping recursive functions | 10,574,227 | 7 | 2012-05-13T18:37:25Z | 10,574,292 | 9 | 2012-05-13T18:45:52Z | [
"python",
"higher-order-functions"
] | How can I wrap a recursive function, recursive calls included? For example, given `foo` and `wrap`:
```
def foo(x):
return foo(x - 1) if x > 0 else 1
def wrap(f):
def wrapped(*args, **kwargs):
print "f was called"
return f(*args, **kwargs)
return wrapped
```
`wrap(foo)(x)` will only outp... | It works if you use your wrapper function as a decorator.
```
def wrap(f):
def wrapped(*args, **kwargs):
print "f was called"
return f(*args, **kwargs)
return wrapped
@wrap
def foo(x):
return foo(x - 1) if x > 0 else 1
```
Reason being that in your example, you're only calling the result... |
using a sage function standalone within python | 10,575,190 | 5 | 2012-05-13T20:58:10Z | 10,639,237 | 12 | 2012-05-17T15:59:46Z | [
"python",
"sage"
] | There is a function within sage, latex, that I want to use in directly from the command line, without dropping into sage the sage client. one way I think this may be possible is to include that sage module into my python script.
using pip install sage doesn't work.
any ideas? | You can't just install Sage as a package with a package, and there is tons of non-Python code in Sage, so it would be hard to do this a priori.
However, you can call Sage from a script pretty easily. [Here](http://ask.sagemath.org/question/646/using-sage-in-a-python-cgi-script) is an example.
For anyone finding this,... |
Python - IOError: [Errno 13] Permission denied: | 10,575,750 | 17 | 2012-05-13T22:29:48Z | 10,575,888 | 9 | 2012-05-13T23:00:10Z | [
"python",
"file",
"io"
] | Im getting IOError: [Errno 13] Permission denied, i dont know what im doing wrong.
Im trying to read a file given an absolute path (meaning only file.asm),
and a relative path (meaning /.../file.asm) and i want the program to write the file
to whatever path is given - if it is absolute, it should write it to the cur... | It looks like you're trying to replace the extension with the following code:
```
if (myFile[-4:] == ".asm"):
newFile = myFile[:4]+".hack"
```
However, you appear to have the array indexes mixed up. Try the following:
```
if (myFile[-4:] == ".asm"):
newFile = myFile[:-4]+".hack"
```
Note the use of `-4` ins... |
Python - IOError: [Errno 13] Permission denied: | 10,575,750 | 17 | 2012-05-13T22:29:48Z | 22,349,898 | 14 | 2014-03-12T11:20:19Z | [
"python",
"file",
"io"
] | Im getting IOError: [Errno 13] Permission denied, i dont know what im doing wrong.
Im trying to read a file given an absolute path (meaning only file.asm),
and a relative path (meaning /.../file.asm) and i want the program to write the file
to whatever path is given - if it is absolute, it should write it to the cur... | **Just Close the opened file where you are going to write.** |
Python: Usable Max and Min values | 10,576,548 | 18 | 2012-05-14T01:16:08Z | 10,576,599 | 9 | 2012-05-14T01:26:14Z | [
"python",
"python-3.x"
] | Python 2.x allows heterogeneous types to be compared.
A useful shortcut (in Python 2.7 here) is that `None` compares smaller than any integer or float value:
```
>>> None < float('-inf') < -sys.maxint * 2l < -sys.maxint
True
```
And in Python 2.7 an empty tuple `()` is an infinite value:
```
>>> () > float('inf') >... | You have the most obvious choices in your question already: `float('-inf')` and `float('inf')`.
Also, note that `None` being less than everything and the empty tuple being higher than everything wasn't ever *guaranteed* in Py2, and, eg, Jython and PyPy are perfectly entitled to use a different ordering if they feel li... |
Python: Usable Max and Min values | 10,576,548 | 18 | 2012-05-14T01:16:08Z | 10,577,337 | 10 | 2012-05-14T03:52:35Z | [
"python",
"python-3.x"
] | Python 2.x allows heterogeneous types to be compared.
A useful shortcut (in Python 2.7 here) is that `None` compares smaller than any integer or float value:
```
>>> None < float('-inf') < -sys.maxint * 2l < -sys.maxint
True
```
And in Python 2.7 an empty tuple `()` is an infinite value:
```
>>> () > float('inf') >... | For numerical comparisons, `+- float("inf")` should work.
EDIT: It doesn't always work (but covers the realistic cases):
```
print(list(sorted([float("nan"), float("inf"), float("-inf"), float("nan"), float("nan")])))
# NaNs sort above and below +-Inf
# However, sorting a container with NaNs makes little sense, so no... |
Python file exercise issue | 10,576,724 | 2 | 2012-05-14T01:52:08Z | 10,576,729 | 7 | 2012-05-14T01:53:07Z | [
"python",
"python-3.x"
] | I'm following a tutorial in a textbook, "Starting out with python 2nd edition" and I'm getting a traceback with this exercise in IDLE 3.2. I can't seem to figure out the issue, it allows me to input the number of sales then only 1 sales amount it the echos "Data written to sales.txt." then displays the prompt for day 2... | You are closing the file inside the for-loop. Next time through the loop when you write to the file, you are trying to write to a file that has been closed, hence the error message that says `I/O operation on closed file.`.
Move the line
```
sales_file.close()
```
to after the print statement at the bottom of the fo... |
How to generate negative random value in python | 10,579,518 | 5 | 2012-05-14T08:04:58Z | 10,579,562 | 19 | 2012-05-14T08:08:12Z | [
"python",
"random"
] | I am starting to learn python, I tried to generate random values by passing in a negative and positive number. Let say `-1`, `1`.
How should I do this in python? | Use [`random.uniform(a, b)`](http://docs.python.org/library/random.html#random.uniform)
```
>>> import random
>>> random.uniform(-1, 1)
0.4779007751444888
>>> random.uniform(-1, 1)
-0.10028581710574902
``` |
ImportError: No module named objectid | 10,579,704 | 9 | 2012-05-14T08:19:01Z | 10,919,658 | 38 | 2012-06-06T18:04:30Z | [
"python",
"django",
"mongodb",
"pymongo",
"django-mongodb-engine"
] | I have currently [django-mongodb-engine](http://django-mongodb.org/) 0.4.0 version installed on my Mac OS X 10.6.8 and weirdly encountered an interesting error while importing the 'compiler' module:
```
>> from django_mongodb_engine import compiler
```
and I got the following error:
```
ImportError Traceback (most r... | I've ran into something similar, for me the problem was this line:
```
from pymongo.objectid import ObjectId
```
The call seems to work in versions of PyMongo < 2.2
In pymongo 2.2 the call to import objectid is:
```
from bson.objectid import ObjectId
``` |
What is the difference between Python vs Jython vs IronPython vs wxPython? | 10,579,824 | 20 | 2012-05-14T08:29:13Z | 10,579,887 | 48 | 2012-05-14T08:34:15Z | [
"python"
] | I am quite new in Python programming. While googling I found some of the `Python` related words. I just wanted to know what is the difference among Python, Jython, IronPython, and wxPython.
I know `wxPython` is for GUI programming. But what are Jython and IronPython?
Please help me. | Jython and IronPython are different python implementations, both of which run on different virtual machines. Jython runs on the JVM (Java virtual machine) and IronPython runs on the CLR (common language runtime). This means that programs using these implementations can take advantage of the libraries and ecosystem of t... |
Comparing two numpy arrays for equality, element-wise | 10,580,676 | 78 | 2012-05-14T09:30:18Z | 10,580,782 | 130 | 2012-05-14T09:37:13Z | [
"python",
"arrays",
"python-3.x",
"numpy",
"elementwise-operations"
] | What is the simplest way to compare two numpy arrays for equality (where equality is defined as: A = B iff for all indices i: `A[i]Â == B[i]`)?
Simply using `==` gives me a boolean array:
```
>>> numpy.array([1,1,1]) == numpy.array([1,1,1])
array([ True, True, True], dtype=bool)
```
Do I have to `and` the elemen... | ```
(A==B).all()
```
test if all values of array (A==B) are True.
**Edit** (from dbaupp's answer and yoavram's comment)
It should be noted that:
* this solution can have a strange behavior in a particular case: if either `A` or `B` is empty and the other one contains a single element, then it return `True`. For som... |
Comparing two numpy arrays for equality, element-wise | 10,580,676 | 78 | 2012-05-14T09:30:18Z | 10,582,030 | 51 | 2012-05-14T11:00:58Z | [
"python",
"arrays",
"python-3.x",
"numpy",
"elementwise-operations"
] | What is the simplest way to compare two numpy arrays for equality (where equality is defined as: A = B iff for all indices i: `A[i]Â == B[i]`)?
Simply using `==` gives me a boolean array:
```
>>> numpy.array([1,1,1]) == numpy.array([1,1,1])
array([ True, True, True], dtype=bool)
```
Do I have to `and` the elemen... | The `(A==B).all()` solution is very neat, but there are some built-in functions for this task. Namely [`array_equal`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.array_equal.html), [`allclose`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html#numpy.allclose) and [`array_equiv`](http... |
Comparing two numpy arrays for equality, element-wise | 10,580,676 | 78 | 2012-05-14T09:30:18Z | 35,579,156 | 7 | 2016-02-23T13:42:04Z | [
"python",
"arrays",
"python-3.x",
"numpy",
"elementwise-operations"
] | What is the simplest way to compare two numpy arrays for equality (where equality is defined as: A = B iff for all indices i: `A[i]Â == B[i]`)?
Simply using `==` gives me a boolean array:
```
>>> numpy.array([1,1,1]) == numpy.array([1,1,1])
array([ True, True, True], dtype=bool)
```
Do I have to `and` the elemen... | Let's measure the performance by using the following piece of code.
```
import numpy as np
import time
exec_time0 = []
exec_time1 = []
exec_time2 = []
sizeOfArray = 5000
numOfIterations = 200
for i in xrange(numOfIterations):
A = np.random.randint(0,255,(sizeOfArray,sizeOfArray))
B = np.random.randint(0,25... |
Python Subversion wrapper library | 10,582,469 | 6 | 2012-05-14T11:31:23Z | 10,583,978 | 9 | 2012-05-14T13:09:08Z | [
"python",
"svn",
"easy-install"
] | In Subversion's [documentation](http://svnbook.red-bean.com/en/1.7/svn.developer.usingapi.html#svn.developer.usingapi.otherlangs) there's an example of using Subversion from Python
```
#!/usr/bin/python
import svn.fs, svn.core, svn.repos
def crawl_filesystem_dir(root, directory):
"""Recursively crawl DIRECTORY un... | The library referred to by this documentation is the SWIG-based wrappers which build and ship with Subversion itself. Thus -- if your operating system's package is `subversion`, look for a `subversion-python` package to ship alongside it. If you're building subversion from source, you'll want to use the `--with-python`... |
Python: why can isinstance return False, when it should return True? | 10,582,774 | 8 | 2012-05-14T11:50:12Z | 10,582,820 | 10 | 2012-05-14T11:54:12Z | [
"python",
"isinstance"
] | I'm currently in pdb trace to figure this out
```
ipdb> isinstance(var, Type)
False
ipdb> type(var)
<class 'module.Type'>
ipdb> Type
<class 'module.Type'>
```
Why can this happen?
P. S. `isinstance(var, type(var))` returns `True` as expected | 1. I can only guess, but if you do in `module`
```
class Type(object): pass
var = Type()
class Type(object): pass
```
then both types look like `<class 'module.Type'>`, but are nevertheless different.
You could check that with
```
print(id(Type), id(var.__class__))
```
or with
... |
Finding the full width half maximum of a peak | 10,582,795 | 10 | 2012-05-14T11:52:06Z | 10,583,774 | 9 | 2012-05-14T12:55:38Z | [
"python",
"matplotlib"
] | I have been trying to figure out the full width half maximum (FWHM) of the the blue peak (see image). The green peak and the magenta peak combined make up the blue peak. I have been using the following equation to find the FWHM of the green and magenta peaks: `fwhm = 2*np.sqrt(2*(math.log(2)))*sd` where sd = standard d... | You can use spline to fit the [blue curve - peak/2], and then find it's roots:
```
import numpy as np
from scipy.interpolate import UnivariateSpline
def make_norm_dist(x, mean, sd):
return 1.0/(sd*np.sqrt(2*np.pi))*np.exp(-(x - mean)**2/(2*sd**2))
x = np.linspace(10, 110, 1000)
green = make_norm_dist(x, 50, 10)
... |
Uncaught ReferenceError: django is not defined | 10,583,652 | 14 | 2012-05-14T12:47:19Z | 10,584,539 | 25 | 2012-05-14T13:43:45Z | [
"javascript",
"python",
"django",
"forms",
"widget"
] | I'm trying to use the Admin Widgets with a couple of DateField on my formulary but only the first of them gets the widget displayed correctly, for the other one I get an error:
> DateTimeShortcuts.js:205 Uncaught ReferenceError: django is not defined
(The line indicated is:
```
django.jQuery(document).bind('keyup', ... | `django.jQuery` is defined in `django/contrib/admin/static/admin/js/jquery.init.js` and relies on `django/contrib/admin/static/admin/js/jquery.js`. You need to load those js files in your template directly
```
<script type="text/javascript" src="/static/admin/js/jquery.min.js"></script>
<script type="text/javascript" ... |
Count all elements in list of arbitrary nested list without recursion | 10,584,873 | 13 | 2012-05-14T14:02:51Z | 10,584,955 | 17 | 2012-05-14T14:07:03Z | [
"python",
"recursion",
"iteration"
] | I have just learned about recursion in Python and have completed assignments, one of which was to count all the elements within a list of arbitrarily nested lists. I have searched this site and the answers found all seem to use recursive calls. Since it has been taught that anything which could be expressed recursively... | Here is one way to do it:
```
def element_count(p):
q = p[:]
count = 0
while q:
entry = q.pop()
if isinstance(entry, list):
q += entry
count += 1
return count
print element_count([1, [], 3])
print element_count([1, [1, 2, [3, 4]]])
print element_count([[[[[[[[1, 2, 3]]]]]]]])
```
The code ... |
Count all elements in list of arbitrary nested list without recursion | 10,584,873 | 13 | 2012-05-14T14:02:51Z | 10,585,041 | 8 | 2012-05-14T14:12:13Z | [
"python",
"recursion",
"iteration"
] | I have just learned about recursion in Python and have completed assignments, one of which was to count all the elements within a list of arbitrarily nested lists. I have searched this site and the answers found all seem to use recursive calls. Since it has been taught that anything which could be expressed recursively... | Usually each recursive problem can be converted to an iterative somehow by using a stack, in this case a `list`:
```
def element_count(p):
elements = list(p)
count = 0
while elements:
entry = elements.pop()
count += 1
if isinstance(entry, list):
elements.extend(entry)
... |
Python how to replace backslash with re.sub() | 10,585,349 | 3 | 2012-05-14T14:29:48Z | 10,585,406 | 12 | 2012-05-14T14:32:46Z | [
"python",
"python-2.7"
] | I have the following string
```
mystr1 = 'mydirname'
myfile = 'mydirname\myfilename'
```
I'm trying to do this
```
newstr = re.sub(mystr1 + "\","",myfile)
```
How do I escape the backslash I'm trying to concatenate to mystr1? | You need a quadruple backslash:
```
newstr = re.sub(mystr1 + "\\\\", "", myfile)
```
Reason:
* Regex to match a single backslash: `\\`
* String to describe this regex: `"\\\\"`.
Or you can use a raw string, so you only need a double backslash: `r"\\"` |
NER naive algorithm | 10,585,864 | 4 | 2012-05-14T14:59:36Z | 10,586,305 | 7 | 2012-05-14T15:24:35Z | [
"python",
"nlp"
] | I never really dealt with NLP but had an idea about NER which should NOT have worked and somehow DOES exceptionally well in one case. I do not understand why it works, why doesn't it work or weather it can be extended.
The idea was to extract names of the main characters in a story through:
1. Building a dictionary f... | From the looks of your program and previous experience with NER, I'd say this "works" because you're not doing a proper evaluation. You've found "Hare" where you should have found "March Hare".
The difficulty in NER (at least for English) is not finding the names; it's detecting their full extent (the "March Hare" exa... |
When should I use @classmethod and when def method(self)? | 10,586,787 | 33 | 2012-05-14T15:54:17Z | 10,586,874 | 31 | 2012-05-14T15:58:43Z | [
"python",
"language-lawyer",
"class-method",
"method-dispatch",
"language-details"
] | While integrating a Django app I have not used before, I found two different ways used to define functions in classes. The author seems to use them both very intentionally. The first one is one I myself use a lot:
```
class Dummy(object):
def some_function(self,*args,**kwargs):
do something here
s... | Your guess is correct - you understand *how* `classmethod`s work.
The why is that these methods can be called both on an instance OR on the class (in both cases, the class object will be passed as the first argument):
```
class Dummy(object):
@classmethod
def some_function(cls,*args,**kwargs):
print ... |
Is there a Mercurial or Git version control plugin for PyScripter? | 10,588,298 | 5 | 2012-05-14T17:34:20Z | 10,725,272 | 7 | 2012-05-23T17:51:42Z | [
"python",
"git",
"version-control",
"mercurial",
"pyscripter"
] | I'm using Python 3.x and PyScripter to write my scripts. I really miss a version control feature in PyScripter - I got spoiled by Qt and MpLab X (I believe this is a subversion of Eclipse). Things were easy back than. Now I don't have any version control in PyScripter, but I do have Mercurial installed. I perfectly rea... | I [just read this post](http://code.google.com/p/pyscripter/issues/detail?id=538) that suggests you can simply use the File Explorer menu of PyScripter, which automatically enables all of the functions from Windows Explorer. I have TortoiseGIT installed, and you can see that from PyScripter's File Explorer window, the ... |
Python function global variables? | 10,588,317 | 112 | 2012-05-14T17:35:49Z | 10,588,342 | 171 | 2012-05-14T17:38:03Z | [
"python",
"global-variables"
] | So I know I should avoid using global variables in the first place due to confusion like this, but if I were to use them, is the following a valid way to go about using them? (I am trying to call the global copy of a variable created in a separate function.)
```
x = somevalue
def func_A ():
global x
# do things... | If you want to simply access a global variable you just use its name. However to **change** its value you need to use the [`global`](https://docs.python.org/reference/simple_stmts.html#the-global-statement) keyword.
E.g.
```
global someVar
someVar = 55
```
This would change the value of the global variable to 55. Ot... |
Python function global variables? | 10,588,317 | 112 | 2012-05-14T17:35:49Z | 10,588,507 | 7 | 2012-05-14T17:52:52Z | [
"python",
"global-variables"
] | So I know I should avoid using global variables in the first place due to confusion like this, but if I were to use them, is the following a valid way to go about using them? (I am trying to call the global copy of a variable created in a separate function.)
```
x = somevalue
def func_A ():
global x
# do things... | As others have noted, you need to declare a variable `global` in a function when you want that function to be able to modify the global variable. If you only want to access it, then you don't need `global`.
To go into a bit more detail on that, what "modify" means is this: if you want to *re-bind* the global name so i... |
Python function global variables? | 10,588,317 | 112 | 2012-05-14T17:35:49Z | 10,588,651 | 48 | 2012-05-14T18:03:33Z | [
"python",
"global-variables"
] | So I know I should avoid using global variables in the first place due to confusion like this, but if I were to use them, is the following a valid way to go about using them? (I am trying to call the global copy of a variable created in a separate function.)
```
x = somevalue
def func_A ():
global x
# do things... | Within a Python scope, any assignment to a variable not already declared within that scope creates a new local variable *unless* that variable is declared earlier in the function as referring to a globally scoped variable with the keyword `global`.
Let's look at a modified version of your pseudocode to see what happen... |
Can I assign values in RowProxy using the sqlalchemy? | 10,588,375 | 5 | 2012-05-14T17:41:29Z | 10,588,443 | 12 | 2012-05-14T17:47:09Z | [
"python",
"sqlalchemy"
] | When I want to display some data in the web, the data need makeup, and I don't know how to achieve, here is the code:
```
from sqlalchemy import create_engine
engine = create_engine('mysql://root:111@localhost/test?charset=utf8')
conn = engine.connect()
articles = conn.execute('SELECT * FROM article')
articles = art... | You can make a dict out of your RowProxy, which would support item assignment.
For example:
```
result_proxy = query.fetchall()
for row in result_proxy:
d = dict(row.items())
d['Tags'] = d['Keywords']
``` |
How can I see the entire HTTP request that's being sent by my Python application? | 10,588,644 | 94 | 2012-05-14T18:03:10Z | 10,588,737 | 50 | 2012-05-14T18:10:50Z | [
"python",
"debugging",
"https",
"python-requests"
] | In my case, I'm using the `requests` library to call PayPal's API over HTTPS. Unfortunately, I'm getting an error from PayPal, and PayPal support cannot figure out what the error is or what's causing it. They want me to "Please provide the entire request, headers included".
How can I do that? | ```
r = requests.get('https://api.github.com', auth=('user', 'pass'))
```
`r` is a response. It has a request attribute which has the information you need.
```
r.request.allow_redirects r.request.headers r.request.response
r.request.auth r.request.hooks r.request.send
r.request.cert ... |
How can I see the entire HTTP request that's being sent by my Python application? | 10,588,644 | 94 | 2012-05-14T18:03:10Z | 16,630,836 | 175 | 2013-05-19T02:17:31Z | [
"python",
"debugging",
"https",
"python-requests"
] | In my case, I'm using the `requests` library to call PayPal's API over HTTPS. Unfortunately, I'm getting an error from PayPal, and PayPal support cannot figure out what the error is or what's causing it. They want me to "Please provide the entire request, headers included".
How can I do that? | A simple method: enable logging in recent versions of Requests (1.x and higher.)
Requests uses the `http.client` and `logging` module configuration to control logging verbosity, as described [here](http://docs.python-requests.org/en/master/api/#api-changes).
## Demonstration
Code excerpted from the linked documentat... |
Python Versions on Mac | 10,589,590 | 10 | 2012-05-14T19:09:59Z | 10,589,660 | 8 | 2012-05-14T19:15:03Z | [
"python",
"osx",
"version",
"homebrew"
] | I'm working on Mac Os 10.7 (Lion) and I have some questions:
1. What is the pre-installed version of python on Lion?
2. I've been working on this computer for some time now, and i've installed lots of software in order to do college work many times I didn't know what I was really doing. The thing is: now I hava on the... | 1. I think that is Python 2.7 but you can check typing python on a command terminal. It will tell you the version.
2. I couldn't tell that you can deleting it, because I don't know what it has... can you give more info about it?
3. Just type "which python" and it will tell you
4. You should use virtualenv and pip: <htt... |
"Can't start a new thread error" in Python | 10,589,766 | 2 | 2012-05-14T19:23:26Z | 10,605,478 | 11 | 2012-05-15T16:58:31Z | [
"python",
"multithreading",
"python-multithreading"
] | I am running a script which extracts the information from debian packages and saves it in a database.
After extracting information from about 100 packages an error occurs. The error is "can't start a new thread"
Why am I facing this error? What can be the possible solution to it?
This is the code used to save the dat... | *Sorry to have an incomplete solution here, I don't have the rating to post in the comment section.*
One thing to check is the total number of threads you have running. I have some code that checks the count of cores (with sys) and then launches threads and checks core loading to test how the OS handles thread distrib... |
Python help understanding sample code | 10,589,933 | 4 | 2012-05-14T19:37:48Z | 10,590,025 | 10 | 2012-05-14T19:44:42Z | [
"python",
"list",
"fuzzer"
] | I've been trying to learn python recently, and ran across something that I'm having a hard time understanding exactly how it works. Primarily, it is the design of a list.
The list in question is from this security article talking about a simple fuzzing tool: <http://blog.securestate.com/post/2009/10/06/How-a-simple-py... | This
```
"""
00 00 00 90
ff 53 4d 42 72 00 00 00 00 18 53 c8 00 00 00 00
00 00 00 00 00 00 00 00 ff ff ff fe 00 00 00 00
00 6d 00 02 50 43 20 4e 45 54 57 4f 52 4b 20 50
52 4f 47 52 41 4d 20 31 2e 30 00 02 4c 41 4e 4d
41 4e 31 2e 30 00 02 57 69 6e 64 6f 77 73 20 66
6f 72 20 57 6f 72 6b 67 72 6f 75 70 73 20 33 2e
31 61 ... |
Consuming a RESTful API with Django | 10,590,497 | 11 | 2012-05-14T20:24:45Z | 10,590,874 | 8 | 2012-05-14T20:54:17Z | [
"python",
"django",
"django-models"
] | I'm building a Django application that needs to interact with a 3rd party RESTful API, making various GETs, PUTs, etc to that resource. What I'm looking for is a good way to represent that API within Django.
The most obvious, but perhaps less elegant solution seems to be creating a model that has various methods mappi... | The [`requests`](http://docs.python-requests.org/en/latest/index.html) library makes it easy to write a REST API consumer. There is also a Python library called [`slumber`](http://slumber.in/), which is built on top of `requests`, for the explicit purpose of consuming REST APIs. How well that will work for you likely d... |
Specifying data type in Pandas csv reader | 10,591,000 | 18 | 2012-05-14T21:01:58Z | 10,781,413 | 12 | 2012-05-28T08:16:28Z | [
"python",
"pandas"
] | I am just getting started with Pandas and I am reading in a csv file using the read\_csv() method. The difficulty I am having is preventing pandas from converting my telephone numbers to large numbers, instead of keeping them as strings. I defined a converter which just left the numbers alone, but then they still conve... | It looks like you can't avoid pandas from trying to convert numeric/boolean values in the CSV file. Take a look at the source code of pandas for the IO parsers, in particular functions `_convert_to_ndarrays`, and `_convert_types`.
<https://github.com/pydata/pandas/blob/master/pandas/io/parsers.py>
You can always assig... |
Specifying data type in Pandas csv reader | 10,591,000 | 18 | 2012-05-14T21:01:58Z | 18,500,854 | 16 | 2013-08-29T01:22:23Z | [
"python",
"pandas"
] | I am just getting started with Pandas and I am reading in a csv file using the read\_csv() method. The difficulty I am having is preventing pandas from converting my telephone numbers to large numbers, instead of keeping them as strings. I defined a converter which just left the numbers alone, but then they still conve... | Since Pandas 0.11.0 you can use dtype argument to explicitly specify data type for each column:
```
d = pandas.read_csv('foo.csv', dtype={'BAR': 'S10'})
``` |
Python, fastest way to iterate over regular expressions but stop on first match | 10,591,068 | 10 | 2012-05-14T21:06:34Z | 10,591,090 | 7 | 2012-05-14T21:08:38Z | [
"performance",
"python-3.x",
"python"
] | I have a function that returns True if a string matches at least one
regular expression in a list and False otherwise. The function is called
often enough that performance is an issue.
When running it through cProfile, the function is spending about 65% of
its time doing matches and 35% of its time iterating over the ... | The way to do this fastest is to combine all the regexes into one with `"|"` between them, then make one regex match call. Also, you'll want to compile it once to be sure you're avoiding repeated regex compilation.
For example:
```
def matches_pattern(s, pats):
pat = "|".join("(%s)" % p for p in pats)
return ... |
Python, fastest way to iterate over regular expressions but stop on first match | 10,591,068 | 10 | 2012-05-14T21:06:34Z | 10,591,106 | 15 | 2012-05-14T21:09:17Z | [
"performance",
"python-3.x",
"python"
] | I have a function that returns True if a string matches at least one
regular expression in a list and False otherwise. The function is called
often enough that performance is an issue.
When running it through cProfile, the function is spending about 65% of
its time doing matches and 35% of its time iterating over the ... | The first thing that comes to mind is pushing the loop to the C side by using a generator expression:
```
def matches_pattern(s, patterns):
return any(p.match(s) for p in patterns)
```
Probably you don't even need a separate function for that.
Another thing you should try out is to build a single, composite rege... |
Remove all occurrences of several chars from a string | 10,591,337 | 13 | 2012-05-14T21:28:06Z | 10,591,372 | 20 | 2012-05-14T21:30:19Z | [
"python",
"string",
"string-formatting",
"built-in"
] | Is there a pythonic way to do what the [`str.strip()`](http://docs.python.org/library/stdtypes.html#str.strip) method does, except for *all* occurrences, not just those at the beginning and end of a string?
Example:
```
>> '::2012-05-14 18:10:20.856000::'.strip(' -.:')
>> '2012-05-14 18:10:20.856000'
```
I want
```... | Use the [`translate`](http://docs.python.org/library/stdtypes.html#str.translate) function to delete the unwanted characters:
```
>>> '::2012-05-14 18:10:20.856000::'.translate(None, ' -.:')
'20120514181020856000'
```
Be sure your string is of `str` type and not `unicode`, as the parameters of the function won't be t... |
Save classifier to disk in scikit-learn | 10,592,605 | 57 | 2012-05-15T00:06:11Z | 10,593,176 | 57 | 2012-05-15T01:41:50Z | [
"python",
"machine-learning",
"scikit-learn",
"classification"
] | How do I save a trained **Naive Bayes classifier** to **disk** and use it to **predict** data?
I have the following sample program from the scikit-learn website:
```
from sklearn import datasets
iris = datasets.load_iris()
from sklearn.naive_bayes import GaussianNB
gnb = GaussianNB()
y_pred = gnb.fit(iris.data, iris.... | Classifiers are just objects that can be pickled and dumped like any other. To continue your example:
```
import cPickle
# save the classifier
with open('my_dumped_classifier.pkl', 'wb') as fid:
cPickle.dump(gnb, fid)
# load it again
with open('my_dumped_classifier.pkl', 'rb') as fid:
gnb_loaded = cPickle... |
Save classifier to disk in scikit-learn | 10,592,605 | 57 | 2012-05-15T00:06:11Z | 11,169,797 | 99 | 2012-06-23T13:16:28Z | [
"python",
"machine-learning",
"scikit-learn",
"classification"
] | How do I save a trained **Naive Bayes classifier** to **disk** and use it to **predict** data?
I have the following sample program from the scikit-learn website:
```
from sklearn import datasets
iris = datasets.load_iris()
from sklearn.naive_bayes import GaussianNB
gnb = GaussianNB()
y_pred = gnb.fit(iris.data, iris.... | You can also use [joblib.dump](http://packages.python.org/joblib/generated/joblib.dump.html) and [joblib.load](http://packages.python.org/joblib/generated/joblib.load.html) which is much more efficient at handling numerical arrays than the default python pickler.
Joblib is included in scikit-learn:
```
>>> from sklea... |
Save classifier to disk in scikit-learn | 10,592,605 | 57 | 2012-05-15T00:06:11Z | 32,174,359 | 23 | 2015-08-24T04:17:11Z | [
"python",
"machine-learning",
"scikit-learn",
"classification"
] | How do I save a trained **Naive Bayes classifier** to **disk** and use it to **predict** data?
I have the following sample program from the scikit-learn website:
```
from sklearn import datasets
iris = datasets.load_iris()
from sklearn.naive_bayes import GaussianNB
gnb = GaussianNB()
y_pred = gnb.fit(iris.data, iris.... | What you are looking for is called **Model persistence** in sklearn words and it is documented in [introduction](http://scikit-learn.org/stable/tutorial/basic/tutorial.html#model-persistence) and in [model persistence](http://scikit-learn.org/stable/modules/model_persistence.html) sections.
So you have initialized you... |
Updating a list of python dictionaries with a key, value pair from another list | 10,592,674 | 7 | 2012-05-15T00:15:58Z | 10,592,728 | 16 | 2012-05-15T00:23:58Z | [
"python",
"list",
"dictionary"
] | Let's say I have the following list of python dictionary:
```
dict1 = [{'domain':'Ratios'},{'domain':'Geometry'}]
```
and a list like:
```
list1 = [3, 6]
```
I'd like to update `dict1` or create another list as follows:
```
dict1 = [{'domain':'Ratios', 'count':3}, {'domain':'Geometry', 'count':6}]
```
How would I... | ```
>>> l1 = [{'domain':'Ratios'},{'domain':'Geometry'}]
>>> l2 = [3, 6]
>>> for d,num in zip(l1,l2):
d['count'] = num
>>> l1
[{'count': 3, 'domain': 'Ratios'}, {'count': 6, 'domain': 'Geometry'}]
```
Another way of doing it, this time with a list comprehension which does not mutate the original:
```
>>> [d... |
How do i convert a Python program to a runnable .exe Windows program? | 10,592,913 | 24 | 2012-05-15T01:01:51Z | 10,593,209 | 19 | 2012-05-15T01:48:06Z | [
"python",
"exe"
] | I am looking for a way to convert a Python Program to a .exe file WITHOUT using py2exe. py2exe says it requries python 2.6, which is outdated. Any way that this is possible so i can distribute my python program without the end-user having to install python. | Understand that every 'freezing' application for Python will not really secure your code in any way. Every packaging system for a stand-alone executable Python 'program' will include a lot of the Python libraries and interpreter, which will make your program pretty large.
That said, [PyInstaller](http://www.pyinstalle... |
python numpy ln | 10,593,100 | 16 | 2012-05-15T01:30:59Z | 10,593,174 | 8 | 2012-05-15T01:41:39Z | [
"python",
"numpy",
"natural-logarithm"
] | Using numpy, how can I do the following:
```
ln(x)
```
Is it equivalent to:
```
np.log(x)
```
I apologise for such a seemingly trivial question, but my understanding of the difference between `log` and `ln` is that `ln` is logspace e? | Correct, `np.log(x)` is the Natural Log (base `e` log) of `x`.
For other bases, remember this law of logs: `log-b(x) = log-k(x) / log-k(b)` where `log-b` is the log in some arbitrary base `b`, and `log-k` is the log in base `k`, e.g.
here k = `e`
```
l = np.log(x) / np.log(100)
```
and `l` is the log-base-100 of x |
python numpy ln | 10,593,100 | 16 | 2012-05-15T01:30:59Z | 10,593,175 | 30 | 2012-05-15T01:41:46Z | [
"python",
"numpy",
"natural-logarithm"
] | Using numpy, how can I do the following:
```
ln(x)
```
Is it equivalent to:
```
np.log(x)
```
I apologise for such a seemingly trivial question, but my understanding of the difference between `log` and `ln` is that `ln` is logspace e? | `np.log` is `ln`, whereas `np.log10` is your standard base 10 log.
Relevant documentation:
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html>
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.log10.html> |
Django views does not exist or could not import | 10,593,194 | 23 | 2012-05-15T01:45:15Z | 11,307,198 | 56 | 2012-07-03T08:31:30Z | [
"python",
"django",
"view",
"import"
] | This morning i have been working on my project. I finished what i was doing and i pushed new code to git.
Now, i went to run my project to start working on it and index view does not run!
```
Could not import ism.views.index. View does not exist in module ism.views.
```
This view ran without any kind of problem. All... | Try doing a
```
python ./manage.py shell
```
and then importing the view that is giving you the problem. That might end up giving you more useful debugging information.
```
> from ism.views import index
``` |
Django views does not exist or could not import | 10,593,194 | 23 | 2012-05-15T01:45:15Z | 13,778,796 | 7 | 2012-12-08T15:14:09Z | [
"python",
"django",
"view",
"import"
] | This morning i have been working on my project. I finished what i was doing and i pushed new code to git.
Now, i went to run my project to start working on it and index view does not run!
```
Could not import ism.views.index. View does not exist in module ism.views.
```
This view ran without any kind of problem. All... | it happend to me, evevtually the problem was i had a syntax error in one of the forms in forms.py,
and i imported this form into my views.py file.
Django error message still pointed me to view does not exist error |
Pythonic way to access arbitrary element from dictionary | 10,593,651 | 18 | 2012-05-15T03:05:07Z | 10,593,679 | 22 | 2012-05-15T03:09:15Z | [
"python"
] | I have a dictionary, full of items. I want to peek at a single, arbitrary item:
```
print "Amongst our dictionary's items are such diverse elements as: %s" % arb(dictionary)
```
I don't care which item. It doesn't need to be *random*.
I can think of many ways of implementing this, but they all seem wasteful. I am wo... | Similar to your second solution, but slightly more obvious, in my opinion:
```
return next(dictionary.itervalues())
``` |
Pythonic way to access arbitrary element from dictionary | 10,593,651 | 18 | 2012-05-15T03:05:07Z | 10,628,953 | 7 | 2012-05-17T01:55:17Z | [
"python"
] | I have a dictionary, full of items. I want to peek at a single, arbitrary item:
```
print "Amongst our dictionary's items are such diverse elements as: %s" % arb(dictionary)
```
I don't care which item. It doesn't need to be *random*.
I can think of many ways of implementing this, but they all seem wasteful. I am wo... | Avoiding the whole `values`/`itervalues`/`viewvalues` mess, this works equally well in Python2 or Python3
```
dictionary[next(iter(dictionary))]
``` |
Problems with execute parameters type in MySQLdb | 10,594,063 | 2 | 2012-05-15T04:14:44Z | 10,594,134 | 10 | 2012-05-15T04:25:56Z | [
"python",
"string",
"execute",
"mysql-python"
] | ```
c.execute("UPDATE Players SET %s = %d WHERE nick=%s",
(parts[1], int(parts[2]), parts[0]))
```
is giving me the error
```
TypeError: %d format: a number is required, not str
```
I know `execute` should take only `%s`, but `parts[2]` should be cast to int, becacuse it will be an int (inputted as a strin... | I see a couple of problems.
There may be more.
1. You cannot parametrize table nor column names.
You can, however, do the string substitution and then call `.execute()`.
If your program takes user input, you'll want to be wary of the potential for [SQL-injection](http://en.wikipedia.org/wiki/SQL_injection) a... |
Bad idea to catch all exceptions in Python | 10,594,113 | 7 | 2012-05-15T04:23:40Z | 10,594,142 | 19 | 2012-05-15T04:27:33Z | [
"python",
"exception",
"exception-handling"
] | Why is it a bad idea to catch all exceptions in Python ?
I understand that catching all exceptions using the `except:` clause will even catch the 'special' python exceptions: `SystemExit`, `KeyboardInterrupt`, and `GeneratorExit`. So why not just use a `except Exception:` clause to catch all exceptions? | Because it's terribly nonspecific and it doesn't enable you to do anything interesting with the exception. Moreover, if you're catching every exception there could be loads of exceptions that are happening that you don't even know are happening (which could cause your application to fail without you really knowing why)... |
Deploying Django to Heroku (Psycopg2 Error) | 10,596,893 | 8 | 2012-05-15T08:30:01Z | 12,126,242 | 8 | 2012-08-25T22:45:19Z | [
"python",
"django",
"postgresql",
"deployment",
"heroku"
] | So I'm following the getting started guide from heroku with django. However when I run this command:
```
heroku run python manage.py syncdb
```
I get this error
```
psycopg2.OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" and accepting
TCP/IP connections on... | **EDITED:**
As @mipadi has pointed out here (http://stackoverflow.com/questions/13001031/django-heroku-settings-injection/13092534), it can actually be as simple as this:
```
import dj_database_url
DATABASES = {'default' : dj_database_url.config() }
```
This works if you have a DATABASE\_URL env variable set. herok... |
install python and make in cygwin | 10,597,284 | 7 | 2012-05-15T08:55:21Z | 10,597,334 | 9 | 2012-05-15T08:58:33Z | [
"python",
"windows",
"makefile",
"cygwin",
"install"
] | I have installed Cygwin Terminal in OS Windows. But I need to install also python and make in cygwin.All of these programs are needed to run petsc library.
Does Someone know how to install these components in cygwin? | Look into cygwin native package manager, `devel` category. You should find `make` and `python` there. |
Trouble importing model from other app with Django | 10,598,317 | 3 | 2012-05-15T09:58:48Z | 10,601,523 | 7 | 2012-05-15T13:15:40Z | [
"python",
"django",
"model",
"import"
] | I'm in trouble trying to import a model from another app. I've two apps "main" and "administrative". Here the code, where I stripped out some verbose description :
"administrative" model:
```
from django.db import models
from django import forms
from django.forms import ModelForm
class Contract(models.Model):
C... | Your traceback shows the error is with class `ContractForm` which you have defined in `administrative/models.py` on line 28
```
...
File "/media/truecrypt1/develope/Django-1.3.1/dbMobile/../dbMobile/main/models.py", line 5, in <module>
from administrative.models import Contract #, Crefcontr2num
File "/media/truecrypt... |
How to access a specific start_url in a Scrapy CrawlSpider? | 10,598,691 | 5 | 2012-05-15T10:22:42Z | 10,605,941 | 8 | 2012-05-15T17:35:13Z | [
"python",
"django",
"scrapy"
] | I'm using Scrapy, in particular Scrapy's `CrawlSpider` class to scrape web links which contain certain keywords. I have a pretty long `start_urls` list which gets its entries from a SQLite database which is connected to a Django project. I want to save the scraped web links in this database.
I have two Django models, ... | By default you can not access the original start url.
But you can override [`make_requests_from_url`](http://doc.scrapy.org/en/latest/topics/spiders.html#scrapy.spider.BaseSpider.make_requests_from_url) method and put the start url into a [`meta`](http://doc.scrapy.org/en/latest/topics/request-response.html#scrapy.htt... |
Save unicode in redis but fetch error | 10,599,147 | 5 | 2012-05-15T10:48:54Z | 12,285,706 | 24 | 2012-09-05T16:18:37Z | [
"python",
"redis"
] | I'm using mongodb and redis, redis is my cache.
I'm caching mongodb objects with redis-py:
```
obj in mongodb: {u'name': u'match', u'section_title': u'\u6d3b\u52a8', u'title':
u'\u6bd4\u8d5b', u'section_id': 1, u'_id': ObjectId('4fb1ed859b10ed2041000001'), u'id': 1}
```
the obj fetched from redis with hgetall(key, ... | I think I've discovered the problem. After reading this, I had to explicitly decode from redis which is a pain, but works.
I stumbled across a blog post where the author's output was all unicode strings which was obv different to mine.
Looking into the `StrictRedis.__init__` there is a parameter `decode_responses` wh... |
Pandas: where's the memory leak here? | 10,601,041 | 9 | 2012-05-15T12:49:25Z | 10,602,831 | 22 | 2012-05-15T14:22:04Z | [
"python",
"pandas"
] | I face the problem of memory leaks using **pandas** library in **python**. I create pandas.dataframe objects in my class and I have method, that change dataframe size according my conditions. After changing dataframe size and creating new pandas object I rewrite original pandas.dataframe in my class. But memory usage i... | A couple things to point out:
1. In "Check memory after changing size", you haven't deleted the original DataFrame yet, so this will be using strictly more memory
2. The Python interpreter is a bit greedy about holding onto OS memory.
I looked into this and can assure you that pandas is not leaking memory. I'm using ... |
Populating a Python dictionary | 10,601,601 | 5 | 2012-05-15T13:20:42Z | 10,601,709 | 7 | 2012-05-15T13:26:22Z | [
"python",
"dictionary"
] | Hi I'm building a dictionary where each key is a customer name and each value is a list of tuples which are purchased by each customer, like so: (product, quantity). For example:
```
{'customer1': (('milk', 3), ('bread', 5), ('eggs', 2)),
'customer2': (('cheese', 2), ('cereal', 7))}
```
I am populating the dictionar... | First of all, I'd use lists rather than tuples as dictionary entries. The principal difference is that lists are mutable, whereas tuples are not.
I think [`defaultdict`](http://docs.python.org/library/collections.html#collections.defaultdict) is a good for for this problem:
```
from collections import defaultdict
cu... |
Following users like twitter in Django, how would you do it? | 10,602,071 | 5 | 2012-05-15T13:44:33Z | 10,603,296 | 12 | 2012-05-15T14:48:50Z | [
"python",
"django",
"database-design",
"twitter",
"django-models"
] | I am playing with relationships in Django/python and I am wondering how you guys would create a relationship between a User and his followers and a Follower to the users he follows.
Would love to read your opinion... | First, you should understand how to [store additional information about users](https://docs.djangoproject.com/en/1.3/topics/auth/#storing-additional-information-about-users). It requires another model that has a relation to one user, the "profile" model.
Then, you could use an M2M field, assuming you'd use [django-ann... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.