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 |
|---|---|---|---|---|---|---|---|---|---|
Counting lines, words, and characters within a text file using Python | 4,783,899 | 6 | 2011-01-24T15:45:30Z | 4,783,948 | 19 | 2011-01-24T15:50:12Z | [
"python"
] | I'm having a bit of a rough time laying out how I would count certain elements within a text file using Python. I'm a few months into Python and I'm familiar with the following functions;
* raw\_input
* open
* split
* len
* print
* rsplit()
Here's my code so far:
```
fname = "feed.txt"
fname = open('feed.txt', 'r')
... | Try this:
```
fname = "feed.txt"
num_lines = 0
num_words = 0
num_chars = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_lines += 1
num_words += len(words)
num_chars += len(line)
```
Back to your code:
```
fname = "feed.txt"
fname = open('feed.txt', 'r')
`... |
Why list indices must be integers, not tuple? | 4,784,054 | 4 | 2011-01-24T15:59:06Z | 4,784,085 | 11 | 2011-01-24T16:01:11Z | [
"python",
"list",
"dictionary",
"tuples"
] | I have this simple program:
```
x = {}
x[1,2] = 3
print x
print x[1,2]
```
It works fine. The fist `print` generates `{(1,2):3}` and the second one generates `3`.
But in my "big" program I seems to do the same but get a `list indices must be integers, not tuple` error. What this error message can mean and how I can ... | If you're getting that error, then you are trying to index a list, and not a dictionary.
A Python list, like `[1, 2, 3]`, must be indexed with integer values. A dictionary, which is what you have in your example, can be indexed by a wider range of different values. |
Show a ManyToManyField as Checkboxes in Django Admin | 4,784,567 | 13 | 2011-01-24T16:45:21Z | 4,784,709 | 32 | 2011-01-24T16:57:48Z | [
"python",
"django",
"django-models",
"django-admin",
"manytomanyfield"
] | Is there a simple way to show a ManyToManyField as Checkboxes in Django Admin?? Any suggestions? | From [this answer](http://stackoverflow.com/questions/1760421/django-manytomany/1760592#1760592) it seems like it is possible to use [ModelAdmin.formfield\_overrides](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_overrides) to override the ManyToManyField to use [Chec... |
LDAP query in python | 4,784,775 | 11 | 2011-01-24T17:04:22Z | 4,785,530 | 9 | 2011-01-24T18:17:00Z | [
"python",
"ldap",
"ldap-query"
] | I want to execute the following query in the ldap
> ldapsearch -h hostname -b dc=ernet,dc=in -x "(&(uid=w2lame)(objectClass=posixAccount))" gidnumber
>
> ldapsearch -h hostname -b dc=ernet,dc=in -x "(&(gidNumber=1234)(objectClass=posixGroup))" cn
And use the variables thus obtained. How can I do that? | You probably want to us the ["ldap"](http://www.python-ldap.org) module. Code would look something like:
```
import ldap
l = ldap.initialize('ldap://ldapserver')
username = "uid=%s,ou=People,dc=mydotcom,dc=com" % username
password = "my password"
try:
l.protocol_version = ldap.VERSION3
... |
LDAP query in python | 4,784,775 | 11 | 2011-01-24T17:04:22Z | 28,880,749 | 13 | 2015-03-05T14:52:29Z | [
"python",
"ldap",
"ldap-query"
] | I want to execute the following query in the ldap
> ldapsearch -h hostname -b dc=ernet,dc=in -x "(&(uid=w2lame)(objectClass=posixAccount))" gidnumber
>
> ldapsearch -h hostname -b dc=ernet,dc=in -x "(&(gidNumber=1234)(objectClass=posixGroup))" cn
And use the variables thus obtained. How can I do that? | While the accepted answer does in fact show a proper way to bind to an LDAP server I do feel it didn't answer the question holistically. Here is what I ended up implementing to grab the mail and department of a user. This somewhat blends the required attributes from the original question.
```
l = ldap.initialize('ldap... |
cherrypy.tree.mount and mod_wsgi | 4,785,228 | 4 | 2011-01-24T17:47:39Z | 4,786,535 | 9 | 2011-01-24T20:01:15Z | [
"python",
"apache",
"mod-wsgi",
"cherrypy"
] | I used to use cherrypy with mod\_python and I built my controller trees with `cherrypy.tree.mount` calls and I would like to keep them (they are spread through the code).
Now I have to use mod\_wsgi. Example: [from cherrypy wiki](http://tools.cherrypy.org/wiki/ModWSGI)
```
import sys
sys.stdout = sys.stderr
import at... | Finally! Got it myself - from the manual...
`cherrypy.tree` is itself a WSGI object so you simply do:
```
cherrypy.tree.mount(...)
cherrypy.tree.mount(...)
cherrypy.tree.mount(...)
application = cherrypy.tree
``` |
Search a text file and print related lines in Python? | 4,785,244 | 18 | 2011-01-24T17:49:24Z | 4,785,306 | 32 | 2011-01-24T17:55:25Z | [
"python",
"file",
"search"
] | How do I search a text file for a key-phrase or keyword and then print the line that key-phrase or keyword is in? | ```
searchfile = open("file.txt", "r")
for line in searchfile:
if "searchphrase" in line: print line
searchfile.close()
```
To print out multiple lines (in a simple way)
```
f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
if "searchphrase" in line:
... |
Search a text file and print related lines in Python? | 4,785,244 | 18 | 2011-01-24T17:49:24Z | 4,785,377 | 12 | 2011-01-24T18:01:43Z | [
"python",
"file",
"search"
] | How do I search a text file for a key-phrase or keyword and then print the line that key-phrase or keyword is in? | ```
with open('file.txt', 'r') as searchfile:
for line in searchfile:
if 'searchphrase' in line:
print line
```
With apologies to [senderle](http://stackoverflow.com/questions/4785244/how-would-i-search-a-text-file-in-python/4785306#4785306) who I blatantly copied. |
Python: Using xpath locally / on a specific element | 4,785,864 | 24 | 2011-01-24T18:49:21Z | 4,785,929 | 38 | 2011-01-24T18:58:07Z | [
"python",
"xpath",
"lxml"
] | I'm trying to get the links from a page with xpath. The problem is that I only want the links inside a table, but if I apply the xpath expression on the whole page I'll capture links which I don't want.
For example:
```
tree = lxml.html.parse(some_response)
links = tree.xpath("//a[contains(@href, 'http://www.example.... | Your xpath starts with a slash (`/`) and is therefore absolute. Add a dot (`.`) in front to make it relative to the current element i.e.
```
links = table.xpath(".//a[contains(@href, 'http://www.example.com/filter/')]")
``` |
excluding file types when packaging an rpm | 4,786,101 | 4 | 2011-01-24T19:16:11Z | 16,937,657 | 16 | 2013-06-05T10:34:31Z | [
"python",
"packaging",
"rpm"
] | In my spec file for packaging a python rpm, I want to remove certain filetypes in certain directories:
e.g., I want to exclude source \*.py files in these directories:
```
lib/*.py
comm/*.py
```
I think I should do this in the %file section of my spec. Any suggestions? | You need to use %exclude macro, i.e.
```
%files
%exclude /lib/*.py
%exclude /comm/*.py
``` |
How do I split this string up? | 4,786,765 | 2 | 2011-01-24T20:24:26Z | 4,786,785 | 8 | 2011-01-24T20:26:25Z | [
"python",
"io"
] | ```
...
1947q2 -0.6
1947q3 -0.3
1947q4 6.2
1948q1 16.5
...
```
How do I get this text file into a list? I'm having problems with the spacing between the year and corresponding values.
This is what I have so far:
```
data = []
for line in open("file"):
if '1947' i... | Just using `split()` without arguments splits by whitespace, and eats consecutive whitespace:
```
>>> s=' 1947q2 -0.6'
>>> s.split()
['1947q2', '-0.6']
``` |
Django: How to replace/overwrite/update/change a file of FileField? | 4,787,141 | 8 | 2011-01-24T21:04:03Z | 4,788,847 | 8 | 2011-01-25T00:36:04Z | [
"python",
"django",
"django-models"
] | In Django, I have the following model:
```
from django.db import models
from django.core.files.base import File
import os, os.path
class Project(models.Model):
video = models.FileField(upload_to="media")
def replace_video(self):
"""Convert video to WebM format."""
# This is where the conversi... | You have two choices.
I'll assume your `Project` model is only a snippet of code.
Option 1 is to break your model down so that a Project does not have a single file, but rather a Project model is associated with a ProjectFile model. Perhaps one-to-many. One Project as many ProjectFiles. That is, ProjectFile has a For... |
Does Django have a way to open a HTTP long poll connection? | 4,787,530 | 14 | 2011-01-24T21:45:55Z | 4,788,034 | 12 | 2011-01-24T22:37:11Z | [
"python",
"django",
"http",
"rest"
] | Leave the connection open, until an event occurs. | Have a look at [Django / Comet (Push): Least of all evils?](http://stackoverflow.com/questions/4310706/django-comet-push-least-of-all-evils) or [The latest recommendation for Comet in Python?](http://stackoverflow.com/questions/1514899/the-latest-recommendation-for-comet-in-python) - COMET is another name for "ajax lon... |
Does Django have a way to open a HTTP long poll connection? | 4,787,530 | 14 | 2011-01-24T21:45:55Z | 14,304,023 | 7 | 2013-01-13T13:37:50Z | [
"python",
"django",
"http",
"rest"
] | Leave the connection open, until an event occurs. | For the future readers :)
I created a simple long polling django class views using Gevent, you can find it on github on <https://github.com/tbarbugli/django_longpolling> or get it from pypi (django\_longpolling)
EDIT: I did some further experiment / deployment with django long polling / async workers and I can say th... |
How do I correctly use Or with strings in an if statement | 4,787,645 | 3 | 2011-01-24T21:55:59Z | 4,787,661 | 8 | 2011-01-24T21:56:52Z | [
"python"
] | This is a function I wrote. If I enter Wednesday as the day of the week, the program can't get to it to execute the print code. What is the correct syntax for that line of code to make Wednesday work correctly?
```
def day(dayOfWeek):
if dayOfWeek == ("Monday" or "Wednesday"):
print("Poetry: 6-7:15 in Chem... | The expression `("Monday" or "Wednesday")` in your code is always evaluated to `"Monday"`. The operator `or` is a logical `or` that first tries if its first operand [evaluates to `True`](http://docs.python.org/library/stdtypes.html#truth-value-testing). If yes, it returns the first operand, otherwise it returns the sec... |
Python 3.2 skip a line in csv.DictReader | 4,787,723 | 14 | 2011-01-24T22:02:10Z | 4,787,764 | 16 | 2011-01-24T22:06:46Z | [
"python",
"csv",
"python-3.x"
] | How do I skip a line of records in a CSV when using a DictReader?
Code:
```
import csv
reader = csv.DictReader(open('test2.csv'))
# Skip first line
reader.next()
for row in reader:
print(row)
```
Error:
```
Traceback (most recent call last):
File "learn.py", line 3, in <module>
reader.next()
AttributeErro... | You use `next(reader)` instead.
Source: [csv.DictReader documentation](http://docs.python.org/dev/library/csv.html#csv.csvreader.__next__) |
Python: strftime, gmtime not respecting timezone | 4,788,533 | 9 | 2011-01-24T23:47:33Z | 4,788,566 | 16 | 2011-01-24T23:53:30Z | [
"python",
"timezone"
] | ```
import time
print time.strftime("%a, %d %b %Y %I:%M %p %Z", time.gmtime())
```
I live in California. For some reason, this code is reporting the time in GMT, instead of respecting the system time zone. I know that strftime knows I'm in pacific, because it still prints 'PST' at the end, but it's still 8 hours ahead... | [`time.gmtime()`](http://docs.python.org/library/time.html#time.gmtime) returns the time in UTC. What you need is [`time.localtime()`](http://docs.python.org/library/time.html#time.localtime), which *is* timezone-aware. This behaviour is well-documented in the [`time` module documentation](http://docs.python.org/librar... |
Insert a node for an element in XML with Python/ElementTree | 4,788,633 | 5 | 2011-01-25T00:01:52Z | 4,789,163 | 10 | 2011-01-25T01:38:32Z | [
"python",
"xml",
"elementtree"
] | I need to traverse the XML tree to add sub element when the value is less than 5.
For example, this XML can be modified into
```
<?xml version="1.0" encoding="UTF-8"?>
<A value="45">
<B value="30">
<C value="10"/>
<C value ="20"/>
</B>
<B value="15">
<C value = "5" />
<C val... | You probably made a typo because in the example, an error element is appended as the child of an element whose value is 10, which is not less than 5. But I think this is the idea:
```
#!/usr/bin/env python
from xml.etree.ElementTree import fromstring, ElementTree, Element
def validate_node(elem):
for child in el... |
In Django, how do I check if a user is in a certain group? | 4,789,021 | 67 | 2011-01-25T01:09:53Z | 4,789,038 | 59 | 2011-01-25T01:11:53Z | [
"python",
"django",
"django-authentication"
] | I created a custom group in Django's admin site.
In my code, I want to check if a user is in this group. How do I do that? | You can access the groups simply through the `groups` attribute on `User`.
```
from django.contrib.auth.models import User, Group
group = Group(name="Editor")
group.save() # save this new group for this example
user = User.objects.get(pk=1) # assuming, there is one initial user
user.groups.add(group... |
In Django, how do I check if a user is in a certain group? | 4,789,021 | 67 | 2011-01-25T01:09:53Z | 15,029,952 | 7 | 2013-02-22T17:30:08Z | [
"python",
"django",
"django-authentication"
] | I created a custom group in Django's admin site.
In my code, I want to check if a user is in this group. How do I do that? | If you need the list of users that are in a group, you can do this instead:
```
from django.contrib.auth.models import Group
users_in_group = Group.objects.get(name="group name").user_set.all()
```
and then check
```
if user in users_in_group:
# do something
```
to check if the user is in the group. |
In Django, how do I check if a user is in a certain group? | 4,789,021 | 67 | 2011-01-25T01:09:53Z | 20,110,261 | 90 | 2013-11-21T00:45:04Z | [
"python",
"django",
"django-authentication"
] | I created a custom group in Django's admin site.
In my code, I want to check if a user is in this group. How do I do that? | Your **User** object is linked to the **Group** object through a **ManyToMany** relationship.
You can thereby apply the **filter** method to **user.groups**.
So, to check if a given User is in a certain group ("Member" for the example), just do this :
```
def is_member(user):
return user.groups.filter(name='Memb... |
Split a string into 2 in Python | 4,789,601 | 13 | 2011-01-25T03:04:29Z | 4,789,617 | 24 | 2011-01-25T03:07:25Z | [
"python",
"string",
"split"
] | Is there a way to split a string into 2 equal halves without using a loop in Python? | ```
firstpart, secondpart = string[:len(string)/2], string[len(string)/2:]
``` |
Scope of imported modules/functions in Python | 4,789,711 | 3 | 2011-01-25T03:31:16Z | 4,789,757 | 8 | 2011-01-25T03:42:12Z | [
"python",
"import",
"scope"
] | I'm new here and am not 100% sure how to ask this question so I'll just dive right in. Should I be using import statements at the beginning of every function I write that import all of the various modules/functions I need for that function's scope? i.e.
```
def func1()
import os.path
print func(2)
do somet... | [Usually](http://www.python.org/dev/peps/pep-0008/#imports) all imports are placed at the beginning of the file. Importing a module in a function body will `import` a module in that scope only:
```
def f():
import sys
print 'f', sys.version_info
def g():
print 'g', sys.version_info
if __name__ == '__main... |
How to terminate a python subprocess launched with shell=True | 4,789,837 | 142 | 2011-01-25T03:58:43Z | 4,791,612 | 203 | 2011-01-25T09:07:49Z | [
"python",
"linux",
"subprocess",
"kill-process"
] | I'm launching a subprocess with the following command:
```
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
```
However, when I try to kill using:
```
p.terminate()
```
or
```
p.kill()
```
The command keeps running in the background, so I was wondering how can I actually terminate the process.
Note ... | Use a [process group](http://en.wikipedia.org/wiki/Process_group) so as to enable sending a signal to all the process in the groups. For that, you should attach a [session id](http://pubs.opengroup.org/onlinepubs/009695399/functions/setsid.html) to the parent process of the spawned/child processes, which is a shell in ... |
How to terminate a python subprocess launched with shell=True | 4,789,837 | 142 | 2011-01-25T03:58:43Z | 13,143,013 | 36 | 2012-10-30T16:01:25Z | [
"python",
"linux",
"subprocess",
"kill-process"
] | I'm launching a subprocess with the following command:
```
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
```
However, when I try to kill using:
```
p.terminate()
```
or
```
p.kill()
```
The command keeps running in the background, so I was wondering how can I actually terminate the process.
Note ... | ```
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
p.kill()
```
`p.kill()` ends up killing the shell process and `cmd` is still running.
I found a convenient fix this by:
```
p = subprocess.Popen("exec " + cmd, stdout=subprocess.PIPE, shell=True)
```
This will cause cmd to inherit the shell process, ... |
How to terminate a python subprocess launched with shell=True | 4,789,837 | 142 | 2011-01-25T03:58:43Z | 17,614,872 | 9 | 2013-07-12T12:24:49Z | [
"python",
"linux",
"subprocess",
"kill-process"
] | I'm launching a subprocess with the following command:
```
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
```
However, when I try to kill using:
```
p.terminate()
```
or
```
p.kill()
```
The command keeps running in the background, so I was wondering how can I actually terminate the process.
Note ... | I could do it using
```
from subprocess import Popen
process = Popen(command, shell=True)
Popen("TASKKILL /F /PID {pid} /T".format(pid=process.pid))
```
it killed the `cmd.exe` and the program that i gave the command for.
(On Windows) |
How to terminate a python subprocess launched with shell=True | 4,789,837 | 142 | 2011-01-25T03:58:43Z | 25,134,985 | 12 | 2014-08-05T09:07:15Z | [
"python",
"linux",
"subprocess",
"kill-process"
] | I'm launching a subprocess with the following command:
```
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
```
However, when I try to kill using:
```
p.terminate()
```
or
```
p.kill()
```
The command keeps running in the background, so I was wondering how can I actually terminate the process.
Note ... | If you can use [psutil](https://pypi.python.org/pypi/psutil/), then this works perfectly:
```
import subprocess
import psutil
def kill(proc_pid):
process = psutil.Process(proc_pid)
for proc in process.get_children(recursive=True):
proc.kill()
process.kill()
proc = subprocess.Popen(["infinite_a... |
Python PIL: How to draw an ellipse in the middle of an image? | 4,789,894 | 8 | 2011-01-25T04:12:29Z | 4,790,962 | 13 | 2011-01-25T07:28:48Z | [
"python",
"python-imaging-library",
"ellipse"
] | I seem to be having some trouble getting this code to work:
```
import Image, ImageDraw
im = Image.open("1.jpg")
draw = ImageDraw.Draw(im)
draw.ellipse((60, 60, 40, 40), fill=128)
del draw
im.save('output.png')
im.show()
```
This should draw an ellipse at (60,60) which is 40 by 40 pixels. The image returns nothin... | The bounding box is a 4-tuple `(x0, y0, x1, y1)` where `(x0, y0)` is the top-left bound of the box and `(x1, y1)` is the lower-right bound of the box.
To draw an ellipse to the center of the image, you need to define how large you want your ellipse's bounding box to be (variables `eX` and `eY` in my code snippet below... |
gnuplot alternative with higher time precision | 4,789,972 | 5 | 2011-01-25T04:24:48Z | 4,792,208 | 10 | 2011-01-25T10:13:43Z | [
"python",
"precision",
"gnuplot"
] | At present I'm using gnuplot to plot data against a time line. However the precision of the time line is in milliseconds but gnuplot only seems to be able to handle seconds.
I've looked at a couple of alternatives, but really I just need something like gnuplot that can cope with fractions of a second.
The programming... | You can set the ticks format with
```
set format x '%.6f'
```
or (maybe, I have not tried it, as I now prefer to use [Matplotlib](http://matplotlib.sourceforge.net/gallery.html) and do not have gnuplot installed on my machines):
```
set timefmt "%Y-%m-%d-%H:%M:%.6S"
```
(note the number of digits specified along wi... |
gnuplot alternative with higher time precision | 4,789,972 | 5 | 2011-01-25T04:24:48Z | 18,825,927 | 7 | 2013-09-16T10:35:20Z | [
"python",
"precision",
"gnuplot"
] | At present I'm using gnuplot to plot data against a time line. However the precision of the time line is in milliseconds but gnuplot only seems to be able to handle seconds.
I've looked at a couple of alternatives, but really I just need something like gnuplot that can cope with fractions of a second.
The programming... | According to the [gnuplot 4.6 manual](http://www.gnuplot.info/documentation.html) it states, under "Time/date specifiers" (page 114 of the gnuplot 4.6 PDF):
> %S - second, integer 0â60 on output, (double) on input
What this means is that when reading timestamps such as `2013-09-16 09:56:59.412` the fractional porti... |
Python HTMLParser: UnicodeDecodeError | 4,790,078 | 12 | 2011-01-25T04:45:34Z | 4,790,654 | 17 | 2011-01-25T06:37:14Z | [
"python",
"character-encoding",
"html-parsing"
] | I'm using HTMLParser to parse pages I pull down with urllib, and am coming across `UnicodeDecodeError` exceptions when passing some to `HTMLParser`.
I tried using `chardet` to detect the encodings and to convert to `ascii`, or `utf-8` (the [docs](http://docs.python.org/library/htmlparser.html) don't seem to say what i... | It is UTF-8, indeed. This works:
```
from HTMLParser import HTMLParser
import urllib
class search_youtube(HTMLParser):
def __init__(self, search_terms):
HTMLParser.__init__(self)
self.track_ids = []
for search in search_terms:
self.__in_result = False
search = urll... |
What is the de facto library for creating Python Daemons | 4,790,876 | 25 | 2011-01-25T07:13:52Z | 4,830,247 | 10 | 2011-01-28T15:56:22Z | [
"python",
"daemon",
"python-daemon"
] | I am attempting to use the [python-daemon](http://pypi.python.org/pypi/python-daemon/) library which seemed to me to be the safest way to create a Daemon without forgetting anything. The documentation is quite poor, being just [PEP 3143](http://www.python.org/dev/peps/pep-3143/).
**On the other hand**, I have found a ... | I went with Sander Marechal's [A simple unix/linux daemon in Python](http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/), it **is** simple, and you work with it by creating a subclass and overriding the `run()` method, which feels a very natural way to do things (rather than the `with context:`... |
Delete newline / return carriage in file output | 4,791,080 | 7 | 2011-01-25T07:51:14Z | 4,791,113 | 11 | 2011-01-25T07:57:25Z | [
"python",
"file",
"io"
] | I have a wordlist that contains returns to separate each new letter. Is there a way to programatically delete each of these returns using file I/O in Python?
Edit: I know how to manipulate strings to delete returns. I want to physically edit the file so that those returns are deleted.
I'm looking for something like t... | You can use a string's [rstrip](http://docs.python.org/2/library/stdtypes.html#str.rstrip) method to remove the newline characters from a string.
```
>>> 'something\n'.rstrip('\r\n')
>>> 'something'
``` |
Delete newline / return carriage in file output | 4,791,080 | 7 | 2011-01-25T07:51:14Z | 4,791,169 | 14 | 2011-01-25T08:07:05Z | [
"python",
"file",
"io"
] | I have a wordlist that contains returns to separate each new letter. Is there a way to programatically delete each of these returns using file I/O in Python?
Edit: I know how to manipulate strings to delete returns. I want to physically edit the file so that those returns are deleted.
I'm looking for something like t... | ```
>>> string = "testing\n"
>>> string
'testing\n'
>>> string = string[:-1]
>>> string
'testing'
```
This basically says "chop off the last thing in the string" The `:` is the "slice" operator. It would be a good idea to read up on how it works as it is *very* useful.
**EDIT**
I just read your updated question. I t... |
What is the trick in this website? | 4,791,253 | 2 | 2011-01-25T08:23:20Z | 4,791,272 | 11 | 2011-01-25T08:26:31Z | [
"python",
"urllib"
] | I can access this webpage in my firefox browser:
<http://www.ip-adress.com/ip_tracer/74.82.190.99>
So I can get the information about this IP.
However, when I fetch it using Python, there will be errors:
```
import urllib
f = urllib.urlopen("http://www.ip-adress.com/ip_tracer/74.82.190.99")
print f.read()
```
I get ... | Probably the server reads your [`User-Agent`](http://en.wikipedia.org/wiki/User_agent) header and decides not to serve your request. Alternatively it can rely on some other headers being typically set by normal browsers (like FF).
I tried this one:
```
import urllib2
request = urllib2.Request("http://www.ip-adress.c... |
How do I do greater than/less than using MongoDB? | 4,791,555 | 16 | 2011-01-25T09:01:22Z | 4,791,583 | 23 | 2011-01-25T09:05:12Z | [
"python",
"database",
"mongodb"
] | I'm using the pymongo driver.
Can someone take a look at pymongo and tell me how to do greater than? I"m used to doing : for everything. | Have you seen [the doc](http://api.mongodb.org/python/1.9%2B/tutorial.html#range-queries) ? Take from the manual :
```
>>> d = datetime.datetime(2009, 11, 12, 12)
>>> for post in posts.find({"date": {"$lt": d}}).sort("author"):
... post
...
{u'date': datetime.datetime(2009, 11, 10, 10, 45), u'text': u'and pretty eas... |
How do I do greater than/less than using MongoDB? | 4,791,555 | 16 | 2011-01-25T09:01:22Z | 4,791,611 | 14 | 2011-01-25T09:07:27Z | [
"python",
"database",
"mongodb"
] | I'm using the pymongo driver.
Can someone take a look at pymongo and tell me how to do greater than? I"m used to doing : for everything. | If you wanna query and find docs which have a field greater than something you can
```
users.find({"age": {"$gt": 20}})
```
Check out the advanced query section of Mongodb for more reference.
--Sai |
In python, how do I take the highest occurrence of something in a list, and sort it that way? | 4,791,599 | 4 | 2011-01-25T09:06:44Z | 4,791,688 | 13 | 2011-01-25T09:18:27Z | [
"python",
"list",
"list-manipulation"
] | ```
[3, 3, 3, 4, 4, 2]
```
Would be:
```
[ (3, 3), (4, 2), (2, 1) ]
```
The output should be sorted by highest count first to lowest count. In this case, 3 to 2 to 1. | You can use a [Counter](http://docs.python.org/library/collections#collections.Counter) in Python 2.7+ ([this recipe](http://code.activestate.com/recipes/576611-counter-class/) works on 2.5+):
```
from collections import Counter
print Counter([3, 3, 3, 4, 4, 2]).most_common()
# [(3, 3), (4, 2), (2, 1)]
``` |
How to import 'GDB' in python | 4,792,483 | 17 | 2011-01-25T10:41:23Z | 10,240,053 | 22 | 2012-04-20T04:00:33Z | [
"python",
"gdb"
] | I am using python 2.7 & python 3.1.3.
But in my python i am unable to
"import gdb"
It is giving me error as
```
>>> import gdb
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
ImportError: No module named gdb
>>>
```
Whats a reason for this, how should i has
to solve this problem. | `import gdb` only works when your Python code is running within the GDB process. It's not supposed to work from the regular system Python interpreter.
# Explanation
* GDB embeds the Python interpreter so it can use Python as an extension language.
* You **can't** just `import gdb` from `/usr/bin/python` like it's an ... |
Speeding up string splitting and concatenation | 4,793,247 | 4 | 2011-01-25T12:03:07Z | 4,793,281 | 8 | 2011-01-25T12:07:53Z | [
"python",
"primes"
] | I'm trying to solve [Project Euler's problem #35](http://projecteuler.net/index.php?section=problems&id=35)
> The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
>
> How many circular primes are there below one million?
**This is my solution:**
``... | 1. Use a set for membership testing instead of an array. The hash lookup will be O(1) instead of O(n). This is the biggest bottleneck.
2. Break out of the loop as soon as you see that it's not a circular prime instead of trying the other rotations. This is another bottleneck.
---
Here, I've isolated the circularity t... |
How can I create a copy of an object in Python? | 4,794,244 | 60 | 2011-01-25T13:48:41Z | 4,794,254 | 66 | 2011-01-25T13:49:33Z | [
"python",
"oop",
"object",
"copy"
] | I would like to create a copy of an object. I want the new object to possess all properties of the old object (values of the fields). But I want to have independent objects. So, if I change values of the fields of the new object, the old object should not be affected by that. | Have a look at the [`copy.deepcopy()`](http://docs.python.org/library/copy.html#copy.deepcopy) function. It should do exactly what you need. Also have a look at [this answer](http://stackoverflow.com/questions/3975376/understanding-dict-copy-shallow-or-deep/3975388#3975388) to a related question for a nice explanation. |
Unit testing Django JSON View | 4,794,457 | 9 | 2011-01-25T14:12:11Z | 4,794,737 | 8 | 2011-01-25T14:38:22Z | [
"python",
"json",
"ajax",
"django",
"unit-testing"
] | I'm trying to write some unit tests for some Django json\_view views and I'm having trouble passing the json\_string to the view. I posted a related question yesterday about passing a json string to a Django view from the JS, the issue was that in my JS I was just passing the json string where I needed to be passing th... | Final edit
I originally stated that header `HTTP_X_REQUESTED_WITH='XMLHttpRequest'` was necessary in the post call but this is currently false while in tests. This header is necessary for the csrf middleware but csrf is disabled in tests. However, I still believe it is a good practice to put in test even if middleware... |
Python list does not shuffle in a loop | 4,794,663 | 7 | 2011-01-25T14:31:23Z | 4,794,685 | 15 | 2011-01-25T14:33:05Z | [
"python",
"random",
"for-loop"
] | I'm trying to create an randomized list of keys by iterating:
```
import random
keys = ['1', '2', '3', '4', '5']
random.shuffle(keys)
print keys
```
This works perfect. However, if I put it in a loop and capture the output:
```
a = []
for x in range(10):
random.shuffle(keys)
a.append(keys)
```
I am getting... | The problem is that you are shuffling the list in place and then adding the *reference* of the list to the combined list. Thus you end up with same list structure 10 times.
"Fundamental change" is that the list has to be copied before appending it.
Here is a bit more "pythonic" way of achieving the same result with li... |
Pass variable to subprocess call in python | 4,795,190 | 11 | 2011-01-25T15:18:35Z | 4,795,226 | 17 | 2011-01-25T15:21:20Z | [
"python",
"subprocess"
] | I am trying to pass my variables from raw\_input to my subprocess command. I am new to python. Any help would he appreciated.
```
#!/usr/bin/python
import subprocess
print "\nWhat user name"
username = str(raw_input('username: '))
print "\nWhat is the user id"
userid = int(raw_input('Enter user id: '))
print "\nWhat... | Try separating the values with commas:
```
subprocess.call(['useradd', '-m', '-g', _primarygroup, '-G', _secondarygroup, '-u', _userid, _username])
```
See <http://docs.python.org/library/subprocess.html#subprocess.call> - It takes an array where the first argument is the program and all other arguments are passed as... |
An elegant and fast way to consecutively iterate over two or more containers in Python? | 4,795,772 | 8 | 2011-01-25T16:03:14Z | 4,795,833 | 8 | 2011-01-25T16:08:27Z | [
"python",
"iterator"
] | I have three collection.deques and what I need to do is to iterate over each of them and perform the same action:
```
for obj in deque1:
some_action(obj)
for obj in deque2:
some_action(obj)
for obj in deque3:
some_action(obj)
```
I'm looking for some function XXX which would ideally allow me to ... | The answer is in [itertools](http://docs.python.org/library/itertools.html)
> itertools.chain(\*iterables)
>
> ```
> Make an iterator that returns elements from the first iterable until
> ```
>
> it is exhausted, then proceeds to the
> next iterable, until all of the
> iterables are exhausted. Used for
> treating cons... |
An elegant and fast way to consecutively iterate over two or more containers in Python? | 4,795,772 | 8 | 2011-01-25T16:03:14Z | 4,795,845 | 11 | 2011-01-25T16:08:59Z | [
"python",
"iterator"
] | I have three collection.deques and what I need to do is to iterate over each of them and perform the same action:
```
for obj in deque1:
some_action(obj)
for obj in deque2:
some_action(obj)
for obj in deque3:
some_action(obj)
```
I'm looking for some function XXX which would ideally allow me to ... | Depending on what order you want to process the items:
```
import itertools
for items in itertools.izip(deque1, deque2, deque3):
for item in items:
some_action(item)
for item in itertools.chain(deque1, deque2, deque3):
some_action(item)
```
I'd recommend doing this to avoid hard-coding the actual de... |
Read file from line 2 or skip header row | 4,796,764 | 105 | 2011-01-25T17:25:08Z | 4,796,785 | 176 | 2011-01-25T17:26:45Z | [
"python",
"file-io"
] | How can I skip the header row and start reading a file from line2? | ```
with open(fname) as f:
next(f)
for line in f:
#do something
``` |
Read file from line 2 or skip header row | 4,796,764 | 105 | 2011-01-25T17:25:08Z | 4,796,812 | 39 | 2011-01-25T17:29:40Z | [
"python",
"file-io"
] | How can I skip the header row and start reading a file from line2? | ```
f = open(fname,'r')
lines = f.readlines()[1:]
f.close()
``` |
Read file from line 2 or skip header row | 4,796,764 | 105 | 2011-01-25T17:25:08Z | 28,916,979 | 12 | 2015-03-07T16:18:03Z | [
"python",
"file-io"
] | How can I skip the header row and start reading a file from line2? | If you want the first line and then you want to perform some operation on file this code will helpful.
```
with open(filename , 'r') as f:
first_line = f.readline()
for line in f:
# Perform some operations
``` |
GAE: How to get the blob-image height | 4,796,793 | 6 | 2011-01-25T17:27:42Z | 4,798,806 | 13 | 2011-01-25T21:05:37Z | [
"python",
"google-app-engine",
"blob",
"python-imaging-library"
] | Given is the follwing model on GAE:
```
avatar = db.BlobProperty()
```
By calling the image instance properties height or width ([see documentation](http://code.google.com/appengine/docs/python/images/imageclass.html#Image_height)) with:
```
height = profile.avatar.height
```
the following error is thrown:
> Attri... | If the image is stored in a BlobProperty, then the data is stored in the datastore, and if `profile` is your entity, then the height can be accessed as:
```
from google.appengine.api import images
height = images.Image(image_data=profile.avatar).height
```
If the image is in the blobstore, (blobstore.BlobReferencePro... |
Does pip handle extras_requires from setuptools/distribute based sources? | 4,796,936 | 16 | 2011-01-25T17:41:04Z | 4,806,441 | 8 | 2011-01-26T15:38:05Z | [
"python",
"setuptools",
"pip",
"distribute"
] | I have package "A" with a setup.py and an [extras\_requires](https://pythonhosted.org/setuptools/setuptools.html#declaring-extras-optional-features-with-their-own-dependencies) line like:
```
extras_require = {
'ssh': ['paramiko'],
},
```
And a package "B" that depends on util:
```
install_requires = ['A[ssh]']... | This is suppported since pip 1.1, which was released in February 2012 (one year after this question was asked). |
Does pip handle extras_requires from setuptools/distribute based sources? | 4,796,936 | 16 | 2011-01-25T17:41:04Z | 18,879,288 | 16 | 2013-09-18T18:07:34Z | [
"python",
"setuptools",
"pip",
"distribute"
] | I have package "A" with a setup.py and an [extras\_requires](https://pythonhosted.org/setuptools/setuptools.html#declaring-extras-optional-features-with-their-own-dependencies) line like:
```
extras_require = {
'ssh': ['paramiko'],
},
```
And a package "B" that depends on util:
```
install_requires = ['A[ssh]']... | We use `setup.py` and `pip` to manage development dependencies for our packages, though you need a newer version of `pip` (we're using 1.4.1 currently).
```
#!/usr/bin/env python
from setuptools import setup
from myproject import __version__
required = [
'gevent',
'flask',
...
]
extras = {
'develop'... |
ListProperty vs StringListProperty on Google App Engine | 4,797,433 | 3 | 2011-01-25T18:32:05Z | 4,798,122 | 10 | 2011-01-25T19:49:11Z | [
"python",
"google-app-engine",
"list",
"bigtable",
"datastore"
] | I want to store lists of integers (user ids), should I make them strings and use a StringListProperty, or just use a ListProperty, I'm wondering what is more optimized, the specific StringListProperty of the heterogeneous ListProperty (when used with only Integers).
I will need to add users to the list until it reache... | StringListProperty is just a very thin wrapper around ListProperty. there's no meaningful difference other than element type.
from [the code itself](http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/ext/db/__init__.py#3066):
```
class StringListProperty(ListProperty):
def __init__... |
how to group objects in reportlab, so that they stay together across new pages | 4,797,536 | 8 | 2011-01-25T18:45:26Z | 4,880,116 | 7 | 2011-02-02T21:35:02Z | [
"python",
"reportlab"
] | I'm generating some pdf files using reportlab. I have a certain section that is repeated. It contains of a header and a table:
```
Story.append(Paragraph(header_string, styleH))
Story.append(table)
```
How can I group the paragraph with the table (in latex I would put them into the same enviro... | You can try to put them together in a `KeepTogether` flowable, like so:
```
Story.append(KeepTogether([Paragraph(header_string, styleH), table])
```
However be aware that, last I checked, the implementation was not perfect and would still split up items too frequently. I know it does a good job of keeping a single fl... |
Executing a Django Shell Command from the Command Line | 4,797,671 | 11 | 2011-01-25T18:59:51Z | 18,067,339 | 21 | 2013-08-05T20:41:33Z | [
"python",
"django",
"django-shell"
] | I would like to execute a command via Django's manage.py shell function solely from the command line
e.g.
```
manage.py shell -c "from myapp import models; print models.MyModel.some_calculation()"
```
the came way you might use the -c option with the normal Python interpreter
e.g.
```
python -c "print 'hello world... | Pipe it ;)
```
echo "print 'hello world'" | python manage.py shell
``` |
Webpy: how to set http status code to 300 | 4,797,704 | 14 | 2011-01-25T19:03:17Z | 4,798,493 | 18 | 2011-01-25T20:31:54Z | [
"python",
"http-headers",
"http-status-codes",
"web.py"
] | Maybe it is a stupid question but I cannot figure out how to a http status code in webpy.
In the documentation I can see a list of types for the main status codes, but is there a generic function to set the status code?
I'm trying to implement an `unAPI` server and it's required to reply with a `300 Multiple Choices`... | The way web.py does this for 301 and other redirect types is by subclassing `web.HTTPError` (which in turn sets `web.ctx.status`). For example:
```
class MultipleChoices(web.HTTPError):
def __init__(self, choices):
status = '300 Multiple Choices'
headers = {'Content-Type': 'text/html'}
data... |
What could cause a python module to be imported twice? | 4,798,589 | 10 | 2011-01-25T20:42:11Z | 4,798,648 | 19 | 2011-01-25T20:49:47Z | [
"python",
"module",
"import"
] | As far as I understand, a python module is never imported twice, i.e. the code in the module only gets executed the first time it is imported. Subsequent import statements just add the module to the scope of the import.
I have a module called "TiledConvC3D.py" that seems to be imported multiple times though. I use pdb... | A Python module can be imported twice if the module is found twice in the path. For example, say your project is laid out like so:
* src/
+ package1/
- spam.py
- eggs.py
Suppose your PYTHONPATH (sys.path) includes src and src/package1:
```
PYTHONPATH=/path/to/src:/path/to/src/package1
```
If that's the ca... |
Modular multiplicative inverse function in Python | 4,798,654 | 39 | 2011-01-25T20:50:20Z | 4,798,776 | 26 | 2011-01-25T21:02:35Z | [
"python",
"algorithm"
] | Does some standard Python module contain a function to compute [modular multiplicative inverse](http://en.wikipedia.org/wiki/Modular_multiplicative_inverse) of a number, i.e. a number `y = invmod(x, p)` such that `x*y == 1 (mod p)`? Google doesn't seem to give any good hints on this.
Of course, one can come up with ho... | If your modulus is prime (you call it `p`) then you may simply compute:
```
y = x**(p-2) mod p # Pseudocode
```
Or in Python proper:
```
y = pow(x, p-2, p)
```
Here is someone who has implemented some number theory capabilities in Python: <http://userpages.umbc.edu/~rcampbel/Computers/Python/numbthy.html>
Here is... |
Modular multiplicative inverse function in Python | 4,798,654 | 39 | 2011-01-25T20:50:20Z | 4,801,358 | 13 | 2011-01-26T04:13:14Z | [
"python",
"algorithm"
] | Does some standard Python module contain a function to compute [modular multiplicative inverse](http://en.wikipedia.org/wiki/Modular_multiplicative_inverse) of a number, i.e. a number `y = invmod(x, p)` such that `x*y == 1 (mod p)`? Google doesn't seem to give any good hints on this.
Of course, one can come up with ho... | You might also want to look at the [gmpy](http://code.google.com/p/gmpy/) module. It is an interface between Python and the GMP multiple-precision library. gmpy provides an invert function that does exactly what you need:
```
>>> import gmpy
>>> gmpy.invert(1234567, 1000000007)
mpz(989145189)
```
**Updated answer**
... |
Modular multiplicative inverse function in Python | 4,798,654 | 39 | 2011-01-25T20:50:20Z | 9,758,173 | 47 | 2012-03-18T12:08:49Z | [
"python",
"algorithm"
] | Does some standard Python module contain a function to compute [modular multiplicative inverse](http://en.wikipedia.org/wiki/Modular_multiplicative_inverse) of a number, i.e. a number `y = invmod(x, p)` such that `x*y == 1 (mod p)`? Google doesn't seem to give any good hints on this.
Of course, one can come up with ho... | Maybe someone will find this useful (from [wikibooks](https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm)):
```
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
... |
Python's super(), abstract base classes, and NotImplementedError | 4,799,401 | 5 | 2011-01-25T22:06:36Z | 4,799,447 | 7 | 2011-01-25T22:12:48Z | [
"python",
"abstract-class",
"super"
] | [Abstract base classes can still be handy in Python.](http://stackoverflow.com/questions/3570796/why-use-abstract-base-classes-in-python) In writing an abstract base class where I want every subclass to have, say, a `spam()` method, I want to write something like this:
```
class Abstract(object):
def spam(self):
... | You can do this cleanly in python 2.6+ with the [abc module](http://docs.python.org/library/abc.html):
```
>>> import abc
>>> class B(object):
... __metaclass__ = abc.ABCMeta
... @abc.abstractmethod
... def foo(self):
... print 'In B'
...
>>> class C(B):
... def foo(self):
... ... |
changing from tuple to list and vice versa | 4,799,785 | 2 | 2011-01-25T22:54:51Z | 4,799,830 | 10 | 2011-01-25T23:01:08Z | [
"python",
"list"
] | how could i change `[('a', 1), ('c', 3), ('b', 2)]` to `['a',1,'c',3,'b',2]` and vice versa?
Thanks | Going in the first direction from `[('a', 1), ('c', 3), ('b', 2)]` to `['a',1,'c',3,'b',2]` is [flattening a list](http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python). Taking the accepted answer from there and modifying for this example:
```
>>> L = [('a', 1), ('c', 3), ('b', 2)]
>>> list(it... |
Decode function tries to encode Python | 4,799,917 | 7 | 2011-01-25T23:14:44Z | 4,799,931 | 8 | 2011-01-25T23:17:32Z | [
"python",
"unicode",
"unicode-escapes"
] | I am trying to print a unicode string without the specific encoding hex in it. I'm grabbing this data from facebook which has an encoding type in the html headers of UTF-8. When I print the type - it says its unicode, but then when I try to decode it with unicode-escape says there is an encoding error. Why is it trying... | It's not the decode that's failing. It's because you are trying to display the result to the console. When you use print it encodes the string using the default encoding which is ASCII. Don't use print and it should work.
```
>>> a=u'really long string containing \\u20ac and some other text'
>>> type(a)
<type 'unicode... |
Continue on Except of a Try block in Python | 4,799,974 | 26 | 2011-01-25T23:23:20Z | 4,799,981 | 32 | 2011-01-25T23:24:43Z | [
"python",
"exception",
"continue"
] | I'd expect this to be a duplicate, but I couldn't find it.
Here's Python code, expected outcome of which should be obvious:
```
x = {1: False, 2: True} # no 3
for v in [1,2,3]:
try:
print x[v]
except Exception, e:
print e
continue
```
I get the following exception: `SyntaxError: 'continue' not... | Your code works for me. I suspect you have some problem with indentation. Check that you are only using spaces, and don't have any tabs in your file.
However in that specific example there's actually no need to write continue because you're already at the end of the block. Just omit it. If on the other hand you have o... |
Continue on Except of a Try block in Python | 4,799,974 | 26 | 2011-01-25T23:23:20Z | 4,799,992 | 8 | 2011-01-25T23:25:53Z | [
"python",
"exception",
"continue"
] | I'd expect this to be a duplicate, but I couldn't find it.
Here's Python code, expected outcome of which should be obvious:
```
x = {1: False, 2: True} # no 3
for v in [1,2,3]:
try:
print x[v]
except Exception, e:
print e
continue
```
I get the following exception: `SyntaxError: 'continue' not... | Since you've handled the exception, just exit the exception handler; the code after the try block will resume, which in this case means that it will go back tot he top of the loop with the next element, if there is one. |
Sorting or Finding Max Value by the second element in a nested list. Python | 4,800,419 | 12 | 2011-01-26T00:37:22Z | 4,800,441 | 32 | 2011-01-26T00:41:48Z | [
"python",
"list",
"nested",
"element",
"max"
] | So I have a list like this
```
alkaline_earth_values = [['beryllium', 4],['magnesium', 12],['calcium', 20],['strontium', 38],['barium', 56], ['radium', 88]]
```
If I simply use the `max(list)` method, it will return the answer strontium, which would be correct if I was trying to find the max name, however I'm trying ... | ```
max(alkaline_earth_values, key=lambda x: x[1])
```
The reason this works is because the *key* argument of the *max* function specifies a function that is called when *max* wants to know the value by which the maximum element will be searched. *max* will call that function for each element in the sequence. And "lam... |
Accessing a value in a tuple that is in a list | 4,800,811 | 40 | 2011-01-26T02:03:57Z | 4,800,816 | 42 | 2011-01-26T02:05:07Z | [
"python",
"list",
"tuples"
] | ```
[(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
```
How do I return the 2nd value from each tuple inside this list? | With a list comprehension.
```
[x[1] for x in L]
``` |
Accessing a value in a tuple that is in a list | 4,800,811 | 40 | 2011-01-26T02:03:57Z | 4,801,357 | 33 | 2011-01-26T04:13:10Z | [
"python",
"list",
"tuples"
] | ```
[(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
```
How do I return the 2nd value from each tuple inside this list? | Ignacio's answer is what you want. However, as someone also learning Python, let me try to dissect it for you... As mentioned, it is a list comprehension (covered in [DiveIntoPython3](http://diveintopython3.org/comprehensions.html#listcomprehension), for example). Here are a few points:
`[x[1] for x in L]`
* Notice t... |
What's wrong with my PCA? | 4,801,259 | 9 | 2011-01-26T03:50:01Z | 4,803,141 | 10 | 2011-01-26T09:48:21Z | [
"python",
"numpy",
"machine-learning",
"linear-algebra",
"pca"
] | My code:
```
from numpy import *
def pca(orig_data):
data = array(orig_data)
data = (data - data.mean(axis=0)) / data.std(axis=0)
u, s, v = linalg.svd(data)
print s #should be s**2 instead!
print v
def load_iris(path):
lines = []
with open(path) as input_file:
lines = input_file.r... | You decomposed the wrong matrix.
Principal Component Analysis requires manipulating the eigenvectors/eigenvalues
of the ***covariance matrix***, not the data itself. The covariance matrix, created from an m x n data matrix, will be an m x m matrix with ones along the main diagonal.
You can indeed use the *cov* functi... |
How can I use pyparsing to parse nested expressions that have mutiple opener/closer types? | 4,801,403 | 11 | 2011-01-26T04:26:24Z | 4,802,004 | 19 | 2011-01-26T06:50:33Z | [
"python",
"pyparsing"
] | I'd like to use pyparsing to parse an expression of the form: `expr = '(gimme [some {nested [lists]}])'`, and get back a python list of the form: `[[['gimme', ['some', ['nested', ['lists']]]]]]`. Right now my grammar looks like this:
nestedParens = nestedExpr('(', ')')
nestedBrackets = nestedExpr('[', ']')
neste... | Here's a pyparsing solution that uses a self-modifying grammar to dynamically match the correct closing brace character.
```
from pyparsing import *
data = '(gimme [some {nested, nested [lists]}])'
opening = oneOf("( { [")
nonBracePrintables = ''.join(c for c in printables if c not in '(){}[]')
closingFor = dict(zip... |
How to use SequenceMatcher to find similarity between two strings? | 4,802,137 | 10 | 2011-01-26T07:10:28Z | 4,802,214 | 20 | 2011-01-26T07:26:43Z | [
"python",
"difflib"
] | ```
import difflib
a='abcd'
b='ab123'
seq=difflib.SequenceMatcher(a=a.lower(),b=b.lower())
seq=difflib.SequenceMatcher(a,b)
d=seq.ratio()*100
print d
```
I used the above code but obtained output is 0.0. How can I get a valid answer? | You forgot the first parameter to SequenceMatcher.
```
>>> import difflib
>>>
>>> a='abcd'
>>> b='ab123'
>>> seq=difflib.SequenceMatcher(None, a,b)
>>> d=seq.ratio()*100
>>> print d
44.4444444444
```
<http://docs.python.org/library/difflib.html> |
How to use SequenceMatcher to find similarity between two strings? | 4,802,137 | 10 | 2011-01-26T07:10:28Z | 24,063,352 | 8 | 2014-06-05T14:48:29Z | [
"python",
"difflib"
] | ```
import difflib
a='abcd'
b='ab123'
seq=difflib.SequenceMatcher(a=a.lower(),b=b.lower())
seq=difflib.SequenceMatcher(a,b)
d=seq.ratio()*100
print d
```
I used the above code but obtained output is 0.0. How can I get a valid answer? | This is from the python docs:
> The [SequenceMatcher](https://docs.python.org/2/library/difflib.html#sequencematcher-objects) class has this constructor:
>
> class difflib.**SequenceMatcher**(isjunk=None, a='', b='', autojunk=True)
The problem in your code is that by doing
```
seq=difflib.SequenceMatcher(a,b)
```
y... |
how to send success message if we use django generic views | 4,802,482 | 8 | 2011-01-26T08:19:19Z | 21,599,742 | 25 | 2014-02-06T10:10:35Z | [
"python",
"django",
"django-generic-views"
] | I am new to django (1.2.4). I have created some crud with generic views. But How can I show something like "The student was added successfully" when student is created using django's messaging framework? | As of **Django 1.6+**, using any [class-based generic views](https://docs.djangoproject.com/en/1.10/topics/class-based-views/), you can rely on the [successMessageMixin](https://docs.djangoproject.com/en/1.10/ref/contrib/messages/#django.contrib.messages.views.SuccessMessageMixin). It's as simple as adding the mixin to... |
How do I flush everything from Celery? | 4,802,807 | 2 | 2011-01-26T09:09:07Z | 4,803,074 | 7 | 2011-01-26T09:41:45Z | [
"python",
"django",
"celery"
] | I accidently added too many things to the queue, and now it froze.
Can't get it to do anything else. | Have you tried to restart the celery service with --discard parameter ? |
Python - file to dictionary? | 4,803,999 | 41 | 2011-01-26T11:24:22Z | 4,804,039 | 75 | 2011-01-26T11:28:47Z | [
"python",
"file",
"dictionary"
] | I have a file comprising two columns, i.e.,
```
1 a
2 b
3 c
```
I wish to read this file to a dictionary such that column 1 is the key and column 2 is the value, i.e.,
```
d = {1:'a', 2:'b', 3:'c'}
```
The file is small, so efficiency is not an issue.
Thanks,
S. | ```
d = {}
with open("file.txt") as f:
for line in f:
(key, val) = line.split()
d[int(key)] = val
``` |
Matplotlib figure facecolor (background color) | 4,804,005 | 38 | 2011-01-26T11:25:11Z | 4,805,178 | 50 | 2011-01-26T13:38:54Z | [
"python",
"matplotlib"
] | Can someone please explain why the code below does not work when setting the facecolor of the figure?
```
import matplotlib.pyplot as plt
# create figure instance
fig1 = plt.figure(1)
fig1.set_figheight(11)
fig1.set_figwidth(8.5)
rect = fig1.patch
rect.set_facecolor('red') # works with plt.show().
... | It's because `savefig` overrides the facecolor for the background of the figure.
(This is deliberate, actually... The assumption is that you'd probably want to control the background color of the saved figure with the `facecolor` kwarg to `savefig`. It's a confusing and inconsistent default, though!)
The easiest work... |
Matplotlib figure facecolor (background color) | 4,804,005 | 38 | 2011-01-26T11:25:11Z | 20,163,612 | 10 | 2013-11-23T14:37:00Z | [
"python",
"matplotlib"
] | Can someone please explain why the code below does not work when setting the facecolor of the figure?
```
import matplotlib.pyplot as plt
# create figure instance
fig1 = plt.figure(1)
fig1.set_figheight(11)
fig1.set_figwidth(8.5)
rect = fig1.patch
rect.set_facecolor('red') # works with plt.show().
... | I had to use the transparent keyword to get the color I chose with my initial
```
fig=figure(facecolor='black')
```
like this:
```
savefig('figname.png', facecolor=fig.get_facecolor(), transparent=True)
``` |
Cassandra low perfomance? | 4,804,630 | 8 | 2011-01-26T12:36:25Z | 4,805,919 | 12 | 2011-01-26T14:51:30Z | [
"python",
"mongodb",
"nosql",
"cassandra"
] | I have to choose Cassandra or MongoDB(or another nosql database, I accept suggestions) for a project with a lot of inserts(1M/day).
So I create a small test to measure the write perfomance. Here's the code to insert in Cassandra:
```
import time
import os
import random
import string
import pycassa
def get_random_stri... | There is no equivalent to Mongo's unsafe mode in Cassandra. (We used to have one, but we took it out, because it's just a Bad Idea.)
The other main problem is that you're doing single-threaded inserts. Cassandra is designed for high concurrency; you need to use a multithreaded test. See the graph at the bottom of <htt... |
How to get different colored lines for different plots in a single figure? | 4,805,048 | 56 | 2011-01-26T13:25:10Z | 4,805,456 | 159 | 2011-01-26T14:11:28Z | [
"python",
"colors",
"matplotlib"
] | I am using matplotlib to create the plots. I have to identify each plot with a different colour which should be automatically generated by Python. Can you please give me a method to put different colors for different plots in the same figure? | Matplotlib does this by default.
E.g.:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)
plt.show()
```

And, as you may already know, you can... |
problem with unicode decoding | 4,805,267 | 4 | 2011-01-26T13:50:12Z | 4,805,308 | 8 | 2011-01-26T13:54:43Z | [
"python",
"encoding",
"utf-8",
"iso-8859-1",
"latin1"
] | This is funny.. I am trying to read geographic lookup data from openstreetmap. The code that performs the query looks like this
```
params = urllib.urlencode({'q': ",".join([e for e in full_address]), 'format': "json", "addressdetails" : "1"})
query = "http://nominatim.openstreetmap.org/search?%s" % params
print query... | > When I go and print the response, the
> u with umlaut is encoded latin1 (0xFC)
You are just misinterpreting the output. It's a unicode string (you can tell by the u in prefix), there's no encoding "attached" - the \xFC means there it's the codepoint with number 0xFC, which happens to be the U-Umlaut (see <http://www... |
Programmatically generate thumbnail CAP for small video | 4,805,563 | 7 | 2011-01-26T14:21:10Z | 4,806,273 | 7 | 2011-01-26T15:23:42Z | [
"python",
"video",
"thumbnails",
"python-imaging-library"
] | How can python make a simple cap for a video.
Ideia: take 9 snapshots for 9 even placed (on the timeline) times, and displace then in a JGP
How should I do this?
Is PIL the only way? (it's not going to be easy to do what I want, right?)
Aren't there any module (python seens to have GREAT modeles for almoust anythin... | This is a quick change to something I've done some time ago, using ffmpeg for frame extraction and PIL to create the full thumbs image.
```
import os, sys
from PIL import Image
# Use "ffmpeg -i <videofile>" to get total length by parsing the error message
chout, chin, cherr = os.popen3("ffmpeg -i %s" % sys.argv[1])
o... |
Disable Django Debugging for Celery | 4,806,314 | 11 | 2011-01-26T15:26:13Z | 4,806,384 | 26 | 2011-01-26T15:32:42Z | [
"python",
"django",
"celery"
] | Is it possible to set DEBUG=False for only a specific app in Django? Celery has a [known memory leak](http://groups.google.com/group/celery-users/browse_thread/thread/b26579b70e7d21ae) when debugging is enabled. I have a development server where I want Celery to run as a service, without debugging so it doesn't leak me... | Celery doesn't have a memory leak, it's how Django works:
When DEBUG is enabled Django appends every executed SQL statement to `django.db.connection.queries`, this will grow unbounded in a long running process environment.
I guess you could use a hack like:
```
if "celeryd" in sys.argv:
DEBUG = False
``` |
String Comparison Technique Used by Python | 4,806,911 | 25 | 2011-01-26T16:17:41Z | 4,806,946 | 40 | 2011-01-26T16:19:58Z | [
"python",
"string",
"comparison"
] | I'm wondering how Python does string comparison, more specifically how it determines the outcome when a less than (<) or greater than (>) sign is used.
For instance if I put print('abc' < 'bac') I get true. I understand that it compares corresponding characters in the string, however its unclear as to why there is mor... | From the [docs](http://docs.python.org/tutorial/datastructures.html#comparing-sequences-and-other-types):
> The comparison uses lexicographical
> ordering: first the first two items
> are compared, and if they differ this
> determines the outcome of the
> comparison; if they are equal, the
> next two items are compare... |
Python: Best practice for dynamically constructing regex | 4,807,141 | 5 | 2011-01-26T16:35:33Z | 4,807,230 | 19 | 2011-01-26T16:43:19Z | [
"python",
"regex"
] | I have a simple function to remove a "word" from some text:
```
def remove_word_from(word, text):
if not text or not word: return text
rec = re.compile(r'(^|\s)(' + word + ')($|\s)', re.IGNORECASE)
return rec.sub(r'\1\3', text, 1)
```
The problem, of course, is that if word contains characters such as... | You can use `re.escape(word)` to escape the word. |
Apache mod_wsgi error: Forbidden You don't have permission to access / on this server | 4,807,176 | 9 | 2011-01-26T16:39:18Z | 4,809,427 | 12 | 2011-01-26T20:04:56Z | [
"python",
"django",
"apache",
"mod-wsgi",
"wsgi"
] | I'm using Ubuntu 10.04.
I create a django project under `/home/wong2/Code/python/django2/` named `atest`
and create a wsgi file `setting.wsgi` in the same directory
Here is the content of `setting.wsgi` :
```
import os
import sys
path = '/home/wong2/Code/python/django2'
if path not in sys.path:
sys.path.a... | The second directory block doesn't match where you have your WSGI script file installed. It is very bad practice though to stick the WSGI script file in a location where source code or other sensitive files exist, ie., same directory or sub directory. Instead you should stick it in a sub directory of its own. Thus:
``... |
Apache mod_wsgi error: Forbidden You don't have permission to access / on this server | 4,807,176 | 9 | 2011-01-26T16:39:18Z | 25,893,961 | 7 | 2014-09-17T14:56:46Z | [
"python",
"django",
"apache",
"mod-wsgi",
"wsgi"
] | I'm using Ubuntu 10.04.
I create a django project under `/home/wong2/Code/python/django2/` named `atest`
and create a wsgi file `setting.wsgi` in the same directory
Here is the content of `setting.wsgi` :
```
import os
import sys
path = '/home/wong2/Code/python/django2'
if path not in sys.path:
sys.path.a... | With Django 1.5+ you should use the suggested way described in the documentation:
```
WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py
WSGIPythonPath /path/to/mysite.com
<Directory /path/to/mysite.com/mysite>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
```
<https://docs.djangoproject.com/en/1.7/how... |
How to set other Inline title in Django Admin? | 4,807,479 | 11 | 2011-01-26T17:03:32Z | 4,807,567 | 9 | 2011-01-26T17:10:47Z | [
"python",
"django",
"django-models",
"django-admin"
] | I need to change the `inline title` (name) to something other than the verbose\_name of the class Meta in the Model. Is there a variable to do this?? | If you mean in the admin section for django, then it's well documented in the source.
You can find your answer at the following url:
<http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin.verbose_name> |
How to set other Inline title in Django Admin? | 4,807,479 | 11 | 2011-01-26T17:03:32Z | 15,361,245 | 18 | 2013-03-12T12:29:49Z | [
"python",
"django",
"django-models",
"django-admin"
] | I need to change the `inline title` (name) to something other than the verbose\_name of the class Meta in the Model. Is there a variable to do this?? | As documented, you need to set the values of your InlineModelAdmin subclass:
InlineModelAdmin.verbose\_name -
An override to the verbose\_name found in the modelâs inner Meta class.
InlineModelAdmin.verbose\_name\_plural -
An override to the verbose\_name\_plural found in the modelâs inner Meta class.
In this ex... |
Python list initialization in for loop | 4,807,864 | 2 | 2011-01-26T17:37:50Z | 4,807,915 | 8 | 2011-01-26T17:41:44Z | [
"python",
"list",
"list-comprehension"
] | How do initialize a list in a for loop:
```
for x, y in zip(list_x, list_y):
x = f(x, y)
```
unfortunately, this loop does not alter list\_x even though I want it to.
Is there a way to have references to the elements of list\_x in the loop?
I realize I could use a list comprehension, but that's hard to read wh... | why would list-comprehension be complicated?
```
list_x[:] = [f(tup) for tup in zip(list_x, list_y)]
```
Instead of having 20-line for loop, you could use a set of generator expressions or abstract a subset of code into an `f` function.
It's really is pointless to talk about what *could* be done w/o seeing the code. |
Is there a "bounding box" function (slice with non-zero values) for a ndarray in NumPy? | 4,808,221 | 12 | 2011-01-26T18:14:06Z | 4,809,040 | 15 | 2011-01-26T19:29:00Z | [
"python",
"arrays",
"numpy",
"trim",
"bounding"
] | I am dealing with arrays created via numpy.array(), and I need to draw points on a canvas simulating an image. Since there is a lot of zero values around the central part of the array which contains the meaningful data, I would like to "trim" the array, erasing columns that only contain zeros and rows that only contain... | This should do it:
```
from numpy import array, argwhere
A = array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])
B = argwhere(A)
(ysta... |
Find occurrence using multiple attributes in ElementTree/Python | 4,808,753 | 8 | 2011-01-26T19:02:58Z | 4,809,350 | 15 | 2011-01-26T19:57:15Z | [
"python",
"xml",
"elementtree"
] | I have the following XML.
```
<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="10" failures="0" disabled="0" errors="0" time="0.001" name="AllTests">
<testsuite name="TestOne" tests="5" failures="0" disabled="0" errors="0" time="0.001">
<testcase name="DefaultConstructor" status="run" time="0" classname... | This depends on what version you're using. If you have ElementTree 1.3+ (including in Python 2.7 standard library) you can use a basic xpath expression, as [described in the docs](http://effbot.org/zone/element-xpath.htm), like `[@attrib=âvalueâ]`:
```
x = ElmentTree(file='testdata.xml')
cases = x.findall(".//test... |
Removing items randomly from a dictionary | 4,809,044 | 3 | 2011-01-26T19:29:33Z | 4,809,123 | 7 | 2011-01-26T19:36:36Z | [
"python",
"random",
"dictionary"
] | How do I remove random items from a dictionary in Python?
I have to remove a specified number of items from a dictionary and so I tried to use `dict.popitem` which I thought was random, but it is seems it is not.
As the [docs](http://docs.python.org/library/stdtypes.html#dict.popitem) say:
> Remove and return an arb... | `popitem()` is arbitrary but not random. If you want to access a random element
```
import random
key = random.choice(d.keys())
val = d[key]
del d[key]
``` |
Removing items randomly from a dictionary | 4,809,044 | 3 | 2011-01-26T19:29:33Z | 4,809,138 | 14 | 2011-01-26T19:37:42Z | [
"python",
"random",
"dictionary"
] | How do I remove random items from a dictionary in Python?
I have to remove a specified number of items from a dictionary and so I tried to use `dict.popitem` which I thought was random, but it is seems it is not.
As the [docs](http://docs.python.org/library/stdtypes.html#dict.popitem) say:
> Remove and return an arb... | Is this what you're talking about?
```
import random
for i in range(4):
some_dict.pop( random.choice(some_dict.keys()) )
``` |
Removing items randomly from a dictionary | 4,809,044 | 3 | 2011-01-26T19:29:33Z | 4,809,154 | 8 | 2011-01-26T19:39:18Z | [
"python",
"random",
"dictionary"
] | How do I remove random items from a dictionary in Python?
I have to remove a specified number of items from a dictionary and so I tried to use `dict.popitem` which I thought was random, but it is seems it is not.
As the [docs](http://docs.python.org/library/stdtypes.html#dict.popitem) say:
> Remove and return an arb... | Removing an "arbitrary" element means that the function can remove whatever item it likes. That doesn't mean that it has to be especially random about it.
For real randomness you should use the [`random`](http://docs.python.org/library/random.html) module. For example:
```
import random
for key in random.sample(d.key... |
Does anyone know a regular expression to validate MSISDN-format mobile numbers? | 4,809,186 | 3 | 2011-01-26T19:41:37Z | 4,809,239 | 8 | 2011-01-26T19:46:58Z | [
"python",
"regex",
"mobile",
"phone-number"
] | Does anyone know a regular expression to validate MSISDN-format mobile numbers?
I looked into a solution posted at <http://charlvn.blogspot.com/2010/06/msisdn-regular-expressions.html> but I think that's not a generic solution.
I'm looking for a validation regex that could validate any MSISDN-standard mobile number.
... | This should do -- I'm not sure how much more generic you can get:
```
/^[1-9][0-9]{10,14}$/
```
To check a number to belong to a particular country, modify the pattern to preface the country code, and then adjust the remaining digits to match:
```
/^(873[1-9][0-9]{7,11}|91[1-9][0-9]{8,12})$/ # India
/^46[1-9][0-... |
Correlation of Two Variables in a Time Series in Python? | 4,809,577 | 8 | 2011-01-26T20:18:38Z | 6,181,132 | 16 | 2011-05-30T22:08:16Z | [
"python",
"statistics"
] | If I have two different data sets that are in a time series, is there a simple way to find the correlation between the two sets in python?
For example with:
```
# [ (dateTimeObject, y, z) ... ]
x = [ (8:00am, 12, 8), (8:10am, 15, 10) .... ]
```
How might I get the correlation of y and z in Python? | Little slow on the uptake here. pandas (http://github.com/wesm/pandas and pandas.sourceforge.net) is probably your best bet. I'm biased because I wrote it but:
```
In [7]: ts1
Out[7]:
2000-01-03 00:00:00 -0.945653010936
2000-01-04 00:00:00 0.759529904445
2000-01-05 00:00:00 0.177646448683
2000-01-06 00:00:00... |
Tab key not indenting in Python | 4,809,820 | 3 | 2011-01-26T20:44:29Z | 4,809,894 | 9 | 2011-01-26T20:52:48Z | [
"python",
"shell",
"python-2.7"
] | I recently upgraded to python2.7 and noticed that the tab key does not function appropriately in the shell. Instead, it appears to search through the underlying directory (the standard unix behavior).
If I change back over to python2.6, it works appropriately. Is there a way to add this functionality back to 2.7?
For... | This is a known bug with python 2.7 on Mac OSX. More details (including a fix) can be found in [the bug report](http://bugs.python.org/issue10472). |
Django objects.filter() values_list() vs python list comprehension for __in query | 4,812,035 | 22 | 2011-01-27T01:10:41Z | 4,812,361 | 44 | 2011-01-27T03:10:18Z | [
"python",
"django",
"django-models",
"django-queryset"
] | I have a quirk(?) with Django queryset filtering:
```
ipdb> MagazineIssue.objects.filter(id__in=l_magazines.values_list('id'))
Out[0]: []
```
or
```
ipdb> MagazineIssue.objects.filter(id__in=[l_magazine.id for l_magazine in l_magazines])
Out[0]: [<MagazineIssue: Architecture Australia, Jan 1995 (#1)>]
```
and
```
... | Try `l_magazines.values_list('id', flat=True)`. That returns a list of ids instead of a list of single id tuples. |
Writing utf-8 string inside my python files | 4,812,186 | 8 | 2011-01-27T02:43:27Z | 4,815,930 | 11 | 2011-01-27T11:48:48Z | [
"python",
"unicode",
"utf-8"
] | This line in my .py file is giving me a: "UnicodeDecodeError: 'utf8' codec can't decode bytes in position 8-13: unsupported Unicode code range"
```
if line.startswith(u"FuÃnote"):
```
The file is saved in utf-8 and has the encoding at the top:
# -*- coding: utf-8 -*-
I've got a lot of other py files with utf-8 enco... | Let's examine that error message very closely:
"UnicodeDecodeError: 'utf8' codec can't decode bytes in position 8-13: unsupported Unicode code range"
Note carefully that it says "bytes in position 8-13" -- that's a **6-byte UTF-8 sequence**. That might have been valid in the dark ages, but *since Unicode was frozen a... |
Nonalphanumeric list order from os.listdir() in Python | 4,813,061 | 19 | 2011-01-27T05:30:29Z | 4,813,116 | 19 | 2011-01-27T05:41:17Z | [
"python",
"list",
"directory-listing",
"listdir"
] | I often use python to process directories of data. Recently, I have noticed that the default order of the lists has changed to something almost nonsensical. For example, if I am in a current directory containing the following subdirectories: run01, run02, ... run19, run20, and then I generate a list from the following ... | I think the order has to do with the way the files are indexed on your FileSystem.
If you really want to make it adhere to some order you can always sort the list after getting the files. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.