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 |
|---|---|---|---|---|---|---|---|---|---|
Django Template Variables and Javascript | 298,772 | 92 | 2008-11-18T13:52:31Z | 8,483,184 | 22 | 2011-12-13T01:15:07Z | [
"javascript",
"python",
"django",
"google-app-engine",
"django-templates"
] | When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using `{{ myVar }}`.
Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to ... | A solution that worked for me is using the hidden input field in the template
```
<input type="hidden" id="myVar" name="variable" value="{{ variable }}">
```
Then getting the value in javascript this way,
```
var myVar = document.getElementById("myVar").value;
``` |
Django Template Variables and Javascript | 298,772 | 92 | 2008-11-18T13:52:31Z | 25,538,871 | 21 | 2014-08-28T00:14:04Z | [
"javascript",
"python",
"django",
"google-app-engine",
"django-templates"
] | When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using `{{ myVar }}`.
Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to ... | **CAUTION** Check ticket [#17419](https://code.djangoproject.com/ticket/17419) for discussion on adding similar tag into Django core and possible XSS vulnerabilities introduced by using this template tag with user generated data. [Comment](https://code.djangoproject.com/ticket/17419#comment:27) from amacneil discusses ... |
How do I change directory back to my original working directory with Python? | 299,446 | 5 | 2008-11-18T17:19:47Z | 299,462 | 10 | 2008-11-18T17:24:48Z | [
"python"
] | I have a function that resembles the one below. I'm not sure how to use the os module to get back to my original working directory at the conclusion of the jar's execution.
```
def run():
owd = os.getcwd()
#first change dir to build_dir path
os.chdir(testDir)
#run jar from test directory
os.system... | You simply need to add the line:
```
os.chdir(owd)
```
Just a note this was also answered in your other [question](http://stackoverflow.com/questions/299249/how-can-i-get-my-python-version-25-script-to-run-a-jar-file-inside-a-folder-ins). |
Validating with an XML schema in Python | 299,588 | 67 | 2008-11-18T17:59:56Z | 299,611 | 7 | 2008-11-18T18:09:40Z | [
"python",
"xml",
"validation",
"xsd"
] | I have an XML file and an XML schema in another file and I'd like to validate that my XML file adheres to the schema. How do I do this in Python?
I'd prefer something using the standard library, but I can install a third-party package if necessary. | lxml provides etree.DTD
from the tests on <http://lxml.de/api/lxml.tests.test_dtd-pysrc.html>
```
...
root = etree.XML(_bytes("<b/>"))
dtd = etree.DTD(BytesIO("<!ELEMENT b EMPTY>"))
self.assert_(dtd.validate(root))
``` |
Validating with an XML schema in Python | 299,588 | 67 | 2008-11-18T17:59:56Z | 299,635 | 42 | 2008-11-18T18:16:53Z | [
"python",
"xml",
"validation",
"xsd"
] | I have an XML file and an XML schema in another file and I'd like to validate that my XML file adheres to the schema. How do I do this in Python?
I'd prefer something using the standard library, but I can install a third-party package if necessary. | I am assuming you mean using XSD files. Surprisingly there aren't many python XML libraries that support this. lxml does however. Check [Validation with lxml](http://lxml.de/validation.html). The page also lists how to use lxml to validate with other schema types. |
Validating with an XML schema in Python | 299,588 | 67 | 2008-11-18T17:59:56Z | 1,946,225 | 12 | 2009-12-22T12:54:33Z | [
"python",
"xml",
"validation",
"xsd"
] | I have an XML file and an XML schema in another file and I'd like to validate that my XML file adheres to the schema. How do I do this in Python?
I'd prefer something using the standard library, but I can install a third-party package if necessary. | The PyXB package at <http://pyxb.sourceforge.net/> generates validating bindings for Python from XML schema documents. It handles almost every schema construct and supports multiple namespaces. |
Validating with an XML schema in Python | 299,588 | 67 | 2008-11-18T17:59:56Z | 5,566,672 | 20 | 2011-04-06T12:53:52Z | [
"python",
"xml",
"validation",
"xsd"
] | I have an XML file and an XML schema in another file and I'd like to validate that my XML file adheres to the schema. How do I do this in Python?
I'd prefer something using the standard library, but I can install a third-party package if necessary. | As for "pure python" solutions: the package index lists:
* [pyxsd](http://pypi.python.org/pypi/pyxsd), the description says it uses xml.etree.cElementTree, which is not "pure python" (but included in stdlib), but source code indicates that it falls back to xml.etree.ElementTree, so this would count as pure python. Hav... |
How to unquote a urlencoded unicode string in python? | 300,445 | 38 | 2008-11-18T22:49:27Z | 300,531 | 8 | 2008-11-18T23:22:24Z | [
"python",
"unicode",
"urllib"
] | I have a unicode string like "Tanım" which is encoded as "Tan%u0131m" somehow. How can i convert this encoded string back to original unicode.
Apparently urllib.unquote does not support unicode. | ```
def unquote(text):
def unicode_unquoter(match):
return unichr(int(match.group(1),16))
return re.sub(r'%u([0-9a-fA-F]{4})',unicode_unquoter,text)
``` |
How to unquote a urlencoded unicode string in python? | 300,445 | 38 | 2008-11-18T22:49:27Z | 300,533 | 60 | 2008-11-18T23:22:44Z | [
"python",
"unicode",
"urllib"
] | I have a unicode string like "Tanım" which is encoded as "Tan%u0131m" somehow. How can i convert this encoded string back to original unicode.
Apparently urllib.unquote does not support unicode. | %uXXXX is a [non-standard encoding scheme](http://en.wikipedia.org/wiki/Percent-encoding#Non-standard_implementations) that has been rejected by the w3c, despite the fact that an implementation continues to live on in JavaScript land.
The more common technique seems to be to UTF-8 encode the string and then % escape t... |
Python - Backslash Quoting in String Literals | 301,068 | 34 | 2008-11-19T05:22:47Z | 301,075 | 52 | 2008-11-19T05:26:43Z | [
"python",
"string"
] | I have a string that contains both double-quotes and backslashes that I want to set to a variable in Python. However, whenever I try to set it, the quotes or slashes are either removed or escaped. Here's an example:
```
>>> foo = 'baz "\"'
>>> foo
'baz ""'
```
So instead of `baz "\"` like I want I'm getting `baz ""`.... | You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)
```
>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
>>> print foo
baz "\"
```
Incidentally, there's another string form which might be a bit clearer:
```
>>> print r'baz "\"'
baz "\"
``` |
Python - Backslash Quoting in String Literals | 301,068 | 34 | 2008-11-19T05:22:47Z | 301,076 | 17 | 2008-11-19T05:29:45Z | [
"python",
"string"
] | I have a string that contains both double-quotes and backslashes that I want to set to a variable in Python. However, whenever I try to set it, the quotes or slashes are either removed or escaped. Here's an example:
```
>>> foo = 'baz "\"'
>>> foo
'baz ""'
```
So instead of `baz "\"` like I want I'm getting `baz ""`.... | Use a raw string:
```
>>> foo = r'baz "\"'
>>> foo
'baz "\\"'
```
Note that although it looks wrong, it's actually right. There is only one backslash in the string `foo`.
This happens because when you just type `foo` at the prompt, python displays the result of `__repr__()` on the string. This leads to the following... |
Dynamic module import in Python | 301,134 | 281 | 2008-11-19T06:09:57Z | 301,146 | 176 | 2008-11-19T06:17:18Z | [
"python",
"python-import"
] | I'm writing a Python application that takes as a command as an argument, for example:
```
$ python myapp.py command1
```
I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:
```... | With Python older than 2.7/3.1, that's pretty much how you do it. For newer versions, see `importlib.import_module` [for 2.7+](https://docs.python.org/2/library/importlib.html#importlib.import_module) and [for 3.1+](https://docs.python.org/3.1/library/importlib.html#importlib.import_module).
You can use `exec` if you ... |
Dynamic module import in Python | 301,134 | 281 | 2008-11-19T06:09:57Z | 301,165 | 19 | 2008-11-19T06:28:28Z | [
"python",
"python-import"
] | I'm writing a Python application that takes as a command as an argument, for example:
```
$ python myapp.py command1
```
I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:
```... | Use the [imp module](http://docs.python.org/library/imp.html#imp.load_module), or the more direct [`__import__()`](http://docs.python.org/library/functions.html#__import__) function. |
Dynamic module import in Python | 301,134 | 281 | 2008-11-19T06:09:57Z | 301,298 | 107 | 2008-11-19T08:21:25Z | [
"python",
"python-import"
] | I'm writing a Python application that takes as a command as an argument, for example:
```
$ python myapp.py command1
```
I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:
```... | As mentioned the [imp](http://docs.python.org/library/imp.html) module provides you loading functions:
```
imp.load_source(name, path)
imp.load_compiled(name, path)
```
I've used these before to perform something similar.
In my case I defined a specific class with defined methods that were required.
Once I loaded th... |
Dynamic module import in Python | 301,134 | 281 | 2008-11-19T06:09:57Z | 8,028,743 | 10 | 2011-11-06T17:08:08Z | [
"python",
"python-import"
] | I'm writing a Python application that takes as a command as an argument, for example:
```
$ python myapp.py command1
```
I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:
```... | If you want it in your locals:
```
>>> mod = 'sys'
>>> locals()['my_module'] = __import__(mod)
>>> my_module.version
'2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]'
```
same would work with `globals()` |
Dynamic module import in Python | 301,134 | 281 | 2008-11-19T06:09:57Z | 14,000,967 | 142 | 2012-12-22T07:33:46Z | [
"python",
"python-import"
] | I'm writing a Python application that takes as a command as an argument, for example:
```
$ python myapp.py command1
```
I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:
```... | The recommended way for Python 2.7 and later is to use [`importlib`](http://docs.python.org/2/library/importlib.html#importlib.import_module) module:
```
my_module = importlib.import_module('os.path')
``` |
Which language is easiest and fastest to work with XML content? | 301,493 | 13 | 2008-11-19T10:35:18Z | 301,630 | 17 | 2008-11-19T11:31:34Z | [
"java",
".net",
"python",
"xml",
"ruby"
] | We have developers with knowledge of these languages - Ruby , Python, .Net or Java. We are developing an application which will mainly handle XML documents. Most of the work is to convert predefined XML files into database tables, providing mapping between XML documents through database, creating reports from database ... | A dynamic language rules for this. Why? The mappings are easy to code and change. You don't have to recompile and rebuild.
Indeed, with a little cleverness, you can have your "XML XPATH to a Tag -> DB table-field" mappings as disjoint blocks of Python code that your main application imports.
The block of Python code ... |
Which language is easiest and fastest to work with XML content? | 301,493 | 13 | 2008-11-19T10:35:18Z | 301,649 | 8 | 2008-11-19T11:40:58Z | [
"java",
".net",
"python",
"xml",
"ruby"
] | We have developers with knowledge of these languages - Ruby , Python, .Net or Java. We are developing an application which will mainly handle XML documents. Most of the work is to convert predefined XML files into database tables, providing mapping between XML documents through database, creating reports from database ... | ## XSLT
I suggest using [XSLT templates](http://en.wikipedia.org/wiki/Xslt) to transform the XML into INSERT statements (or whatever you need), as required.
You should be able to invoke XSLT from any of the languages you mention.
This will result in a lot less code than doing it the long way round. |
Convert a string with date and time to a date | 301,528 | 18 | 2008-11-19T10:45:01Z | 301,580 | 44 | 2008-11-19T11:05:41Z | [
"python",
"datetime"
] | I've got this date time string:
```
post["date"] = "2007-07-18 10:03:19"
```
I'd like to extract just "2007-07-18" as a date. I've seen some reference to `strptime` but I'm not sure how to use it. How can I extract the date from this string? | The other two answers are fine, but if you actually want the date for something else, you can use the `datetime` module:
```
from datetime import datetime
d = datetime.strptime('2007-07-18 10:03:19', '%Y-%m-%d %H:%M:%S')
day_string = d.strftime('%Y-%m-%d')
```
It might be overkill for now, but it'll come in useful. Y... |
Python: urllib/urllib2/httplib confusion | 301,924 | 52 | 2008-11-19T13:44:20Z | 301,998 | 8 | 2008-11-19T14:19:19Z | [
"python",
"http",
"urllib2"
] | I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles.
Here's what I need to do:
1. Do a POST with a few parameters and headers.
2. Follow a redirect
3. Retrieve the HTML body.
Now, I'm relatively new to python, but the two things I've tested so far h... | I'd give Mechanize (<http://wwwsearch.sourceforge.net/mechanize/>) a shot. It may well handle your cookie/headers transparently. |
Python: urllib/urllib2/httplib confusion | 301,924 | 52 | 2008-11-19T13:44:20Z | 302,099 | 31 | 2008-11-19T14:52:47Z | [
"python",
"http",
"urllib2"
] | I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles.
Here's what I need to do:
1. Do a POST with a few parameters and headers.
2. Follow a redirect
3. Retrieve the HTML body.
Now, I'm relatively new to python, but the two things I've tested so far h... | Focus on `urllib2` for this, it works quite well. Don't mess with `httplib`, it's not the top-level API.
What you're noting is that `urllib2` doesn't follow the redirect.
You need to fold in an instance of `HTTPRedirectHandler` that will catch and follow the redirects.
Further, you may want to subclass the default `... |
Python: urllib/urllib2/httplib confusion | 301,924 | 52 | 2008-11-19T13:44:20Z | 302,184 | 11 | 2008-11-19T15:12:08Z | [
"python",
"http",
"urllib2"
] | I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles.
Here's what I need to do:
1. Do a POST with a few parameters and headers.
2. Follow a redirect
3. Retrieve the HTML body.
Now, I'm relatively new to python, but the two things I've tested so far h... | I had to do this exact thing myself recently. I only needed classes from the standard library. Here's an excerpt from my code:
```
from urllib import urlencode
from urllib2 import urlopen, Request
# encode my POST parameters for the login page
login_qs = urlencode( [("username",USERNAME), ("password",PASSWORD)] )
# ... |
Python: urllib/urllib2/httplib confusion | 301,924 | 52 | 2008-11-19T13:44:20Z | 302,205 | 13 | 2008-11-19T15:17:31Z | [
"python",
"http",
"urllib2"
] | I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles.
Here's what I need to do:
1. Do a POST with a few parameters and headers.
2. Follow a redirect
3. Retrieve the HTML body.
Now, I'm relatively new to python, but the two things I've tested so far h... | @S.Lott, thank you. Your suggestion worked for me, with some modification. Here's how I did it.
```
data = urllib.urlencode(params)
url = host+page
request = urllib2.Request(url, data, headers)
response = urllib2.urlopen(request)
cookies = CookieJar()
cookies.extract_cookies(response,request)
cookie_handler= urllib2... |
Python: urllib/urllib2/httplib confusion | 301,924 | 52 | 2008-11-19T13:44:20Z | 4,836,113 | 15 | 2011-01-29T09:33:42Z | [
"python",
"http",
"urllib2"
] | I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles.
Here's what I need to do:
1. Do a POST with a few parameters and headers.
2. Follow a redirect
3. Retrieve the HTML body.
Now, I'm relatively new to python, but the two things I've tested so far h... | Here's my take on this issue.
```
#!/usr/bin/env python
import urllib
import urllib2
class HttpBot:
"""an HttpBot represents one browser session, with cookies."""
def __init__(self):
cookie_handler= urllib2.HTTPCookieProcessor()
redirect_handler= urllib2.HTTPRedirectHandler()
self._o... |
Global hotkey for Python application in Gnome | 302,163 | 6 | 2008-11-19T15:08:12Z | 1,359,417 | 8 | 2009-08-31T21:03:58Z | [
"python",
"gnome"
] | I would like to assign a global hotkey to my Python application, running in Gnome. How do I do that? All I can find are two year old posts saying, well, pretty much nothing :-) | There is python-keybinder which is that same code, but packaged standalone. Also available in debian and ubuntu repositories now.
<https://github.com/engla/keybinder> |
Use only some parts of Django? | 302,651 | 29 | 2008-11-19T17:14:42Z | 302,847 | 36 | 2008-11-19T18:17:41Z | [
"python",
"django"
] | I like Django, but for a particular application I would like to use only parts of it, but I'm not familiar enough with how Django works on the inside, so maybe someone can point me into the right direction as to what I have to check out.
Specifically, I *want to use*:
* The models and database abstraction
* The [cach... | I myself use Django for its object/db mapping without using its urlconfigs. Simply create a file called `djangosettings.py` and insert the necessary configuration, for example:
```
DATABASE_ENGINE = 'oracle'
DATABASE_HOST = 'localhost'
DATABASE_NAME = 'ORCL'
DATABASE_USER = 'scott'
DATABASE_PASSWORD = '... |
Use only some parts of Django? | 302,651 | 29 | 2008-11-19T17:14:42Z | 304,352 | 11 | 2008-11-20T04:46:55Z | [
"python",
"django"
] | I like Django, but for a particular application I would like to use only parts of it, but I'm not familiar enough with how Django works on the inside, so maybe someone can point me into the right direction as to what I have to check out.
Specifically, I *want to use*:
* The models and database abstraction
* The [cach... | Django, being a web framework, is extremely efficient at creating websites. However, it's also equally well-suited to tackling problems off the web. This is the *loose coupling* that the project prides itself on. Nothing stops you from installing a complete version of Django, and just using what you need. As a rule, ve... |
Running a Django site under mod_wsgi | 302,679 | 9 | 2008-11-19T17:21:02Z | 1,038,087 | 10 | 2009-06-24T12:35:32Z | [
"python",
"django",
"apache",
"mod-wsgi"
] | I am trying to run my Django sites with mod\_wsgi instead of mod\_python (RHEL 5). I tried this with all my sites, but get the same problem. I configured it the standard way everyone recommends, but requests to the site simply time out.
Apache conf:
```
<VirtualHost 74.54.144.34>
DocumentRoot /wwwclients/thymeand... | The real problem is permissions on Apache log directory. It is necessary to tell Apache/mod\_wsgi to use an alternate location for the UNIX sockets used to communicate with the daemon processes. See:
[http://code.google.com/p/modwsgi/wiki/ConfigurationIssues#Location\_Of\_UNIX\_Sockets](http://code.google.com/p/modwsg... |
scons : src and include dirs | 302,835 | 5 | 2008-11-19T18:13:08Z | 302,984 | 8 | 2008-11-19T19:05:01Z | [
"python",
"scons"
] | can someone give a scons config file which allows the following structure
```
toplevel/
/src - .cc files
/include .h files
```
at top level I want the o and final exe. | Here is one example of Sconscript file
```
env=Environment(CPPPATH='/usr/include/glib-2.0/:/usr/lib/glib-2.0/include:inc',
CPPDEFINES=[],
LIBS=['glib-2.0'])
env.Program('runme', Glob('src/*.c'))
```
(The environment line is not really necessary for the example, but I have it to includ... |
Best Django 'CMS' component for integration into existing site | 302,983 | 13 | 2008-11-19T19:04:55Z | 1,257,116 | 7 | 2009-08-10T20:46:34Z | [
"python",
"django",
"content-management-system"
] | So I have a relatively large (enough code that it would be easier to write this CMS component from scratch than to rewrite the app to fit into a CMS) webapp that I want to add basic Page/Menu/Media management too, I've seen several Django pluggables addressing this issue, but many seem targeted as full CMS platforms.
... | If you do not necessarily want a finished CMS with a fixed feature set, but rather tools on top of Django to build your own CMS I recommend looking into FeinCMS. It follows a toolkit philosophy instead of trying to solve everything and (too) often failing to do so.
<http://github.com/matthiask/feincms/tree/master>
Di... |
Best Django 'CMS' component for integration into existing site | 302,983 | 13 | 2008-11-19T19:04:55Z | 3,892,818 | 25 | 2010-10-08T17:16:32Z | [
"python",
"django",
"content-management-system"
] | So I have a relatively large (enough code that it would be easier to write this CMS component from scratch than to rewrite the app to fit into a CMS) webapp that I want to add basic Page/Menu/Media management too, I've seen several Django pluggables addressing this issue, but many seem targeted as full CMS platforms.
... | I have worked with all three (and more) and they are all built for different use cases IMHO. I would agree that these are the top-teir choices.
The grid comparison at djangopluggables.com certainly can make evaluating each of these easier.
**django-cms** is the most full-featured and is something you could actually h... |
How do I remove/delete a folder that is not empty with Python? | 303,200 | 484 | 2008-11-19T20:15:38Z | 303,225 | 770 | 2008-11-19T20:23:16Z | [
"python",
"file"
] | I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: `os.remove("/folder_name")`.
What is the most effective way of removing/deleting a folder/directory that is not empty? | ```
import shutil
shutil.rmtree('/folder_name')
```
[Standard Library Reference: shutil.rmtree](http://docs.python.org/library/shutil.html#shutil.rmtree). |
How do I remove/delete a folder that is not empty with Python? | 303,200 | 484 | 2008-11-19T20:15:38Z | 303,228 | 90 | 2008-11-19T20:23:41Z | [
"python",
"file"
] | I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: `os.remove("/folder_name")`.
What is the most effective way of removing/deleting a folder/directory that is not empty? | From [the python docs](http://docs.python.org/library/os.html#os.walk) on `os.walk()`:
```
# Delete everything reachable from the directory named in 'top',
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs... |
How do I remove/delete a folder that is not empty with Python? | 303,200 | 484 | 2008-11-19T20:15:38Z | 25,172,642 | 40 | 2014-08-07T00:59:15Z | [
"python",
"file"
] | I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: `os.remove("/folder_name")`.
What is the most effective way of removing/deleting a folder/directory that is not empty? | ```
import shutil
shutil.rmtree(dest, ignore_errors=True)
``` |
Newbie Python Question about tuples | 303,664 | 5 | 2008-11-19T22:36:37Z | 303,697 | 9 | 2008-11-19T22:51:00Z | [
"python",
"tuples",
"cx-oracle"
] | I am new to Python, and I'm working on writing some database code using the `cx_Oracle` module. In the [cx\_Oracle documentation](http://cx-oracle.sourceforge.net/html/module.html) they have a code example like this:
```
import sys
import cx_Oracle
connection = cx_Oracle.Connection("user/pw@tns")
cursor = connection.... | ```
error, = exc.args
```
This is a case of [sequence unpacking](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences).
A more readable way to write the same, and the style I personally favor, is:
```
[error] = exc.args
```
There are two bits required to understand the previous example:
1. When... |
Emacs 23 and iPython | 304,049 | 24 | 2008-11-20T01:12:16Z | 312,741 | 8 | 2008-11-23T17:26:07Z | [
"python",
"emacs",
"ipython",
"emacs23"
] | Is there anyone out there using iPython with emacs 23? The documents on the emacs wiki are a bit of a muddle and I would be interested in hearing from anyone using emacs for Python development. Do you use the download python-mode and ipython.el? What do you recommend? | I got it working quite well with emacs 23. The only open issue is the focus not returning to the python buffer after sending the buffer to the iPython interpreter.
<http://www.emacswiki.org/emacs/PythonMode#toc10>
```
(setq load-path
(append (list nil
"~/.emacs.d/python-mode-1.0/"
... |
Data Modelling Advice for Blog Tagging system on Google App Engine | 304,117 | 8 | 2008-11-20T01:56:32Z | 307,727 | 7 | 2008-11-21T03:22:38Z | [
"python",
"google-app-engine",
"bigtable",
"data-modeling"
] | Am wondering if anyone might provide some conceptual advice on an efficient way to build a data model to accomplish the simple system described below. Am somewhat new to thinking in a non-relational manner and want to try avoiding any obvious pitfalls. It's my understanding that a basic principal is that "storage is ch... | Thanks to both of you for your suggestions. I've implemented (first iteration) as follows. Not sure if it's the best approach, but it's working.
Class A = Articles. Has a StringListProperty which can be queried on it's list elements
Class B = Tags. One entity per tag, also keeps a running count of the total number of... |
What's the best way to find the inverse of datetime.isocalendar()? | 304,256 | 36 | 2008-11-20T03:38:52Z | 1,700,069 | 53 | 2009-11-09T09:57:08Z | [
"python",
"datetime"
] | The Python [`datetime.isocalendar()`](http://www.python.org/doc/2.5.2/lib/datetime-datetime.html) method returns a tuple `(ISO_year, ISO_week_number, ISO_weekday)` for the given `datetime` object. Is there a corresponding inverse function? If not, is there an easy way to compute a date given a year, week number and day... | I recently had to solve this problem myself, and came up with this solution:
```
import datetime
def iso_year_start(iso_year):
"The gregorian calendar date of the first day of the given ISO year"
fourth_jan = datetime.date(iso_year, 1, 4)
delta = datetime.timedelta(fourth_jan.isoweekday()-1)
return fo... |
The best way to invoke methods in Python class declarations? | 304,655 | 4 | 2008-11-20T08:40:40Z | 304,679 | 14 | 2008-11-20T08:50:18Z | [
"python",
"class",
"declaration",
"static-methods",
"invocation"
] | Say I am declaring a class `C` and a few of the declarations are very similar. I'd like to use a function `f` to reduce code repetition for these declarations. It's possible to just declare and use `f` as usual:
```
>>> class C(object):
... def f(num):
... return '<' + str(num) + '>'
... v = f(9)
.... | Quite simply, the solution is that f does not need to be a member of the class. I am assuming that your thought-process has gone through a Javaish language filter causing the mental block. It goes a little something like this:
```
def f(n):
return '<' + str(num) + '>'
class C(object):
v = f(9)
w = f(42)
... |
What do I use on linux to make a python program executable | 304,883 | 39 | 2008-11-20T10:27:57Z | 304,896 | 80 | 2008-11-20T10:32:27Z | [
"python",
"linux",
"file-permissions"
] | I just installed a linux system (Kubuntu) and was wondering if there is a program to make python programs executable for linux. | Just put this in the first line of your script :
```
#!/usr/bin/env python
```
Make the file executable with
```
chmod +x myfile.py
```
Execute with
```
./myfile.py
``` |
What do I use on linux to make a python program executable | 304,883 | 39 | 2008-11-20T10:27:57Z | 14,232,463 | 8 | 2013-01-09T09:53:50Z | [
"python",
"linux",
"file-permissions"
] | I just installed a linux system (Kubuntu) and was wondering if there is a program to make python programs executable for linux. | If you want to obtain a stand-alone binary application in Python try to use a tool like py2exe or [PyInstaller](http://www.pyinstaller.org/). |
Correct way to detect sequence parameter? | 305,359 | 17 | 2008-11-20T13:52:44Z | 306,222 | 18 | 2008-11-20T17:52:46Z | [
"python",
"types",
"sequences"
] | I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I **don't** want it to be restricted to a hardcoded list.
In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid s... | As of 2.6, use [abstract base classes](http://docs.python.org/library/abc.html#module-abc).
```
>>> import collections
>>> isinstance([], collections.Sequence)
True
>>> isinstance(0, collections.Sequence)
False
```
Furthermore ABC's can be customized to account for exceptions, such as not considering strings to be se... |
List of tables, db schema, dump etc using the Python sqlite3 API | 305,378 | 64 | 2008-11-20T14:00:23Z | 305,395 | 12 | 2008-11-20T14:07:20Z | [
"python",
"api",
"sqlite",
"dump"
] | For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:
```
.tables
.dump
```
using the Python sqlite3 API.
Is there anything like that? | I'm not familiar with the Python API but you can always use
```
SELECT * FROM sqlite_master;
``` |
List of tables, db schema, dump etc using the Python sqlite3 API | 305,378 | 64 | 2008-11-20T14:00:23Z | 305,639 | 58 | 2008-11-20T15:26:39Z | [
"python",
"api",
"sqlite",
"dump"
] | For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:
```
.tables
.dump
```
using the Python sqlite3 API.
Is there anything like that? | You can fetch the list of tables and schemata by querying the SQLITE\_MASTER table:
```
sqlite> .tab
job snmptarget t1 t2 t3
sqlite> select name from sqlite_master where type = 'table';
job
t1
t2
snmptarget
t3
sqlite> .schema job
CREATE TABLE job (
id INTEGER PRIMARY KEY,
da... |
List of tables, db schema, dump etc using the Python sqlite3 API | 305,378 | 64 | 2008-11-20T14:00:23Z | 601,222 | 14 | 2009-03-02T03:47:31Z | [
"python",
"api",
"sqlite",
"dump"
] | For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:
```
.tables
.dump
```
using the Python sqlite3 API.
Is there anything like that? | Apparently the version of sqlite3 included in Python 2.6 has this ability: <http://docs.python.org/dev/library/sqlite3.html>
```
# Convert file existing_db.db to SQL dump file dump.sql
import sqlite3, os
con = sqlite3.connect('existing_db.db')
with open('dump.sql', 'w') as f:
for line in con.iterdump():
f... |
List of tables, db schema, dump etc using the Python sqlite3 API | 305,378 | 64 | 2008-11-20T14:00:23Z | 10,746,045 | 94 | 2012-05-24T22:15:42Z | [
"python",
"api",
"sqlite",
"dump"
] | For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:
```
.tables
.dump
```
using the Python sqlite3 API.
Is there anything like that? | In Python:
```
con = sqlite3.connect('database.db')
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())
```
Watch out for my other [answer](http://stackoverflow.com/a/33100538/236830). There is a much faster way using pandas. |
List of tables, db schema, dump etc using the Python sqlite3 API | 305,378 | 64 | 2008-11-20T14:00:23Z | 33,100,538 | 12 | 2015-10-13T10:38:59Z | [
"python",
"api",
"sqlite",
"dump"
] | For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:
```
.tables
.dump
```
using the Python sqlite3 API.
Is there anything like that? | The FASTEST way of doing this in python is using Pandas (version 0.16 and up).
Dump one table:
```
db = sqlite3.connect('database.db')
table = pd.read_sql_query("SELECT * from table_name", db)
table.to_csv(table_name + '.csv', index_label='index')
```
Dump all tables:
```
import sqlite3
import pandas as pd
def to... |
In Python, how can you get the name of a member function's class? | 305,924 | 7 | 2008-11-20T16:30:30Z | 305,980 | 10 | 2008-11-20T16:42:42Z | [
"python",
"reflection",
"metaprogramming"
] | I have a function that takes another function as a parameter. If the function is a member of a class, I need to find the name of that class. E.g.
```
def analyser(testFunc):
print testFunc.__name__, 'belongs to the class, ...
```
I thought
```
testFunc.__class__
```
would solve my problems, but that just tells ... | ```
testFunc.im_class
```
<https://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy>
> `im_class` is the class of `im_self` for
> bound methods or the class that asked
> for the method for unbound methods |
Python decorator makes function forget that it belongs to a class | 306,130 | 41 | 2008-11-20T17:24:39Z | 306,277 | 36 | 2008-11-20T18:08:33Z | [
"python",
"reflection",
"metaprogramming"
] | I am trying to write a decorator to do logging:
```
def logger(myFunc):
def new(*args, **keyargs):
print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__)
return myFunc(*args, **keyargs)
return new
class C(object):
@logger
def f():
pass
C().f()
```
I would like ... | Claudiu's answer is correct, but you can also cheat by getting the class name off of the `self` argument. This will give misleading log statements in cases of inheritance, but will tell you the class of the object whose method is being called. For example:
```
from functools import wraps # use this to preserve functi... |
Python decorator makes function forget that it belongs to a class | 306,130 | 41 | 2008-11-20T17:24:39Z | 307,263 | 18 | 2008-11-20T23:16:51Z | [
"python",
"reflection",
"metaprogramming"
] | I am trying to write a decorator to do logging:
```
def logger(myFunc):
def new(*args, **keyargs):
print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__)
return myFunc(*args, **keyargs)
return new
class C(object):
@logger
def f():
pass
C().f()
```
I would like ... | Functions only become methods at runtime. That is, when you get `C.f` you get a bound function (and `C.f.im_class is C`). At the time your function is defined it is just a plain function, it is not bound to any class. This unbound and disassociated function is what is decorated by logger.
`self.__class__.__name__` wil... |
Python decorator makes function forget that it belongs to a class | 306,130 | 41 | 2008-11-20T17:24:39Z | 3,412,743 | 13 | 2010-08-05T07:54:48Z | [
"python",
"reflection",
"metaprogramming"
] | I am trying to write a decorator to do logging:
```
def logger(myFunc):
def new(*args, **keyargs):
print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__)
return myFunc(*args, **keyargs)
return new
class C(object):
@logger
def f():
pass
C().f()
```
I would like ... | Ideas proposed here are excellent, but have some disadvantages:
1. `inspect.getouterframes` and `args[0].__class__.__name__` are not suitable for plain functions and static-methods.
2. `__get__` must be in a class, that is rejected by `@wraps`.
3. `@wraps` itself should be hiding traces better.
So, I've combined some... |
"is" operator behaves unexpectedly with integers | 306,313 | 264 | 2008-11-20T18:21:16Z | 306,347 | 18 | 2008-11-20T18:29:48Z | [
"python",
"int",
"comparison",
"operators",
"identity"
] | Why does the following behave unexpectedly in Python?
```
>>> a = 256
>>> b = 256
>>> a is b
True # This is an expected result
>>> a = 257
>>> b = 257
>>> a is b
False # What happened here? Why is this False?
>>> 257 is 257
True # Yet the literal numbers compare properly
```
I am using Py... | I think your hypotheses is correct. Experiment with id (identity of object)..
```
In [1]: id(255)
Out[1]: 146349024
In [2]: id(255)
Out[2]: 146349024
In [3]: id(257)
Out[3]: 146802752
In [4]: id(257)
Out[4]: 148993740
In [5]: a=255
In [6]: b=255
In [7]: c=257
In [8]: d=257
In [9]: id(a), id(b), id(c), id(d)
Ou... |
"is" operator behaves unexpectedly with integers | 306,313 | 264 | 2008-11-20T18:21:16Z | 306,353 | 222 | 2008-11-20T18:30:20Z | [
"python",
"int",
"comparison",
"operators",
"identity"
] | Why does the following behave unexpectedly in Python?
```
>>> a = 256
>>> b = 256
>>> a is b
True # This is an expected result
>>> a = 257
>>> b = 257
>>> a is b
False # What happened here? Why is this False?
>>> 257 is 257
True # Yet the literal numbers compare properly
```
I am using Py... | Take a look at this:
```
>>> a = 256
>>> b = 256
>>> id(a)
9987148
>>> id(b)
9987148
>>> a = 257
>>> b = 257
>>> id(a)
11662816
>>> id(b)
11662828
```
EDIT: Here's what I found in the Python 2 documentation, ["Plain Integer Objects"](https://docs.python.org/2/c-api/int.html) (It's the same for [Python 3](https://docs... |
"is" operator behaves unexpectedly with integers | 306,313 | 264 | 2008-11-20T18:21:16Z | 306,377 | 46 | 2008-11-20T18:36:06Z | [
"python",
"int",
"comparison",
"operators",
"identity"
] | Why does the following behave unexpectedly in Python?
```
>>> a = 256
>>> b = 256
>>> a is b
True # This is an expected result
>>> a = 257
>>> b = 257
>>> a is b
False # What happened here? Why is this False?
>>> 257 is 257
True # Yet the literal numbers compare properly
```
I am using Py... | It depends on whether you're looking to see if 2 things are equal, or the same object.
"is" checks to see if they are the same object, not just equal. The small ints are probably pointing to the same memory location for space efficiency
```
In [29]: a = 3
In [30]: b = 3
In [31]: id(a)
Out[31]: 500729144
In [32]: id(b... |
"is" operator behaves unexpectedly with integers | 306,313 | 264 | 2008-11-20T18:21:16Z | 306,603 | 29 | 2008-11-20T19:50:11Z | [
"python",
"int",
"comparison",
"operators",
"identity"
] | Why does the following behave unexpectedly in Python?
```
>>> a = 256
>>> b = 256
>>> a is b
True # This is an expected result
>>> a = 257
>>> b = 257
>>> a is b
False # What happened here? Why is this False?
>>> 257 is 257
True # Yet the literal numbers compare properly
```
I am using Py... | As you can check in [source file *intobject.c*](http://svn.python.org/projects/python/trunk/Objects/intobject.c), Python caches small integers for efficiency. Every time you create a reference to a small integer, you are referring the cached small integer, not a new object. 257 is not an small integer, so it is calcula... |
"is" operator behaves unexpectedly with integers | 306,313 | 264 | 2008-11-20T18:21:16Z | 307,594 | 10 | 2008-11-21T01:58:53Z | [
"python",
"int",
"comparison",
"operators",
"identity"
] | Why does the following behave unexpectedly in Python?
```
>>> a = 256
>>> b = 256
>>> a is b
True # This is an expected result
>>> a = 257
>>> b = 257
>>> a is b
False # What happened here? Why is this False?
>>> 257 is 257
True # Yet the literal numbers compare properly
```
I am using Py... | For immutable value objects, like ints, strings or datetimes, object identity is not especially useful. It's better to think about equality. Identity is essentially an implementation detail for value objects - since they're immutable, there's no effective difference between having multiple refs to the same object or mu... |
"is" operator behaves unexpectedly with integers | 306,313 | 264 | 2008-11-20T18:21:16Z | 15,522,094 | 7 | 2013-03-20T11:20:46Z | [
"python",
"int",
"comparison",
"operators",
"identity"
] | Why does the following behave unexpectedly in Python?
```
>>> a = 256
>>> b = 256
>>> a is b
True # This is an expected result
>>> a = 257
>>> b = 257
>>> a is b
False # What happened here? Why is this False?
>>> 257 is 257
True # Yet the literal numbers compare properly
```
I am using Py... | `is` *is* the identity equality operator (functioning like `id(a) == id(b)`); it's just that two equal numbers aren't necessarily the same object. For performance reasons some small integers happen to be [memoized](http://en.wikipedia.org/wiki/Memoization) so they will tend to be the same (this can be done since they a... |
"is" operator behaves unexpectedly with integers | 306,313 | 264 | 2008-11-20T18:21:16Z | 28,864,111 | 19 | 2015-03-04T20:20:12Z | [
"python",
"int",
"comparison",
"operators",
"identity"
] | Why does the following behave unexpectedly in Python?
```
>>> a = 256
>>> b = 256
>>> a is b
True # This is an expected result
>>> a = 257
>>> b = 257
>>> a is b
False # What happened here? Why is this False?
>>> 257 is 257
True # Yet the literal numbers compare properly
```
I am using Py... | > # Python's âisâ operator behaves unexpectedly with integers?
Let me emphasize: ***Do not use `is` to compare integers.***
This isn't behavior you should have any expectations about.
Instead, use `==` and `!=` to compare for equality and inequality, respectively.
To know this, you need to know the following.
... |
How do I randomly select an item from a list using Python? | 306,400 | 824 | 2008-11-20T18:42:21Z | 306,417 | 1,462 | 2008-11-20T18:46:39Z | [
"python",
"list",
"random"
] | Assume I have the following list:
```
foo = ['a', 'b', 'c', 'd', 'e']
```
What is the simplest way to retrieve an item at random from this list? | Use [`random.choice`](https://docs.python.org/2/library/random.html#random.choice):
```
import random
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))
``` |
How do I randomly select an item from a list using Python? | 306,400 | 824 | 2008-11-20T18:42:21Z | 12,373,205 | 63 | 2012-09-11T15:31:16Z | [
"python",
"list",
"random"
] | Assume I have the following list:
```
foo = ['a', 'b', 'c', 'd', 'e']
```
What is the simplest way to retrieve an item at random from this list? | In case you also need the index:
```
foo = ['a', 'b', 'c', 'd', 'e']
from random import randrange
random_index = randrange(0,len(foo))
print foo[random_index]
``` |
How do I randomly select an item from a list using Python? | 306,400 | 824 | 2008-11-20T18:42:21Z | 16,514,203 | 14 | 2013-05-13T02:47:36Z | [
"python",
"list",
"random"
] | Assume I have the following list:
```
foo = ['a', 'b', 'c', 'd', 'e']
```
What is the simplest way to retrieve an item at random from this list? | I propose a script for removing randomly picked up items off a list until it is empty:
Maintain a `set` and remove randomly picked up element (with `choice`) until list is empty.
```
s=set(range(1,6))
import random
while len(s)>0:
s.remove(random.choice(list(s)))
print(s)
```
Three runs give three different ans... |
How do I randomly select an item from a list using Python? | 306,400 | 824 | 2008-11-20T18:42:21Z | 30,488,952 | 34 | 2015-05-27T17:07:07Z | [
"python",
"list",
"random"
] | Assume I have the following list:
```
foo = ['a', 'b', 'c', 'd', 'e']
```
What is the simplest way to retrieve an item at random from this list? | If you want to randomly select more than one item from a list, or select an item from a set, I'd recommend using `random.sample` instead.
```
import random
group_of_items = {1, 2, 3, 4} # a sequence or set will work here.
num_to_select = 2 # set the number to select here.
list_o... |
function pointers in python | 307,494 | 2 | 2008-11-21T01:09:28Z | 307,538 | 16 | 2008-11-21T01:30:33Z | [
"python",
"function-pointers"
] | I would like to do something like the following:
```
def add(a, b):
#some code
def subtract(a, b):
#some code
operations = [add, subtract]
operations[0]( 5,3)
operations[1](5,3)
```
In python, is it possible to assign something like a function pointer? | Did you try it? What you wrote works exactly as written. Functions are first-class objects in Python. |
How to force iPython to use an older version of Python? | 308,254 | 9 | 2008-11-21T09:26:19Z | 308,260 | 10 | 2008-11-21T09:28:51Z | [
"python",
"ipython"
] | I am running an Ubuntu 8.10, using Python 2.5 out of the box. This is fine from the system point of view, but I need Python2.4 since I dev on Zope / Plone.
Well, installing python2.4 is no challenge, but I can't find a (clean) way to make iPython use it : no option in the man nor in the config file.
Before, there was... | Ok, I answer my own question : I'm dumb :-)
```
ls /usr/bin/ipython*
/usr/bin/ipython /usr/bin/ipython2.4 /usr/bin/ipython2.5
```
Now it's built-in... |
Python data structures overhead/performance | 308,912 | 3 | 2008-11-21T14:22:56Z | 308,982 | 19 | 2008-11-21T14:47:13Z | [
"python",
"optimization"
] | Is there any performance advantage to using lists over dictionaries over tuples in Python?
If I'm optimising for speed, is there any reason to prefer one over another? | Rich,
Lists and dicts are beasts suitable for different needs. Make sure you don't use lists for linear searches where dicts hashes are perfect, because it's way slower. Also, if you just need a list of elements to traverse, don't use dicts because it will take much more space than lists.
That may sound obvious, but ... |
What does functools.wraps do? | 308,999 | 265 | 2008-11-21T14:53:40Z | 309,000 | 467 | 2008-11-21T14:53:47Z | [
"python",
"decorator",
"wraps"
] | In a comment on the [answer to another question](http://stackoverflow.com/questions/306130/python-decorator-makes-function-forget-that-it-belongs-to-a-class#306277), someone said they weren't sure what functools.wraps was doing. So I'm asking this question so that there will be a record of it on StackOverflow for futur... | When you use a decorator, you're replacing one function with another. In other words, if you have a decorator
```
def logged(func):
def with_logging(*args, **kwargs):
print func.__name__ + " was called"
return func(*args, **kwargs)
return with_logging
```
then when you say
```
@logged
def f(x... |
What does functools.wraps do? | 308,999 | 265 | 2008-11-21T14:53:40Z | 1,843,920 | 11 | 2009-12-03T23:46:43Z | [
"python",
"decorator",
"wraps"
] | In a comment on the [answer to another question](http://stackoverflow.com/questions/306130/python-decorator-makes-function-forget-that-it-belongs-to-a-class#306277), someone said they weren't sure what functools.wraps was doing. So I'm asking this question so that there will be a record of it on StackOverflow for futur... | I very often use classes, rather than functions, for my decorators. I was having some trouble with this because an object won't have all the same attributes that are expected of a function. For example, an object won't have the attribute `__name__`. I had a specific issue with this that was pretty hard to trace where D... |
Why can't I inherit from dict AND Exception in Python? | 309,129 | 18 | 2008-11-21T15:37:42Z | 309,563 | 20 | 2008-11-21T17:30:50Z | [
"python",
"multiple-inheritance"
] | I got the following class :
```
class ConstraintFailureSet(dict, Exception) :
"""
Container for constraint failures. It act as a constraint failure itself
but can contain other constraint failures that can be accessed with a dict syntax.
"""
def __init__(self, **failures) :
dict.__... | Both `Exception` and `dict` are implemented in C.
I think you can test this the follwing way:
```
>>> class C(object): pass
...
>>> '__module__' in C.__dict__
True
>>> '__module__' in dict.__dict__
False
>>> '__module__' in Exception.__dict__
False
```
Since `Exception` and `dict` have different ideas of how to stor... |
How to setup setuptools for python 2.6 on Windows? | 309,412 | 84 | 2008-11-21T16:44:44Z | 309,783 | 102 | 2008-11-21T18:56:40Z | [
"python",
"windows",
"setuptools"
] | Is there any way to install setuptools for python 2.6 in Windows without having an .exe installer?
There isn't one built at the moment, and the maintainer of setuptools has stated that it's probable be a while before he'll get to it.
Does anyone know of a way to install it anyway? | First Option - Online Installation (i.e. remaining connected to the Internet during the entire installation process):
1. Download [setuptools-0.6c9.tar.gz](http://pypi.python.org/pypi/setuptools#files)
2. Use [7-zip](http://www.7-zip.org/) to extract it to a folder(directory) outside your Windows Python installation f... |
How to setup setuptools for python 2.6 on Windows? | 309,412 | 84 | 2008-11-21T16:44:44Z | 425,318 | 50 | 2009-01-08T18:27:59Z | [
"python",
"windows",
"setuptools"
] | Is there any way to install setuptools for python 2.6 in Windows without having an .exe installer?
There isn't one built at the moment, and the maintainer of setuptools has stated that it's probable be a while before he'll get to it.
Does anyone know of a way to install it anyway? | You could download and run <http://peak.telecommunity.com/dist/ez_setup.py>. This will download and install setuptools.
[update]
This script no longer works - the version of setuptools the it downloads is not at the URI specified in ez\_setup.py -navigate to <http://pypi.python.org/packages/2.7/s/setuptools/> for the... |
How to setup setuptools for python 2.6 on Windows? | 309,412 | 84 | 2008-11-21T16:44:44Z | 675,337 | 10 | 2009-03-23T21:37:23Z | [
"python",
"windows",
"setuptools"
] | Is there any way to install setuptools for python 2.6 in Windows without having an .exe installer?
There isn't one built at the moment, and the maintainer of setuptools has stated that it's probable be a while before he'll get to it.
Does anyone know of a way to install it anyway? | The Nov. 21 answer didn't work for me. I got it working on my 64 bit Vista machine by following the Method 1 instructions, except for Step 3 I typed:
setup.py install
So, in summary, I did:
1. Download setuptools-0.6c9.tar.gz
2. Use 7-zip to extract it to a folder (directory) outside your Windows Python installation... |
How to quote a string value explicitly (Python DB API/Psycopg2) | 309,945 | 22 | 2008-11-21T19:47:11Z | 312,423 | 22 | 2008-11-23T11:47:54Z | [
"python",
"sql",
"django",
"psycopg2"
] | For some reasons, I would like to do an explicit quoting of a string value (becoming a part of constructed SQL query) instead of waiting for implicit quotation performed by `cursor.execute` method on contents of its second parameter.
By "implicit quotation" I mean:
```
value = "Unsafe string"
query = "SELECT * FROM s... | Ok, so I was curious and went and looked at the source of psycopg2. Turns out I didn't have to go further than the examples folder :)
And yes, this is psycopg2-specific. Basically, if you just want to quote a string you'd do this:
```
from psycopg2.extensions import adapt
print adapt("Hello World'; DROP DATABASE Wor... |
How to quote a string value explicitly (Python DB API/Psycopg2) | 309,945 | 22 | 2008-11-21T19:47:11Z | 24,590,439 | 10 | 2014-07-05T20:46:46Z | [
"python",
"sql",
"django",
"psycopg2"
] | For some reasons, I would like to do an explicit quoting of a string value (becoming a part of constructed SQL query) instead of waiting for implicit quotation performed by `cursor.execute` method on contents of its second parameter.
By "implicit quotation" I mean:
```
value = "Unsafe string"
query = "SELECT * FROM s... | I guess you're looking for the [mogrify](http://initd.org/psycopg/docs/cursor.html#cursor.mogrify) function.
Example:
```
>>> cur.mogrify("INSERT INTO test (num, data) VALUES (%s, %s)", (42, 'bar'))
"INSERT INTO test (num, data) VALUES (42, E'bar')"
``` |
How can I translate the following filename to a regular expression in Python? | 310,199 | 2 | 2008-11-21T21:08:07Z | 311,214 | 11 | 2008-11-22T11:09:25Z | [
"python",
"regex"
] | I am battling regular expressions now as I type.
I would like to determine a pattern for the following example file: `b410cv11_test.ext`. I want to be able to do a search for files that match the pattern of the example file aforementioned. Where do I start (so lost and confused) and what is the best way of arriving at... | Now that you have a human readable description of your file name, it's quite straight forward to translate it into a regular expression (at least in this case ;)
> must start with
The caret (`^`) anchors a regular expression to the beginning of what you want to match, so your re has to start with this symbol.
> 'b',... |
Python Input/Output, files | 310,629 | 4 | 2008-11-22T00:31:32Z | 310,635 | 10 | 2008-11-22T00:38:24Z | [
"python"
] | I need to write some methods for loading/saving some classes to and from a binary file. However I also want to be able to accept the binary data from other places, such as a binary string.
In c++ I could do this by simply making my class methods use std::istream and std::ostream which could be a file, a stringstream, ... | The Python way to do this is to accept an object that implements read() or write(). If you have a string, you can make this happen with [StringIO](http://docs.python.org/library/stringio.html):
```
from cStringIO import StringIO
s = "My very long string I want to read like a file"
file_like_string = StringIO(s)
data ... |
In Django, how does one filter a QuerySet with dynamic field lookups? | 310,732 | 97 | 2008-11-22T02:06:06Z | 310,785 | 170 | 2008-11-22T02:48:30Z | [
"python",
"django",
"django-models"
] | Given a class:
```
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=20)
```
Is it possible, and if so how, to have a QuerySet that filters based on dynamic arguments? For example:
```
# Instead of:
Person.objects.filter(name__startswith='B')
# ... and:
Person.objec... | Python's argument expansion may be used to solve this problem:
```
kwargs = {
'{0}__{1}'.format('name', 'startswith'): 'A',
'{0}__{1}'.format('name', 'endswith'): 'Z'
}
Person.objects.filter(**kwargs)
```
This is a very common and useful Python idiom. |
Python library to modify MP3 audio without transcoding | 310,765 | 16 | 2008-11-22T02:30:54Z | 310,817 | 8 | 2008-11-22T03:35:23Z | [
"python",
"mp3",
"codec"
] | I am looking for some general advice about the mp3 format before I start a small project to make sure I am not on a wild-goose chase.
My understanding of the internals of the mp3 format is minimal. Ideally, I am looking for a library that would abstract those details away. I would prefer to use Python (but could be co... | If you want to do things low-level, use [pymad](http://spacepants.org/src/pymad/). It turns MP3s into a buffer of sample data.
If you want something a little higher-level, use the Echo Nest [Remix API](http://code.google.com/p/echo-nest-remix/) (disclosure: I wrote part of it for my dayjob). It includes a few examples... |
Cleaning form data in Django | 310,931 | 7 | 2008-11-22T05:44:09Z | 310,968 | 12 | 2008-11-22T06:42:22Z | [
"python",
"django",
"forms",
"slug"
] | How can i clean and modify data from a form in django. I would like to define it on a per field basis for each model, much like using ModelForms.
What I want to achieve is automatically remove leading and trailing spaces from defined fields, or turn a title (from one field) into a slug (which would be another field). | You can define clean\_FIELD\_NAME() methods which can validate and alter data, as documented here: <http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation> |
How do I edit and delete data in Django? | 311,188 | 4 | 2008-11-22T10:28:56Z | 311,191 | 17 | 2008-11-22T10:36:04Z | [
"python",
"django",
"editing"
] | I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change\_form?! or something), **EDIT** it and save it back to the DB. Secondly how do I **DELETE** the data t... | Say you have a model Employee. To edit an entry with primary key emp\_id you do:
```
emp = Employee.objects.get(pk = emp_id)
emp.name = 'Somename'
emp.save()
```
to delete it just do:
```
emp.delete()
```
so a full view would be:
```
def update(request, id):
emp = Employee.objects.get(pk = id)
#you can do th... |
Modern, high performance bloom filter in Python? | 311,202 | 41 | 2008-11-22T10:53:57Z | 311,907 | 25 | 2008-11-22T23:35:59Z | [
"python",
"jython",
"bloom-filter"
] | I'm looking for a production quality bloom filter implementation in Python to handle fairly large numbers of items (say 100M to 1B items with 0.01% false positive rate).
[Pybloom](http://www.imperialviolet.org/pybloom.html) is one option but it seems to be showing its age as it throws DeprecationWarning errors on Pyth... | I recently went down this path as well; though it sounds like my application was slightly different. I was interested in approximating set operations on a large number of strings.
You do make the key observation that a **fast** bit vector is required. Depending on what you want to put in your bloom filter, you may als... |
Modern, high performance bloom filter in Python? | 311,202 | 41 | 2008-11-22T10:53:57Z | 3,390,002 | 8 | 2010-08-02T17:00:09Z | [
"python",
"jython",
"bloom-filter"
] | I'm looking for a production quality bloom filter implementation in Python to handle fairly large numbers of items (say 100M to 1B items with 0.01% false positive rate).
[Pybloom](http://www.imperialviolet.org/pybloom.html) is one option but it seems to be showing its age as it throws DeprecationWarning errors on Pyth... | Eventually I found [pybloomfiltermap](http://github.com/axiak/pybloomfiltermmap). I haven't used it, but it looks like it'd fit the bill. |
Modern, high performance bloom filter in Python? | 311,202 | 41 | 2008-11-22T10:53:57Z | 4,125,080 | 22 | 2010-11-08T15:10:21Z | [
"python",
"jython",
"bloom-filter"
] | I'm looking for a production quality bloom filter implementation in Python to handle fairly large numbers of items (say 100M to 1B items with 0.01% false positive rate).
[Pybloom](http://www.imperialviolet.org/pybloom.html) is one option but it seems to be showing its age as it throws DeprecationWarning errors on Pyth... | In reaction to Parand, saying "common practice seems to be using something like SHA1 and split up the bits to form multiple hashes", while that may be true in the sense that it's common practice (PyBloom also uses it), it still doesn't mean it's the right thing to do ;-)
For a Bloom filter, the only requirement a hash... |
How to indent Python list-comprehensions? | 311,588 | 31 | 2008-11-22T18:08:18Z | 311,604 | 38 | 2008-11-22T18:19:41Z | [
"python",
"coding-style"
] | List comprehensions can be useful in certain situations, but they can also be rather horrible to read.. As a slightly exaggerated example, how would you indent the following?
```
allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]
``` | It depends on how long they are. I tend to structure them like so:
```
[x.id for x
in self.db.query(schema.allPostsUuid).execute(timeout=20)
if x.type == 'post'
and x.deleted is not False
and ...
and ...]
```
That way every expression has its own line.
If any line becomes too big I like to extract it ... |
How to indent Python list-comprehensions? | 311,588 | 31 | 2008-11-22T18:08:18Z | 311,675 | 27 | 2008-11-22T19:29:24Z | [
"python",
"coding-style"
] | List comprehensions can be useful in certain situations, but they can also be rather horrible to read.. As a slightly exaggerated example, how would you indent the following?
```
allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]
``` | Where I work, our coding guidelines would have us do something like this:
```
all_posts_uuid_query = self.db.query(schema.allPostsUuid)
all_posts_uuid_list = all_posts_uuid_query.execute(timeout=20)
all_uuid_list = [
x.id
for x in all_posts_uuid_list
if (
x.type == "post"
and
no... |
python as a "batch" script (i.e. run commands from python) | 311,601 | 4 | 2008-11-22T18:18:58Z | 311,613 | 17 | 2008-11-22T18:25:47Z | [
"python",
"scripting",
"batch-file"
] | I'm working in a windows environment (my laptop!) and I need a couple of scripts that run other programs, pretty much like a windows batch file.
how can I run a command from python such that the program when run, will replace the script? The program is interactive (for instance, unison) and keeps printing lines and as... | You should create a new processess using the [subprocess module](http://www.python.org/doc/2.5.2/lib/module-subprocess.html).
I'm not fluent in windows processes but its Popen function is cross-platform, and should be preffered to OS specific solutions.
EDIT: I maintain that you should prefer the Subprocess module to... |
How to print date in a regular format in Python? | 311,627 | 315 | 2008-11-22T18:37:07Z | 311,645 | 60 | 2008-11-22T18:56:08Z | [
"python",
"datetime",
"date"
] | This is my code:
```
import datetime
today = datetime.date.today()
print today
```
This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:
```
import datetime
mylist = []
today = datetime.date.today()
mylist.append(t... | Use date.strftime. The formatting arguments are [described in the documentation](https://docs.python.org/2/library/time.html#time.strftime).
This one is what you wanted:
```
some_date.strftime('%Y-%m-%d')
```
This one takes Locale into account. (do this)
```
some_date.strftime('%c')
``` |
How to print date in a regular format in Python? | 311,627 | 315 | 2008-11-22T18:37:07Z | 311,655 | 496 | 2008-11-22T19:07:07Z | [
"python",
"datetime",
"date"
] | This is my code:
```
import datetime
today = datetime.date.today()
print today
```
This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:
```
import datetime
mylist = []
today = datetime.date.today()
mylist.append(t... | ## The WHY: dates are objects
In Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings, not timestamps nor anything.
Any object in Python have TWO string representations:
* The regular representation that is used by "print", can be get using the `str()` function. It is m... |
How to print date in a regular format in Python? | 311,627 | 315 | 2008-11-22T18:37:07Z | 14,320,620 | 126 | 2013-01-14T14:46:28Z | [
"python",
"datetime",
"date"
] | This is my code:
```
import datetime
today = datetime.date.today()
print today
```
This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:
```
import datetime
mylist = []
today = datetime.date.today()
mylist.append(t... | ```
import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
```
**Edit:**
After Cees suggestion, I have started using time as well:
```
import time
print time.strftime("%Y-%m-%d %H:%M")
``` |
How to print date in a regular format in Python? | 311,627 | 315 | 2008-11-22T18:37:07Z | 18,944,849 | 58 | 2013-09-22T14:26:14Z | [
"python",
"datetime",
"date"
] | This is my code:
```
import datetime
today = datetime.date.today()
print today
```
This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:
```
import datetime
mylist = []
today = datetime.date.today()
mylist.append(t... | The date, datetime, and time objects all support a strftime(format) method,
to create a string representing the time under the control of an explicit format
string.
Here is a list of the format codes with their directive and meaning.
```
%a Localeâs abbreviated weekday name.
%A Localeâs full weekday nam... |
How to print date in a regular format in Python? | 311,627 | 315 | 2008-11-22T18:37:07Z | 20,066,760 | 15 | 2013-11-19T08:39:04Z | [
"python",
"datetime",
"date"
] | This is my code:
```
import datetime
today = datetime.date.today()
print today
```
This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:
```
import datetime
mylist = []
today = datetime.date.today()
mylist.append(t... | This is shorter:
```
>>> import time
>>> time.strftime("%Y-%m-%d %H:%M")
'2013-11-19 09:38'
``` |
How to print date in a regular format in Python? | 311,627 | 315 | 2008-11-22T18:37:07Z | 20,776,958 | 11 | 2013-12-25T21:37:07Z | [
"python",
"datetime",
"date"
] | This is my code:
```
import datetime
today = datetime.date.today()
print today
```
This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:
```
import datetime
mylist = []
today = datetime.date.today()
mylist.append(t... | Or even
```
from datetime import datetime, date
"{:%d.%m.%Y}".format(datetime.now())
```
Out: '25.12.2013
or
```
"{} - {:%d.%m.%Y}".format("Today", datetime.now())
```
Out: 'Today - 25.12.2013'
```
"{:%A}".format(date.today())
```
Out: 'Wednesday'
```
'{}__{:%Y.%m.%d__%H-%M}.log'.format(__name__, datetime.now(... |
Parsing GPS receiver output via regex in Python | 311,763 | 12 | 2008-11-22T20:50:33Z | 311,769 | 8 | 2008-11-22T20:54:18Z | [
"python",
"regex",
"parsing",
"gps",
"nmea"
] | I have a friend who is finishing up his masters degree in aerospace engineering. For his final project, he is on a small team tasked with writing a program for tracking weather balloons, rockets and satellites. The program receives input from a GPS device, does calculations with the data, and uses the results of those ... | It's simpler to use split than a regex.
```
>>> line="$GPRMC,092204.999,4250.5589,S,14718.5084,E,1,12,24.4,89.6,M,,,0000*1F "
>>> line.split(',')
['$GPRMC', '092204.999', '4250.5589', 'S', '14718.5084', 'E', '1', '12', '24.4', '89.6', 'M', '', '', '0000*1F ']
>>>
``` |
Parsing GPS receiver output via regex in Python | 311,763 | 12 | 2008-11-22T20:50:33Z | 311,778 | 14 | 2008-11-22T21:00:01Z | [
"python",
"regex",
"parsing",
"gps",
"nmea"
] | I have a friend who is finishing up his masters degree in aerospace engineering. For his final project, he is on a small team tasked with writing a program for tracking weather balloons, rockets and satellites. The program receives input from a GPS device, does calculations with the data, and uses the results of those ... | splitting should do the trick. Here's a good way to extract the data, as well:
```
>>> line = "$GPRMC,199304.973,3248.7780,N,11355.7832,W,1,06,02.2,25722.5,M,,,*00"
>>> line = line.split(",")
>>> neededData = (float(line[2]), line[3], float(line[4]), line[5], float(line[9]))
>>> print neededData
(3248.7779999999998, '... |
Python - Create a list with initial capacity | 311,775 | 110 | 2008-11-22T20:56:41Z | 311,783 | 43 | 2008-11-22T21:07:18Z | [
"python",
"list",
"dictionary",
"initialization"
] | Code like this often happens:
```
l = []
while foo:
#baz
l.append(bar)
#qux
```
This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements.
In Java, you can create an ArrayList with an initial capacity. If you h... | Python lists have no built-in pre-allocation. If you really need to make a list, and need to avoid the overhead of appending (and you should verify that you do), you can do this:
```
l = [None] * 1000 # Make a list of 1000 None's
for i in xrange(1000):
# baz
l[i] = bar
# qux
```
Perhaps you could avoid th... |
Python - Create a list with initial capacity | 311,775 | 110 | 2008-11-22T20:56:41Z | 311,833 | 89 | 2008-11-22T22:02:34Z | [
"python",
"list",
"dictionary",
"initialization"
] | Code like this often happens:
```
l = []
while foo:
#baz
l.append(bar)
#qux
```
This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements.
In Java, you can create an ArrayList with an initial capacity. If you h... | ```
def doAppend( size=10000 ):
result = []
for i in range(size):
message= "some unique object %d" % ( i, )
result.append(message)
return result
def doAllocate( size=10000 ):
result=size*[None]
for i in range(size):
message= "some unique object %d" % ( i, )
result[i]... |
Python - Create a list with initial capacity | 311,775 | 110 | 2008-11-22T20:56:41Z | 5,533,598 | 22 | 2011-04-04T00:48:00Z | [
"python",
"list",
"dictionary",
"initialization"
] | Code like this often happens:
```
l = []
while foo:
#baz
l.append(bar)
#qux
```
This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements.
In Java, you can create an ArrayList with an initial capacity. If you h... | Short version: use
```
pre_allocated_list = [None] * size
```
to pre-allocate a list (that is, to be able to address 'size' elements of the list instead of gradually forming the list by appending). This operation is VERY fast, even on big lists. Allocating new objects that will be later assigned to list elements will... |
Python - Create a list with initial capacity | 311,775 | 110 | 2008-11-22T20:56:41Z | 24,173,567 | 10 | 2014-06-11T22:21:01Z | [
"python",
"list",
"dictionary",
"initialization"
] | Code like this often happens:
```
l = []
while foo:
#baz
l.append(bar)
#qux
```
This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements.
In Java, you can create an ArrayList with an initial capacity. If you h... | The Pythonic way for this is:
```
x = [None] * numElements
```
or whatever default value you wish to prepop with, e.g.
```
bottles = [Beer()] * 99
sea = [Fish()] * many
vegetarianPizzas = [None] * peopleOrderingPizzaNotQuiche
```
Python's default approach can be pretty efficient, although that efficiency decays as ... |
Effective Keyboard Input Handling | 312,263 | 9 | 2008-11-23T07:26:06Z | 312,270 | 17 | 2008-11-23T07:32:57Z | [
"python",
"user-interface",
"keyboard",
"user-input",
"interactive"
] | What is a good way to implement keyboard handling? In any language, where I write a keyboard-interactive program (such as a tetris game), I end up having some code that looks like this:
```
for event in pygame.event.get():
if event.type == KEYDOWN:
if False: pass #make everything an elif
e... | You could create a dictionary where the keys are the input and the value is a function that handles the keypress:
```
def handle_quit():
quit()
def handle_left():
curpiece.shift(-1, 0)
shadowpiece = curpiece.clone(); setupshadow(shadowpiece)
def handle_right():
curpiece.shift(1, 0)
shadowpiece = cu... |
Fetching attachments from gmail via either python or php | 312,284 | 7 | 2008-11-23T08:03:16Z | 312,317 | 10 | 2008-11-23T09:08:39Z | [
"php",
"python",
"gmail",
"attachment"
] | I have been trying to find information on how to retrieve attachments from a gmail account in either python or PHP, I'm hoping that someone here can be of some help, thanks.
Related:
* [How can I download all emails with attachments from Gmail?](http://stackoverflow.com/questions/348630/how-can-i-download-all-emails-... | You will have to enable IMAP access to your GMail account (Settings â Forwarding and POP/IMAP), and then use `imaplib.IMAP4_SSL` to access it.
Use the raw text of every message as an argument to `email.message_from_string` in order to process any attachments. |
How do you split a list into evenly sized chunks? | 312,443 | 959 | 2008-11-23T12:15:52Z | 312,464 | 1,227 | 2008-11-23T12:33:53Z | [
"python",
"list",
"split",
"chunks"
] | I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially e... | Here's a generator that yields the chunks you want:
```
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
```
---
```
import pprint
pprint.pprint(list(chunks(range(10, 75), 10)))
[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.