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 |
|---|---|---|---|---|---|---|---|---|---|
re.match vs re.search performance difference | 12,803,709 | 12 | 2012-10-09T15:44:27Z | 12,815,771 | 9 | 2012-10-10T09:09:01Z | [
"python",
"regex"
] | I tried to compare `re.match` and `re.search` using `timeit` module and I found that match was better than search when the string I want to found was at the beginning of the string.
```
>>> s1 = '''
... import re
... re.search(r'hello','helloab'*100000)
... '''
>>> timeit.timeit(stmt=s1,number=10000)
32.12064480781555... | > *"So, the updated question is now why search is out-performing match?"*
In this particular instance where a literal string is used rather than a regex pattern, indeed `re.search` is slightly faster than `re.match` for the default CPython implementation (I have not tested this in other incarnations of Python).
```
>... |
Django - How to sort queryset by number of character in a field | 12,804,801 | 6 | 2012-10-09T16:54:57Z | 12,804,856 | 13 | 2012-10-09T16:59:54Z | [
"python",
"django",
"django-queryset"
] | MyModel:
```
name = models.CharField(max_length=255)
```
I try to sort the queryset. I just think about this:
```
obj = MyModel.objects.all().sort_by(-len(name)) #???
```
Any idea? | you might have to sort that in python..
`sorted(MyModel.objects.all(),key=lambda o:len(o.name),reverse=True)`
or I lied ( A quick google search found the following)
```
MyModel.objects.extra(select={'length':'Length(name)'}).order_by('length')
``` |
QIcon.fromTheme not displaying icon in PyQt | 12,805,036 | 10 | 2012-10-09T17:13:37Z | 12,825,838 | 10 | 2012-10-10T18:21:13Z | [
"python",
"pyqt",
"icons",
"pyqt4",
"qt-designer"
] | I am having troubles to display the icon of a QAction selected from the current icon theme. I made the ui with Qt designer and exported it with `pyuic4 sample.ui > sample.py`. After setting the icon from the theme with `self.actionSample.setIcon(QtGui.QIcon.fromTheme(_fromUtf8("document-open")))`, I get the following s... | The icon lookup process used by `QIcon.fromTheme` is somewhat complex.
Icon themes are only directly supported on the X11 platform for the GNOME and KDE desktop environments. For other platforms/desktops, it will be necessary to either install a theme along with the application, or tweak the user's environment in vari... |
List of lists: find combinations of elements | 12,805,944 | 3 | 2012-10-09T18:13:47Z | 12,806,000 | 14 | 2012-10-09T18:17:48Z | [
"python",
"list"
] | Say I have a list that contains n lists. Is there a neat way get all possible combinations of those lists that have length n, each element keeping it's position.
Here's an example:
```
lists=[[1],[2,3],[4,5]]
```
output:
```
[[1,2,4],
[1,3,4],
[1,2,5],
[1,3,5]]
``` | You can use [`itertools.product`](http://docs.python.org/library/itertools.html#itertools.product) for this:
```
>>> import itertools
>>> lists = [[1], [2, 3], [4, 5]]
>>> list(itertools.product(*lists))
[(1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5)]
``` |
missing python bz2 module | 12,806,122 | 15 | 2012-10-09T18:26:07Z | 12,806,325 | 34 | 2012-10-09T18:39:32Z | [
"python",
"linux",
"bzip2"
] | I have installed at my home directory.
```
[spatel@~ dev1]$ /home/spatel/python-2.7.3/bin/python -V
Python 2.7.3
```
I am trying to run one script which required python 2.7.x version, and i am getting missing bz2 error
```
[spatel@~ dev1]$ ./import_logs.py
Traceback (most recent call last):
File "./import_logs.py"... | Probably as you built python from source, you don't have bz2 headers.
Install them on Ubuntu/Debian:
```
sudo apt-get install libbz2-dev
```
Fedora:
```
sudo yum install libbz2-devel // or bzip2-devel
```
And build python again.
You may notice that python checks for lots of libraries when configuring/building, if ... |
Django get ContentType in a template | 12,806,276 | 7 | 2012-10-09T18:36:11Z | 20,854,240 | 8 | 2013-12-31T08:27:19Z | [
"python",
"django",
"django-templates",
"django-contenttypes"
] | I have a page with a lot of objects with different content types. I need to have an ability to rate this objects. Here is a class for it:
```
class Score(models.Model):
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(... | To build on @Colleen 's answer, I ended up using a template filter like so:
```
from django import template
from django.contrib.contenttypes.models import ContentType
register = template.Library()
@register.filter
def content_type(obj):
if not obj:
return False
return ContentType.objects.get_for_mode... |
Matplotlib imshow() stretch to "fit width" | 12,806,481 | 13 | 2012-10-09T18:49:13Z | 12,808,001 | 24 | 2012-10-09T20:35:39Z | [
"python",
"matplotlib"
] | I've got an image, and a measure associated with each column of its pixels. I'm using `pyplot` to create a figure with the image on top, and a plot of the column measurements below. I'm using something like this:
```
import numpy as np
import matplotlib.pyplot as plt
A = np.random.rand(34*52).reshape(34,52)
means = n... | Turns out that it's as simple as giving `aspect='auto'` to the `imshow` call.
```
plt.imshow(A, interpolation='nearest', aspect='auto')
``` |
wx.ListCtrl with TextEditMixin - Disable Editing of Selected Cells | 12,806,542 | 5 | 2012-10-09T18:53:30Z | 12,807,799 | 7 | 2012-10-09T20:19:18Z | [
"python",
"listview",
"wxpython"
] | Is there any way to disable the editing of specific cells by the user when using `ListCtrl` with `TextEditMixin`?
I guess there's some way that Vetos the editing event, however I can't find it. | Event wx.EVT\_LIST\_BEGIN\_LABEL\_EDIT:
```
class EditableListCtrl(wx.ListCtrl, listmix.TextEditMixin):
def __init__(self, parent, ID=wx.ID_ANY, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0):
wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
listmix.TextEditMixin.__i... |
The scope of if __name__ == __main__ | 12,807,069 | 3 | 2012-10-09T19:29:26Z | 12,807,083 | 8 | 2012-10-09T19:30:35Z | [
"python",
"scope"
] | What is the scope of `if __name__ == __main__`? Is everything covered by this statement in global space ? | There is nothing special about `if __name__ == '__main__'` block whatsoever. That is to say, its scope is determined by the place it occurs. Since such blocks typically occur at top-level, their scope is global.
If this block were to occur in a function, which is perfectly legal, its scope would be localâexcept that... |
How to determined if a 2 dimensional list contain a value? | 12,807,079 | 8 | 2012-10-09T19:30:22Z | 12,807,101 | 15 | 2012-10-09T19:31:48Z | [
"python",
"list",
"python-2.7"
] | I have a list like following
```
mylist = [('value1', 'value2', 'value3'), ('secval1', 'secval2', 'secval3')]
```
how do I see if the list contains 'value2'? | Use [`any()`](http://docs.python.org/library/functions.html#any):
```
any('value2' in sublist for sublist in mylist)
``` |
Why isn't admin.autodiscover() called automatically in Django when using the admin, why was it designed to be called explicitly? | 12,807,220 | 8 | 2012-10-09T19:38:10Z | 12,807,691 | 9 | 2012-10-09T20:10:43Z | [
"python",
"django"
] | Without putting `admin.autodiscover()` in urls.py the admin page shows `You don't have permission to edit anything` ([See SO thread](http://stackoverflow.com/questions/3718077/django-you-dont-have-permission-to-edit-anything)).
Why is this so? If you always need to add `admin.autodiscover()` to edit information using ... | Before Django 1.7, the recommendation was to put the `admin.autodiscover()` call in urls.py. That allowed it to be disabled if necessary. Requiring `admin.autodiscover()` instead of calling it automatically was an example of the Python philosophy ['Explicit is better than implicit'](http://www.python.org/dev/peps/pep-0... |
Why isn't admin.autodiscover() called automatically in Django when using the admin, why was it designed to be called explicitly? | 12,807,220 | 8 | 2012-10-09T19:38:10Z | 12,808,468 | 9 | 2012-10-09T21:09:15Z | [
"python",
"django"
] | Without putting `admin.autodiscover()` in urls.py the admin page shows `You don't have permission to edit anything` ([See SO thread](http://stackoverflow.com/questions/3718077/django-you-dont-have-permission-to-edit-anything)).
Why is this so? If you always need to add `admin.autodiscover()` to edit information using ... | (edit: Obsoleted after Django 1.7+, not necessary more, see Alasdair's answer)
I think it's about giving you finer control. Consider the code of `contrib.admin.autodiscover`:
```
def autodiscover():
"""
Auto-discover INSTALLED_APPS admin.py modules and fail silently when
not present. This forces an import... |
split items in list | 12,808,420 | 6 | 2012-10-09T21:04:55Z | 12,808,469 | 18 | 2012-10-09T21:09:22Z | [
"python",
"list",
"split"
] | How can I turn the following list
```
['1','2','A,B,C,D','7','8']
```
into
`['1','2','A','B','C','D','7','8']`
in the most pythonic way?
I have very unpythonic code that creates nested list, and then flatterens:
```
sum ( [ word.split(',') for word in words ], [] )
``` | ```
result = [item for word in words for item in word.split(',')]
``` |
Is it possible to call exec so that it's compatible with both Python 3 and Python 2? | 12,809,234 | 6 | 2012-10-09T22:17:56Z | 29,876,520 | 8 | 2015-04-26T10:34:24Z | [
"python",
"python-3.x",
"py2to3"
] | I'm using the `exec` statement in some Python 2 code, and I'm trying to make that code compatible with both Python 2 and Python 3, but in Python 3, `exec` has changed from a statement into a function. Is it possible to write code that is compatible with both Python 2 and 3? I've read about [Python 2 and Python 3 dual d... | Some [Python porting guides get the `exec`](http://python3porting.com/differences.html#exec) **wrong**:
> If you need to pass in the global or local dictionaries you will need to define a custom function with two different implementations, one for Python 2 and one for Python 3. As usual `six` includes an excellent imp... |
How to add up each count in defaultdict? | 12,809,694 | 2 | 2012-10-09T23:06:46Z | 12,809,756 | 9 | 2012-10-09T23:13:58Z | [
"python"
] | This is what I have to count each word in a document:
```
from collections import defaultdict
word_dict=defaultdict(int)
def count_words(newstring):
words=newstring.lower().split()
for word in words:
word_dict[word]+=1
```
When I print `word_dict`, I got the following results:
```
defaultdict(<type ... | You can do this the same way you would any dictionary:
```
>>> d = {'a': 1, 'b': 1, 'c': 3, 'd': 4}
>>> sum(d.values())
9
```
In Python 2.\* you could also use
```
>>> sum(d.itervalues())
9
```
which doesn't create a new list, but frankly it's unlikely your lists are long enough for this to be a bottleneck. And the... |
python, unittest, test a script with command line args | 12,809,970 | 5 | 2012-10-09T23:41:27Z | 12,810,560 | 7 | 2012-10-10T01:06:15Z | [
"python",
"unit-testing",
"parameters"
] | I've written a python script that takes command line arguments and plays one round of Tic Tac Toe.
running it looks like this...
> run ttt o#xo##x## x 0 1
If the move is legal it then prints the new board layout and whether anyone won the game
I have to write tests for it using unittest. I dont know how to test th... | Refactor your program so that its main action (minus the argparsing) happens in a "main" function:
```
def main(args):
...
if __name__ == '__main__':
args = parse_args()
main(args)
```
Then you can write tests for the behavior of `main` and `parse_args`.
PS. It is possible to use the `subprocess` module... |
django global variable | 12,811,523 | 7 | 2012-10-10T03:25:44Z | 12,811,752 | 8 | 2012-10-10T04:01:13Z | [
"python",
"django",
"django-views"
] | In views.py
When I try this one to access a global variable from other `def`:
```
def start(request):
global num
num=5
return HttpResponse("num= %d" %num) # returns 5 no problem....
def other(request):
num=num+1
return HttpResponse("num= %d" %num)
```
`def other` does not return 6, but it should... | Use [sessions](https://docs.djangoproject.com/en/dev/topics/http/sessions/). This is exactly what they are designed for.
```
def foo(request):
num = request.session.get('num')
if not num:
num = 1
request.session['num'] = num
return render(request,'foo.html')
def anotherfoo(request):
num = request... |
Slicing python matrix into quadrants | 12,811,981 | 2 | 2012-10-10T04:32:59Z | 12,812,027 | 7 | 2012-10-10T04:37:58Z | [
"python",
"arrays",
"matrix"
] | Suppose I have the following matrix in python:
`[[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]`
I want to slice it into the following matrices (or quadrants/corners):
```
[[1,2], [5,6]]
[[3,4], [7,8]]
[[9,10], [13,14]]
[[11,12], [15,16]]
```
Is this supported with standard slicing operators in python or is ... | If you are always working with a 4x4 matrix:
```
a = [[1 ,2 , 3, 4],
[5 ,6 , 7, 8],
[9 ,10,11,12],
[13,14,15,16]]
top_left = [a[0][:2], a[1][:2]]
top_right = [a[0][2:], a[1][2:]]
bot_left = [a[2][:2], a[3][:2]]
bot_right = [a[2][2:], a[3][2:]]
```
You could also do the same for an arbitrary size mat... |
How do I pass variables in django through the url? | 12,812,716 | 3 | 2012-10-10T05:47:07Z | 12,812,996 | 10 | 2012-10-10T06:08:18Z | [
"python",
"django",
"templates",
"url",
"view"
] | I am trying to pass a few variables but I am having some trouble and specifically have 3 questions.
How do I encode the url string to take into account the special characters in the string?
What is the correct regex I should use given the strings?
And how do I decode the urls that have been encoded?
# view
```
author... | Pass these variables as it is to template, there use [url](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#url), before sending to template just do this in view.
**View.py**
```
related = urllib.quote(related, safe='')
```
**template**
```
<a href="{% url 'path.to.video_player' author vid... |
How to get file name of logging.FileHandler in Python? | 12,813,415 | 9 | 2012-10-10T06:39:46Z | 12,813,495 | 13 | 2012-10-10T06:46:24Z | [
"python",
"logging",
"file-io"
] | A `logging.FileHandler` is constructed with a file name, so is there any way to get the file name from the `logging.FileHandler` object?
I tried `dir(logging.FileHandler)` but didn't see any possible solutions. | ```
>>> import logging
>>> fh = logging.FileHandler('/Users/defuz/test.txt')
>>> fh.baseFilename
'/Users/defuz/test.txt'
>>> fh.stream.name
'/Users/defuz/test.txt'
``` |
How to assert two list contain the same elements in Python? | 12,813,633 | 56 | 2012-10-10T06:56:45Z | 12,813,684 | 12 | 2012-10-10T06:59:43Z | [
"python",
"unit-testing"
] | When writing test cases, I often need to assert that two list contain the same elements without regard to their order.
I have been doing this by converting the lists to sets.
Is there any simpler way to do this?
**EDIT**:
As @MarkDickinson pointed out, I can just use [TestCase.assertItemsEqual](http://docs.python.o... | Converting your lists to sets will tell you that they contain the same elements. But this method cannot confirm that they contain the same number of all elements. For example, your method will fail in this case:
```
L1 = [1,2,2,3]
L2 = [1,2,3,3]
```
You are likely better off sorting the two lists and comparing them:
... |
How to assert two list contain the same elements in Python? | 12,813,633 | 56 | 2012-10-10T06:56:45Z | 12,813,909 | 17 | 2012-10-10T07:13:08Z | [
"python",
"unit-testing"
] | When writing test cases, I often need to assert that two list contain the same elements without regard to their order.
I have been doing this by converting the lists to sets.
Is there any simpler way to do this?
**EDIT**:
As @MarkDickinson pointed out, I can just use [TestCase.assertItemsEqual](http://docs.python.o... | Slightly faster version of the implementation (If you know that most couples lists will have different lengths):
```
def checkEqual(L1, L2):
return len(L1) == len(L2) and sorted(L1) == sorted(L2)
```
Comparing:
```
>>> timeit(lambda: sorting([1,2,3], [3,2,1]))
2.42745304107666
>>> timeit(lambda: lensorting([1,2,... |
How to assert two list contain the same elements in Python? | 12,813,633 | 56 | 2012-10-10T06:56:45Z | 31,832,447 | 24 | 2015-08-05T12:24:32Z | [
"python",
"unit-testing"
] | When writing test cases, I often need to assert that two list contain the same elements without regard to their order.
I have been doing this by converting the lists to sets.
Is there any simpler way to do this?
**EDIT**:
As @MarkDickinson pointed out, I can just use [TestCase.assertItemsEqual](http://docs.python.o... | As of Python 3.2 `unittest.TestCase.assertItemsEqual` has been replaced by `unittest.TestCase.assertCountEqual` which does exactly what you are looking for, as you can read from the python [standard library documentation](https://docs.python.org/3.2/library/unittest.html). The method is somewhat misleadingly named but ... |
Covert binary 64-bit timestamp offset from the GPS epoch to python datetime object | 12,814,588 | 4 | 2012-10-10T07:56:31Z | 12,831,470 | 9 | 2012-10-11T02:52:23Z | [
"python",
"datetime",
"binary"
] | I'm trying to figure out what I think should be an 8byte/64-bit timestamp.
```
import datetime
GPS_EPOCH = datetime.datetime(1980, 1, 6)
t1 = "\x00\x00\xBF\x13\xDB\x79\xC0\x00" # expected: 2012-10-04 01:00:51.759
t2 = "\x00\x00\xC0\x13\xDB\x79\xC0\x00" # expected: 2012-10-04 01:00:51.760
t3 = "\x00\x00\xC2\x13\xDB\x79... | I have it. You provided just enough examples.
```
>>> t1 = "\x00\x00\xBF\x13\xDB\x79\xC0\x00" # expected: 2012-10-04 01:00:51.759
>>> import struct
>>> import datetime
>>> GPS_EPOCH = datetime.datetime(1980, 1, 6)
>>> t1_unpacked = struct.unpack('<q', t1)[0]
>>> t1_seconds = t1_unpacked / 52428800
>>> t1_us = int(roun... |
How to sort a list according to another list? | 12,814,667 | 16 | 2012-10-10T08:01:24Z | 12,814,719 | 29 | 2012-10-10T08:04:08Z | [
"python",
"list",
"sorting"
] | There is a list:
```
a = [("ax", 1), ("ec",3), ("bk", 5)]
```
another list:
```
b = ["ec", "ax", "bk"]
```
I want to sort a according to `b`:
```
sort_it(a, b)
a = [("ec",3), ("ax", 1), ("bk", 5)]
```
How to do this? | ```
a.sort(key=lambda x: b.index(x[0]))
```
This sorts `a` in-place using the the index in `b` of the first element of each tuple from `a` as the values it sorts on.
Another, possibly cleaner, way of writing it would be:
```
a.sort(key=lambda (x,y): b.index(x))
```
---
If you had large numbers of items, it might b... |
Bitnami - /opt/bitnami/python/bin/.python2.7.bin: error while loading shared libraries: libreadline.so.5 | 12,814,973 | 4 | 2012-10-10T08:20:23Z | 12,898,508 | 7 | 2012-10-15T15:07:00Z | [
"python",
"django",
"centos",
"bitnami"
] | I getting the below issue when firing up django or ipython notebook
**/opt/bitnami/python/bin/.python2.7.bin: error while loading shared libraries: libreadline.so.5**
However libreadline.so.5 exists in my system after locating it as shown below
**root@linux:/opt/bitnami/scripts# locate libreadline.so.5
/opt/bitnami/... | Can you execute the following and see if it solves your issue?
. /opt/bitnami/scripts/setenv.sh
(notice the space between the dot and the path to the script)
Also what are you executing that gives you that error? |
weighted moving average with numpy.convolve | 12,816,011 | 8 | 2012-10-10T09:22:14Z | 12,818,075 | 11 | 2012-10-10T11:18:43Z | [
"python",
"math",
"numpy"
] | I'm writing a moving average function that uses the convolve function in numpy, which should be equivalent to a ([weighted moving average](http://en.wikipedia.org/wiki/Convolution)). When my weights are all equal (as in a simple arithmatic average), it works fine:
```
data = numpy.arange(1,11)
numdays = 5
w = [1.0/num... | What you want is `np.correlate` in a convolution the second argument is inverted basically, so that your expected result would be with `np.convolve(data, w[::-1], 'valid')`. |
Python argparse ignore unrecognised arguments | 12,818,146 | 66 | 2012-10-10T11:22:37Z | 12,818,237 | 120 | 2012-10-10T11:28:09Z | [
"python",
"argparse",
"optparse"
] | Optparse, the old version just ignores all unrecognised arguments and carries on. In most situations, this isn't ideal and was changed in argparse. But there are a few situations where you want to ignore any unrecognised arguments and parse the ones you've specified.
For example:
```
parser = argparse.ArgumentParser(... | Replace
```
args = parser.parse_args()
```
with
```
args, unknown = parser.parse_known_args()
```
For example,
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo')
args, unknown = parser.parse_known_args(['--foo', 'BAR', 'spam'])
print(args)
# Namespace(foo='BAR')
print(unknown)
# ['... |
Python argparse ignore unrecognised arguments | 12,818,146 | 66 | 2012-10-10T11:22:37Z | 25,966,881 | 7 | 2014-09-22T04:51:18Z | [
"python",
"argparse",
"optparse"
] | Optparse, the old version just ignores all unrecognised arguments and carries on. In most situations, this isn't ideal and was changed in argparse. But there are a few situations where you want to ignore any unrecognised arguments and parse the ones you've specified.
For example:
```
parser = argparse.ArgumentParser(... | You can puts the remaining parts into a new argument with `parser.add_argument('args', nargs=argparse.REMAINDER)` if you want to use them. |
Django, name parameter in urlpatterns | 12,818,377 | 17 | 2012-10-10T11:34:50Z | 12,818,945 | 24 | 2012-10-10T12:06:25Z | [
"python",
"django",
"django-class-based-views",
"urlconf",
"url-pattern"
] | I'm following a tutorial where my urlpatterns are:
```
urlpatterns = patterns('',
url(r'^passwords/$', PasswordListView.as_view(), name='passwords_api_root'),
url(r'^passwords/(?P<id>[0-9]+)$', PasswordInstanceView.as_view(), name='passwords_api_instance'),
...other urls here...,
)
```
The *PasswordListVi... | No. It is just that django gives you the option to name your views in case you need to refer to them from your code, or your templates. This is useful and good practice because you avoid hardcoding urls on your code or inside your templates. Even if you change the actual url, you don't have to change anything else, sin... |
Sort python dictionary by Keys formatted as strings | 12,820,960 | 2 | 2012-10-10T13:50:32Z | 12,821,087 | 8 | 2012-10-10T13:56:43Z | [
"python",
"sorting",
"dictionary"
] | I have a dictionary with strings as keys formatted as yyyy-mm-dd and want to sort the dictionary by keys with the earliest dates first:
I am currently using `sorted(datesAndText.keys())` but this isn't reliably working because the month and day fields are not always zero padded.
I have looked at [Sort python dictiona... | Are you sure your keys are exactly in the format `yyyy-mm-dd`? For example:
```
>>> '2010-1-15' < '2010-02-15'
False
```
You may be forced to sort something like this:
```
sorted(d,key=lambda x: [int(y) for y in x.split('-')])
```
Another solution (assuming your years are all 4 digits):
```
sorted(d,key=lambda x: ... |
What are ngram counts and how to implement using nltk? | 12,821,201 | 9 | 2012-10-10T14:01:08Z | 12,821,366 | 10 | 2012-10-10T14:07:49Z | [
"python",
"nlp",
"nltk"
] | I've read a paper that uses ngram counts as feature for a classifier, and I was wondering what this exactly means.
Example text: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam"
I can create unigrams, bigrams, trigrams, etc. out of this text, where I have to define on which "level" to create these ... | I found my old code, maybe it's useful.
```
import nltk
from nltk import bigrams
from nltk import trigrams
text="""Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ornare
tempor lacus, quis pellentesque diam tempus vitae. Morbi justo mauris,
congue sit amet imperdiet ipsum dolor sit amet, consectetur a... |
seek() a file within a zip file in Python without passing it to memory | 12,821,961 | 7 | 2012-10-10T14:34:50Z | 12,822,218 | 7 | 2012-10-10T14:48:39Z | [
"python",
"zip",
"zipfile",
"seek"
] | is there anyway to make a file inside a zip file seekable in Python without reading it to memory?
I tried the obvious procedure but I get an error since the file is not seekable:
```
In [74]: inputZipFile = zipfile.ZipFile("linear_g_LAN2A_F_3keV_1MeV_30_small.zip", 'r')
In [76]: inputCSVFile = inputZipFile.open(inpu... | There is no way to do so for all zip files. DEFLATE is a stream compression algorithm, which means that there is no way to decompress arbitrary parts of the file without having decompressed everything before it. It *could* possibly be implemented for files that have been stored, but then you get in the unfavorable posi... |
pylab.ion() in python 2, matplotlib 1.1.1 and updating of the plot while the program runs | 12,822,762 | 18 | 2012-10-10T15:14:48Z | 12,826,273 | 17 | 2012-10-10T18:48:11Z | [
"python",
"matplotlib"
] | what I am trying to do is having a script compute something, prepare a plot and show the already obtained results as a pylab.figure - in python 2 (specifically python 2.7) with a stable matplotlib (which is 1.1.1).
In python 3 (python 3.2.3 with a matplotlib git build ... version 1.2.x), this works fine. As a simple e... | You want the `pause` function to give the gui framework a chance to re-draw the screen:
```
import pylab
import time
import random
import matplotlib.pyplot as plt
dat=[0,1]
fig = plt.figure()
ax = fig.add_subplot(111)
Ln, = ax.plot(dat)
ax.set_xlim([0,20])
plt.ion()
plt.show()
for i in range (18):
dat.append(... |
Best practice for Python & Django constants | 12,822,847 | 24 | 2012-10-10T15:20:08Z | 12,823,236 | 14 | 2012-10-10T15:40:42Z | [
"python",
"django"
] | I have a Django model that relies on a tuple. I'm wondering what the best practice is for refering to constants within that tuple for my Django program. Here, for example, I'd like to specify "`default=0`" as something that is more readable and does not require commenting. Any suggestions?
```
Status = (
(-1, 'Can... | ```
CANCELED, ATTENTION, WIP, COMPLETE = range(-1, 3)
Status = (
(CANCELED, 'Cancelled'),
(ATTENTION, 'Requires attention'),
(WIP, 'Work in progress'),
(COMPLETE, 'Complete'),
)
class Task(models.Model):
status = models.IntegerField(choices=Status, default=CANCELED)
```
---
Keep in mind that as o... |
Best practice for Python & Django constants | 12,822,847 | 24 | 2012-10-10T15:20:08Z | 12,823,272 | 36 | 2012-10-10T15:42:04Z | [
"python",
"django"
] | I have a Django model that relies on a tuple. I'm wondering what the best practice is for refering to constants within that tuple for my Django program. Here, for example, I'd like to specify "`default=0`" as something that is more readable and does not require commenting. Any suggestions?
```
Status = (
(-1, 'Can... | It is quite common to define constants for the integer values as follows:
```
class Task(models.Model):
CANCELLED = -1
REQUIRES_ATTENTION = 0
WORK_IN_PROGRESS = 1
COMPLETE = 2
Status = (
(CANCELLED, 'Cancelled'),
(REQUIRES_ATTENTION, 'Requires attention'),
(WORK_IN_PROGRESS... |
Python strip XML tags from document | 12,823,568 | 5 | 2012-10-10T15:57:23Z | 12,824,035 | 16 | 2012-10-10T16:23:38Z | [
"python",
"xml",
"regex"
] | I am trying to strip XML tags from a document using Python, a language I am a novice in. Here is my first attempt using regex, whixh was really a hope-for-the-best idea.
```
mfile = file("somefile.xml","w")
for line in mfile:
re.sub('<./>',"",line) #trying to match elements between < and />
```
That failed miser... | The most reliable way to do this is probably with [LXML](http://lxml.de/api.html).
```
from lxml import etree
...
tree = etree.parse('somefile.xml')
notags = etree.tostring(tree, encoding='utf8', method='text')
print(notags)
```
It will avoid the problems with "parsing" XML with regular expressions, and should correc... |
How to format a number with comma and specified precision digits in Python | 12,824,077 | 4 | 2012-10-10T16:25:59Z | 12,824,146 | 8 | 2012-10-10T16:30:04Z | [
"python",
"number-formatting",
"string-formatting"
] | The question is for Python 2.6, that is what we have in production.
I have this requirement for formatting a number (like 1234567.0987 or 1234567.0) with comma, and specified number of digits after decimal points. So, it if precision is three, 1234567.0987 may look like 1,234,567.099.
I tried using Locale, as suggest... | for python 2.7 and 3.x you can do something like:
```
>>> num=1234567890.0876543
>>> "{0:,f}".format(num)
'1,234,567,890.087654'
>>> "{0:,f}".format(1234)
'1,234.000000'
>>> "{0:,f}".format(123)
'123.000000'
``` |
How to format a number with comma and specified precision digits in Python | 12,824,077 | 4 | 2012-10-10T16:25:59Z | 12,824,161 | 15 | 2012-10-10T16:30:57Z | [
"python",
"number-formatting",
"string-formatting"
] | The question is for Python 2.6, that is what we have in production.
I have this requirement for formatting a number (like 1234567.0987 or 1234567.0) with comma, and specified number of digits after decimal points. So, it if precision is three, 1234567.0987 may look like 1,234,567.099.
I tried using Locale, as suggest... | I don't think you looked deep enough into the locale module. [`locale.format()`](http://docs.python.org/library/locale.html#locale.format) is what you want, but make sure you set a locale first or you won't get grouping at all.
```
>>> locale.setlocale(locale.LC_ALL, '')
'en_US.UTF-8'
>>> locale.format("%.4f", 12345.6... |
python execute many with "on duplicate key update"? | 12,825,232 | 2 | 2012-10-10T17:43:37Z | 12,825,529 | 7 | 2012-10-10T18:02:22Z | [
"python",
"mysql-python"
] | I am trying to executemany in python with on duplicate key update, with the following script:
```
# data from a previous query (returns 4 integers in each row)
rows = first_cursor.fetchall()
query="""
INSERT INTO data (a, b, c)
VALUES (%s,%s,%s) ON DUPLICATE KEY UPDATE a=%s
"""
second_cursor.executemany(query,rows)
`... | This is a bug in MySQLdb due to the regex that MySQLdb uses to parse `INSERT` statements:
In **/usr/lib/pymodules/python2.7/MySQLdb/cursors.py**:
```
restr = (r"\svalues\s*"
r"(\(((?<!\\)'[^\)]*?\)[^\)]*(?<!\\)?'"
r"|[^\(\)]|"
r"(?:\([^\)]*\))"
r")+\))")
insert_values= re.compile(rest... |
The __str__ method returning a unicode string works in one environment but fails in another | 12,825,390 | 2 | 2012-10-10T17:52:40Z | 12,825,451 | 7 | 2012-10-10T17:56:49Z | [
"python"
] | I thought, I understood unicode and python. But this issue confuses me a lot.
Look at this small test program:
```
# -*- coding: utf-8 -*-
class TestC(object):
def __str__(self):
return u'äöü'
import sys
print sys.version
print sys.stdin.encoding
print sys.stdout.encoding
print u'öäü' #this wo... | See this related question: [Python \_\_str\_\_ versus \_\_unicode\_\_](http://stackoverflow.com/questions/1307014/python-str-versus-unicode)
Basically, you should probably be implementing the special method `__unicode__` rather than `__str__`, and add a stub `__str__` that calls `__unicode__`:
```
def __str__(self):
... |
django translation template {% trans "something" %} | 12,826,101 | 7 | 2012-10-10T18:36:52Z | 22,695,869 | 12 | 2014-03-27T18:12:12Z | [
"python",
"django",
"templates",
"translation"
] | Ok I have been searching like crazy for this I think simple problem.
I use Django 1.4
The problem is that django won't translate a simple {% trans "work" %} in my template.
This is what I have done:
Settings.py:
```
LANGUAGE_CODE = 'en-us'
USE_I18N = True
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middlew... | I just spent few hours trying to fix this issue in Django 1.5 while working on my new project [Sportolio](http://www.sportolio.pl) and it turned out I was missing a **comma** at the end of LOCALE\_PATH
```
LOCALE_PATHS = (
'/path/to/my/project/locale/',
)
```
This is very crucial, as Django expects LOCALE\_PATHS ... |
Possible to extract the git repo revision hash via Python code? | 12,826,723 | 2 | 2012-10-10T19:18:35Z | 18,283,905 | 8 | 2013-08-17T00:27:28Z | [
"python",
"git",
"version"
] | Are there any easy ways to grab the git repository (on GitHub) version hash with Python code? I want to use this to handle versioning of 'dev' releases of my software on github. | ```
def git_version():
from subprocess import Popen, PIPE
gitproc = Popen(['git', 'rev-parse','HEAD'], stdout = PIPE)
(stdout, _) = gitproc.communicate()
return stdout.strip()
``` |
Quickly applying string operations in a pandas DataFrame | 12,829,428 | 6 | 2012-10-10T22:29:44Z | 12,847,586 | 16 | 2012-10-11T20:03:34Z | [
"python",
"pandas"
] | Suppose I have a `DataFrame` with 100k rows and a column `name`. I would like to split this name into first and last name as efficiently as possibly. My current method is,
```
def splitName(name):
return pandas.Series(name.split()[0:2])
df[['first', 'last']] = df.apply(lambda x: splitName(x['name']), axis=1)
```
U... | Try (requires pandas >= 0.8.1):
```
splits = x['name'].split()
df['first'] = splits.str[0]
df['last'] = splits.str[1]
``` |
Python package installed globally, but not in a virtualenv (PyGTK) | 12,830,662 | 3 | 2012-10-11T00:55:34Z | 13,108,389 | 7 | 2012-10-28T11:23:01Z | [
"python",
"pygtk",
"virtualenv"
] | I'm having some strange issues with PyGTK in "virtualenv". gtk does not import in my virtualenv, while it does import in my global python install. (I wasn't having this particular issue last week, guessing some software update upset something.)
Is there a good way to resolve this behavior?
Shown here: importing gtk g... | Try creating your virtual environment with the --system-site-packages flag. |
How python handles object instantiation in a ' for' loop | 12,831,280 | 5 | 2012-10-11T02:25:33Z | 12,831,312 | 10 | 2012-10-11T02:29:38Z | [
"python",
"memory-management",
"for-loop",
"instantiation",
"reference-counting"
] | I've got a highly complex class :
```
class C:
pass
```
And I've got this test code :
```
for j in range(10):
c = C()
print c
```
Which gives :
```
<__main__.C instance at 0x7f7336a6cb00>
<__main__.C instance at 0x7f7336a6cab8>
<__main__.C instance at 0x7f7336a6cb00>
<__main__.C instance at 0x7f7336a6c... | There is no need to be "complex" here:
In the first example, you keep no other reference to the object referenced by the name "c" - when running the code in the line "c = C()" on subsequent iterations of the loop, the one reference previously held in "c" is lost.
Since standard Python uses reference counting to keep t... |
How to use Python to find out the words begin with vowels in a list? | 12,833,512 | 2 | 2012-10-11T06:31:01Z | 12,833,541 | 8 | 2012-10-11T06:33:16Z | [
"python",
"list",
"search"
] | ```
words = ['apple', 'orange', 'pear', 'milk', 'otter', 'snake','iguana','tiger','eagle']
vowel=[]
for vowel in words:
if vowel [0]=='a,e':
words.append(vowel)
print (words)
```
My code doesn't right, and it will print out all the words in the original list. | ```
words = ['apple', 'orange', 'pear', 'milk', 'otter', 'snake','iguana','tiger','eagle']
for word in words:
if word[0] in 'aeiou':
print(word)
```
You can also use a list comprehension like this
```
words_starting_with_vowel = [word for word in words if word[0] in 'aeiou']
``` |
How to use Python to find out the words begin with vowels in a list? | 12,833,512 | 2 | 2012-10-11T06:31:01Z | 12,833,575 | 7 | 2012-10-11T06:36:02Z | [
"python",
"list",
"search"
] | ```
words = ['apple', 'orange', 'pear', 'milk', 'otter', 'snake','iguana','tiger','eagle']
vowel=[]
for vowel in words:
if vowel [0]=='a,e':
words.append(vowel)
print (words)
```
My code doesn't right, and it will print out all the words in the original list. | Here is a one-liner answer with list comprehension:
```
>>> print [w for w in words if w[0] in 'aeiou']
['apple', 'orange', 'otter', 'iguana', 'eagle']
``` |
Having options in argparse with a dash | 12,834,785 | 40 | 2012-10-11T07:56:07Z | 12,834,980 | 8 | 2012-10-11T08:08:53Z | [
"python",
"argparse"
] | I want to have some options in argparse module such as `--pm-export` however when I try to use it like `args.pm-export` I get the error that there is not attribute `pm`. How can I get around this issue ? Is it possible to have `-` in command line options ? | Dashes are converted to underscores:
```
import argparse
pa = argparse.ArgumentParser()
pa.add_argument('--foo-bar')
args = pa.parse_args(['--foo-bar', '24'])
print args # Namespace(foo_bar='24')
``` |
Having options in argparse with a dash | 12,834,785 | 40 | 2012-10-11T07:56:07Z | 12,834,986 | 51 | 2012-10-11T08:09:06Z | [
"python",
"argparse"
] | I want to have some options in argparse module such as `--pm-export` however when I try to use it like `args.pm-export` I get the error that there is not attribute `pm`. How can I get around this issue ? Is it possible to have `-` in command line options ? | As [indicated in the `argparse` docs](http://docs.python.org/dev/library/argparse.html#dest):
> For optional argument actions, the value of dest is normally inferred from the option strings. ArgumentParser generates the value of dest by taking the first long option string and **stripping away the initial `--` string**... |
Having options in argparse with a dash | 12,834,785 | 40 | 2012-10-11T07:56:07Z | 20,250,435 | 34 | 2013-11-27T18:38:57Z | [
"python",
"argparse"
] | I want to have some options in argparse module such as `--pm-export` however when I try to use it like `args.pm-export` I get the error that there is not attribute `pm`. How can I get around this issue ? Is it possible to have `-` in command line options ? | Unfortunately, dash-to-underscore replacement doesn't work for positionalarguments (not prefixed by `--`) like
```
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('logs-dir',
help='Directory with .log and .log.gz files')
parser.add_argument('results-csv', ... |
What are the use cases for Python's __new__? | 12,835,176 | 4 | 2012-10-11T08:20:45Z | 12,835,637 | 9 | 2012-10-11T08:47:02Z | [
"python"
] | I understand what `__new__` does (and how it's different from `__init__`) so I'm not interested in definitions, I'm interested in when and how to use `__new__`.
The documentation says:
> In general, you shouldn't need to override `__new__` unless you're subclassing an immutable type like `str`, `int`, `unicode` or `t... | Answering for myself, I've used it to
* create a singleton pattern (though there are [ways](http://stackoverflow.com/a/12305625/566644) to do that without using `__new__`)
* [dynamically extend classes from external modules](http://stackoverflow.com/a/4714744/566644) without actually editing the source
* customize cla... |
Sequence of letters in Python | 12,835,674 | 7 | 2012-10-11T08:49:00Z | 12,835,711 | 17 | 2012-10-11T08:50:35Z | [
"python",
"letters"
] | Is there a built-in method / module in Python to generate letters such as the built-in constant LETTERS or letters constant in R?
The R built-in constant works as `letters[n]` where if `n = 1:26` the lower-case letters of the alphabet are produced.
Thanks. | It's called [`string.ascii_lowercase`](http://docs.python.org/library/string.html#string.ascii_lowercase).
If you wanted to pick *n* many random lower case letters, then:
```
from string import ascii_lowercase
from random import choice
letters = [choice(ascii_lowercase) for _ in range(5)]
```
If you wanted it as a ... |
Convert list to tuple in Python | 12,836,128 | 212 | 2012-10-11T09:13:13Z | 12,836,173 | 302 | 2012-10-11T09:15:17Z | [
"python",
"python-2.7",
"tuples"
] | I'm trying to convert a list to a tuple.
When I google it, I find a lot of answers similar to:
```
l = [4,5,6]
tuple(l)
```
But if I do that I get this error message:
> TypeError: 'tuple' object is not callable
How can I fix this problem? | It should work fine. Don't use `tuple`, `list` or other special names as a variable name. It's probably what's causing your problem.
```
>>> l = [4,5,6]
>>> tuple(l)
(4, 5, 6)
``` |
Convert list to tuple in Python | 12,836,128 | 212 | 2012-10-11T09:13:13Z | 12,836,206 | 72 | 2012-10-11T09:17:16Z | [
"python",
"python-2.7",
"tuples"
] | I'm trying to convert a list to a tuple.
When I google it, I find a lot of answers similar to:
```
l = [4,5,6]
tuple(l)
```
But if I do that I get this error message:
> TypeError: 'tuple' object is not callable
How can I fix this problem? | Expanding on eumiro's comment, normally `tuple(l)` will convert a list `l` into a tuple:
```
In [1]: l = [4,5,6]
In [2]: tuple
Out[2]: <type 'tuple'>
In [3]: tuple(l)
Out[3]: (4, 5, 6)
```
However, if you've redefined `tuple` to be a tuple rather than the `type` `tuple`:
```
In [4]: tuple = tuple(l)
In [5]: tuple... |
Convert list to tuple in Python | 12,836,128 | 212 | 2012-10-11T09:13:13Z | 12,836,211 | 14 | 2012-10-11T09:17:25Z | [
"python",
"python-2.7",
"tuples"
] | I'm trying to convert a list to a tuple.
When I google it, I find a lot of answers similar to:
```
l = [4,5,6]
tuple(l)
```
But if I do that I get this error message:
> TypeError: 'tuple' object is not callable
How can I fix this problem? | You might have done something like this:
```
>>> tuple = 45, 34 # You used `tuple` as a variable here
>>> tuple
(45, 34)
>>> l = [4, 5, 6]
>>> tuple(l) # Will try to invoke the variable `tuple` rather than tuple type.
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
tuple(l)
TypeEr... |
Convert list to tuple in Python | 12,836,128 | 212 | 2012-10-11T09:13:13Z | 17,145,670 | 8 | 2013-06-17T10:46:42Z | [
"python",
"python-2.7",
"tuples"
] | I'm trying to convert a list to a tuple.
When I google it, I find a lot of answers similar to:
```
l = [4,5,6]
tuple(l)
```
But if I do that I get this error message:
> TypeError: 'tuple' object is not callable
How can I fix this problem? | ```
l = [4,5,6]
```
to convert list to tuple,
```
l = tuple(l)
``` |
How can I interleave or create unique permutations of two stings (without recursion) | 12,836,385 | 5 | 2012-10-11T09:27:10Z | 12,837,695 | 11 | 2012-10-11T10:38:43Z | [
"python",
"arrays",
"string",
"algorithm",
"complexity-theory"
] | The question is to print all possible interleavings of two given strings. So I wrote a working code in Python which runs like this:
```
def inter(arr1,arr2,p1,p2,arr):
thisarr = copy(arr)
if p1 == len(arr1) and p2 == len(arr2):
printarr(thisarr)
elif p1 == len(arr1):
thisarr.extend(arr2[p2:... | Your problem can be reduced to that of creating all *unique* permutations of a particular list. Say `A` and `B` are the lengths of the strings `arr1` and `arr2`, respectively. Then construct a list like this:
```
[0] * A + [1] * B
```
There exists a one-to-one correspondence (a bijection) from the unique permutations... |
south: cannot ALTER TABLE because it has pending trigger events | 12,838,111 | 48 | 2012-10-11T11:06:29Z | 12,838,113 | 61 | 2012-10-11T11:06:29Z | [
"python",
"django",
"postgresql",
"django-south"
] | I want to remove null=True from a TextField:
```
- footer=models.TextField(null=True, blank=True)
+ footer=models.TextField(blank=True, default='')
```
I created a schema migration:
```
manage.py schemamigration fooapp --auto
```
Since some footer columns contain NULL I get this error if I run the migration:
... | Every migration is inside a transaction. In PostgreSQL you must not update the table and then alter the table schema in one transaction.
You need to split the data migration and the schema migration. First create the data migration with this code:
```
for sender in orm['fooapp.EmailSender'].objects.filter(footer=Non... |
south: cannot ALTER TABLE because it has pending trigger events | 12,838,111 | 48 | 2012-10-11T11:06:29Z | 16,016,330 | 10 | 2013-04-15T13:24:50Z | [
"python",
"django",
"postgresql",
"django-south"
] | I want to remove null=True from a TextField:
```
- footer=models.TextField(null=True, blank=True)
+ footer=models.TextField(blank=True, default='')
```
I created a schema migration:
```
manage.py schemamigration fooapp --auto
```
Since some footer columns contain NULL I get this error if I run the migration:
... | Have just hit this problem. You can also use db.start\_transaction() and db.commit\_transaction() in the schema migration to separate data changes from schema changes. Probably not so clean as to have a separate data migration but in my case I would need schema, data, and then another schema migration so I decided to d... |
south: cannot ALTER TABLE because it has pending trigger events | 12,838,111 | 48 | 2012-10-11T11:06:29Z | 22,021,024 | 45 | 2014-02-25T16:58:06Z | [
"python",
"django",
"postgresql",
"django-south"
] | I want to remove null=True from a TextField:
```
- footer=models.TextField(null=True, blank=True)
+ footer=models.TextField(blank=True, default='')
```
I created a schema migration:
```
manage.py schemamigration fooapp --auto
```
Since some footer columns contain NULL I get this error if I run the migration:
... | Another reason for this maybe because you try to set a column to `NOT NULL` when it actually already has `NULL` values. |
Merge two integers in Python | 12,838,549 | 9 | 2012-10-11T11:32:52Z | 12,838,572 | 17 | 2012-10-11T11:33:56Z | [
"python"
] | How can I merge two integer numbers (ex. 10 and 20) in Python and have a number **1020**.
Thanks | Cast both to a string, concatenate the strings and then cast the result back to an integer:
```
z = int(str(x) + str(y))
``` |
Merge two integers in Python | 12,838,549 | 9 | 2012-10-11T11:32:52Z | 12,838,701 | 7 | 2012-10-11T11:40:37Z | [
"python"
] | How can I merge two integer numbers (ex. 10 and 20) in Python and have a number **1020**.
Thanks | Using math is probably faster than solutions that convert to str and back:
If you can assume a two digit second number:
```
def f(x, y):
return x*100+y
```
Usage:
```
>>> f(1,2)
102
>>> f(10,20)
1020
```
Although, you probably would want some checks included to verify the second number is not more than two dig... |
Scipy Normaltest how is it used? | 12,838,993 | 18 | 2012-10-11T11:56:46Z | 12,839,537 | 28 | 2012-10-11T12:28:19Z | [
"python",
"scipy"
] | I need to use normaltest in scipy for testing if the dataset is normal distributet. But I cant seem to find any good examples how to use this function.
My dataset has more than 100 values.
scipy.stats.mstats.normaltest | ```
In [12]: import scipy.stats as stats
In [13]: x = stats.norm.rvs(size = 100)
In [14]: stats.normaltest(x)
Out[14]: (1.627533590094232, 0.44318552909231262)
```
[`normaltest`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.normaltest.html#scipy.stats.normaltest) returns a 2-tuple of the chi-squar... |
AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF' | 12,839,213 | 13 | 2012-10-11T12:10:11Z | 12,839,276 | 9 | 2012-10-11T12:14:05Z | [
"python",
"django",
"settings",
"localhost",
"attributeerror"
] | Following on from my last question [Error: No module named psycopg2.extensions](http://stackoverflow.com/questions/12728004/error-no-module-named-psycopg2-extensions), I have updated my mac OS to Mountain Lion and installed Xcode. I have also installed psycopg2 using 'sudo port install py27-psycopg2'. I am now trying t... | From django [docs](https://docs.djangoproject.com/en/1.4/ref/settings/#root-urlconf):
> A Django settings file contains all the configuration of your Django installation.
> When you use Django, you have to tell it which settings you're using.
> Do this by using an environment variable, `DJANGO_SETTINGS_MODULE`.
>
> Th... |
Python string comparison pointing to the result | 12,840,451 | 3 | 2012-10-11T13:17:09Z | 12,840,538 | 9 | 2012-10-11T13:21:18Z | [
"python"
] | Im trying to compare 2 1000 byte string and would like to know where the difference exactly starts, ie; from which byte the string is different.. Is there any function to determine it? | Maybe use `next` plus a generator?
```
next(idx for idx,c in enumerate(your_string1) if c != your_string2[idx])
```
This will give you the index where the difference starts and raise `StopIteration` if they are equal.
It might even be slightly more elegant with `itertools.izip`:
```
next(idx for idx,(c1,c2) in enum... |
Remove Python list element | 12,840,747 | 4 | 2012-10-11T13:32:22Z | 12,840,840 | 7 | 2012-10-11T13:37:02Z | [
"python",
"list"
] | I have two list,
```
l1 = [1,2,3,4,5,6]
l2 = [3,2]
```
what i want is to remove the element of list l1 which is in l2, for that i have done something like this,
```
for x in l1:
if x in l2:
l1.remove(x)
```
it gives output like
```
[1, 3, 4, 5, 6]
```
but the output should be like
```
[1, 4, 5, 6]
``... | Why not making it a bit simpler? No need to actually iterate over `l1` if we only want to remove elements present in `l2`:
```
for item in l2:
while item in l1:
l1.remove(item)
```
This gives you exactly the output desired...
Also, as commenters point out, if there is a possibility that we can have dupli... |
Remove Python list element | 12,840,747 | 4 | 2012-10-11T13:32:22Z | 12,840,897 | 9 | 2012-10-11T13:38:52Z | [
"python",
"list"
] | I have two list,
```
l1 = [1,2,3,4,5,6]
l2 = [3,2]
```
what i want is to remove the element of list l1 which is in l2, for that i have done something like this,
```
for x in l1:
if x in l2:
l1.remove(x)
```
it gives output like
```
[1, 3, 4, 5, 6]
```
but the output should be like
```
[1, 4, 5, 6]
``... | This is easily explained like this.
consider the first array you have:
```
| 1 | 2 | 3 | 4 | 5 | 6 |
```
Now you start iterating
```
| 1 | 2 | 3 | 4 | 5 | 6 |
^
```
Nothing happens, iterator increments
```
| 1 | 2 | 3 | 4 | 5 | 6 |
^
```
2 gets removed
```
| 1 | 3 | 4 | 5 | 6 |
^
```
iterator inc... |
uwsgi: What defines the number of workers/process that a django app needs? | 12,842,148 | 14 | 2012-10-11T14:38:40Z | 12,842,442 | 12 | 2012-10-11T14:53:00Z | [
"python",
"django",
"nginx",
"celery",
"uwsgi"
] | I have a question for sysadmins and developers.
I see that uWSGI allows me to set the number or workers or processes when running uWSGI and I had read that it depends on the installed machine, so I have the next questions:
1. What are the rules that define the number of workers for the machine?
2. When used with nginx... | * What are the rules that define the number of workers for the machine?
From the [uWsgi docs](http://projects.unbit.it/uwsgi/wiki/ThingsToKnow):
> There is no magic rule for setting the number of processes or threads. It is application and system dependent. Do not think using simple math like 2\*cpucores will be ... |
Download google docs public spreadsheet to csv with python | 12,842,341 | 6 | 2012-10-11T14:48:20Z | 12,842,633 | 11 | 2012-10-11T15:01:08Z | [
"python",
"google-spreadsheet"
] | I can download a google docs csv with wget:
```
wget --no-check-certificate --output-document=locations.csv 'https://docs.google.com/spreadsheet/ccc?key=0ArM5yzzCw9IZdEdLWlpHT1FCcUpYQ2RjWmZYWmNwbXc&output=csv'
```
But I cant download the same csv with python:
```
import urllib2
request = urllib2.Request('https://do... | Just use requests, it is way better than using urllib.
Try this.
```
import requests
response = requests.get('https://docs.google.com/spreadsheet/ccc?key=0ArM5yzzCw9IZdEdLWlpHT1FCcUpYQ2RjWmZYWmNwbXc&output=csv')
assert response.status_code == 200, 'Wrong status code'
print response.content
``` |
Download google docs public spreadsheet to csv with python | 12,842,341 | 6 | 2012-10-11T14:48:20Z | 15,935,465 | 9 | 2013-04-10T20:10:17Z | [
"python",
"google-spreadsheet"
] | I can download a google docs csv with wget:
```
wget --no-check-certificate --output-document=locations.csv 'https://docs.google.com/spreadsheet/ccc?key=0ArM5yzzCw9IZdEdLWlpHT1FCcUpYQ2RjWmZYWmNwbXc&output=csv'
```
But I cant download the same csv with python:
```
import urllib2
request = urllib2.Request('https://do... | **You're not storing cookies.**
First let me say that I completely endorse the recommendation to use the [most-excellent `requests` library](http://docs.python-requests.org/).
However, if you need to do this in vanilla Python 2, the problem lies in the fact that Google is bouncing you around via HTTP 302 redirects, a... |
Why is processing a sorted array not faster than an unsorted array in Python? | 12,842,717 | 8 | 2012-10-11T15:05:37Z | 12,842,901 | 16 | 2012-10-11T15:14:14Z | [
"python",
"performance"
] | In this post [Why is processing a sorted array faster than random array](http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array), it says that branch predicton is the reason of the performance boost in sorted arrays.
But I just tried the example using Python; and I t... | I may be wrong, but I see a fundamental difference between the linked question and your example: Python interprets bytecode, C++ compiles to native code.
In the C++ code that `if` translates directly to a `cmp`/`jl` sequence, that can be considered by the CPU branch predictor as a single "prediction spot", specific to... |
Python: Logging TypeError: not all arguments converted during string formatting | 12,843,099 | 9 | 2012-10-11T15:23:29Z | 12,843,139 | 19 | 2012-10-11T15:25:17Z | [
"python",
"logging",
"string-formatting"
] | Here is what I am doing
```
>>> import logging
>>> logging.getLogger().setLevel(logging.INFO)
>>> from datetime import date
>>> date = date.today()
>>> logging.info('date={}', date)
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py"... | You cannot use new-style formatting when using the logging module; use `%s` instead of `{}`.
```
logging.info('date=%s', date)
```
The logging module uses the old-style `%` operator to format the log string. See the [`debug` method](http://docs.python.org/library/logging.html#logging.Logger.debug) for more detail.
I... |
Python: Logging TypeError: not all arguments converted during string formatting | 12,843,099 | 9 | 2012-10-11T15:23:29Z | 12,843,568 | 7 | 2012-10-11T15:48:31Z | [
"python",
"logging",
"string-formatting"
] | Here is what I am doing
```
>>> import logging
>>> logging.getLogger().setLevel(logging.INFO)
>>> from datetime import date
>>> date = date.today()
>>> logging.info('date={}', date)
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py"... | You could do the formatting yourself:
```
logging.info('date={}'.format(date))
```
As was pointed out by Martijn Pieters, this will always run the string formatting, while using the logging module would cause the formatting to only be performed if the message is actually logged. |
How can I get an error when no results are fetched with DB query? | 12,843,551 | 2 | 2012-10-11T15:47:40Z | 12,843,696 | 7 | 2012-10-11T15:54:55Z | [
"python",
"mysql",
"sqlalchemy",
"pyramid"
] | I'm trying to learn and advance with SQLAlchemy. Today I wanted to learn about exceptions it raises.
I'm working on a Pyramid based project, MySQL server (InnoDB) and SQLAlchemy.
I am trying to except all errors since `NoResultFound` error would not raise or print in console. So I except `exc.SQLAlchemyError`.
When ... | Indeed this code will not raise an exception if no records are found. So instead you should throw your own exception:
```
import logging
try:
records = Session.query(MyTable).\
filter(Terms.column == my_string).all()
if len(records) == 0:
raise MyException('No records found')
except MyException... |
Integer division: is a//b == int(a/b) true for all integers a,b? | 12,843,750 | 6 | 2012-10-11T15:58:22Z | 12,843,820 | 8 | 2012-10-11T16:01:58Z | [
"python",
"python-3.x",
"integer-division"
] | I know that integer division will always return the same answer as truncation of a floating point result if the numbers are both positive. Is it true if one or both of them are negative?
I was just curious to know if there was an integer division expression that would return the same results in Python 2 and Python 3 (... | It is not true in Python 3, and you can test it for yourself:
```
>>> int(-1/3) == -1//3
False
```
Integer division and modulo of `a` and `b` giving `q` (quotient) and `r` (remainder) respectively will always return numbers that satisfy `b*q + r == a` and `(a*b)>0 == q>0` (i.e. `a*b` and `q` have the same sign) and `... |
How to start daemon process from python on windows? | 12,843,903 | 3 | 2012-10-11T16:06:52Z | 12,854,376 | 7 | 2012-10-12T07:37:39Z | [
"python",
"windows",
"daemon"
] | Can my python script spawn a process that will run indefinitely?
I'm not too familiar with python, nor with spawning deamons, so I cam up with this:
```
si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NEW_CONSOLE
subprocess.Popen(executable, close_fds = True, startup... | Using the [answer](http://stackoverflow.com/questions/2970045/python-launch-a-long-running-process-from-a-web-app/2974177#2974177) Janne Karila pointed out this is how you can run a process that doen't die when its parent dies, no need to use the `win32process` module.
```
DETACHED_PROCESS = 8
subprocess.Popen(executa... |
add empty directory to tarfile | 12,844,384 | 5 | 2012-10-11T16:35:57Z | 12,844,555 | 8 | 2012-10-11T16:46:45Z | [
"python",
"tar"
] | How do I add an empty directory to a tarfile in python, without creating it on disk first?
Creating an empty directory in my local filesystem, and adding this to the tar-file is easy enough, but creates unnecessary overhead.
Creating one directly in the tar-file, however seems non-trivial.
My attempts looks like:
``... | Use [addfile()](http://docs.python.org/library/tarfile.html#tarfile.TarFile.addfile) and change the [TarInfo.type](http://docs.python.org/library/tarfile.html#tarfile.TarInfo.type) to tarfile.DIRTYPE
```
import tarfile
with tarfile.open("test.tbz2",mode='w:bz2') as f:
t = tarfile.TarInfo('mydir')
t.type =... |
No numeric types to aggregate - change in groupby() behaviour? | 12,844,529 | 7 | 2012-10-11T16:45:14Z | 12,846,154 | 13 | 2012-10-11T18:25:07Z | [
"python",
"pandas"
] | I have a problem with some groupy code which I'm quite sure once ran (on an older pandas version). On 0.9, I get *No numeric types to aggregate* errors. Any ideas?
```
In [31]: data
Out[31]:
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2557 entries, 2004-01-01 00:00:00 to 2010-12-31 00:00:00
Freq: <1 DateOffs... | How are you generating your data?
See how the output shows that your data is of 'object' type? the groupby operations specifically check whether each column is a numeric dtype first.
```
In [31]: data
Out[31]:
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2557 entries, 2004-01-01 00:00:00 to 2010-12-31 00:00:... |
Sum of all numbers | 12,844,919 | 9 | 2012-10-11T17:10:21Z | 12,845,012 | 14 | 2012-10-11T17:16:36Z | [
"python"
] | I need to write a function that calculates the sum of all numbers n.
```
Row 1: 1
Row 2: 2 3
Row 3: 4 5 6
Row 4: 7 8 9 10
Row 5: 11 12 13 14 15
Row 6: 16 17 18 19 20 21
```
It helps to imagine the above rows as a 'number triangle.' The function should take a number, n, which d... | The leftmost number in column 5 is `11 = (4+3+2+1)+1` which is `sum(range(5))+1`. This is generally true for any `n`.
So:
```
def triangle_sum(n):
start = sum(range(n))+1
return sum(range(start,start+n))
```
---
As noted by a bunch of people, you can express `sum(range(n))` analytically as `n*(n-1)//2` so t... |
Python: Make last item of array become the first | 12,845,112 | 5 | 2012-10-11T17:23:00Z | 12,845,121 | 11 | 2012-10-11T17:23:44Z | [
"python",
"list"
] | This is a very simple question, but I haven't seem to be able to find a satisfactory answer for it.
What is the best way, in Python, make the last item of a list become the first one "pushing" the rest of the list.
Something that does:
```
>>> a=[1,2,3,4]
>>> a[?????]
[4, 1, 2, 3]
```
I know I can always play with ... | Slicing is a little smarter than that; you can use *negative* indices to count from the end:
```
a[-1:] + a[:-1]
```
Demo:
```
>>> a=[1,2,3,4]
>>> a[-1:] + a[:-1]
[4, 1, 2, 3]
```
This works for an arbitrary number of elements to be moved to the front:
```
>>> a[-2:] + a[:-2]
[3, 4, 1, 2]
```
Using slicing like t... |
Python: Make last item of array become the first | 12,845,112 | 5 | 2012-10-11T17:23:00Z | 12,845,127 | 8 | 2012-10-11T17:24:11Z | [
"python",
"list"
] | This is a very simple question, but I haven't seem to be able to find a satisfactory answer for it.
What is the best way, in Python, make the last item of a list become the first one "pushing" the rest of the list.
Something that does:
```
>>> a=[1,2,3,4]
>>> a[?????]
[4, 1, 2, 3]
```
I know I can always play with ... | ```
In [103]: a=[1,2,3,4]
In [104]: a.insert(0,a.pop(-1)) # pop(-1) removes the last element
# and use insert() to insert the popped
# element at 0th endex
In [105]: a
Out[105]: [4, 1, 2, 3]
``` |
Python: Make last item of array become the first | 12,845,112 | 5 | 2012-10-11T17:23:00Z | 12,845,330 | 8 | 2012-10-11T17:36:24Z | [
"python",
"list"
] | This is a very simple question, but I haven't seem to be able to find a satisfactory answer for it.
What is the best way, in Python, make the last item of a list become the first one "pushing" the rest of the list.
Something that does:
```
>>> a=[1,2,3,4]
>>> a[?????]
[4, 1, 2, 3]
```
I know I can always play with ... | You might want to look at [deque](http://docs.python.org/library/collections.html#collections.deque), which are optimized (memory wise) to do what you're asking, if you're doing a lot of these.
```
from collections import deque
>>> a = deque([1,2,3,4])
>>> a.rotate(1)
... deque([4, 1, 2, 3])
```
Since we're doing `t... |
How to iterate over urlparse.urlsplit() result Python | 12,845,161 | 4 | 2012-10-11T17:26:36Z | 12,845,289 | 7 | 2012-10-11T17:33:45Z | [
"python",
"url",
"urllib"
] | Let's say I have this code:
```
>>> import urlparse
>>> url = "http://google.com"
>>> s = urlparse.urlsplit(url)
>>> print s
SplitResult(scheme='http', netloc='google.com', path='', query='', fragment='')
>>> print 'scheme ',s.scheme
scheme http
>>> print 'netloc ',s.netloc
netloc google.com
```
As you can see,... | You could use the internal `_asdict` method:
```
>>> import urlparse
>>> url = "http://google.com"
>>> s = urlparse.urlsplit(url)
>>> s
SplitResult(scheme='http', netloc='google.com', path='', query='', fragment='')
>>> s._asdict()
OrderedDict([('scheme', 'http'), ('netloc', 'google.com'), ('path', ''), ('query', ''),... |
Grep on elements of a list | 12,845,288 | 14 | 2012-10-11T17:33:40Z | 12,845,341 | 24 | 2012-10-11T17:37:04Z | [
"python",
"list",
"grep"
] | I have a list of files names:
```
names = ['aet2000','ppt2000', 'aet2001', 'ppt2001']
```
While I have found some functions that can work to grep character strings, I haven't figured out how to grep all elements of a list.
for instance I would like to:
```
grep(names,'aet')
```
and get:
```
['aet2000','aet2001']
... | Use `filter()`:
```
>>> names = ['aet2000','ppt2000', 'aet2001', 'ppt2001']
>>> filter(lambda x:'aet' in x, names)
['aet2000', 'aet2001']
```
with `regex`:
```
>>> import re
>>> filter(lambda x:re.search(r'aet', x), names)
['aet2000', 'aet2001']
``` |
shufler() takes exactly 1 positional argument (2 given) | 12,845,389 | 3 | 2012-10-11T17:39:57Z | 12,845,444 | 7 | 2012-10-11T17:42:44Z | [
"python",
"python-3.x"
] | Below is my code.
```
def __init__(self):
self.node=[]
self.fronts=[]
self.GoalNode=['1','2','3','4','5','6','7','8','0']
self.StartNode=['1','2','3','4','5','6','7','8','0']
self.PreviousNode=[]
self.prePreviousNode=[]
self.PreviousCount=1
def Solve(self):
self.shufler(10)
......
... | ```
self.shufler(10)
```
This calls `shufler` with two arguments, (1) `self` and (2) `10`. The object to the left of the `.` is used as the first argument.
To handle the `10` argument, add a second parameter to `shufler`'s definition:
```
def shufler(self, count):
``` |
Calling a function from string inside the same module in Python? | 12,846,054 | 9 | 2012-10-11T18:18:23Z | 12,846,076 | 18 | 2012-10-11T18:19:43Z | [
"python",
"string",
"function"
] | Lets say I have a function `bar` inside a module called `foo.py` . Somewhere inside foo.py, I want to be able to call bar() from the string "bar". How do I do that?
```
# filename: foo.py
import sys
def bar():
print 'Hello, called bar()!'
if __name__ == '__main__':
funcname = 'bar'
# Here I should be able to c... | `globals` is probably easier to understand. It returns the current module's `__dict__`, so you could do:
```
func_I_want = globals()['bar'] #Get the function
func_I_want() #call it
```
If you *really* want the module object, you can get it from `sys.modules` (but you usually don't need it):
```
import sys.module... |
Calling a function from string inside the same module in Python? | 12,846,054 | 9 | 2012-10-11T18:18:23Z | 12,846,090 | 9 | 2012-10-11T18:20:39Z | [
"python",
"string",
"function"
] | Lets say I have a function `bar` inside a module called `foo.py` . Somewhere inside foo.py, I want to be able to call bar() from the string "bar". How do I do that?
```
# filename: foo.py
import sys
def bar():
print 'Hello, called bar()!'
if __name__ == '__main__':
funcname = 'bar'
# Here I should be able to c... | Use a dictionary that keeps the mapping of functions you want to call:
```
if __name__ == '__main__':
funcnames = {'bar': bar}
funcnames['bar']()
``` |
scrapy - parsing items that are paginated | 12,847,965 | 16 | 2012-10-11T20:26:23Z | 12,848,077 | 24 | 2012-10-11T20:33:46Z | [
"python",
"scrapy"
] | I have a url of the form:
```
example.com/foo/bar/page_1.html
```
There are a total of 53 pages, each one of them has ~20 rows.
I basically want to get all the rows from all the pages, i.e. ~53\*20 items.
I have working code in my parse method, that parses a single page, and also goes one page deeper per item, to g... | You have two options to solve your problem. The general one is to use `yield` to generate new requests instead of `return`. That way you can issue more than one new request from a single callback. Check the second example at <http://doc.scrapy.org/en/latest/topics/spiders.html#basespider-example>.
In your case there i... |
scrapy - parsing items that are paginated | 12,847,965 | 16 | 2012-10-11T20:26:23Z | 15,887,425 | 8 | 2013-04-08T19:36:58Z | [
"python",
"scrapy"
] | I have a url of the form:
```
example.com/foo/bar/page_1.html
```
There are a total of 53 pages, each one of them has ~20 rows.
I basically want to get all the rows from all the pages, i.e. ~53\*20 items.
I have working code in my parse method, that parses a single page, and also goes one page deeper per item, to g... | You could use the CrawlSpider instead of the BaseSpider and use SgmlLinkExtractor to extract the pages in the pagination.
For instance:
```
start_urls = ["www.example.com/page1"]
rules = ( Rule (SgmlLinkExtractor(restrict_xpaths=('//a[@class="next_page"]',))
, follow= True),
Rule (SgmlLinkEx... |
print the value of a variable in Python/Django? | 12,848,286 | 4 | 2012-10-11T20:48:44Z | 12,848,303 | 8 | 2012-10-11T20:49:59Z | [
"python",
"django",
"windows"
] | In PHP I'm used to being able to do `print $var` or `print_r($var)`.
I can print variables in my views in python but they end up in my cmd window not on the page itself. This is fine for some things but windows' cmd window isn't exactly the most readable when it starts wrapping output and turning it into gibberish.
I... | ```
<html>
{{ this_is_my_variable_that_is_passed_to_my_view }}
</html>
```
the `{{` allow variable access to the item which will call the items `__unicode__` function if it exists otherwise it will call its `__str__` function |
getattr vs. inspect.getmembers | 12,848,507 | 4 | 2012-10-11T21:05:30Z | 12,858,675 | 7 | 2012-10-12T12:04:58Z | [
"python"
] | It is possible to grab an object attribute using either getattr(obj, attr) or inspect.getmembers(obj) and then filtering by name:
```
import inspect
class Foo(object):
def __init__(self):
self.a = 100
def method(self): pass
foo = Foo()
method_by_getattr = getattr(foo, 'method')
foo_members = insp... | millimoose gets the green check, but I thought I'd add a bit.
**tl;dr**
Bound method objects are transient. That is, they are created anew each time you grab them.
```
class Foo(object):
def bar(object): pass
foo = Foo()
m1 = foo.bar
m2 = foo.bar
print (id(m1))
print (id(m2))
# 38121264
# 38952752
```
**More ... |
Repeat python function and return value | 12,849,691 | 4 | 2012-10-11T22:41:57Z | 12,849,710 | 8 | 2012-10-11T22:43:56Z | [
"python"
] | I am trying to have a function repeat itself if a certain criteria is not met. For instance:
```
def test():
print "Hello",
x = raw_input()
if x in '0123456789':
return x
test()
```
In this program if you type a number the first time, it will return the number. If you type some non-number, it ... | you need to `return test()` at the tail of the function to return the value that the valid call into test() returns. |
Why does python pickle load and dump inflate the size of of an object on disk? | 12,849,791 | 5 | 2012-10-11T22:52:30Z | 12,849,926 | 9 | 2012-10-11T23:06:39Z | [
"python",
"serialization",
"load",
"pickle",
"dump"
] | I have a pickled object in a file named b1.pkl:
```
$ ls -l b*
-rw-r--r-- 1 fireball staff 64743950 Oct 11 15:32 b1.pkl
```
Then I run the following python code to load the object and dump it to a new file:
```
import numpy as np
import cPickle as pkl
fin = open('b1.pkl', 'r')
fout = open('b2.pkl', 'w')
x = pkl... | It could be that the original pickle used some other protocol. For example try specifying `protocol=2` as a keyword argument to the second `pickle.dump` and test it again. Binary pickle should be much smaller in size. |
how to combine two data frames in python pandas | 12,850,345 | 10 | 2012-10-11T23:53:37Z | 12,850,453 | 18 | 2012-10-12T00:07:38Z | [
"python",
"pandas"
] | I'm using python pandas data frame , I have a initial data frame say D. I extract two data frames from it like this:
`A = D[D.label == k]`
`B = D[D.label != k]`
then I change the label in A and B:
```
A.label = 1
```
`B.label = -1`
I want to combine A and B so I can have them as one data frame something like unio... | I believe you can use the append
```
bigdata=data1.append(data2,ignore_index = True)
```
to keep their indexes just dont use the ignore\_index keyword ... |
how to combine two data frames in python pandas | 12,850,345 | 10 | 2012-10-11T23:53:37Z | 30,557,040 | 8 | 2015-05-31T11:47:29Z | [
"python",
"pandas"
] | I'm using python pandas data frame , I have a initial data frame say D. I extract two data frames from it like this:
`A = D[D.label == k]`
`B = D[D.label != k]`
then I change the label in A and B:
```
A.label = 1
```
`B.label = -1`
I want to combine A and B so I can have them as one data frame something like unio... | You can also use `pd.concat`, which is particularly helpful when you are joining more than two dataframes:
```
bigdata = pd.concat([data1, data2], ignore_index=True)
``` |
How to remove duplicates in a csv file based on two columns? | 12,850,909 | 8 | 2012-10-12T01:13:20Z | 12,851,143 | 12 | 2012-10-12T01:50:03Z | [
"python"
] | I have a csv file like this :
```
column1 column2
john kerry
adam stephenson
ashley hudson
john kerry
etc..
```
I want to remove duplicates from this file, to get only :
```
column1 column2
john kerry
adam stephenson
ashley hudson
```
I wrote this script that removes du... | You're really close. Use those columns as the set entry
```
entries = set()
for row in reader:
key = (row[0], row[1]) # instead of just the last name
if key not in entries:
writer.writerow(row)
entries.add(key)
``` |
How can I fix "ImportError: no module named shell" error for IPython | 12,852,887 | 5 | 2012-10-12T05:35:51Z | 12,852,906 | 13 | 2012-10-12T05:38:15Z | [
"python",
"ipython"
] | I've seen a number of people recommend that I use the following snippet to embed an IPython shell or drop to an IPython shell from e.g. a django view.
```
from IPython.Shell import IPShellEmbed
ipython = IPShellEmbed()
ipython()
```
But when I do this, I get
```
>>> from IPython.Shell import IPShellEmbed
Traceback (... | The solution is to [use the following](http://ipython.org/ipython-doc/dev/interactive/reference.html#embedding-ipython) instead:
```
import IPython
IPython.embed()
```
[Issue 286](https://github.com/ipython/ipython/issues/286) on the [IPython github repo](https://github.com/ipython/ipython/) explains that the Shell m... |
Connect to SMTP (SSL or TLS) using Python | 12,854,572 | 11 | 2012-10-12T07:53:33Z | 13,003,002 | 8 | 2012-10-21T22:54:04Z | [
"python",
"sockets",
"smtp",
"gmail"
] | I am attempting to connect to the gmail smtp mailserver and perform tasks as outlined by the skeleton code given to me. Only the use of sockets is allowed. I need to: send HELO command, Mail FROM, RCPT TO, and DATA.
There are many cases of similar problems posted, but they haven't received the proper answer. Example i... | When using SSL, you need to connect to port 465 instead of port 587. If you use STARTTLS, you still need to use `ssl.wrap_socket`, you just do it later - specifically, after receiving the `220` response to the `STARTTLS` command. After doing `STARTTLS`, you're supposed to do `HELO` again, since the server is supposed t... |
How to evaluate two or more element in an set or not in Python | 12,854,611 | 2 | 2012-10-12T07:56:32Z | 12,854,635 | 7 | 2012-10-12T07:58:14Z | [
"python"
] | ```
s = set([1,2,3])
```
I could do this:
```
1 in s
#=> True
```
I'm wondering without using loop, is there a way to do something like:
```
1,2 in s
#=>True
``` | You can use set intersection:
```
>>> s = {1, 2, 3}
>>> t = {1, 2}
>>> s & t == t
True
```
Of course this still has a loop internally.
As spicavigo pointed out you can use `issuperset`, or more concisely you can use `>=` which is equivalent:
```
>>> s >= t
True
```
Again it still has a loop internally, but you pro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.