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 |
|---|---|---|---|---|---|---|---|---|---|
How to add a Delete button to django.forms generated form? | 5,160,306 | 4 | 2011-03-01T21:02:44Z | 5,160,445 | 10 | 2011-03-01T21:15:48Z | [
"python",
"django"
] | How to add a Delete button to [django.forms](http://docs.djangoproject.com/en/dev/topics/forms/) generated edit form (note, NOT admin)?
Its very easy to add a delete view on (`/app/model/<id>/delete/` etc) but how to add a "Delete" button alongside the generated form?
I've got to be missing something easy? | Add a submit button to the template, set the name as 'delete', check in your view if it was clicked:
```
if request.POST.get('delete'):
obj.delete()
``` |
Python: in-memory object database which supports indexing? | 5,161,164 | 20 | 2011-03-01T22:25:11Z | 5,161,225 | 9 | 2011-03-01T22:31:50Z | [
"python",
"database",
"data-munging"
] | I'm doing some data munging which would be quite a bit simpler if I could stick a bunch of dictionaries in an in-memory database, then run simply queries against it.
For example, something like:
```
people = db([
{"name": "Joe", "age": 16},
{"name": "Jane", "favourite_color": "red"},
])
over_16 = db.filter(ag... | What about using an in-memory SQLite database via the [sqlite3 standard library module](http://docs.python.org/library/sqlite3.html), using the special value `:memory:` for the connection? If you don't want to write your on SQL statements, you can always use an ORM, like [SQLAlchemy](http://www.sqlalchemy.org/docs/dial... |
Python handling specific error codes? | 5,161,167 | 17 | 2011-03-01T22:25:39Z | 5,161,286 | 22 | 2011-03-01T22:40:16Z | [
"python",
"sockets",
"exception",
"exception-handling"
] | Hey I'm wondering how to handle specific error codes. For example, `[Errno 111] Connection refused`
I want to catch this specific error in the socket module and print something. | If you want to get the error code, this seems to do the trick;
```
import errno
try:
socketConnection()
except socket.error, v:
errorcode=v[0]
if errorcode==errno.ECONNREFUSED:
print "Connection Refused"
```
You can look up [`errno` error codes](https://docs.python.org/2/library/errno.html). |
Python handling specific error codes? | 5,161,167 | 17 | 2011-03-01T22:25:39Z | 5,161,289 | 23 | 2011-03-01T22:40:31Z | [
"python",
"sockets",
"exception",
"exception-handling"
] | Hey I'm wondering how to handle specific error codes. For example, `[Errno 111] Connection refused`
I want to catch this specific error in the socket module and print something. | On Unix platforms, at least, you can do the following.
```
import socket, errno
try:
# Do something...
except socket.error as e:
if e.errno == errno.ECONNREFUSED:
# Handle the exception...
else:
raise
```
Before Python 2.6, use `e.args[ 0 ]` instead of `e.errno`. |
Reuse existing objects for immutable objects? | 5,161,424 | 9 | 2011-03-01T22:55:40Z | 5,166,373 | 9 | 2011-03-02T10:48:02Z | [
"python",
"immutability"
] | In Python, how is it possible to reuse existing equal immutable objects (like is done for `str`)? Can this be done just by defining a `__hash__` method, or does it require more complicated measures? | If you want to create via the class constructor and have it return a previously created object then you will need to provide a `__new__` method (because by the time you get to `__init__` the object has already been created).
Here is a simple example - if the value used to initialise has been seen before then a previou... |
Django admin application for master/detail page | 5,161,477 | 5 | 2011-03-01T23:02:33Z | 5,161,516 | 9 | 2011-03-01T23:06:38Z | [
"python",
"django",
"django-admin"
] | Consider this simplified model in Django:
```
class Item(models.Model):
title = models.CharField(max_length=200)
pub_date = models.DateTimeField()
class ItemDetail(models.Model):
item = models.ForeignKey(Item)
name = models.CharField(max_length=200)
value = models.CharField(max_length=200)
dis... | That's actually the only direction django is good at dealing with relationships for -- the other way around is harder (directly editing the related parent from the child).
To get the format you want, look into ModelAdmin inlines:
<http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.InlineMod... |
Python Curses Handling Window (Terminal) Resize | 5,161,552 | 6 | 2011-03-01T23:10:49Z | 5,192,143 | 7 | 2011-03-04T09:51:54Z | [
"python",
"resize",
"curses"
] | This is two questions really:
* how do I resize a curses window, and
* how do I deal with a terminal resize in curses?
Is it possible to know when a window has changed size?
I really can't find any good doc, not even covered on <http://docs.python.org/library/curses.html> | Terminal resize event will result in the `curses.KEY_RESIZE` key code. Therefore you can handle terminal resize as part of a standard main loop in a curses program, waiting for input with `getch`. |
Elegant way of reducing list by averaging? | 5,162,130 | 5 | 2011-03-02T00:34:07Z | 5,162,574 | 8 | 2011-03-02T01:49:49Z | [
"python",
"list"
] | Is there a more elegant way of writing this function?
```
def reduce(li):
result=[0 for i in xrange((len(li)/2)+(len(li)%2))]
for i,e in enumerate(li):
result[int(i/2)] += e
for i in range(len(result)):
result[i] /= 2
if (len(li)%2 == 1):
result[len(result)-1] *= 2
return re... | what you actually want to do is to apply a moving average of 2 samples trough your list, mathematically you convolve a window of [.5,.5], then take just the even samples. To avoid dividing by two the last element of odd arrays, you should duplicate it, this does not affect even arrays.
Using numpy it gets pretty elega... |
List Manipulation in Python with pop() | 5,162,991 | 11 | 2011-03-02T03:11:13Z | 5,163,010 | 15 | 2011-03-02T03:13:46Z | [
"python",
"list"
] | In short, I need to remove multiple items from a list according to their indexes. However, I can't use pop because it shifts the indexes (without some clumsy compensating system). Is there a way to remove multiple items simultaneously?
I have an algorithm that goes through a list, and if the conditions are right remov... | You want a list comprehension:
```
L = [c for c in L if c not in ['a', 'c']]
```
Or, if you really don't want to create a copy, go backwards:
```
for i in reversed(range(len(L))):
if L[i] in ['a', 'c']:
L.pop(i) # del L[i] is more efficient
```
Thanks to ncoghlan for `reversed()` & phooji for `del L[... |
List Manipulation in Python with pop() | 5,162,991 | 11 | 2011-03-02T03:11:13Z | 5,163,023 | 16 | 2011-03-02T03:15:12Z | [
"python",
"list"
] | In short, I need to remove multiple items from a list according to their indexes. However, I can't use pop because it shifts the indexes (without some clumsy compensating system). Is there a way to remove multiple items simultaneously?
I have an algorithm that goes through a list, and if the conditions are right remov... | Are your lists large? If so, use `ifilter` from [`itertools`](http://docs.python.org/library/itertools.html) to filter out elements that you don't want lazily (with no up front cost).
Lists not so large? Just use a list comprehension:
```
newlist = [x for x in oldlist if x not in ['a', 'c'] ]
```
This will create a... |
List Manipulation in Python with pop() | 5,162,991 | 11 | 2011-03-02T03:11:13Z | 5,172,425 | 7 | 2011-03-02T19:32:52Z | [
"python",
"list"
] | In short, I need to remove multiple items from a list according to their indexes. However, I can't use pop because it shifts the indexes (without some clumsy compensating system). Is there a way to remove multiple items simultaneously?
I have an algorithm that goes through a list, and if the conditions are right remov... | ### Summary
* use list comprehension (or genexpr) to remove multiple items from a list
* if your input is a large byte-string then use `str.translate()` to delete characters
* deleting one item at a time `del L[i]` is slow for large lists
---
If items are bytes as in your example you could use [`str.translate()`](ht... |
Python: print a generator expression? | 5,164,642 | 41 | 2011-03-02T07:34:17Z | 5,164,661 | 12 | 2011-03-02T07:37:11Z | [
"python"
] | In the Python shell, if I enter a list comprehension such as:
```
>>> [x for x in string.letters if x in [y for y in "BigMan on campus"]]
```
I get a nicely printed result:
```
['a', 'c', 'g', 'i', 'm', 'n', 'o', 'p', 's', 'u', 'B', 'M']
```
Same for a dictionary comprehension:
```
>>> {x:x*2 for x in range(1,10)}... | You can just wrap the expression in a call to `list`:
```
>>> list((x for x in string.letters if x in (y for y in "BigMan on campus")))
['a', 'c', 'g', 'i', 'm', 'n', 'o', 'p', 's', 'u', 'B', 'M']
``` |
Python: print a generator expression? | 5,164,642 | 41 | 2011-03-02T07:34:17Z | 5,165,222 | 69 | 2011-03-02T08:48:57Z | [
"python"
] | In the Python shell, if I enter a list comprehension such as:
```
>>> [x for x in string.letters if x in [y for y in "BigMan on campus"]]
```
I get a nicely printed result:
```
['a', 'c', 'g', 'i', 'm', 'n', 'o', 'p', 's', 'u', 'B', 'M']
```
Same for a dictionary comprehension:
```
>>> {x:x*2 for x in range(1,10)}... | **Quick answer:**
Doing `list()` around a generator expression is (almost) exactly equivalent to having `[]` brackets around it. So yeah, you can do
```
>>> list((x for x in string.letters if x in (y for y in "BigMan on campus")))
```
But you can just as well do
```
>>> [x for x in string.letters if x in (y for y i... |
How can I extend Image class? | 5,165,317 | 5 | 2011-03-02T09:00:46Z | 5,165,352 | 8 | 2011-03-02T09:05:44Z | [
"python",
"inheritance",
"python-imaging-library"
] | I want to extend "Image" class in PIL.
```
#module Image
def open(file): ...
class Image:
def method1:...
def method2:...
#module myOriginal
from Image import Image
class ExtendedImage(Image):
def method3:...
#module test
import myOriginal
im = myOriginal.open("picture.jpg")
```
RESULT: Error.myOriginal... | [According to Fredrik Lundh](http://mail.python.org/pipermail/image-sig/2006-March/003832.html), the author of PIL:
> the Image class isn't designed to be
> subclassed by application code. if
> you want custom behaviour, use a
> delegating wrapper.
**myOriginal.py**:
To delegate individual methods:
```
class Extend... |
How do I stream a file using werkzeug? | 5,166,129 | 6 | 2011-03-02T10:29:18Z | 5,166,423 | 15 | 2011-03-02T10:52:06Z | [
"python",
"werkzeug"
] | I want to stream a big file via [werkzeug](http://werkzeug.pocoo.org/).
Currently my wsgi application looks like this:
```
from werkzeug.wrappers import Request, Response
from werkzeug.wsgi import ClosingIterator, wrap_file
import os
class Streamer(object):
def __init__(self):
pass
def __call__(se... | Haven't tried myself but I think following will work.
```
g = file(path_to_bigfile) # or any generator
return Response(g, direct_passthrough=True)
``` |
Inheritance and init method in Python | 5,166,473 | 19 | 2011-03-02T10:56:47Z | 5,166,539 | 10 | 2011-03-02T11:02:29Z | [
"python",
"inheritance",
"init"
] | I'm begginer of python. I can't understand inheritance and **init**().
```
class Num:
def __init__(self,num):
self.n1 = num
class Num2(Num):
def show(self):
print self.n1
mynumber = Num2(8)
mynumber.show()
```
RESULT: 8
This is OK.But I replace Num2 with
```
class Num2(Num):
def __init... | When you override the init you have also to call the init of the parent class
```
super(Num2, self).__init__(num)
```
[Understanding Python super() and init methods](http://stackoverflow.com/questions/576169/understanding-python-super) |
Inheritance and init method in Python | 5,166,473 | 19 | 2011-03-02T10:56:47Z | 5,166,588 | 39 | 2011-03-02T11:06:07Z | [
"python",
"inheritance",
"init"
] | I'm begginer of python. I can't understand inheritance and **init**().
```
class Num:
def __init__(self,num):
self.n1 = num
class Num2(Num):
def show(self):
print self.n1
mynumber = Num2(8)
mynumber.show()
```
RESULT: 8
This is OK.But I replace Num2 with
```
class Num2(Num):
def __init... | In the first situation, `Num2` is extending the class `Num` and since you are not redefining the special method named `__init__()` in `Num2`, it gets inherited from `Num`.
> When a class defines an `__init__()`
> method, class instantiation
> automatically invokes `__init__()` for
> the newly-created class instance.
... |
Unique items in python list | 5,166,569 | 3 | 2011-03-02T11:04:31Z | 5,166,617 | 13 | 2011-03-02T11:08:35Z | [
"python"
] | I am trying to make a unique collection of dates in a Python list.
Only add a date to the collection if it not already present in the collection.
```
timestamps = []
timestamps = [
'2011-02-22', '2011-02-05', '2011-02-04', '2010-12-14', '2010-12-13',
'2010-12-12', '2010-12-11', '2010-12-07', '2010-12-02', '... | You can use sets for this.
```
date = "2010-11-22"
timestamps = set(['2011-02-22', '2011-02-05', '2011-02-04', '2010-12-14', '2010-12-13', '2010-12-12', '2010-12-11', '2010-12-07', '2010-12-02', '2010-11-30', '2010-11-26', '2010-11-23', '2010-11-22', '2010-11-16'])
#then you can just update it like so
timestamps.updat... |
sort dates in python array | 5,166,842 | 5 | 2011-03-02T11:29:41Z | 5,166,878 | 22 | 2011-03-02T11:33:22Z | [
"python"
] | How to sort the below array of dates on python 2.4
```
timestamps = ['2011-06-2', '2011-08-05', '2011-02-04', '2010-1-14', '2010-12-13', '2010-1-12', '2010-2-11', '2010-2-07', '2010-12-02', '2011-11-30', '2010-11-26', '2010-11-23', '2010-11-22', '2010-11-16']
``` | ```
>>> import datetime
>>> dates = [datetime.datetime.strptime(ts, "%Y-%m-%d") for ts in timestamps]
>>> dates.sort()
>>> sorted = [datetime.datetime.strftime(ts, "%Y-%m-%d") for ts in dates]
>>> sorted
['2010-01-12', '2010-01-14', '2010-02-07', '2010-02-11', '2010-11-16', '2010-11-
22', '2010-11-23', '2010-11-26', '2... |
sort dates in python array | 5,166,842 | 5 | 2011-03-02T11:29:41Z | 5,166,911 | 13 | 2011-03-02T11:36:57Z | [
"python"
] | How to sort the below array of dates on python 2.4
```
timestamps = ['2011-06-2', '2011-08-05', '2011-02-04', '2010-1-14', '2010-12-13', '2010-1-12', '2010-2-11', '2010-2-07', '2010-12-02', '2011-11-30', '2010-11-26', '2010-11-23', '2010-11-22', '2010-11-16']
``` | ```
sorted(timestamps, key=lambda d: map(int, d.split('-')))
``` |
Get around raising IndexError | 5,166,887 | 7 | 2011-03-02T11:34:30Z | 5,363,582 | 14 | 2011-03-19T17:23:47Z | [
"python",
"django",
"list",
"exception"
] | My code is as follows :
```
for p in qs:
set = None
try:
set = p.property.property_locations.all()
except IndexError:
pass
if set:
```
Problem is that when set is none it still throws IndexError from this part of django.db.models.query:
```
try:
qs = self._clone()
qs.query.se... | In any case, there are two mistakes in your code:
1. set is a builtin (as you can see from SO's syntax highlighting), so by giving your variable that name you're shadowing the builtin for no purpose, which is at least bad practice, and likely to cause issues later in the code.
2. The canonical way to check if set is n... |
Trouble with Tornado and JavaScript Libraries | 5,167,109 | 5 | 2011-03-02T11:55:53Z | 5,167,252 | 12 | 2011-03-02T12:11:07Z | [
"javascript",
"python",
"templates",
"tornado",
"protovis"
] | I'm trying to write a simple python web application using the Tornado web server and am having trouble using the JavaScript libraries I need. I wanted to use the Protovis JavaScript plotting library, so I added the following 'Hello World' code snippet to my template.html:
```
<script type="text/javascript" src="/proto... | You should read the documentation about [static files](http://www.tornadoweb.org/en/branch2.4/overview.html?highlight=static%20path#static-files-and-aggressive-file-caching).
In particular, the standard way is to:
* Create a 'static' directory in the root of your application
* Add the following to your application se... |
Why does os.path.getsize() return a negative number for a 10gb file? | 5,167,120 | 7 | 2011-03-02T11:57:02Z | 5,167,398 | 10 | 2011-03-02T12:22:33Z | [
"python",
"linux",
"file-io"
] | I am using the function `os.path.getsize()` which gives the size of the file in bytes.
As my one file size is 10gb it give me size in negative(bytes).
so can anyone give me any idea why this happen?
This is my code:
```
import os
ospathsize = os.path.getsize('/home/user/Desktop/test1.nrg')
print (ospathsize)
``` | Your Linux kernel obviously has large file support, since `ls -l` works correctly. Thus, it's your Python installation that is lacking the support. (Are you using your distribution's Python package? What distribution is it?)
The documentation on [POSIX large file support in Python](http://docs.python.org/library/posix... |
ValueError: invalid literal for int() with base 10: | 5,168,035 | 3 | 2011-03-02T13:20:42Z | 5,168,091 | 7 | 2011-03-02T13:27:30Z | [
"python",
"django",
"django-models",
"django-views"
] | i am getting this value error, when i try to insert some data to django model. My python script is :
```
from task.employeeDetails.models import EmployeeDetails
def dumpdata():
userName = "John"
designation = 'Software Engineer'
employeeID = 2312
contactNumber = 9495321257
project = 'AOL'
... | Don't use positional arguments, use keywords to specify which field is being populated with what data.
```
EmployeeDetails(userName=userName, designation=designation) #etc
```
Also, if you are going to call `save()` anyways, you can use `EmployeeDetails.objects.create(...)` |
Can Python be embedded in HTML like PHP and JSP? | 5,168,588 | 16 | 2011-03-02T14:10:29Z | 5,168,643 | 15 | 2011-03-02T14:14:17Z | [
"python",
"html"
] | Is there a way of writing Python embedded in HTML like I do with PHP or JSP? | Use a template engine, such as:
* [Jinja2](http://jinja.pocoo.org/docs/) (based on [Django's templating](http://docs.djangoproject.com/en/dev/topics/templates/#topics-templates))
* [mako](http://www.makotemplates.org/)
* [Cog](http://nedbatchelder.com/code/cog/)
* [Cheetah](http://www.cheetahtemplate.org/index.html)
... |
How to stop myself overwriting Python functions when coding? | 5,168,830 | 4 | 2011-03-02T14:26:57Z | 5,168,894 | 9 | 2011-03-02T14:30:57Z | [
"python",
"function",
"builtin"
] | A source of constant headache when tracking down bugs in my Python code are seemingly innocuous snippets like this:
```
list = ['a', 'b', 'c', 'c']
list(set(list))
```
This fails because I've overwritten the function list() with the variable list.
A contrived example obviously, but the point is Python happily lets... | You should use [Pylint](http://www.logilab.org/857). If you are using Eclipse + PyDev, you can configure it to run automatically within the IDE and highlight this issue (and many many others). |
__init__ and arguments in Python | 5,169,257 | 14 | 2011-03-02T14:55:57Z | 5,169,458 | 24 | 2011-03-02T15:11:35Z | [
"python",
"class",
"arguments",
"init"
] | I want to understand arguments of the constructor `__init__` in Python.
```
class Num:
def __init__(self,num):
self.n = num
def getn(self):
return self.n
def getone():
return 1
myObj = Num(3)
print myObj.getn()
```
RESULT: 3
I call the `getone()` method:
```
print myObj.getone()... | Python instance methods require the self argument. Class methods take the class as a first argument. Static methods do not require either the instance (`self`) or the class (`cls`) argument.
`__init__` is a special function and without overriding `__new__` it will always be given the instance of the class as its first... |
How do I list the current line in python PDB? | 5,169,702 | 19 | 2011-03-02T15:31:19Z | 5,169,808 | 10 | 2011-03-02T15:39:21Z | [
"python",
"pdb"
] | In the perl debugger, if you repeatedly list segments of code taking you away from the current line, you can return to the current line by entering the command `.` (dot).
I have not been able to find anything comparable using the python PDB module. If I *list* myself away from the current line and want to view it agai... | Well, I don't think there's a command similar to `.` in perl debugger, but you can always find the current line using the `where` / `w` command. That will show you both the current (contextual) frame as well as the most recent frame, which I believe is where the debugger was triggered. |
How do I list the current line in python PDB? | 5,169,702 | 19 | 2011-03-02T15:31:19Z | 11,847,915 | 19 | 2012-08-07T14:13:11Z | [
"python",
"pdb"
] | In the perl debugger, if you repeatedly list segments of code taking you away from the current line, you can return to the current line by entering the command `.` (dot).
I have not been able to find anything comparable using the python PDB module. If I *list* myself away from the current line and want to view it agai... | Late but hopefully still helpful. Make the following alias:
```
alias ll u;;d;;l
```
Then whenever you type `ll`, pdb will list from the current position. It works by going up the stack and then down the stack, which resets 'l' to show from the current position. (This won't work if you are at the top of the stack tra... |
What's the best way to handle -like entities in XML documents with lxml? | 5,170,252 | 9 | 2011-03-02T16:14:38Z | 5,170,641 | 11 | 2011-03-02T16:48:08Z | [
"python",
"lxml"
] | Consider the following:
```
from lxml import etree
from StringIO import StringIO
x = """<?xml version="1.0" encoding="utf-8"?>\n<aa> â</aa>"""
p = etree.XMLParser(remove_blank_text=True, resolve_entities=False)
r = etree.parse(StringIO(x), p)
```
This would fail with:
`lxml.etree.XMLSyntaxError: Entity ... | You can't ignore entities as they are part of the XML definition. Your document is not well-formed if it doesn't have a DTD or standalone="yes" or if it includes entities without an entity definition in the DTD. Lie and claim your document is HTML.
<https://mailman-mail5.webfaction.com/pipermail/lxml/2008-February/003... |
How to set the color of a single cell in a pygtk treeview? | 5,171,300 | 3 | 2011-03-02T17:43:33Z | 5,176,250 | 7 | 2011-03-03T03:13:33Z | [
"python",
"gtk",
"pygtk",
"gtktreeview",
"cellrenderer"
] | I have a PyGtk treeview with a couple of columns. During runtime i add constantly new rows. Each cell contains a string. Normaly, i would use a `gtk.CellRenderer` for each row, but I want to set the background color of each cell, according to the value inside the cell.
I tried a couple of solutions, but it seems that ... | You can define background and foreground for your treeview cells in extra fields of the treeview data source. Then setup foreground and background attributes for the treeview columns to get their values from the corresponding data source fields.
Below is a small example:
```
import gtk
test_data = [
{ 'column0' ... |
Tools / best practices for managing application dependencies? | 5,172,029 | 11 | 2011-03-02T18:58:47Z | 5,172,158 | 17 | 2011-03-02T19:09:29Z | [
"python",
"dependency-management"
] | What tools or best practices are available for tracking and managing dependencies of the software I'm developing? I'm using Python / Django, and to date all my software requirements are open source.
I'm developing a web application that, while modest, has a number of dependencies. At a minimum, I'd like to track the s... | Use `pip` and `virtualenv`. With `virtualenv`, you can create a "virtual environment" which has all your Python packages installed into a local directory. With `pip install -r`, you can install all packages listed in a specific requirements file.
Rough example:
```
virtualenv /path/to/env --no-site-packages --unzip-s... |
Why is an instance of webapp.WSGIApplication always defined as a global variable in google app engine code? | 5,172,694 | 6 | 2011-03-02T20:00:17Z | 5,172,969 | 7 | 2011-03-02T20:22:42Z | [
"python",
"google-app-engine",
"global-variables"
] | I'm starting to learn to use google app engine and, in much of the code I've come across, they declare the instance of the webapp.WSGIApplication as a global variable. This doesn't seem to be necessary, as the code works fine when it is locally declared in the main function.
I was always advised that global variables s... | Google App Engine offers a neat feature called [App caching](http://code.google.com/appengine/docs/python/runtime.html#App_Caching).
The first time the main handler is invoked, the full script is evaluated importing the modules and creating the global elements.
If the handler is called after the script has already ... |
Django templates syntax highlighting in Eclipse | 5,173,024 | 25 | 2011-03-02T20:28:03Z | 6,933,282 | 13 | 2011-08-03T21:05:50Z | [
"python",
"django",
"ide",
"syntax-highlighting",
"pydev"
] | I use Eclipse and pydev for django development. This has worked more or less ok, including debugging. Syntax highlighting doesn't seem to work everywhere though. I couldn't get any highlighting for the templates thought. Is there a way to get the highlighting and code suggestions for the templates? | ## For clarity
Django Templates Editor is only available with Aptana 3.0 and later. Pydev in eclipse alone does not support it. Aptana is available as an eclipse plugin or stand alone.
As mentioned by mcoconnor Window -> Preferences -> General -> Editor -> File Associations will give you a list of extensions.
1. Cho... |
Django templates syntax highlighting in Eclipse | 5,173,024 | 25 | 2011-03-02T20:28:03Z | 11,850,638 | 45 | 2012-08-07T16:55:10Z | [
"python",
"django",
"ide",
"syntax-highlighting",
"pydev"
] | I use Eclipse and pydev for django development. This has worked more or less ok, including debugging. Syntax highlighting doesn't seem to work everywhere though. I couldn't get any highlighting for the templates thought. Is there a way to get the highlighting and code suggestions for the templates? | [Django Editor Plugin for Eclipse](http://eclipse.kacprzak.org/) |
python import seems to behave differently in mercurial_keyring.py file | 5,173,197 | 4 | 2011-03-02T20:43:56Z | 5,175,586 | 7 | 2011-03-03T01:24:30Z | [
"python",
"mercurial",
"import",
"abort"
] | A bizarre `import` error is preventing me from installing a mercurial extension.
I'm trying to get the `mercurial_keyring` extension running so that I don't have to type in my user name and password every time I use mercurial for a project.
I'm using Python 2.7.1. I installed mercurial with the binary provided at <ht... | Most likely, `hg` is running using the system python (2.6) rather than the copy of 2.7 you have installed.
Try installing `mercurial_keyring` and `keyring` under 2.6, and see if that gets things working as expected. |
Python monitoring stderr and stdout of a subprocess | 5,173,945 | 10 | 2011-03-02T21:47:42Z | 5,174,089 | 12 | 2011-03-02T22:01:14Z | [
"python",
"multithreading",
"subprocess",
"stdout",
"stderr"
] | I trying to start a program (HandBreakCLI) as a subprocess or thread from within python 2.7. I have gotten as far as starting it, but I can't figure out how to monitor it's stderr and stdout.
The program outputs it's status (% done) and info about the encode to stderr and stdout, respectively. I'd like to be able to p... | I have accomplished the same with ffmpeg. This is a stripped down version of the relevant portions. `bufsize=1` means line buffering and may not be needed.
```
def Run(command):
proc = subprocess.Popen(command, bufsize=1,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True)
... |
iterating through files with carriage returns | 5,174,243 | 6 | 2011-03-02T22:19:49Z | 5,174,274 | 12 | 2011-03-02T22:23:03Z | [
"python"
] | Is there a way to iterate through a text file using the syntax,
```
with open(filename,'r') as f:
for line in f:
print f
```
if the file only contains carriage returns and no newline characters?
So far all I can do is
```
with open(filename,'r') as f:
for line in f.read().split('\r'):
print f
```
But t... | You can use Python's [universal newline support for `open()`](http://docs.python.org/library/functions.html#open)
> In addition to the standard fopen() values mode may be `'U'` or `'rU'`. Python is usually built with universal newline support; supplying `'U'` opens the file as a text file, but lines may be terminated ... |
Python returning `<itertools.combinations object at 0x10049b470>` - How can I access this? | 5,176,232 | 13 | 2011-03-03T03:09:42Z | 5,176,243 | 17 | 2011-03-03T03:12:27Z | [
"python"
] | I have this simple piece of code that returns what's in the title. Why doesn't the array simply print? This is not just an `itertools` issue I've also noticed it for other code where it'll just return the object location.
Here is the code. I'm running 2.7.1, an enthought distribution (pylab) - using it for class.
```... | It doesn't print a simple list because the returned object is not a list. Apply the `list` function on it if you really need a list.
```
print list(itertools.combinations(number, 4))
```
---
`itertools.combinations` returns an iterator. An iterator is something that you can `for` on. Usually, elements of an iterator... |
Python returning `<itertools.combinations object at 0x10049b470>` - How can I access this? | 5,176,232 | 13 | 2011-03-03T03:09:42Z | 5,176,245 | 7 | 2011-03-03T03:13:00Z | [
"python"
] | I have this simple piece of code that returns what's in the title. Why doesn't the array simply print? This is not just an `itertools` issue I've also noticed it for other code where it'll just return the object location.
Here is the code. I'm running 2.7.1, an enthought distribution (pylab) - using it for class.
```... | Try this:
```
for x in itertools.combinations(number, 4):
print x
```
Or shorter:
```
results = [x for x in itertools.combinations(number, 4) ]
```
Basically, all of the [itertools](http://docs.python.org/library/itertools.html) module functions return this type of object. The idea is that, rather than computing... |
nose, unittest.TestCase and metaclass: auto-generated test_* methods not discovered | 5,176,396 | 11 | 2011-03-03T03:40:29Z | 5,177,625 | 16 | 2011-03-03T06:55:27Z | [
"python",
"unit-testing",
"metaclass",
"nose"
] | This is a follow-up question for [unittest and metaclass: automatic test\_\* method generation](http://stackoverflow.com/questions/5175942/unittest-and-metaclass-automatic-test-method-generation):
For this (fixed) unittest.TestCase layout:
```
#!/usr/bin/env python
import unittest
class TestMaker(type):
def _... | So, after sleuthing through both stdlib's `unittest` and nose's loader and selector source code, it turns out that nose overrides `unittest.TestLoader.getTestCaseNames` to use its own selector (with plugin points).
Now, nose's selector looks for a potential method's `method.__name__` to match certain regexes, black an... |
Argparse - How to Specify a Default Subcommand | 5,176,691 | 14 | 2011-03-03T04:35:07Z | 5,176,820 | 9 | 2011-03-03T04:55:34Z | [
"python",
"argparse"
] | I am using the argparse package of Python 2.7 to write some option-parsing logic for a command-line tool. The tool should accept one of the following arguments:
"ON": Turn a function on.
"OFF": Turn a function off.
[No arguments provided]: Echo the current state of the function.
Looking at the argparse documentat... | The defaults of the top-level parser override the defaults on the sub-parsers, so setting the default value of `func` on the sub-parsers is ignored, but the value of `newstate` from the sub-parser defaults is correct.
I don't think you want to use subcommands. Subcommands are used when the available options and positi... |
Why does argparse give me a list-in-a-list? | 5,176,846 | 19 | 2011-03-03T04:59:28Z | 5,176,913 | 28 | 2011-03-03T05:10:48Z | [
"python",
"argparse"
] | I just noticed a behavior in argparse that puzzled me (guess I'd never used it for a dumb list of files before):
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('multi', action='append', nargs='+')
print(parser.parse_args())
```
This gives me the output:
```
~$ ./testargs.py foo bar baz
Na... | You are calling
```
parser.add_argument('multi', action='append', nargs='+')
```
And it is taking all the arguments and appending as a single item in the multi list.
If you want it as individual items, just don't use append
```
parser.add_argument('multi', nargs='+')
```
From the docs
'append' - This stores a lis... |
Trouble using Vim's syn-include and syn-region to embed syntax highlighting | 5,176,972 | 11 | 2011-03-03T05:21:18Z | 5,182,769 | 13 | 2011-03-03T15:27:04Z | [
"python",
"vim",
"latex",
"syntax-highlighting",
"tex"
] | I am trying to get Vim to syntax highlight any file that ends with extension `.Rtex` in the following way:
* All top level text is highlighted as TeX
* Exception: any text enclosed in `\begin{python}...\end{python}` is highlighted as Python
I am able to achieve each of these criteria individually, but unable to achie... | After some more study of the manual, and much more trial and error, I have finally answered my own question (a simultaneously embarrassing and sublime accomplishment), which I now preserve here for posterity.
Basically, I think the problem is that the python highlighting wouldn't take effect because the `pythonCode` r... |
python urllib error | 5,177,219 | 2 | 2011-03-03T05:58:57Z | 5,177,429 | 8 | 2011-03-03T06:26:18Z | [
"python",
"python-3.x",
"request",
"urllib"
] | so I have this code:
```
def crawl(self, url):
data = urllib.request.urlopen(url)
print(data)
```
but then when I call the function, it returns
```
data = urllib.request.urlopen(url)
AttributeError: 'module' object has no attribute 'request'
```
what did I do wrong? I already imported urllib..
using py... | In python3, urllib is a package with three modules request, response, and error for its respective purposes.
Whenever you had `import urllib` or `import urllib2` in Python2.
Replace them with
```
import urllib.request
import urllib.response
import urllib.error
```
The classs and methods are same.
BTW, use `2to3` to... |
Postponing functions in python | 5,177,439 | 9 | 2011-03-03T06:29:13Z | 5,177,467 | 8 | 2011-03-03T06:32:25Z | [
"python",
"multithreading",
"setinterval"
] | In JavaScript I am used to being able to call functions to be executed at a later time, like this
```
function foo() {
alert('bar');
}
setTimeout(foo, 1000);
```
This does not block the execution of other code.
I do not know how to achieve something similar in Python. I can use sleep
```
import time
def foo():... | You want a [`Timer`](http://docs.python.org/library/threading.html#timer-objects) object from the [`threading`](http://docs.python.org/library/threading.html) module.
```
from threading import Timer
from time import sleep
def foo():
print "timer went off!"
t = Timer(4, foo)
t.start()
for i in range(11):
print... |
Postponing functions in python | 5,177,439 | 9 | 2011-03-03T06:29:13Z | 14,040,516 | 8 | 2012-12-26T12:22:29Z | [
"python",
"multithreading",
"setinterval"
] | In JavaScript I am used to being able to call functions to be executed at a later time, like this
```
function foo() {
alert('bar');
}
setTimeout(foo, 1000);
```
This does not block the execution of other code.
I do not know how to achieve something similar in Python. I can use sleep
```
import time
def foo():... | To execute a function after a delay or to repeat a function in given number of seconds using an event-loop (no threads), you could:
## Tkinter
```
#!/usr/bin/env python
from Tkinter import Tk
def foo():
print("timer went off!")
def countdown(n, bps, root):
if n == 0:
root.destroy() # exit mainloop
... |
Python String encode method | 5,177,502 | 6 | 2011-03-03T06:36:59Z | 5,177,584 | 10 | 2011-03-03T06:48:32Z | [
"python",
"unicode"
] | In Python, there is an `encode` method in unicode strings to encode from unicode to byte string. There is a `decode` method in string to do the reverse.
But I'm confused what the `encode` method in string for? | It's useful for non-text codecs.
```
>>> 'Hello, world!'.encode('hex')
'48656c6c6f2c20776f726c6421'
>>> 'Hello, world!'.encode('base64')
'SGVsbG8sIHdvcmxkIQ==\n'
>>> 'Hello, world!'.encode('zlib')
'x\x9c\xf3H\xcd\xc9\xc9\xd7Q(\xcf/\xcaIQ\x04\x00 ^\x04\x8a'
``` |
numpy - 2d array indexing | 5,178,009 | 5 | 2011-03-03T07:51:36Z | 5,178,111 | 8 | 2011-03-03T08:06:31Z | [
"python",
"indexing",
"numpy",
"multidimensional-array"
] | According to [docs](http://docs.scipy.org/doc/numpy/reference/internals.html#multidimensional-array-indexing-order-issues) numpy's default behaviour is to index arrays first by rows then by columns:
```
a = numpy.arange(6).reshape(3,2)
[[0 1]
[2 3]
[4 5]]
print a[0][1] # is 1
```
I want to index the array using t... | You can write `a.T[0][1]` to use indices of the transpose of the array, which are the other way around in 2D. |
pip install mysql-python fails with EnvironmentError: mysql_config not found | 5,178,292 | 463 | 2011-03-03T08:32:51Z | 5,178,698 | 727 | 2011-03-03T09:15:32Z | [
"python",
"pip",
"mysql-python"
] | **This is the error I get**
```
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install mysql-python
Downloading/unpacking mysql-python
Downloading MySQL-python-1.2.3.tar.gz (70Kb): 70Kb downloaded
Running setup.py egg_info for package mysql-python
sh: mysql_config: not found
Traceback (most recent... | It seems mysql\_config is missing on your system or the installer could not find it.
Be sure mysql\_config is really installed.
For example on Debian/Ubuntu you must install the package:
```
sudo apt-get install libmysqlclient-dev
```
Maybe the mysql\_config is not in your path, it will be the case when you compile ... |
pip install mysql-python fails with EnvironmentError: mysql_config not found | 5,178,292 | 463 | 2011-03-03T08:32:51Z | 12,621,216 | 195 | 2012-09-27T12:18:50Z | [
"python",
"pip",
"mysql-python"
] | **This is the error I get**
```
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install mysql-python
Downloading/unpacking mysql-python
Downloading MySQL-python-1.2.3.tar.gz (70Kb): 70Kb downloaded
Running setup.py egg_info for package mysql-python
sh: mysql_config: not found
Traceback (most recent... | Running Mac OSX Mountain Lion, I simply ran this in terminal to fix:
```
export PATH=$PATH:/usr/local/mysql/bin
```
This is the quickest fix I found - it adds it to the path, but I think you're better off adding it permanently (ie add it to `/etc/paths`) if you plan to install MySQL-python in another environment. |
pip install mysql-python fails with EnvironmentError: mysql_config not found | 5,178,292 | 463 | 2011-03-03T08:32:51Z | 12,839,135 | 19 | 2012-10-11T12:05:19Z | [
"python",
"pip",
"mysql-python"
] | **This is the error I get**
```
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install mysql-python
Downloading/unpacking mysql-python
Downloading MySQL-python-1.2.3.tar.gz (70Kb): 70Kb downloaded
Running setup.py egg_info for package mysql-python
sh: mysql_config: not found
Traceback (most recent... | You can use the MySQL Connector/Python
**Installation via PyPip**
```
pip install mysql-connector-python
```
Further information can be found on the [MySQL Connector/Python 1.0.5 beta announcement](http://geert.vanderkelen.org/mysql-connector-python-1-0-5-beta/) blog.
On Launchpad there's [a good example of how to ... |
pip install mysql-python fails with EnvironmentError: mysql_config not found | 5,178,292 | 463 | 2011-03-03T08:32:51Z | 13,697,561 | 81 | 2012-12-04T06:51:35Z | [
"python",
"pip",
"mysql-python"
] | **This is the error I get**
```
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install mysql-python
Downloading/unpacking mysql-python
Downloading MySQL-python-1.2.3.tar.gz (70Kb): 70Kb downloaded
Running setup.py egg_info for package mysql-python
sh: mysql_config: not found
Traceback (most recent... | ```
apt-get install libmysqlclient-dev python-dev
```
Seemed to do the trick. |
pip install mysql-python fails with EnvironmentError: mysql_config not found | 5,178,292 | 463 | 2011-03-03T08:32:51Z | 17,869,253 | 11 | 2013-07-25T21:40:34Z | [
"python",
"pip",
"mysql-python"
] | **This is the error I get**
```
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install mysql-python
Downloading/unpacking mysql-python
Downloading MySQL-python-1.2.3.tar.gz (70Kb): 70Kb downloaded
Running setup.py egg_info for package mysql-python
sh: mysql_config: not found
Traceback (most recent... | I was trying to install `mysql-python` on an Amazon EC2 Linux instance and I had to install these :
```
yum install mysql mysql-devel mysql-common mysql-libs gcc
```
But then I got this error :
```
_mysql.c:29:20: fatal error: Python.h: No such file or directory
```
So I installed :
```
yum install python-devel
``... |
pip install mysql-python fails with EnvironmentError: mysql_config not found | 5,178,292 | 463 | 2011-03-03T08:32:51Z | 19,605,676 | 9 | 2013-10-26T10:37:24Z | [
"python",
"pip",
"mysql-python"
] | **This is the error I get**
```
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install mysql-python
Downloading/unpacking mysql-python
Downloading MySQL-python-1.2.3.tar.gz (70Kb): 70Kb downloaded
Running setup.py egg_info for package mysql-python
sh: mysql_config: not found
Traceback (most recent... | ```
sudo apt-get install libmysqlclient-dev
```
works for Ubuntu 12.04 LTS |
pip install mysql-python fails with EnvironmentError: mysql_config not found | 5,178,292 | 463 | 2011-03-03T08:32:51Z | 22,013,331 | 34 | 2014-02-25T11:49:39Z | [
"python",
"pip",
"mysql-python"
] | **This is the error I get**
```
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install mysql-python
Downloading/unpacking mysql-python
Downloading MySQL-python-1.2.3.tar.gz (70Kb): 70Kb downloaded
Running setup.py egg_info for package mysql-python
sh: mysql_config: not found
Traceback (most recent... | There maybe various answers for the above issue, below is a aggregated solution.
For Ubuntu:
```
sudo apt-get update
sudo apt-get install python-dev
sudo apt-get install python-MySQLdb
```
For CentOS:
```
yum install python-devel mysql-devel
``` |
pip install mysql-python fails with EnvironmentError: mysql_config not found | 5,178,292 | 463 | 2011-03-03T08:32:51Z | 37,021,642 | 7 | 2016-05-04T07:51:20Z | [
"python",
"pip",
"mysql-python"
] | **This is the error I get**
```
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install mysql-python
Downloading/unpacking mysql-python
Downloading MySQL-python-1.2.3.tar.gz (70Kb): 70Kb downloaded
Running setup.py egg_info for package mysql-python
sh: mysql_config: not found
Traceback (most recent... | For **centos** users:
`yum install -y mysql-devel python-devel python-setuptools`
then
`pip install MySQL-python`
---
If this solution **doesn't work**, and print gcc compile error like:
`_mysql.c:29:20: error: Python.h: No such file or directory`
You need to specify the path of `Python.h`, like this:
`pip in... |
pip install lxml error | 5,178,416 | 197 | 2011-03-03T08:45:48Z | 5,178,444 | 372 | 2011-03-03T08:48:42Z | [
"python",
"lxml",
"pip"
] | this is my error :
```
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install lxml
Downloading/unpacking lxml
Running setup.py egg_info for package lxml
Building lxml version 2.3.
Building without Cython.
ERROR: /bin/sh: xslt-config: not found
** make sure the development packages of libxml... | > \*\* make sure the development packages of libxml2 and libxslt are installed \*\*
Assuming you are running a Debian-based distribution
```
sudo apt-get install python-dev libxml2-dev libxslt1-dev zlib1g-dev
```
If you're installing for Python 3 on Debian-based distributions, you'll want to install `python3-dev` to... |
pip install lxml error | 5,178,416 | 197 | 2011-03-03T08:45:48Z | 5,178,803 | 31 | 2011-03-03T09:26:14Z | [
"python",
"lxml",
"pip"
] | this is my error :
```
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install lxml
Downloading/unpacking lxml
Running setup.py egg_info for package lxml
Building lxml version 2.3.
Building without Cython.
ERROR: /bin/sh: xslt-config: not found
** make sure the development packages of libxml... | No you are missing the Python header files. This mostly happens on Linux when you are using the system Python (there are [reasons not to do that](http://regebro.wordpress.com/2011/02/02/newbie-hint-on-installing-python-and-its-modules-and-packages/), but that's a different question).
You probably need to install some ... |
pip install lxml error | 5,178,416 | 197 | 2011-03-03T08:45:48Z | 12,896,566 | 88 | 2012-10-15T13:24:20Z | [
"python",
"lxml",
"pip"
] | this is my error :
```
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install lxml
Downloading/unpacking lxml
Running setup.py egg_info for package lxml
Building lxml version 2.3.
Building without Cython.
ERROR: /bin/sh: xslt-config: not found
** make sure the development packages of libxml... | This worked for me
```
yum install libxslt-devel libxml2-devel
``` |
pip install lxml error | 5,178,416 | 197 | 2011-03-03T08:45:48Z | 17,378,157 | 69 | 2013-06-29T08:12:05Z | [
"python",
"lxml",
"pip"
] | this is my error :
```
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install lxml
Downloading/unpacking lxml
Running setup.py egg_info for package lxml
Building lxml version 2.3.
Building without Cython.
ERROR: /bin/sh: xslt-config: not found
** make sure the development packages of libxml... | In case, you are using Ubuntu/Lubuntu 13.04 or Ubuntu 13.10 and having problem with "/usr/bin/ld: cannot find -lz", you may need also install zlib1g-dev package:
```
sudo apt-get install -y zlib1g-dev
```
Put it all together:
```
sudo apt-get install -y libxml2-dev libxslt1-dev zlib1g-dev python3-pip
sudo pip3 insta... |
pip install lxml error | 5,178,416 | 197 | 2011-03-03T08:45:48Z | 21,995,912 | 7 | 2014-02-24T18:25:56Z | [
"python",
"lxml",
"pip"
] | this is my error :
```
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install lxml
Downloading/unpacking lxml
Running setup.py egg_info for package lxml
Building lxml version 2.3.
Building without Cython.
ERROR: /bin/sh: xslt-config: not found
** make sure the development packages of libxml... | I solved this issue by increasing my server ram.
I was running only 512 MB and when I upgraded to 1 GB I had no problem.
I also installed every package manually prior to this in an attempt to fix the problem, but I'm not sure whether this is a necessary step. |
Equivalent of setInterval in python | 5,179,467 | 16 | 2011-03-03T10:28:24Z | 5,179,753 | 9 | 2011-03-03T10:53:45Z | [
"python",
"multithreading",
"setinterval"
] | I have recently posted a [question](http://stackoverflow.com/questions/5177439/postponing-functions-in-python) about how to postpone execution of a function in Python (kind of equivalent to Javascript `setTimeout`) and it turns out to be a simple task using `threading.Timer` (well, simple as long as the function does n... | Your solution looks fine to me.
There are several ways to communicate with threads. To order a thread to stop, you can use `threading.Event()`, which has a `wait()` method that you can use instead of `time.sleep()`.
```
stop_event = threading.Event()
...
stop_event.wait(1.)
if stop_event.isSet():
return
...
```
... |
Continuous 3D plotting (i.e. figure update) using python-matplotlib? | 5,179,589 | 7 | 2011-03-03T10:38:17Z | 5,185,453 | 7 | 2011-03-03T19:22:54Z | [
"python",
"3d",
"matplotlib",
"plot"
] | I have a simulation which calculates surface data for each iteration of the simulation.
I would like to continuously plot that data as a surface plot to the same window (updating the plot in each iteration) in order to see how it evolves and to check the algorithm.
My Idea was to create a class that would initialize t... | You do not need to `plt.show()` if it is an animated (interactive) plot. You also want interactive set to True, not False which is the same as calling `ion()` in your 2d example. Also, you need to `remove()` the surface plots from previous frames if you do not want to see them all.
Otherwise you were pretty close.
Th... |
Python limit of the * operator and zip() function | 5,179,663 | 5 | 2011-03-03T10:44:52Z | 5,179,812 | 9 | 2011-03-03T10:58:38Z | [
"python",
"memory",
"zip"
] | I have a Python code similar to this one:
```
for lines in zip(*files):
# do something
```
where `files` is a list of files, each `file` is a list of `lines` and each `line` is a list of `string`s. Therefore, the code above should first unpack the list `files` and then apply the function `zip()`, returning a tuple... | If one of the files is empty, `zip` will return an empty list. As of Python 2.6 you can use [`itertools.izip_longest`](http://docs.python.org/library/itertools.html#itertools.izip_longest) to handle that. On older versions, you can use `map(None, *files)`, courtesy of @Sven Marnach. |
how to select an object from a list of objects by its attribute in python | 5,180,092 | 8 | 2011-03-03T11:25:30Z | 5,180,111 | 9 | 2011-03-03T11:28:05Z | [
"python",
"oop"
] | Apologies if this question has already been asked but I do not think I know the correct terminology to search for an appropriate solution through google.
I would like to select an object from a list of objects by the value of it's attribute, for example:
```
class Example():
def __init__(self):
self.pList... | Try
```
dave = next(person for person in a.pList if person.num == 123)
```
or
```
for person in a.pList:
if person.num == 123:
break
else:
print "Not found."
dave = person
``` |
Python Remove Comma In Dollar Amount | 5,180,184 | 7 | 2011-03-03T11:35:27Z | 5,180,218 | 22 | 2011-03-03T11:39:09Z | [
"python",
"string"
] | Using Python v2, I have the user entering an amount into a string as below:
```
RawPurchaseAmount = raw_input("Please enter purchase amount: ")
PurchaseAmount = float(RawPurchaseAmount.strip().lstrip("$"))
```
This is stripping out any blank spaces at the front of the input, and removing the $ sign if one is entered... | You could use `replace` to remove all commas:
`"10,000.00".replace(",", "")` |
Python Remove Comma In Dollar Amount | 5,180,184 | 7 | 2011-03-03T11:35:27Z | 5,180,507 | 15 | 2011-03-03T12:07:15Z | [
"python",
"string"
] | Using Python v2, I have the user entering an amount into a string as below:
```
RawPurchaseAmount = raw_input("Please enter purchase amount: ")
PurchaseAmount = float(RawPurchaseAmount.strip().lstrip("$"))
```
This is stripping out any blank spaces at the front of the input, and removing the $ sign if one is entered... | ```
>>> import re
>>> re.sub("[^\d\.]", "", "$1,000,000.01")
'1000000.01'
```
Regular expression pattern says "anything that isn't a number or a decimal point". Anything matching that regex is replaced with "".
You may need to bear in mind that some European countries use . as the thousand seperator and , as the deci... |
Python Add Comma Into Number String | 5,180,365 | 17 | 2011-03-03T11:52:58Z | 5,180,405 | 36 | 2011-03-03T11:56:26Z | [
"python",
"string"
] | Using Python v2, I have a value running through my program
that puts out a number rounded to 2 decimal places at the end:
like this:
```
print ("Total cost is: ${:0.2f}".format(TotalAmount))
```
Is there a way to insert a comma value every 3 digits left of the decimal point?
Ie: 10000.00 becomes 10,000.00 or 100000... | In Python 2.7 or above, you can use
```
print ("Total cost is: ${:,.2f}".format(TotalAmount))
```
This is documented in [PEP 378](http://www.python.org/dev/peps/pep-0378/).
(From your code, I can't tell which Python version you are using.) |
Python Add Comma Into Number String | 5,180,365 | 17 | 2011-03-03T11:52:58Z | 5,180,615 | 11 | 2011-03-03T12:17:55Z | [
"python",
"string"
] | Using Python v2, I have a value running through my program
that puts out a number rounded to 2 decimal places at the end:
like this:
```
print ("Total cost is: ${:0.2f}".format(TotalAmount))
```
Is there a way to insert a comma value every 3 digits left of the decimal point?
Ie: 10000.00 becomes 10,000.00 or 100000... | You could use [`locale.currency`](http://docs.python.org/library/locale.html#locale.currency) if `TotalAmount` represents money. It works on Python <2.7 too:
```
>>> locale.setlocale(locale.LC_ALL, '')
'en_US.utf8'
>>> locale.currency(123456.789, symbol=False, grouping=True)
'123,456.79'
```
Note: it doesn't work wit... |
Python 2 and 3 csv reader | 5,180,555 | 8 | 2011-03-03T12:12:18Z | 5,181,085 | 10 | 2011-03-03T13:06:38Z | [
"python",
"encoding",
"csv",
"python-3.x"
] | I'm trying to use the csv module to read a utf-8 csv file, and I have some trouble to create a generic code for python 2 and 3 due to encoding.
Here is the original code in Python 2.7:
```
with open(filename, 'rb') as csvfile:
csv_reader = csv.reader(csvfile, quotechar='\"')
langs = next(csv_reader)[1:]
f... | Indeed, in Python 2 the file should be opened in binary mode, but in Python 3 in text mode. [Also in Python 3 `newline=''` should be specified](http://docs.python.org/py3k/library/csv.html#module-csv) (which you forgot).
You'll have to do the file opening in an if-block.
```
import sys
if sys.version_info[0] < 3:
... |
eclipse, pydev, easy_install-ed eggs problem | 5,181,160 | 5 | 2011-03-03T13:14:16Z | 5,182,332 | 13 | 2011-03-03T14:54:02Z | [
"python",
"eclipse"
] | I have a problem with eclipse and easy\_install'ed packages into virtualenv.
If I have
```
from sqlalchemy.ext.serializer import loads
```
import statement and put mouse cursor on "load" I get message
```
loads Found at: __module_not_in_the_pythonpath__
```
and it repeats with any module on `PYTHONPATH` while I hav... | If you add a package after configuring the interpreter in Eclipse, you need to configure the interpreter again
See [PyDev's manual](http://pydev.org/manual_101_interpreter.html#what-if-i-add-something-new-in-my-system-pythonpath-after-configuring-it):
> If you add something to your python
> installation, you need to ... |
Under what circumstances are __rmul__ called? | 5,181,320 | 26 | 2011-03-03T13:28:19Z | 5,182,501 | 65 | 2011-03-03T15:04:10Z | [
"python",
"operators"
] | In Python, say I have a list `l`.
Under what circumstance is `l.__rmul__(self, other)` called? | When Python attempts to multiply two objects, it first tries to call the left object's `__mul__()` method. If the left object doesn't have a `__mul__()` method (or the method returns `NotImpemented`, indicating it doesn't work with the right operand in question), then Python wants to know if the right object can do the... |
Using the multiprocessing module for cluster computing | 5,181,949 | 36 | 2011-03-03T14:21:49Z | 5,182,130 | 10 | 2011-03-03T14:37:49Z | [
"python",
"parallel-processing",
"multiprocessing"
] | I'm interested in running a Python program using a computer cluster. I have in the past been using Python MPI interfaces, but due to difficulties in compiling/installing these, I would prefer solutions which use built-in modules, such as Python's [multiprocessing](http://docs.python.org/library/multiprocessing.html) mo... | In the past I've used [Pyro](http://www.xs4all.nl/~irmen/pyro3/) to do this quite succesfully. If you turn on mobile code it will automatically send over the wire required modules the nodes don't have already. Pretty nifty. |
Using the multiprocessing module for cluster computing | 5,181,949 | 36 | 2011-03-03T14:21:49Z | 5,182,131 | 29 | 2011-03-03T14:37:52Z | [
"python",
"parallel-processing",
"multiprocessing"
] | I'm interested in running a Python program using a computer cluster. I have in the past been using Python MPI interfaces, but due to difficulties in compiling/installing these, I would prefer solutions which use built-in modules, such as Python's [multiprocessing](http://docs.python.org/library/multiprocessing.html) mo... | If by cluster computing you mean distributed memory systems (multiple nodes rather that SMP) then Python's multiprocessing may not be a suitable choice. It can spawn multiple processes but they will still be bound within a single node.
What you will need is a framework that handles spawing of processes across multiple... |
Multiple assignment semantics | 5,182,573 | 47 | 2011-03-03T15:09:48Z | 5,182,675 | 53 | 2011-03-03T15:19:52Z | [
"python",
"variable-assignment"
] | In Python one can do:
```
a, b = 1, 2
(a, b) = 1, 2
[a, b] = 1, 2
```
I checked the generated bytecode using `dis` and they are identical.
So why allow this at all? Would I ever need one of these instead of the others? | One case when you need to include more structure on the left hand side of the assignment is when you're asking Python unpack a slightly more complicated sequence. E.g.:
```
# Works
>>> a, (b, c) = [1, [2, 3]]
# Does not work
>>> a, b, c = [1, [2, 3]]
Traceback (most recent call last):
File "<stdin>", line 1, in <mo... |
Multiple assignment semantics | 5,182,573 | 47 | 2011-03-03T15:09:48Z | 5,182,754 | 9 | 2011-03-03T15:25:48Z | [
"python",
"variable-assignment"
] | In Python one can do:
```
a, b = 1, 2
(a, b) = 1, 2
[a, b] = 1, 2
```
I checked the generated bytecode using `dis` and they are identical.
So why allow this at all? Would I ever need one of these instead of the others? | Python tuples can often be written with or without the parentheses:
```
a = 1, 2, 3
```
is equivalent to
```
a = (1, 2, 3)
```
In some cases, you need parentheses to resolve ambiguities, for examples if you want to pass the tuple `(1, 2)` to the function `f`, you will have to write `f((1, 2))`. Because the parenthe... |
Do python's variable length arguments (*args) expand a generator at function call time? | 5,182,758 | 8 | 2011-03-03T15:26:18Z | 5,182,801 | 12 | 2011-03-03T15:29:06Z | [
"python",
"function",
"iteration",
"generator"
] | Consider the following Python code:
```
def f(*args):
for a in args:
pass
foo = ['foo', 'bar', 'baz']
# Python generator expressions FTW
gen = (f for f in foo)
f(*gen)
```
Does `*args` automatically expand the generator at call-time? Put another way, am I iterating over `gen` twice within `f(*gen)`, on... | The generator is expanded at the time of the function call, as you can easily check:
```
def f(*args):
print args
foo = ['foo', 'bar', 'baz']
gen = (f for f in foo)
f(*gen)
```
will print
```
('foo', 'bar', 'baz')
``` |
Can I use Fabric to perform interactive shell commands? | 5,182,857 | 11 | 2011-03-03T15:32:39Z | 5,200,258 | 10 | 2011-03-04T23:06:31Z | [
"python",
"shell",
"interactive",
"fabric"
] | I`m trying to use [fabric](http://pypi.python.org/pypi/Fabric/0.9.4) to install and deploy a web project during which I need to create a postgresql database and configure a RabbitMQ server. Both these operations are interactive and requires input from the user for creating a database, adding a user, setting password et... | This is in Fabric 1.0. I've tried it and it works for me.
> Older versions of Fabric (and similar high level SSH libraries) run remote programs in limbo, unable to be touched from the local end. This is problematic when you have a serious need to enter passwords or otherwise interact with the remote program.
>
> Fabri... |
Python String replace based on chars NOT in RegEx | 5,183,488 | 6 | 2011-03-03T16:22:45Z | 5,183,500 | 12 | 2011-03-03T16:23:43Z | [
"python",
"regex"
] | Is it possible to create a reqex that finds characters that are NOT is a specific set?
Rather than Blacklisting a bunch of characters and replacing them, it would be easier for me to allow a certain set and replace characters that are not in that set.
My set looks like this:
[.a-zA-Z0-9]
I would like to do something... | Yes, use the `^` negation "modifier": `r'[^.a-zA-Z0-9]'` |
How to make List from Numpy Matrix in Python | 5,183,533 | 25 | 2011-03-03T16:26:49Z | 5,183,572 | 14 | 2011-03-03T16:30:31Z | [
"python",
"list",
"matrix",
"numpy"
] | I using the dot() function from numpy to multiply a matrix of 3x3 with a numpy.array of 1x3. The output is for example this:
[[ 0.16666667 0.66666667 0.16666667]]
which is of type:
```
<class 'numpy.matrixlib.defmatrix.matrix'>
```
how can I convert this to a list. Because I know the result will always be a matrix ... | Use the [tolist()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.tolist.html) method on the matrix object :
```
>>> import numpy
>>> m = numpy.matrix([1, 2, 3])
>>> type(m)
<class 'numpy.core.defmatrix.matrix'>
>>> m.tolist()
[[1, 2, 3]]
``` |
How to make List from Numpy Matrix in Python | 5,183,533 | 25 | 2011-03-03T16:26:49Z | 5,183,583 | 13 | 2011-03-03T16:31:08Z | [
"python",
"list",
"matrix",
"numpy"
] | I using the dot() function from numpy to multiply a matrix of 3x3 with a numpy.array of 1x3. The output is for example this:
[[ 0.16666667 0.66666667 0.16666667]]
which is of type:
```
<class 'numpy.matrixlib.defmatrix.matrix'>
```
how can I convert this to a list. Because I know the result will always be a matrix ... | If `a` is your matrix, try
```
a.ravel().tolist()
```
but you don't need to turn it into a list to iterate over it. |
How to make List from Numpy Matrix in Python | 5,183,533 | 25 | 2011-03-03T16:26:49Z | 5,183,592 | 32 | 2011-03-03T16:32:02Z | [
"python",
"list",
"matrix",
"numpy"
] | I using the dot() function from numpy to multiply a matrix of 3x3 with a numpy.array of 1x3. The output is for example this:
[[ 0.16666667 0.66666667 0.16666667]]
which is of type:
```
<class 'numpy.matrixlib.defmatrix.matrix'>
```
how can I convert this to a list. Because I know the result will always be a matrix ... | May not be the optimal way to do this but the following works:
```
a = numpy.matrix([[ 0.16666667, 0.66666667, 0.16666667]])
list(numpy.array(a).reshape(-1,))
```
or
```
numpy.array(a).reshape(-1,).tolist()
```
or
```
numpy.array(a)[0].tolist()
``` |
How to make List from Numpy Matrix in Python | 5,183,533 | 25 | 2011-03-03T16:26:49Z | 5,183,720 | 9 | 2011-03-03T16:43:28Z | [
"python",
"list",
"matrix",
"numpy"
] | I using the dot() function from numpy to multiply a matrix of 3x3 with a numpy.array of 1x3. The output is for example this:
[[ 0.16666667 0.66666667 0.16666667]]
which is of type:
```
<class 'numpy.matrixlib.defmatrix.matrix'>
```
how can I convert this to a list. Because I know the result will always be a matrix ... | Another way:
```
>>> import numpy as np
>>> m = np.matrix([1,2,3])
>>> np.array(m).flatten().tolist()
[1,2,3]
``` |
How to get the current running module path/name | 5,183,601 | 19 | 2011-03-03T16:32:41Z | 5,183,989 | 7 | 2011-03-03T17:06:15Z | [
"python",
"python-2.6"
] | I've searched and this seems to be a simple question without a simple answer.
I have the file `a/b/c.py` which would be called with `python -m a.b.c`. I would like to obtain the value `a.b.c` in the module level.
```
USAGE = u'''\
Usage:
python -m %s -h
''' % (what_do_i_put_here,)
```
So when I receive the `-h` ... | I think you're actually looking for the `__name__` special variable. From the [Python documentation](http://docs.python.org/tutorial/modules.html):
> Within a module, the moduleâs name (as a string) is available as the value of the global variable `__name__`.
If you run a file directly, this name will `__main__`. H... |
How to get the current running module path/name | 5,183,601 | 19 | 2011-03-03T16:32:41Z | 8,789,689 | 19 | 2012-01-09T14:10:07Z | [
"python",
"python-2.6"
] | I've searched and this seems to be a simple question without a simple answer.
I have the file `a/b/c.py` which would be called with `python -m a.b.c`. I would like to obtain the value `a.b.c` in the module level.
```
USAGE = u'''\
Usage:
python -m %s -h
''' % (what_do_i_put_here,)
```
So when I receive the `-h` ... | This works for me:
```
__loader__.fullname
```
Also if I do python -m b.c from a\ I get 'b.c' as expected.
Not entirely sure what the \_\_loader\_\_ attribute is so let me know if this is no good.
**edit**: It comes from PEP 302: <http://www.python.org/dev/peps/pep-0302/>
Interesting snippets from the link:
> The... |
How do I update a Python package? | 5,183,672 | 14 | 2011-03-03T16:40:11Z | 5,183,714 | 9 | 2011-03-03T16:43:11Z | [
"python",
"packages"
] | I'm running Ubuntu 9:10 and a package called M2Crypto is installed (version is 0.19.1). I need to download, build and install the latest version of the M2Crypto package (0.20.2).
The 0.19.1 package has files in a number of locations including (/usr/share/pyshared and /usr/lib/pymodules.python2.6).
How can I completel... | You might want to look into a Python package manager like pip (http://pip.openplans.org/). If you don't want to use a Python package manager, you should be able to download M2Crypto and build/compile/install over the old installation. |
How do I update a Python package? | 5,183,672 | 14 | 2011-03-03T16:40:11Z | 27,183,923 | 20 | 2014-11-28T07:34:26Z | [
"python",
"packages"
] | I'm running Ubuntu 9:10 and a package called M2Crypto is installed (version is 0.19.1). I need to download, build and install the latest version of the M2Crypto package (0.20.2).
The 0.19.1 package has files in a number of locations including (/usr/share/pyshared and /usr/lib/pymodules.python2.6).
How can I completel... | The best way I've found is to run this command from terminal
```
sudo pip install [package] --upgrade
``` |
Python TypeError on regex | 5,184,483 | 40 | 2011-03-03T17:50:46Z | 5,185,462 | 55 | 2011-03-03T19:23:38Z | [
"python",
"regex",
"python-3.x",
"typeerror"
] | So, I have this code:
```
url = 'http://google.com'
linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>')
m = urllib.request.urlopen(url)
msg = m.read()
links = linkregex.findall(msg)
```
But then python returns this error:
```
links = linkregex.findall(msg)
TypeError: can't use a string p... | > `TypeError: can't use a string pattern`
> `on a bytes-like object`
>
> what did i do wrong??
You used a string pattern on a bytes object. Use a bytes pattern instead:
```
linkregex = re.compile(b'<a\s*href=[\'|"](.*?)[\'"].*?>')
^
Add the b there, it makes it into a bytes object
`... |
How can I let android emulator talk to the localhost? | 5,185,016 | 6 | 2011-03-03T18:39:27Z | 5,185,046 | 16 | 2011-03-03T18:42:15Z | [
"python",
"android",
"android-emulator",
"webview"
] | I'm running an android app on the emulator. This app tries to load a html file using the webview api.
I also have a simple http server running on the same computer under the directory where I want to serve the request using the following python command:
*python -m SimpleHTTPServer 800*
However, I couldn't access thi... | Use address 10.0.2.2 instead of localhost. |
Python Conditional "With" Lock Design | 5,185,568 | 9 | 2011-03-03T19:34:22Z | 5,185,712 | 23 | 2011-03-03T19:47:47Z | [
"python",
"locking",
"with-statement"
] | Quick question, hopefully...
I am trying to do some shared locking using with statements
```
def someMethod(self, hasLock = False):
with self.my_lock:
self.somethingElse(hasLock=True)
def somethingElse(self, hasLock = False):
#I want this to be conditional...
with self.my_lock:
print... | Just use a `threading.RLock` which is re-entrant meaning it can be acquired multiple times by the same thread.
<http://docs.python.org/library/threading.html#rlock-objects>
For clarity, the `RLock` is used in the `with` statements, just like in your sample code:
```
lock = threading.RLock()
def func1():
with lo... |
Filter Foreignkey within Inlineform | 5,185,808 | 5 | 2011-03-03T19:55:04Z | 5,186,578 | 7 | 2011-03-03T21:09:40Z | [
"python",
"django",
"django-admin"
] | Hello I cant seem to filter a Foreignkey Dropdown within an Inline form.
These are my classes:
```
class Author(models.Model):
name = models.CharField(max_length=50)
desc = models.CharField(max_length=50)
class Book(models.Model):
author = models.ForeignKey(Author)
title= models.CharField(max_length=... | I'm a little confused by your question but found it interesting.
You want the author dropdown on the inlines to be the selected author -- so the inline will always only have 1 choice, the current author?
Well, normally you'd use `formfield_for_foreignkey`
<http://docs.djangoproject.com/en/dev/ref/contrib/admin/#djang... |
How to plot 3D function as 2D colormap in python? | 5,186,282 | 11 | 2011-03-03T20:39:29Z | 5,186,360 | 8 | 2011-03-03T20:48:29Z | [
"python",
"visualization",
"plot",
"matplotlib"
] | Are there any python libraries that will let me plot z = f(x,y) where z is represented as the color in a densely rasterized image (as opposed to the color of a bunch of scatterplot points) ? If so, what function do I use?
It looks like some of the contour functions in matplotlib.pyplot come close to what I want, but t... | Take a look at the documentation for `pcolor` or `imshow` in `matplotlib`.
Another good place to start is take a look at the matplotlib gallery and see if there is a plot type that matches what you are looking for and then use the sample code as a jumping off point for your own work:
<http://matplotlib.sourceforge.ne... |
How to plot 3D function as 2D colormap in python? | 5,186,282 | 11 | 2011-03-03T20:39:29Z | 21,296,416 | 8 | 2014-01-22T23:37:34Z | [
"python",
"visualization",
"plot",
"matplotlib"
] | Are there any python libraries that will let me plot z = f(x,y) where z is represented as the color in a densely rasterized image (as opposed to the color of a bunch of scatterplot points) ? If so, what function do I use?
It looks like some of the contour functions in matplotlib.pyplot come close to what I want, but t... | here's a concrete simple example (works also for functions which can't take matrix arguments for `x` and `y`):
```
# the function to be plotted
def func(x,y):
# gives vertical color bars if x is horizontal axis
return x
import pylab
# define the grid over which the function should be plotted (xx and yy a... |
download file in python | 5,186,389 | 2 | 2011-03-03T20:52:13Z | 5,186,402 | 8 | 2011-03-03T20:53:48Z | [
"python",
"download"
] | when i want download jpeg in python with this code:
```
def download(url, dest):
s = urllib2.urlopen(url)
content = s.read()
s.close()
d = open(dest,'w')
d.write(content)
d.close()
```
the file on hdd is not readable but when i open jpeg in mozilla its ok,
i am using windows and python 2.6
som... | You are opening the file in text mode and corrupting it. Python is interpreting certain byte sequences as EOL characters and writing them out as the appropriate EOL for that operating system. You need to tell Python to open the destination file in binary mode.
Change `d = open(dest,'w')` to `d = open(dest,'wb')` and e... |
Python Property Change Listener Pattern | 5,186,520 | 10 | 2011-03-03T21:04:51Z | 5,186,698 | 10 | 2011-03-03T21:21:00Z | [
"python"
] | Anyone know of any easy way to track changes to a dictionary object in python? I am at a high level doing crud, so I have a couple methods that handle changing a dictionary, if the dictionary changes I want to call a function to basically do an Observer/Notify.
```
class MyClass(object):
def update(self, item):
... | You can derive from the `dict` class and add a callback on any changes. This requires to overwrite any methods that change the dictionary:
```
class NotifyDict(dict):
__slots__ = ["callback"]
def __init__(self, callback, *args, **kwargs):
self.callback = callback
dict.__init__(self, *args, **kw... |
Using ctypes with jython | 5,186,670 | 5 | 2011-03-03T21:17:09Z | 5,186,920 | 8 | 2011-03-03T21:41:03Z | [
"python",
"jython",
"ctypes"
] | I have a trouble with using ctypes lib in my python script. Here is my code (found on the Internet):
```
if __name__ == "__main__":
from ctypes import *
user32 = windll.user32
kernel32 = windll.kernel32
class RECT(Structure):
_fields_ = [
("left", c_ulong),
("top", c_ul... | `ctypes` in Jython experimental and not complete.
From the jython-users mailing list in a thread titled "[ctypes in Jython](http://sourceforge.net/mailarchive/forum.php?thread_name=AANLkTikZpn1%2Bkbjd-0z1-sBd%2BGf7BQSLCcD7tj%2B%2BTC3k%40mail.gmail.com&forum_name=jython-users)" Jim Baker (a Jython committer) wrote on N... |
Python Replace \\ with \ | 5,186,839 | 15 | 2011-03-03T21:34:16Z | 5,187,097 | 22 | 2011-03-03T21:56:54Z | [
"python",
"string",
"replace",
"double",
"slash"
] | So I can't seem to figure this out... I have a string say, `"a\\nb"` and I want this to become `"a\nb"`. I've tried all the following and none seem to work;
```
>>> a
'a\\nb'
>>> a.replace("\\","\")
File "<stdin>", line 1
a.replace("\\","\")
^
SyntaxError: EOL while scanning string literal
... | There is no reason to use replace for this, Python comes with batteries included.
What you have is a encoded string (using the `string_escape` encoding) and you want to decode it:
```
>>> s = r"Escaped\nNewline"
>>> print s
Escaped\nNewline
>>> s.decode('string_escape')
'Escaped\nNewline'
>>> print s.decode('string_e... |
Cannot find appcfg.py or dev_appserver.py? | 5,187,602 | 10 | 2011-03-03T22:48:36Z | 5,188,313 | 16 | 2011-03-04T00:25:39Z | [
"python",
"google-app-engine",
"osx",
"bash"
] | My computer says...
"-bash: appcfg.py: command not found"
What is wrong?
I can run my application using google-app-engine-launcher and I have python pre-installed.
I am trying to upload my app using "appcfg.py update *myapp*"
I am new to Mac development. | In App Engine launcher there is a menu option called "Make Symlinks..." that adds symlinks for the various App Engine utility commands, like appcfg.py. |
How to check a string for specific characters? | 5,188,792 | 78 | 2011-03-04T01:47:24Z | 5,188,909 | 115 | 2011-03-04T02:07:17Z | [
"python",
"string"
] | How can I check if a string value has exact characters in it using Python2?
Specifically, I am looking to detect if it has dollar signs ("$"), commas (","), and numbers. | Assuming your string is `s`:
```
'$' in s # found
'$' not in s # not found
# original answer given, but less Pythonic than the above...
s.find('$')==-1 # not found
s.find('$')!=-1 # found
```
And so on for other characters.
... or
```
pattern = re.compile(r'\d\$,')
if pattern.findall(s):
print('Found... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.