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 |
|---|---|---|---|---|---|---|---|---|---|
MySQL: Get column name or alias from query | 5,010,042 | 22 | 2011-02-15T22:01:17Z | 15,044,590 | 10 | 2013-02-23T19:23:03Z | [
"python",
"mysql",
"mysql-python"
] | I'm not asking for the SHOW COLUMNS command.
I want to create an application that works similiarly to heidisql, where you can specify an SQL query and when you execute it ... you get a result set with rows and columns representing your query result. The column names in the result set should match your selected columns... | This is the same as thefreeman but more in pythonic way using list and dictionary comprehension
```
columns = cursor.description
result = [{columns[index][0]:column for index, column in enumerate(value)} for value in cursor.fetchall()]
pprint.pprint(result)
``` |
Python: Perform an operation on each dictionary value | 5,010,536 | 9 | 2011-02-15T22:57:59Z | 5,010,557 | 9 | 2011-02-15T23:00:54Z | [
"python",
"dictionary"
] | In python 2.6 I want to perform an operation on each dictionary value, for example, I want to multiply by 2 for each of them. How to code less for this task? | ```
# Multiply every value in my_dict by 2
for key in my_dict:
my_dict[key] *= 2
``` |
Python: Perform an operation on each dictionary value | 5,010,536 | 9 | 2011-02-15T22:57:59Z | 16,993,582 | 32 | 2013-06-07T21:57:43Z | [
"python",
"dictionary"
] | In python 2.6 I want to perform an operation on each dictionary value, for example, I want to multiply by 2 for each of them. How to code less for this task? | ```
# A nice one liner (edited to remove square brackets)
my_dict.update((x, y*2) for x, y in my_dict.items())
``` |
how to use "group" in pymongo to group similar rows? | 5,010,624 | 8 | 2011-02-15T23:08:18Z | 5,014,441 | 15 | 2011-02-16T09:04:41Z | [
"python",
"mongodb",
"pymongo"
] | I am very new to mongodb/pymongo. I have successfully imported my data into mongo and would like to use the group function to group similar row together. For example, if my data set looks like this:
```
data = [{uid: 1 , event: 'a' , time: 1} ,
{uid: 1 , event: 'b' , time: 2} ,
{uid: 2 , event: 'c' , ... | You needn't use the `reduce` function to actually *reduce* anything. For example:
```
>>> coll.insert(dict(uid=1,event='a',time=1))
ObjectId('4d5b91d558839f06a8000000')
>>> coll.insert(dict(uid=1,event='b',time=2))
ObjectId('4d5b91e558839f06a8000001')
>>> coll.insert(dict(uid=2,event='c',time=2))
ObjectId('4d5b91f3588... |
How do I clear the cookies in urllib.request (python3) | 5,010,915 | 7 | 2011-02-15T23:53:49Z | 5,011,094 | 15 | 2011-02-16T00:20:55Z | [
"python",
"python-3.x",
"urllib"
] | Looking through the docs my first guess was that I call urllib.request.HTTPCookieProcessor().cookiejar.clear(), however that didn't work. My next guess is maybe I need to subclass it and build/install it with an opener? I don't know how to do that, I can if need be of course, but it really seems like overkill for what ... | By default, `urllib.request` won't store any cookies, so there is nothing to clear. If you build an `OpenerDirector` containing and `HTTPCookieProcessor` instance as one of the handlers, you have to clear the `cookiejar` of this instance. [Example from the docs](http://docs.python.org/py3k/library/http.cookiejar.html#e... |
python tornado setup | 5,011,135 | 5 | 2011-02-16T00:25:38Z | 5,081,687 | 8 | 2011-02-22T17:35:00Z | [
"python",
"tornado"
] | I want to use a Python framework that handles sessions (user auth), templating along with MySQL database access (although I can use MySQLdb quite nicely)
Tornado looks promising but, I just can't see how to use it. The sample given has a port listen feature. Does it replace Apache? Exactly how do I configure my server... | If you are using tornado for production, you can follow their [nginx setup guide](http://www.tornadoweb.org/en/latest/overview.html#running-tornado-in-production). |
how to query seed used by random.random()? | 5,012,560 | 20 | 2011-02-16T04:32:57Z | 5,012,617 | 22 | 2011-02-16T04:46:51Z | [
"python",
"random",
"seed"
] | Is there any way to find out what seed Python used to seed its random number generator?
I know I can specify my own seed, but I'm quite happy with Python managing it. But, I do want to know what seed it used, so that if I like the results I'm getting in a particular run, I could reproduce that run later. If I had the ... | (I assume you mean `random.random()`, since `math` doesn't contain it.)
It is not possible to get the automatic seed back out from the generator. I normally generate seeds like this:
```
seed = random.randint(0, sys.maxint)
myRand = random.Random(seed)
```
This way it is time-based, so each time you run the script (... |
how to query seed used by random.random()? | 5,012,560 | 20 | 2011-02-16T04:32:57Z | 5,012,724 | 13 | 2011-02-16T05:12:13Z | [
"python",
"random",
"seed"
] | Is there any way to find out what seed Python used to seed its random number generator?
I know I can specify my own seed, but I'm quite happy with Python managing it. But, I do want to know what seed it used, so that if I like the results I'm getting in a particular run, I could reproduce that run later. If I had the ... | The state of the random number generator isn't always simply a seed. For example, a secure PRNG typically has an entropy buffer, which is a larger block of data.
You can, however, save and restore the entire state of the randon number generator, so you can reproduce its results later on:
```
import random
old_state ... |
how to convert this date string to "2011-02-15T12:00+00:00" python datetime object | 5,012,592 | 2 | 2011-02-16T04:41:14Z | 5,012,738 | 7 | 2011-02-16T05:14:28Z | [
"python"
] | how to convert this date string to "2011-02-15T12:00+00:00" python datetime object in following format "Wed, Feb, 15, 2011 15:00" ? | It seems ISO 8601 format. Try using [iso8601](http://code.google.com/p/pyiso8601/) package â you can install it through `pip` or `easy_install`.
> Many file formats and standards use the ISO 8601 date format (e.g. 2007-01-14T20:34:22+00:00) to store dates in a neutral, unambiguous manner. This simple module parses t... |
How to restrict user to select date between range of years in django? | 5,013,041 | 2 | 2011-02-16T06:05:24Z | 5,013,276 | 8 | 2011-02-16T06:39:53Z | [
"python",
"django",
"model",
"datefield"
] | **models.py**
```
class Completion(models.Model):
start_date = models.DateField()
end_date = models.DateField()
batch = models.ForeignKey(Batch)
topic = models.ForeignKey(Topic)
```
In above code `DateField()` generates a date selecting widget in admin site where you can select proper date or enter it... | Check out [validators](http://docs.djangoproject.com/en/dev/ref/validators/)!
First, define your validator:
```
from django.core.exceptions import ValidationError
def validate_current_century(value):
if value < 2000 or value > 2100:
raise ValidationError(u'%s is not a valid year!' % value)
```
Now you c... |
how to run this code in django template | 5,013,367 | 23 | 2011-02-16T06:53:46Z | 5,013,438 | 35 | 2011-02-16T07:02:30Z | [
"python",
"django",
"templates"
] | this is my code :
```
{% for i,j in enumerate(a) %}
{{i}} ,{{j}}
{% endfor%}
```
but , it show a error , i think it cant run the `enumerate` method ,
so how to run the `enumerate` in django template ,
thanks | The template subsystem has some special constructs built into the for/endfor block that allows you to access the current index of the loop without having to call `enumerate`.
```
{% for j in a %}
{{ forloop.counter0 }}, {{ j }}
{% endfor %}
```
While this snippet solves your immediate problem, if you're expecting... |
Open file by filename wildcard | 5,013,532 | 3 | 2011-02-16T07:12:29Z | 5,013,622 | 8 | 2011-02-16T07:25:07Z | [
"python",
"file",
"filenames",
"wildcard"
] | I have a directory of text files that all have the extension `.txt`. My goal is to print the contents of the text file. I wish to be able use the wildcard `*.txt` to specify the file name I wish to open (I'm thinking along the lines of something like `F:\text\*.txt`?), split the lines of the text file, then print the o... | ```
import os
import re
path = "/home/mypath"
for filename in os.listdir(path):
if re.match("text\d+.txt", filename):
with open(os.path.join(path, filename), 'r') as f:
for line in f:
print line,
```
Although you ignored my perfectly fine solution, here you go:
```
import glob
... |
If a command line program is unsure of stdout's encoding, what encoding should it output? | 5,013,599 | 7 | 2011-02-16T07:22:30Z | 5,013,644 | 7 | 2011-02-16T07:27:04Z | [
"python",
"linux",
"shell",
"command-line",
"unicode"
] | I have a command line program written in Python, and when I pipe it through another program on the command line, `sys.stdout.encoding` is `None`. This makes sense, I suppose -- the output could be another program, or a file you're redirecting it into, or whatever, and it doesn't know what encoding is desired. But neith... | I suggest you use the current locale.
```
Python2> import locale
Python2> locale.getpreferredencoding()
'UTF-8'
```
The system knows what it should be, and the other side, if it also uses the current locale, will do the right thing. |
Run all Python files in a directory | 5,015,316 | 4 | 2011-02-16T10:34:13Z | 5,015,346 | 16 | 2011-02-16T10:37:18Z | [
"python",
"bash",
"matplotlib"
] | What is the best way to run all Python files in a directory?
```
python *.py
```
only executes one file. Writing one line per file in a shell script (or make file) seems cumbersome. I need this b/c I have a series of small matplotlib scripts each creating a png file and want to create all of the images at once.
PS: ... | bash has loops:
```
for f in *.py; do python "$f"; done
``` |
Calling Haskell functions from Python | 5,015,447 | 19 | 2011-02-16T10:46:41Z | 5,015,515 | 13 | 2011-02-16T10:54:36Z | [
"python",
"haskell",
"binding",
"ffi"
] | I want to use some Haskell libraries (e.g. Darcs, Pandoc) from Python, but it seems thereâs no direct foreign function interface to Haskell in Python. Is there any way to do that? | Provided you can get your Python code to call C, you can call Haskell functions that have been exported via the [FFI](http://www.haskell.org/haskellwiki/FFI_Introduction)
Another approach would be to write a standard IPC interface, in the case of darcs and pandoc just calling them as vanilla executables and parsing th... |
Calling Haskell functions from Python | 5,015,447 | 19 | 2011-02-16T10:46:41Z | 5,018,082 | 7 | 2011-02-16T15:05:22Z | [
"python",
"haskell",
"binding",
"ffi"
] | I want to use some Haskell libraries (e.g. Darcs, Pandoc) from Python, but it seems thereâs no direct foreign function interface to Haskell in Python. Is there any way to do that? | One additional idea: Something less efficient than a direct C binding, but more efficient than shelling out to Haskell is an rpc system such as Apache Thrift: <http://incubator.apache.org/thrift/>
I've found thrift easy to use, well supported, and reasonably performant. Once you have your Haskell server running, the c... |
Test if an attribute is present in a tag in BeautifulSoup | 5,015,483 | 22 | 2011-02-16T10:50:45Z | 5,017,483 | 34 | 2011-02-16T14:15:11Z | [
"python",
"beautifulsoup"
] | I would like to get all the `<script>` tags in a document and then process each one based on the presence (or absence) of certain attributes.
E.g., for each `<script>` tag, if the attribute `for` is present do something; else if the attribute `bar` is present do something else.
Here is what I am doing currently:
```... | If i understand well, you just want all the script tags, and then check for some attributes in them?
```
scriptTags = outputDoc.findAll('script')
for script in scriptTags:
if script.has_attr('some_attribute'):
do_something()
``` |
Test if an attribute is present in a tag in BeautifulSoup | 5,015,483 | 22 | 2011-02-16T10:50:45Z | 17,984,291 | 22 | 2013-08-01T02:32:11Z | [
"python",
"beautifulsoup"
] | I would like to get all the `<script>` tags in a document and then process each one based on the presence (or absence) of certain attributes.
E.g., for each `<script>` tag, if the attribute `for` is present do something; else if the attribute `bar` is present do something else.
Here is what I am doing currently:
```... | For future reference, has\_key has been deprecated is beautifulsoup 4. Now you need to use has\_attr
```
scriptTags = outputDoc.findAll('script')
for script in scriptTags:
if script.has_attr('some_attribute'):
do_something()
``` |
Configure GAE application app.yaml for subdomains | 5,015,882 | 3 | 2011-02-16T11:32:56Z | 5,020,131 | 8 | 2011-02-16T17:51:43Z | [
"python",
"google-app-engine",
"yaml"
] | I have some subdomains with my domain on GAE. They are, for example, blog.mysite.com, projects.mysite.com and docs.mysite.com. As it is configured now, they all are processed with such settings in `main.py`:
```
def main():
applications = {
'blog.mysite.com': webapp.WSGIApplication([('/', BlogHandler)]),
... | This is not exactly an answer to your question but you may want to look into [webapp2](http://code.google.com/p/webapp-improved/). It is a drop-in replacement for Google's webapp that adds some really useful features, including a new routing system that can route by domain.
Check out the [routes.py](http://code.google... |
How to detect if numpy is installed | 5,016,186 | 19 | 2011-02-16T12:05:14Z | 5,016,216 | 15 | 2011-02-16T12:07:36Z | [
"python",
"numpy"
] | I'm writing Python code. I want to check if numpy and wxpython are installed on machine. How to do that?? | The traditional method for checking for packages in Python is "it's better to beg forgiveness than ask permission", or rather, "it's better to catch an exception than test a condition."
```
try:
import numpy
HAS_NUMPY = True
except ImportError:
HAS_NUMPY = False
``` |
How to detect if numpy is installed | 5,016,186 | 19 | 2011-02-16T12:05:14Z | 5,016,218 | 35 | 2011-02-16T12:07:51Z | [
"python",
"numpy"
] | I'm writing Python code. I want to check if numpy and wxpython are installed on machine. How to do that?? | You can try importing them and then handle the ImportError if the module doesn't exist.
```
try:
import numpy
except ImportError:
print "numpy is not installed"
``` |
How to detect if numpy is installed | 5,016,186 | 19 | 2011-02-16T12:05:14Z | 19,766,562 | 11 | 2013-11-04T11:14:10Z | [
"python",
"numpy"
] | I'm writing Python code. I want to check if numpy and wxpython are installed on machine. How to do that?? | I think you also may use this
```
>> import numpy
>> print numpy.__version__
``` |
What is the difference between static files and media files in Django? | 5,016,589 | 47 | 2011-02-16T12:45:11Z | 5,016,626 | 45 | 2011-02-16T12:50:20Z | [
"python",
"django"
] | I'm moving to Django 1.3 and find this separation of media and static files a bit confusing. Here is how default `settings.py` looks like:
```
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media... | Static files are are meant for js/images etc, but media files is for user-uploaded content. |
What is the difference between static files and media files in Django? | 5,016,589 | 47 | 2011-02-16T12:45:11Z | 5,017,638 | 23 | 2011-02-16T14:29:51Z | [
"python",
"django"
] | I'm moving to Django 1.3 and find this separation of media and static files a bit confusing. Here is how default `settings.py` looks like:
```
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media... | As Uku Loskit said, static files are for things like your applications' css files, javascript files, images, etc. Media files are typically user or admin uploadable files.
Normally you will want `MEDIA_ROOT` and `STATIC_ROOT` to be separate directories. Keep in mind that `STATIC_ROOT` is where the management command `... |
What does underscoring methods connote? | 5,017,282 | 5 | 2011-02-16T13:52:01Z | 5,017,317 | 10 | 2011-02-16T13:56:03Z | [
"python",
"double-underscore"
] | I am relatively new to the Python language and encountered this in doing the following:
```
help(list)
```
Here is what I encountered:
```
__add__(...)
| x.__add__(y) <==> x+y
|
| __contains__(...)
| x.__contains__(y) <==> y in x
|
| __delitem__(...)
| x.__delitem__(y) <==> del x[y]
```
Regardi... | See [the Python style guide](http://www.python.org/dev/peps/pep-0008/) for a comprehensive explanation.
In practice:
```
the following special forms using leading or trailing
underscores are recognized (these can generally be combined with any case
convention):
- _single_leading_underscore: weak "internal use" indic... |
How to raise a numpy array to a power? (corresponding to repeated matrix multiplications, not elementwise) | 5,018,552 | 8 | 2011-02-16T15:46:22Z | 5,018,638 | 15 | 2011-02-16T15:53:37Z | [
"python",
"numpy",
"scipy"
] | I want to raise a 2-dimensional numpy `array`, let's call it `A`, to the power of some number `n`, but I have thus far failed to find the function or operator to do that.
I'm aware that I could cast it to the `matrix` type and use the fact that then (similar to what would be the behaviour in Matlab), `A**n` does just ... | I believe you want [`numpy.linalg.matrix_power`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.matrix_power.html)
As a quick example:
```
import numpy as np
x = np.arange(9).reshape(3,3)
y = np.matrix(x)
a = y**3
b = np.linalg.matrix_power(x, 3)
print a
print b
assert np.all(a==b)
```
This yield... |
Python using 'with' to delete a file after use | 5,019,209 | 4 | 2011-02-16T16:34:20Z | 5,020,214 | 7 | 2011-02-16T17:58:08Z | [
"python"
] | I am using an explicitly named file as a temporary file. In order to make sure I delete the file correctly I've had to create a wrapper class for open().
This seems to work but
A] is it safe?
B] is there a better way?
```
import os
string1 = """1. text line
2. text line
3. text line
4. text line
5. text line
"""
c... | I guess you can do a bit simpler with `contextlib.contextmanager`:
```
from contextlib import contextmanager
@contextmanager
def tempOpen( path, mode ):
# if this fails there is nothing left to do anyways
file = open(path, mode)
try:
yield file
finally:
file.close()
os.remove(... |
Python: A resilient, actually working CSV implementation for non-ascii? | 5,020,446 | 10 | 2011-02-16T18:19:36Z | 5,021,445 | 14 | 2011-02-16T19:57:22Z | [
"python",
"unicode",
"encoding"
] | [Update] Appreciate the answers and input all around, but **working code** would be most welcome. If you can supply code that can read the sample files you are king (or queen).
[Update 2] Thanks for the excellent answers and discussion. What I need to do with these is to read them in, parse them, and save parts of the... | You are attempting to apply a solution to a **different** problem. Note this:
def utf\_8\_encoder(**unicode\_csv\_data**)
You are feeding it `str` objects.
The problems with reading your non-ASCII CSV files is that you don't know the encoding and you don't know the delimiter. If you do know the encoding (and it's an... |
Python: get output from a command line which exits with nonzero exit code | 5,020,538 | 5 | 2011-02-16T18:26:34Z | 5,021,641 | 8 | 2011-02-16T20:17:40Z | [
"python",
"subprocess",
"stdout",
"windows-server-2008-r2",
"stderr"
] | I am Using `Python 2.7.1` on a Windows Server 2008 R2 x64 box.
I'm trying to get the output of a command line process which gives a nonzero exit status after outputting the information I need.
I was initially using `subprocess.check_output`, and catching the CalledProcessError which occurs with nonzero exit status, b... | You code works fine. Turns out that the process that you are calling is probably outputing to CON. See the following example
```
import subprocess
def check_output(command):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
output = proc... |
Python: convert camel case to space delimited using RegEx and taking Acronyms into account | 5,020,906 | 13 | 2011-02-16T19:06:21Z | 5,020,947 | 16 | 2011-02-16T19:08:58Z | [
"python",
"regex"
] | I am trying to convert camel case to space separated values using python. For example:
> divLineColor -> div Line Color
This line does that successfully:
```
label = re.sub("([A-Z])"," \g<0>",label)
```
The problem I am having is with things like `simpleBigURL` they should do this:
> simpleBigURL -> simple Big URL... | `\g<0>` references the matched string of the whole pattern while `\g<1>` refereces the matched string of the first subpattern (`(â¦)`). So you should use `\g<1>` and `\g<2>` instead:
```
label = re.sub("([a-z])([A-Z])","\g<1> \g<2>",label)
``` |
Python: convert camel case to space delimited using RegEx and taking Acronyms into account | 5,020,906 | 13 | 2011-02-16T19:06:21Z | 9,283,563 | 15 | 2012-02-14T20:15:28Z | [
"python",
"regex"
] | I am trying to convert camel case to space separated values using python. For example:
> divLineColor -> div Line Color
This line does that successfully:
```
label = re.sub("([A-Z])"," \g<0>",label)
```
The problem I am having is with things like `simpleBigURL` they should do this:
> simpleBigURL -> simple Big URL... | This should work with 'divLineColor', 'simpleBigURL', 'OldHTMLFile' and 'SQLServer'.
```
label = re.sub(r'((?<=[a-z])[A-Z]|(?<!\A)[A-Z](?=[a-z]))', r' \1', label)
```
Explanation:
```
label = re.sub(r"""
( # start the group
# alternative 1
(?<=[a-z]) # current position is prec... |
Why does the context hang around after a with statement? | 5,021,528 | 7 | 2011-02-16T20:05:41Z | 5,021,648 | 14 | 2011-02-16T20:18:22Z | [
"python",
"file-io"
] | I would like to know why a file object opened using the with() statement or in a block, remains in scope after exit. Are '<'closed file'>' objects ever cleaned up?
```
>>> with open('test.txt','w') as f:
... f.write('test')
...
>>> f
<closed file 'test.txt', mode 'w' at 0x00E014F0>
>>> f.close()
>>> if True:
...... | In Python new scopes (aka namespaces) are *only* created for modules, classes and functions, but not for any other statement, especially not for `with` and `if` blocks. Identifiers bound within the body of `with` or `for` statements are consequently bound in the inner-most surrounding scope, which is the top-level scop... |
How to draw a line outside of an axis in matplotlib (in figure coordinates)? | 5,021,663 | 9 | 2011-02-16T20:19:29Z | 5,022,412 | 12 | 2011-02-16T21:35:34Z | [
"python",
"matplotlib",
"plot"
] | Matplotlib has a function that writes text in figure coordinates (.figtext())
Is there a way to do the same but for drawing lines?
In particular my goal is to draw lines to group some ticks on the y-axis together. | This will do it:
```
from matplotlib import pyplot, lines
import numpy
x = numpy.linspace(0,10,100)
y = numpy.sin(x)*(1+x)
fig = pyplot.figure()
ax = pyplot.subplot(111)
ax.plot(x,y,label='a')
# new clear axis overlay with 0-1 limits
ax2 = pyplot.axes([0,0,1,1], axisbg=(1,1,1,0))
x,y = numpy.array([[0.05, 0.1, 0.9... |
How to serialize SqlAlchemy result to JSON? | 5,022,066 | 68 | 2011-02-16T21:04:05Z | 7,032,311 | 27 | 2011-08-11T20:20:52Z | [
"python",
"json",
"sqlalchemy"
] | Django has some good automatic serialization of ORM models returned from DB to JSON format.
How to serialize SQLAlchemy query result to JSON format?
I tried `jsonpickle.encode` but it encodes query object itself.
I tried `json.dumps(items)` but it returns
```
TypeError: <Product('3', 'some name', 'some desc')> is no... | You can convert a RowProxy to a dict like this:
```
d = dict(row.items())
```
Then serialize that to JSON ( you will have to specify an encoder for things like `datetime` values )
It's not that hard if you just want one record ( and not a full hierarchy of related records ).
```
json.dumps([(dict(row.items())) for ... |
How to serialize SqlAlchemy result to JSON? | 5,022,066 | 68 | 2011-02-16T21:04:05Z | 10,664,192 | 65 | 2012-05-19T10:05:18Z | [
"python",
"json",
"sqlalchemy"
] | Django has some good automatic serialization of ORM models returned from DB to JSON format.
How to serialize SQLAlchemy query result to JSON format?
I tried `jsonpickle.encode` but it encodes query object itself.
I tried `json.dumps(items)` but it returns
```
TypeError: <Product('3', 'some name', 'some desc')> is no... | # A flat implementation
You could use something like this:
```
from sqlalchemy.ext.declarative import DeclarativeMeta
class AlchemyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj.__class__, DeclarativeMeta):
# an SQLAlchemy class
fields = {}
for field in [x for x in di... |
How to serialize SqlAlchemy result to JSON? | 5,022,066 | 68 | 2011-02-16T21:04:05Z | 11,884,806 | 107 | 2012-08-09T13:42:41Z | [
"python",
"json",
"sqlalchemy"
] | Django has some good automatic serialization of ORM models returned from DB to JSON format.
How to serialize SQLAlchemy query result to JSON format?
I tried `jsonpickle.encode` but it encodes query object itself.
I tried `json.dumps(items)` but it returns
```
TypeError: <Product('3', 'some name', 'some desc')> is no... | You could just output your object as a dict:
```
class User:
def as_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
```
And then you use User.as\_dict() to serialize your object.
As explained in [Convert sqlalchemy row object to python dict](http://stackoverflow.com/quest... |
How to serialize SqlAlchemy result to JSON? | 5,022,066 | 68 | 2011-02-16T21:04:05Z | 23,607,848 | 13 | 2014-05-12T11:31:58Z | [
"python",
"json",
"sqlalchemy"
] | Django has some good automatic serialization of ORM models returned from DB to JSON format.
How to serialize SQLAlchemy query result to JSON format?
I tried `jsonpickle.encode` but it encodes query object itself.
I tried `json.dumps(items)` but it returns
```
TypeError: <Product('3', 'some name', 'some desc')> is no... | I recommend using a recent surfaced library [marshmallow](https://marshmallow.readthedocs.io/). It allows you to create serializers to represent your model instances with support to relations and nested objects.
Have a look at theier [SQLAlchemy Example](https://marshmallow.readthedocs.io/en/latest/examples.html#quote... |
How to serialize SqlAlchemy result to JSON? | 5,022,066 | 68 | 2011-02-16T21:04:05Z | 25,696,535 | 12 | 2014-09-06T03:37:21Z | [
"python",
"json",
"sqlalchemy"
] | Django has some good automatic serialization of ORM models returned from DB to JSON format.
How to serialize SQLAlchemy query result to JSON format?
I tried `jsonpickle.encode` but it encodes query object itself.
I tried `json.dumps(items)` but it returns
```
TypeError: <Product('3', 'some name', 'some desc')> is no... | [Flask-JsonTools](https://pypi.python.org/pypi/flask_jsontools) package has an implementation of [JsonSerializableBase](https://github.com/kolypto/py-flask-jsontools#jsonserializablebase) Base class for your models.
Usage:
```
from sqlalchemy.ext.declarative import declarative_base
from flask.ext.jsontools import Jso... |
How can I get the last-modified time with python3 urllib? | 5,022,083 | 6 | 2011-02-16T21:05:24Z | 5,023,160 | 9 | 2011-02-16T22:50:31Z | [
"python",
"python-3.x",
"urllib",
"2to3"
] | I'm porting over a [program of mine](http://github.com/Daenyth/pkgtools/blob/2to3/scripts/pkgfile.py#L190) from python2 to python3, and I'm hitting the following error: `AttributeError: 'HTTPMessage' object has no attribute 'getdate'`
Here's the code:
```
conn = urllib.request.urlopen(fileslist, timeout=30)
last_modi... | `conn.headers['last-modified']` works under both Python 2 and Python 3. Comparing filestamps seems reasonable to me. |
Understanding the behavior of Python's set | 5,022,247 | 3 | 2011-02-16T21:19:40Z | 5,022,290 | 10 | 2011-02-16T21:23:34Z | [
"python",
"set"
] | The documentation for the built-in type `set` says:
```
class set([iterable])
```
> Return a new set or frozenset object
> whose elements are taken from
> iterable. The elements of a set must
> be hashable.
That is all right but why does this work:
```
>>> l = range(10)
>>> s = set(l)
>>> s
set([0, 1, 2, 3, 4, 5, 6... | When you initialize a set, you provide a list of values that must *each* be hashable.
```
s = set()
s.add([10])
```
is the same as
```
s = set([[10]])
```
which throws the same error that you're seeing right now. |
Converting date from Python to Javascript | 5,022,447 | 22 | 2011-02-16T21:39:31Z | 5,022,488 | 33 | 2011-02-16T21:43:00Z | [
"javascript",
"python",
"date"
] | I'm having difficulty working with dates in Python and Javascript.
```
>>> d = date(2004, 01, 01)
>>> d
datetime.date(2004, 1, 1)
>>> time.mktime(d.timetuple())
1072944000.0
```
Then, in Javascript (data sent over Ajax):
```
>>> new Date(1072944000.0)
Tue Jan 13 1970 02:02:24 GMT-0800 (PST) {}
```
I'm confused. Sho... | Javascript's `Date()` takes milliseconds as an argument. Python's uses seconds. You have to multiply by 1,000. |
Converting date from Python to Javascript | 5,022,447 | 22 | 2011-02-16T21:39:31Z | 5,022,491 | 11 | 2011-02-16T21:43:20Z | [
"javascript",
"python",
"date"
] | I'm having difficulty working with dates in Python and Javascript.
```
>>> d = date(2004, 01, 01)
>>> d
datetime.date(2004, 1, 1)
>>> time.mktime(d.timetuple())
1072944000.0
```
Then, in Javascript (data sent over Ajax):
```
>>> new Date(1072944000.0)
Tue Jan 13 1970 02:02:24 GMT-0800 (PST) {}
```
I'm confused. Sho... | Python is returning the time since the epoch in seconds. Javascript takes the time in milliseconds. Multiply the time by 1000 before passing it to `Date()` and you should get the expected result.
```
new Date(1072944000.0 * 1000)
``` |
Converting date from Python to Javascript | 5,022,447 | 22 | 2011-02-16T21:39:31Z | 14,469,780 | 13 | 2013-01-22T23:11:47Z | [
"javascript",
"python",
"date"
] | I'm having difficulty working with dates in Python and Javascript.
```
>>> d = date(2004, 01, 01)
>>> d
datetime.date(2004, 1, 1)
>>> time.mktime(d.timetuple())
1072944000.0
```
Then, in Javascript (data sent over Ajax):
```
>>> new Date(1072944000.0)
Tue Jan 13 1970 02:02:24 GMT-0800 (PST) {}
```
I'm confused. Sho... | Python:
```
import datetime, time
d = datetime.datetime.utcnow()
for_js = int(time.mktime(d.timetuple())) * 1000
```
Then in JS:
```
new Date({{ for_js }});
```
In Flask you can do:
```
@app.template_filter('date_to_millis')
def date_to_millis(d):
"""Converts a datetime object to the number of milliseconds sin... |
Python subclass inheritance | 5,022,506 | 2 | 2011-02-16T21:44:33Z | 5,022,821 | 7 | 2011-02-16T22:17:11Z | [
"python",
"inheritance"
] | I am trying to build some classes that inherit from a parent class, which contains subclasses that inherit from other parent classes. But when I change attributes in the subclasses in any children, the change affects all child classes. I am looking to avoid having to create instances, as I am using that feature later.
... | The behaviour you are seeing is exactly what you should expect. When you define a class
```
>>> class Foo(object): pass
...
```
you can modify *that class* -- not instances of it, the class itself -- because the class is just another object, stored in the variable Foo. So, for instance, you can get and set attributes... |
how do I measure the memory usage of an object in python? | 5,022,725 | 8 | 2011-02-16T22:07:37Z | 5,023,549 | 14 | 2011-02-16T23:38:26Z | [
"python",
"memory-management"
] | I have a python class "foo" that contains:
* data (ints, floats)
* lists (of ints, of floats, and of other objects)
* dictionaries (of ints, of floats, of other objects)
Assuming that there are no back-references (cycles), is there an easy way to measure the total memory usage of a "foo" object ?
Essentially, I am l... | Try [Pympler](http://pypi.python.org/pypi/Pympler/), which describes itself as *"A development tool to measure, monitor and analyze the memory behavior of Python objects."*
Something along the lines of
```
>>> import pympler
>>> print pympler.asizeof.asizeof(your_object)
```
has been helpful to me in the past.
You ... |
how is this a non-sequence? | 5,024,059 | 3 | 2011-02-17T01:07:34Z | 5,024,064 | 8 | 2011-02-17T01:08:51Z | [
"python",
"list",
"sequences",
"list-comprehension"
] | I'm running a list comprehension of a list of numbers as strings so for example the list looks like this
```
vals = ['0.13', '324', '0.23432']
```
and try a list comprehension like this:
```
best = [x for x in vals > 0.02]
```
and I get a TypeError: iteration over non-sequence.
Isn't a list a sequence that should ... | You need to check if each item is greater than '0.02', not whether the sequence is greater.
```
best = [x for x in vals if x > '0.02']
```
Your original expression, `[x for x in vals > '0.02']` is parsed as `[x for x in (vals > '0.02')]`. Since `vals > '0.02'` is a boolean value, and not a sequence, it's not possible... |
Python 2.7 try and except ValueError | 5,025,399 | 5 | 2011-02-17T05:27:20Z | 5,025,882 | 15 | 2011-02-17T06:47:01Z | [
"python",
"exception-handling"
] | I query user input which is expected to be an int by using int(raw\_input(...))
However when the user doesn't enter an integer, i.e. just hits return, I get a ValueError.
```
def inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue):
rowPos = int(raw_input("Please enter the row, 0 indexed."))
... | A quick and dirty solution is:
```
parsed = False
while not parsed:
try:
x = int(raw_input('Enter the value:'))
parsed = True # we only get here if the previous line didn't throw an exception
except ValueError:
print 'Invalid value!'
```
This will keep prompting the user for input unti... |
How do you set up a Flask application with SQLAlchemy for testing? | 5,025,720 | 22 | 2011-02-17T06:23:58Z | 12,700,343 | 9 | 2012-10-03T00:26:23Z | [
"python",
"unit-testing",
"testing",
"sqlalchemy",
"flask"
] | It seems common practice in Flask to start like this:
```
from flask import Flask
from flaskext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
SQLALCHEMY_DATABASE_URI = 'something'
app.config.from_object(__name__)
db = SQLAlchemy(app)
```
And then import and use `app` and `db` everywhere. But when you create `db`... | Your instinct to use environment variables is correct. However, there is some danger of running unit tests with the wrong db. Also, you may not want to `connect_db` with every request and everywhere you want to use `db`. You can use a config directory and environment variables which you set explicitly. This is the best... |
Why input() gives an error when I just press enter? | 5,025,920 | 9 | 2011-02-17T06:53:52Z | 5,025,939 | 16 | 2011-02-17T06:57:04Z | [
"python"
] | I have the following python code:
```
print 'This is a simple game.'
input('Press enter to continue . . .')
print 'Choose an option:'
...
```
But when I press `Enter` button, I get the following error:
```
Traceback (most recent call last):
File "E:/4.Python/temp.py", line 2, in <module>
input('Press enter to... | For Python 2, you want `raw_input`, not `input`. The former will read a line. The latter will read a line and try to execute it, not advisable if you don't want your code being corrupted by the person entering data.
For example, they could do something like call arbitrary functions, as per the following example:
```
... |
how to test if one python module has been imported? | 5,027,352 | 37 | 2011-02-17T09:54:40Z | 5,027,393 | 39 | 2011-02-17T09:58:34Z | [
"python",
"testing",
"module",
"import"
] | How to test if a module has been imported in python?
for example I need the basics:
```
if not has_imported("sys"):
import sys
```
also
```
if not has_imported("sys.path"):
from sys import path
```
Thanks!
Rgs.
Thanks for all of your comments:
the code been pasted here.
[auto import all sub modules in a f... | If you want to optimize by not importing things twice, save yourself the hassle because Python already takes care of this.
If you *need* this to avoid `NameErrors` or something: Fix your sloppy coding - make sure you don't need this, i.e. define (import) everything before you ever use it (in the case if imports: once,... |
how to test if one python module has been imported? | 5,027,352 | 37 | 2011-02-17T09:54:40Z | 29,126,791 | 10 | 2015-03-18T15:57:55Z | [
"python",
"testing",
"module",
"import"
] | How to test if a module has been imported in python?
for example I need the basics:
```
if not has_imported("sys"):
import sys
```
also
```
if not has_imported("sys.path"):
from sys import path
```
Thanks!
Rgs.
Thanks for all of your comments:
the code been pasted here.
[auto import all sub modules in a f... | I feel the answer that has been accepted is not fully correct.
Python **still has overhead** when importing the same module multiple times. Python **handles it without giving you an error**, sure, but that doesn't mean it won't slow down your script. As you will see from the URL below, there is **significant** overhea... |
constants in Python: at the root of the module or in a namespace inside the module? | 5,027,400 | 17 | 2011-02-17T09:59:07Z | 5,027,545 | 7 | 2011-02-17T10:11:33Z | [
"python"
] | I'm building a Python module with about a hundred constants.
I would like to avoid naming issues when people import my module so I was wondering what would be the best way to do it.
```
MY_CONSTANT = 1
MY_SECOND_CONSTANT = 2
...
MY2_CONSTANT = "a"
MY2_SECOND_CONSTANT = "b"
...
```
Or
```
class My:
CONSTANT = 1
... | From [style guide](http://www.python.org/dev/peps/pep-0008/):
Constants are usually defined on a module level and written in all
capital letters with underscores separating words. Examples include
MAX\_OVERFLOW and TOTAL. |
constants in Python: at the root of the module or in a namespace inside the module? | 5,027,400 | 17 | 2011-02-17T09:59:07Z | 5,027,573 | 13 | 2011-02-17T10:14:12Z | [
"python"
] | I'm building a Python module with about a hundred constants.
I would like to avoid naming issues when people import my module so I was wondering what would be the best way to do it.
```
MY_CONSTANT = 1
MY_SECOND_CONSTANT = 2
...
MY2_CONSTANT = "a"
MY2_SECOND_CONSTANT = "b"
...
```
Or
```
class My:
CONSTANT = 1
... | Every module provides its own namespace, so there's no need to create another one.
Having module `foo.py`:
```
FOO = 1
BAR = 2
SHMOO = 3
```
you may use it like this:
```
import foo
foo.BAR
``` |
constants in Python: at the root of the module or in a namespace inside the module? | 5,027,400 | 17 | 2011-02-17T09:59:07Z | 5,027,585 | 14 | 2011-02-17T10:15:33Z | [
"python"
] | I'm building a Python module with about a hundred constants.
I would like to avoid naming issues when people import my module so I was wondering what would be the best way to do it.
```
MY_CONSTANT = 1
MY_SECOND_CONSTANT = 2
...
MY2_CONSTANT = "a"
MY2_SECOND_CONSTANT = "b"
...
```
Or
```
class My:
CONSTANT = 1
... | Well, it depends. Usually, constants are defined at module level. But if you have many constants for `category_a` and `category_b`, it might even make sense to add a subpackage `constants` with modules `constants.category_a` and `constants.category_b`.
I would refrain from using a `class` - it could be instanciated, w... |
python check if function accepts **kwargs | 5,028,425 | 4 | 2011-02-17T11:38:30Z | 5,028,449 | 7 | 2011-02-17T11:40:53Z | [
"python"
] | is there a way to check if a function accepts \*\*kwargs before calling it e.g.
```
def FuncA(**kwargs):
print 'ok'
def FuncB(id = None):
print 'ok'
def FuncC():
print 'ok'
args = {'id': '1'}
FuncA(**args)
FuncB(**args)
FuncC(**args)
```
When I run this FuncA and FuncB would be okay but FuncC errors w... | ```
try:
f(**kwargs)
except TypeError:
#do stuff
```
It's [easier to ask forgiveness than permission](http://docs.python.org/glossary.html#eafp). |
matching unicode characters in python regular expressions | 5,028,717 | 16 | 2011-02-17T12:08:15Z | 5,028,826 | 28 | 2011-02-17T12:18:18Z | [
"python",
"regex",
"unicode",
"non-ascii-characters",
"character-properties"
] | I have read thru the other questions at Stackoverflow, but still no closer. Sorry, if this is allready answered, but I didn`t get anything proposed there to work.
```
>>> import re
>>> m = re.match(r'^/by_tag/(?P<tag>\w+)/(?P<filename>(\w|[.,!#%{}()@])+)$', '/by_tag/xmas/xmas1.jpg')
>>> print m.groupdict()
{'tag': 'xm... | You need to specify the `re.UNICODE` flag, *and* input your string as a Unicode string by using the `u` prefix:
```
>>> re.match(r'^/by_tag/(?P<tag>\w+)/(?P<filename>(\w|[.,!#%{}()@])+)$', u'/by_tag/påske/øyfjell.jpg', re.UNICODE).groupdict()
{'tag': u'p\xe5ske', 'filename': u'\xf8yfjell.jpg'}
```
This is in Python... |
How to set choices in dynamic with Django choicefield? | 5,028,731 | 5 | 2011-02-17T12:09:19Z | 5,029,262 | 14 | 2011-02-17T13:02:09Z | [
"python",
"django"
] | I want to set choices in dynamic.
I used \_\_set\_choices method but, when request method is POST,
is\_valid method always return False.
```
if request.method=='POST':
_form = MyForm(request.POST)
if _form.is_valid():
#something to do
``` | I often set the choices dynamicly in the constructor:
```
class MyForm(BaseForm):
afield = forms.ChoiceField(choices=INITIAL_CHOICES)
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['afield'].choices = my_computed_choices
``` |
Python: defaultdict of defaultdict? | 5,029,934 | 150 | 2011-02-17T14:04:22Z | 5,029,958 | 277 | 2011-02-17T14:06:19Z | [
"python",
"collections"
] | Is there a way to have a `defaultdict(defaultdict(int))` in order to make the following code work?
```
for x in stuff:
d[x.a][x.b] += x.c_int
```
`d` needs to be built ad-hoc, depending on `x.a` and `x.b` elements.
I could use:
```
for x in stuff:
d[x.a,x.b] += x.c_int
```
but then I wouldn't be able to us... | Yes like this:
```
defaultdict(lambda : defaultdict(int))
``` |
Python: defaultdict of defaultdict? | 5,029,934 | 150 | 2011-02-17T14:04:22Z | 5,029,989 | 32 | 2011-02-17T14:08:34Z | [
"python",
"collections"
] | Is there a way to have a `defaultdict(defaultdict(int))` in order to make the following code work?
```
for x in stuff:
d[x.a][x.b] += x.c_int
```
`d` needs to be built ad-hoc, depending on `x.a` and `x.b` elements.
I could use:
```
for x in stuff:
d[x.a,x.b] += x.c_int
```
but then I wouldn't be able to us... | The parameter to the defaultdict constructor is the function which will be called for building new elements. So let's use a lambda !
```
>>> from collections import defaultdict
>>> d = defaultdict(lambda : defaultdict(int))
>>> print d[0]
defaultdict(<type 'int'>, {})
>>> print d[0]["x"]
0
```
Since Python 2.7, there... |
Python: defaultdict of defaultdict? | 5,029,934 | 150 | 2011-02-17T14:04:22Z | 5,030,081 | 16 | 2011-02-17T14:15:46Z | [
"python",
"collections"
] | Is there a way to have a `defaultdict(defaultdict(int))` in order to make the following code work?
```
for x in stuff:
d[x.a][x.b] += x.c_int
```
`d` needs to be built ad-hoc, depending on `x.a` and `x.b` elements.
I could use:
```
for x in stuff:
d[x.a,x.b] += x.c_int
```
but then I wouldn't be able to us... | I find it slightly more elegant to use `partial`:
```
import functools
dd_int = functools.partial(defaultdict, int)
defaultdict(dd_int)
```
Of course, this is the same as a lambda. |
How to use OpenCV in Python? | 5,030,362 | 24 | 2011-02-17T14:40:21Z | 5,092,295 | 11 | 2011-02-23T14:37:38Z | [
"python",
"opencv",
"importerror",
"python-import"
] | I have just installed OpenCV on my Windows 7 machine. As a result I get a new directory:
`C:\OpenCV2.2\Python2.7\Lib\site-packages`
In this directory I have two files: `cv.lib` and `cv.pyd`.
Then I try to use the opencv from Python. I do the following:
```
import sys
sys.path.append('C:\OpenCV2.2\Python2.7\Lib\site... | The problem was resolved. The following steps has been done:
1. A new version of python (version 2.7) has been installed.
2. After that I still was unable to run OpenCV because I had some problems with the numpy library.
3. I tired to install numpy but the installer did not see my new version of the Python.
4. I delet... |
How to read/write binary 16-bit data in Python 2.x? | 5,030,919 | 5 | 2011-02-17T15:26:10Z | 5,031,191 | 9 | 2011-02-17T15:47:32Z | [
"python",
"binary"
] | I have to read and write binary data, where each element of data:
* size = 2 bytes (16 bit)
* encoding = signed 2's complement
* endiannes = big or little (must be
selectable)
Is it possible without using any external module? If yes,
1. How to read such data from a binary
file using read() into an array L of
... | I think you are best off using the [`array`](http://docs.python.org/library/array.html) module. It stores data in system byte order by default, but you can use `array.byteswap()` to convert between byte orders, and you can use `sys.byteorder` to query the system byte order. Example:
```
# Create an array of 16-bit sig... |
Python 3 Syntax Changes | 5,031,625 | 7 | 2011-02-17T16:23:18Z | 5,031,670 | 10 | 2011-02-17T16:27:46Z | [
"python",
"syntax",
"python-3.x",
"python-2.x"
] | So my work which had used older Python 2 is doing some code updating, anyways I am just learning python and am actually pretty new here, but what are the major syntax changes that went from 2-->3
Or is there really even that much syntax changes at all (like I know print got changed, but what else MAJOR)
Thanks | Whatâs New In Python 3.0:
<http://docs.python.org/release/3.0.1/whatsnew/3.0.html>
PEP: 3000 - Python 3000:
<http://www.python.org/dev/peps/pep-3000/>
PEP: 3099 - Things that will Not Change in Python 3000:
<http://www.python.org/dev/peps/pep-3099/> |
Python - Cleanest way to override __init__ where an optional kwarg must be used after the super() call? | 5,031,711 | 28 | 2011-02-17T16:31:38Z | 5,031,752 | 40 | 2011-02-17T16:35:28Z | [
"python",
"django"
] | I love how beautiful python looks/feels and I'm hoping this can be cleaner (readability is awesome).
What's a clean way to accept an optional keyword argument when overriding a subclassed **init** where the optional `kwarg` has to be used **after** the `super()` call?
I have a django form where I'd like to accept an ... | I usually just do essentially what you're doing here. However, you can shorten/clean up your code by supplying a default argument to `dict.pop`:
```
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(BaseCheckoutForm, self).__init__(*args, **kwargs)
if user is not None:
sel... |
Should I use Python 2.7 32 bit or 64 bit with Windows 7 | 5,032,956 | 20 | 2011-02-17T18:25:55Z | 5,032,978 | 27 | 2011-02-17T18:28:12Z | [
"python",
"django",
"windows-7"
] | I am setting up Django, and am trying to decide whether to use the 32 bit or 64 bit version of Python 2.7 on my Windows 7 machine.
I've seen the issues with the 64 bit installer, but the real question is whether or not all of the necessary libraries are available for 64 bit, or whether one version has any other issues... | ```
if you need more than 4gb of RAM to work with:
return 64
else:
return 32
``` |
Should I use Python 2.7 32 bit or 64 bit with Windows 7 | 5,032,956 | 20 | 2011-02-17T18:25:55Z | 5,033,019 | 26 | 2011-02-17T18:32:14Z | [
"python",
"django",
"windows-7"
] | I am setting up Django, and am trying to decide whether to use the 32 bit or 64 bit version of Python 2.7 on my Windows 7 machine.
I've seen the issues with the 64 bit installer, but the real question is whether or not all of the necessary libraries are available for 64 bit, or whether one version has any other issues... | I recommend the 32-bit one unless you are going to exhaust the address space. Many third-party modules like OpenCV and Numpy are considerably easier to install with 32-bit Python. (You can build those modules from source to get them to work with 64-bit Python but that's probably more time and effort than necessary in m... |
Is there a reason why Python's ctypes.CDLL cannot automatically generate restype and argtypes from C header files? | 5,033,162 | 15 | 2011-02-17T18:45:35Z | 5,033,193 | 9 | 2011-02-17T18:48:42Z | [
"python"
] | For example, it would be nice to be able to do this:
```
from ctypes import CDLL
mylib = CDLL('/my/path/mylib.so',header='/some/path/mylib.h')
```
instead of
```
from ctypes import *
mylib = CDLL('/my/path/mylib.so')
mylib.f.restype = c_double
mylib.f.argtypes = [c_double, c_double]
mylib.g.restype = c_int
mylib.g.a... | I asked myself the same question and before I traveled down that road too far, I ran into ctypesgen:
<http://code.google.com/p/ctypesgen/>
It will handle all of this for you, although you will need to do a little learning up front. We use ctypesgen to generate one version of the Python bindings for the Subversion bin... |
sqlachemy: cascade delete | 5,033,547 | 40 | 2011-02-17T19:22:54Z | 5,034,070 | 80 | 2011-02-17T20:15:00Z | [
"python",
"sqlalchemy"
] | I must be missing something trivial with SQLAlchemy's cascade options because I cannot get a simple cascade delete to operate correctly -- if a parent element is a deleted, the children persist, with `null` foreign keys.
I've put a concise test case here:
```
from sqlalchemy import Column, Integer, ForeignKey
from sq... | The problem is that sqlalchemy considers `Child` as the parent, because that is where you defined your relationship (it doesn't care that you called it "Child" of course).
If you define the relationship on the `Parent` class instead, it will work:
```
children = relationship("Child", cascade="all,delete", backref="pa... |
sqlachemy: cascade delete | 5,033,547 | 40 | 2011-02-17T19:22:54Z | 12,801,654 | 36 | 2012-10-09T13:52:11Z | [
"python",
"sqlalchemy"
] | I must be missing something trivial with SQLAlchemy's cascade options because I cannot get a simple cascade delete to operate correctly -- if a parent element is a deleted, the children persist, with `null` foreign keys.
I've put a concise test case here:
```
from sqlalchemy import Column, Integer, ForeignKey
from sq... | @Steven's asnwer is good when you are deleting through `session.delete()` which never happens in my case. I noticed that most of the time I delete through `session.query().filter().delete()` (which doesn't put elements in the memory and deletes directly from db).
Using this method sqlalchemy's `cascade='all, delete'` d... |
How do I get Pyflakes to ignore a statement? | 5,033,727 | 79 | 2011-02-17T19:40:56Z | 5,304,478 | 7 | 2011-03-14T21:01:07Z | [
"python",
"pyflakes"
] | A lot of our modules start with:
```
try:
import json
except ImportError:
from django.utils import simplejson as json # Python 2.4 fallback.
```
...and it's the only Pyflakes warning in the entire file:
```
foo/bar.py:14: redefinition of unused 'json' from line 12
```
How can I get Pyflakes to ignore this?... | Yep, unfortunately dimod.org is down together with all goodies.
Looking at the pyflakes code, it seems to me that pyflakes is designed so that it will be easy to use it as an "embedded fast checker".
For implementing ignore functionality you will need to write your own that calls the pyflakes checker.
Here you can f... |
How do I get Pyflakes to ignore a statement? | 5,033,727 | 79 | 2011-02-17T19:40:56Z | 10,506,715 | 119 | 2012-05-08T21:22:30Z | [
"python",
"pyflakes"
] | A lot of our modules start with:
```
try:
import json
except ImportError:
from django.utils import simplejson as json # Python 2.4 fallback.
```
...and it's the only Pyflakes warning in the entire file:
```
foo/bar.py:14: redefinition of unused 'json' from line 12
```
How can I get Pyflakes to ignore this?... | If you can use [flake8](http://pypi.python.org/pypi/flake8) instead - which wraps pyflakes as well as the pep8 checker - a line ending with
`# NOQA`
(in which the space is significant - 2 spaces between the end of the code and the `#`, one between it and the `NOQA` text) will tell the checker to ignore any errors on ... |
How do I get Pyflakes to ignore a statement? | 5,033,727 | 79 | 2011-02-17T19:40:56Z | 12,121,404 | 29 | 2012-08-25T11:01:30Z | [
"python",
"pyflakes"
] | A lot of our modules start with:
```
try:
import json
except ImportError:
from django.utils import simplejson as json # Python 2.4 fallback.
```
...and it's the only Pyflakes warning in the entire file:
```
foo/bar.py:14: redefinition of unused 'json' from line 12
```
How can I get Pyflakes to ignore this?... | I know this was questioned some time ago and is already answered.
But I wanted to add what I usually use:
```
try:
import json
assert json # silence pyflakes
except ImportError:
from django.utils import simplejson as json # Python 2.4 fallback.
``` |
How do I pass large numpy arrays between python subprocesses without saving to disk? | 5,033,799 | 21 | 2011-02-17T19:47:57Z | 5,034,106 | 8 | 2011-02-17T20:18:11Z | [
"python",
"numpy",
"subprocess",
"pass-by-reference",
"ctypes"
] | Is there a good way to pass a large chunk of data between two python subprocesses without using the disk? Here's a cartoon example of what I'm hoping to accomplish:
```
import sys, subprocess, numpy
cmdString = """
import sys, numpy
done = False
while not done:
cmd = raw_input()
if cmd == 'done':
don... | Basically, you just want to share a block of memory between processes and view it as a numpy array, right?
In that case, have a look at this (Posted to numpy-discussion by Nadav Horesh awhile back, not my work). There are a couple of similar implementations (some more flexible), but they all essentially use this princ... |
How do I pass large numpy arrays between python subprocesses without saving to disk? | 5,033,799 | 21 | 2011-02-17T19:47:57Z | 5,036,766 | 20 | 2011-02-18T01:26:14Z | [
"python",
"numpy",
"subprocess",
"pass-by-reference",
"ctypes"
] | Is there a good way to pass a large chunk of data between two python subprocesses without using the disk? Here's a cartoon example of what I'm hoping to accomplish:
```
import sys, subprocess, numpy
cmdString = """
import sys, numpy
done = False
while not done:
cmd = raw_input()
if cmd == 'done':
don... | While googling around for more information about the code Joe Kington posted, I found the [numpy-sharedmem](https://bitbucket.org/cleemesser/numpy-sharedmem/src) package. Judging from this [numpy/multiprocessing tutorial](http://folk.uio.no/sturlamo/python/multiprocessing-tutorial.pdf) it seems to share the same intell... |
pycurl - 302 redirect/page moved | 5,033,890 | 3 | 2011-02-17T19:57:08Z | 5,047,522 | 7 | 2011-02-18T23:07:08Z | [
"python",
"redirect",
"http-status-code-302",
"pycurl"
] | Trying to successfully get a page/headers (response/request) using pycurl. I can successfully get it using java/htmlunit.
I'm missing something subtle to get to the new/redirected page.
I was/am trying to get the "new" redirected url, that is then fed into the pycurl for the new page.
thanks
The sample test code is... | Just set the FOLLOWLOCATION flag to 1:
```
crl.setopt(pycurl.FOLLOWLOCATION, 1)
```
The curl will proceed to the next location on 301/302. |
Python super method and calling alternatives | 5,033,903 | 45 | 2011-02-17T19:58:54Z | 5,034,058 | 7 | 2011-02-17T20:13:57Z | [
"python",
"class",
"super"
] | I see everywhere examples that super-class methods should be called by:
```
super(SuperClass, instance).method(args)
```
Is there any disadvantage to doing:
```
SuperClass.method(instance, args)
``` | There's no penalty as-is, though your example is somewhat misguided. In the first example, it should be
```
super(SubClass, instance).method(args) # Sub, not SuperClass
```
and that leads me to quote the [Python docs](http://docs.python.org/library/functions.html#super):
> There are two typical use cases for `super... |
Python super method and calling alternatives | 5,033,903 | 45 | 2011-02-17T19:58:54Z | 5,034,440 | 88 | 2011-02-17T20:46:14Z | [
"python",
"class",
"super"
] | I see everywhere examples that super-class methods should be called by:
```
super(SuperClass, instance).method(args)
```
Is there any disadvantage to doing:
```
SuperClass.method(instance, args)
``` | Consider the following situation:
```
class A(object):
def __init__(self):
print('Running A.__init__')
super(A,self).__init__()
class B(A):
def __init__(self):
print('Running B.__init__')
# super(B,self).__init__()
A.__init__(self)
class C(A):
def __init__(... |
Accessing global attributes from inside a macro in Jinja2 | 5,034,437 | 7 | 2011-02-17T20:46:00Z | 5,035,382 | 8 | 2011-02-17T22:17:27Z | [
"python",
"jinja2"
] | I've been using macros in Jinja2 extensively and find them very DRY-ish; but there is one thing bothering me: how to access global stuff from macros? It would be really neat if I could somehow access url\_for() natively from a macro. | You can make any callable available in the Jinja environment:
```
jinja_env = Environment(...)
jinja_env.globals['url_for'] = url_for
```
For example, this output u'foobar' in a shell:
```
from jinja2 import Environment
env = Environment()
env.globals['foo'] = lambda: "foobar"
env.from_string('{% macro bar() %}{{ fo... |
Django Debug Toolbar Install Problems | 5,034,850 | 5 | 2011-02-17T21:23:58Z | 7,300,251 | 8 | 2011-09-04T15:31:59Z | [
"python",
"django",
"django-debug-toolbar"
] | I am having issues trying to get the [django-debug-toolbar](https://github.com/dcramer/django-debug-toolbar/) up and running. I have all of the necessary info added to `INSTALLED_APPS`, `MIDDLEWARE_CLASSES`, and my ip is in the `INTERNAL_IPS` tuple. I have run the setup.py script and everything seems to load fine as I ... | I had this same issue for awhile.
Have you tried logging into the admin panel? If the toolbar displays there, but does not display in your code, it's very likely that you are missing the opening and closing tags in your template. By default, django debug toolbar attaches to the BODY tag, though you can change this beh... |
Submit without the use of a submit button, Mechanize | 5,035,390 | 10 | 2011-02-17T22:17:55Z | 6,894,179 | 10 | 2011-08-01T04:17:29Z | [
"python",
"mechanize"
] | So, I started out with Mechanize, and apparently the first thing I try it on is a monkey-rhino-level high JavaScript navigated site.
Now the thing I'm stuck on is submitting the form.
Normally I'd do a submit using the Mechanize built-in submit() function.
```
import mechanize
browser = mechanize.Browser()
browser.... | Three ways:
The first method is preferable if the form is submitted using the POST/GET method, otherwise you'll have to resort to second and third method.
1. Submitting the form manually and check for POST/GET requests, their parameters and the post url required to submit the form. Popular tools for checking headers ... |
Python Parameter pass to prevent sql injection. Why is this giving an error? | 5,035,580 | 3 | 2011-02-17T22:36:50Z | 5,036,459 | 8 | 2011-02-18T00:33:43Z | [
"python",
"oracle"
] | ```
from django.db import connection, transaction
def pk_dt_catalog(p_CAT_ID,p_COMMONS_ID):
c1 = connection.cursor()
sql = "SELECT COMMONS_ID, CAT_ID, CAT_NAME
FROM DT_CATALOG"
sql = sql + " WHERE CAT_ID = %s
AND COMMONS_ID = %s "
param =(p_CAT_ID, p_COMMONS_ID)
... | In your code, you're using `%s` which is python substition string syntax, which expects the substitution values on the same line, e.g.
```
sql = sql + " WHERE CAT_ID = %s
AND COMMONS_ID = %s " % (p_CAT_ID, p_COMMONS_ID)
```
However, this (as stated already) is not the best way because (a) it can be a ... |
Python String Argument Parsing | 5,035,702 | 3 | 2011-02-17T22:52:35Z | 5,035,733 | 11 | 2011-02-17T22:56:34Z | [
"python"
] | I am working with the cmd class in python and it passes me all of my arguments as one big string. What is the best way to tokenize this arg string into an array of args[].
Example:
```
args = 'arg arg1 "arg2 with quotes" arg4 arg5=1'
result = split_args(args)
```
And it would look like:
```
result = [
'arg... | ```
import shlex
shlex.split('arg arg1 "arg2 with quotes" arg4 arg5=1')
``` |
Single Django model, multiple tables? | 5,036,357 | 16 | 2011-02-18T00:18:37Z | 5,036,444 | 14 | 2011-02-18T00:31:26Z | [
"python",
"mysql",
"django"
] | I have several temporary tables in a MySQL database that share the same schema and have dynamic names. How would I use Django to interface with those tables? Can a single model draw data from multiple tables? | You could, I believe, make a factory function that would return your model with a dynamic [db\_table](http://docs.djangoproject.com/en/dev/ref/models/options/#db-table).
```
def getModel(db_table):
class MyClass(models.Model):
# define as usual ...
class Meta:
db_table = db_table
return MyClass
... |
Django - Rebuild a query string without one of the variables | 5,036,498 | 8 | 2011-02-18T00:40:14Z | 5,036,797 | 9 | 2011-02-18T01:33:43Z | [
"python",
"django",
"django-views"
] | I have a Django view that processes a GET request. I want to rebuild the query string to include all variables *except* for one.
I was initially using list comprehension:
```
>>> from django.http import QueryDict
>>> q = QueryDict('a=2&b=4&c=test') // <--- make believe this is request.GET
>>> z = QueryDict('').copy()... | Django puts the GET request variables into a dictionary for you, so request.GET is already a QueryDict. You can just do this:
```
z = request.GET.copy()
del z['a']
```
Note that dictionaries in python (and django QueryDicts) don't have a del() method, you have to use python's built in del() function. QueryDicts are i... |
How can you dynamically create variables via a while loop? | 5,036,700 | 76 | 2011-02-18T01:14:00Z | 5,036,775 | 71 | 2011-02-18T01:28:03Z | [
"python",
"variables"
] | I want to create variables dynamically via to a while loop in Python. Anyone have any creative means of doing this? | Unless there is an overwhelming need to create a mess of variable names, I would just use a dictionary, where you can dynamically create the key names and associate a value to each.
```
a = {}
k = 0
while k < 10:
<dynamically create key>
key = ...
<calculate value>
value = ...
a[key] = value
... |
How can you dynamically create variables via a while loop? | 5,036,700 | 76 | 2011-02-18T01:14:00Z | 5,036,827 | 26 | 2011-02-18T01:41:17Z | [
"python",
"variables"
] | I want to create variables dynamically via to a while loop in Python. Anyone have any creative means of doing this? | playing with globals() makes it possible:
```
import random
alphabet = tuple('abcdefghijklmnopqrstuvwxyz')
print '\n'.join(repr(u) for u in globals() if not u.startswith('__'))
for i in xrange(8):
globals()[''.join(random.sample(alphabet,random.randint(3,26)))] = random.choice(alphabet)
print
print '\n'.join... |
How can you dynamically create variables via a while loop? | 5,036,700 | 76 | 2011-02-18T01:14:00Z | 5,037,218 | 17 | 2011-02-18T02:59:46Z | [
"python",
"variables"
] | I want to create variables dynamically via to a while loop in Python. Anyone have any creative means of doing this? | Stuffing things into the global and/or local namespaces is not a good idea. Using a dict is so some-other-language-ish ... `d['constant-key'] = value` just looks awk-ward. Python is OO. In the words of a master: """Namespaces are one honking great idea -- let's do more of those!"""
Like this:
```
>>> class Record(obj... |
How can you dynamically create variables via a while loop? | 5,036,700 | 76 | 2011-02-18T01:14:00Z | 7,422,918 | 12 | 2011-09-14T21:00:38Z | [
"python",
"variables"
] | I want to create variables dynamically via to a while loop in Python. Anyone have any creative means of doing this? | Use the exec() method. For example, say you have a dictionary and you want to turn each key into a variable with its original dictionary value can do the following.
```
>>> c = {"one": 1, "two": 2}
>>> for k,v in c.iteritems():
... exec("%s=%s" % (k,v))
>>> one
1
>>> two
2
``` |
Numpy Lookup (Map, or Point) | 5,036,816 | 6 | 2011-02-18T01:38:32Z | 5,037,996 | 7 | 2011-02-18T05:37:05Z | [
"python",
"indexing",
"numpy"
] | I have a large numpy array:
```
array([[32, 32, 99, 9, 45], # A
[99, 45, 9, 45, 32],
[45, 45, 99, 99, 32],
[ 9, 9, 32, 45, 99]])
```
and a large-ish array of unique values in a particular order:
```
array([ 99, 32, 45, 9]) # B
```
How can I quickly (no python dictionaries, no copies o... | ```
import numpy as np
A=np.array([[32, 32, 99, 9, 45],
[99, 45, 9, 45, 32],
[45, 45, 99, 99, 32],
[ 9, 9, 32, 45, 99]])
B=np.array([ 99, 32, 45, 9])
cutoffs=np.sort(B)
print(cutoffs)
# [ 9 32 45 99]
index=cutoffs.searchsorted(A)
print(index)
# [[1 1 3 0 2]
# [3 2 0 2 1]
# ... |
Mocking out methods on any instance of a python class | 5,036,920 | 9 | 2011-02-18T02:00:48Z | 5,044,894 | 28 | 2011-02-18T18:05:35Z | [
"python",
"testing",
"mocking"
] | I want to mock out methods on any instance of some class in the production code in order to facilitate testing. Is there any library in Python which could facilitate this?
Basically, I want to do the following, but in Python (the following code is Ruby, using the Mocha library):
```
def test_stubbing_an_instance_me... | Needing to mock out methods when testing is very common and there are lots of tools to help you with it in Python. The danger with "monkey patching" classes like this is that if you don't *undo* it afterwards then the class has been modified for all other uses throughout your tests.
My library mock, which is one of th... |
PyTables batch get and update | 5,037,172 | 6 | 2011-02-18T02:50:08Z | 5,044,529 | 10 | 2011-02-18T17:30:23Z | [
"python",
"hdf5",
"pytables"
] | I have daily stock data as an HDF5 file created using PyTables. I would like to get a group of rows, process it as an array and then write it back to disk (update rows) using PyTables. I couldn't figure out a way to do this cleanly. Could you please let me know what will be the best way to accomplish this?
My data:
`... | If I understand well, the next should do what you want:
```
condition = 'Symbol == "abcd"'
indices = table.getWhereList(condition) # get indices
rows_array = table[indices] # get values
new_rows = compute(rows_array) # compute new values
table[indices] = new_rows # update the indices with new values
```
Hope thi... |
Using cPickle to serialize a large dictionary causes MemoryError | 5,037,432 | 8 | 2011-02-18T03:52:37Z | 5,037,684 | 10 | 2011-02-18T04:38:59Z | [
"python",
"serialization",
"pickle",
"inverted-index"
] | I'm writing an inverted index for a search engine on a collection of documents. Right now, I'm storing the index as a dictionary of dictionaries. That is, each keyword maps to a dictionary of docIDs->positions of occurrence.
The data model looks something like:
{word : { doc\_name : [location\_list] } }
Building the ... | cPickle needs to use a bunch of extra memory because it does cycle detection. You could try using the marshal module if you are sure your data has no cycles |
xor each byte with 0x71 | 5,037,762 | 4 | 2011-02-18T04:50:27Z | 5,040,002 | 13 | 2011-02-18T10:11:09Z | [
"python",
"hex",
"binaryfiles"
] | I needed to read a byte from the file, xor it with 0x71 and write it back to another file. However, when i use the following, it just reads the byte as a string, so xoring creates problems.
```
f = open('a.out', 'r')
f.read(1)
```
So I ended up doing the same in C.
```
#include <stdio.h>
int main() {
char buffer[1... | If you want to treat something as an array of bytes, then usually you want a `bytearray` as it behaves as a mutable array of bytes:
```
b = bytearray(open('a.out', 'rb').read())
for i in range(len(b)):
b[i] ^= 0x71
open('b.out', 'wb').write(b)
```
Indexing a byte array returns an integer between 0x00 and 0xff, an... |
What is the history of the import statement? | 5,039,972 | 7 | 2011-02-18T10:07:52Z | 5,040,017 | 11 | 2011-02-18T10:12:15Z | [
"java",
"python",
"programming-languages",
"import"
] | I know of two languages that use `import` statement: Java and Python. And we all know [the `import antigravity` joke](http://xkcd.com/353/).
Which language really introduced this statement? Was it one of the two, or another one altogether? When? | `import` is just one way to specify dependency on some other class/module. Some way of specifying that has been present in many, many languages.
In fact `import` in Java and `import` in Python do two entirely different things:
* In Java `import` only provides the ability to refer to a type (or field/method, if using ... |
Scrapy: skip item and continue with exectuion | 5,040,110 | 3 | 2011-02-18T10:23:09Z | 5,041,889 | 8 | 2011-02-18T13:32:37Z | [
"python",
"web-crawler",
"scrapy"
] | I'm doing a RSS spider. I want to continue with the execution of the
spider ignoring the current node if there isn't a match in the current
item... So far I've got this:
```
if info.startswith('Foo'):
item['foo'] = info.split(':')[1]
else:
return None
```
(info is a string that... | ```
parse(response):
#make some manipulations
if info.startswith('Foo'):
item['foo'] = info.split(':')[1]
return [item]
else:
return []
```
But better is not use return, use `yield` or do nothing
```
parse(response):
#make some manipulations
if info.startswi... |
Python socket doesn't close connection properly | 5,040,491 | 5 | 2011-02-18T11:02:35Z | 5,042,293 | 21 | 2011-02-18T14:11:20Z | [
"python",
"windows",
"linux",
"sockets",
"networking"
] | I am new to socket programming and ran into a puzzling problem:
I have a windows program which I cannot alter (proprietary software) but which tries to connect to a specific ip and port with a tcp socket.
On my linux box I wrote a little python script to serve the socket to the win prog. This works fine until I kill ... | You are experiencing the `TIME_WAIT` state of connected sockets. Even though you've closed your socket, it still has lingering consequences for a couple minutes. The reasons for this, as well as a socket flag you can set to disable the behavior (SO\_REUSEADDR), are explained in the [UNIX guide socket FAQ](http://www.un... |
Python - 'ascii' codec can't decode byte | 5,040,532 | 29 | 2011-02-18T11:07:41Z | 5,040,723 | 20 | 2011-02-18T11:27:47Z | [
"python",
"jinja2"
] | I'm using Python 2.6 and Jinja2 to create HTML reports. I provide the template with many results and the template loops through them and creates HTML tables
When calling template.render, I've suddenly started getting this error.
```
<td>{{result.result_str}}</td>
UnicodeDecodeError: 'ascii' codec can't decode byte 0x... | If you get an error with a string like "ABC", maybe the non-ASCII character is somewhere else. In the template source perhaps?
In any case, use Unicode strings throughout your application to avoid this kind of problems. If your data source provides you with byte strings, you get unicode strings with `byte_string.decod... |
Python - 'ascii' codec can't decode byte | 5,040,532 | 29 | 2011-02-18T11:07:41Z | 5,040,735 | 34 | 2011-02-18T11:29:06Z | [
"python",
"jinja2"
] | I'm using Python 2.6 and Jinja2 to create HTML reports. I provide the template with many results and the template loops through them and creates HTML tables
When calling template.render, I've suddenly started getting this error.
```
<td>{{result.result_str}}</td>
UnicodeDecodeError: 'ascii' codec can't decode byte 0x... | From <http://jinja.pocoo.org/docs/api/#unicode>
> Jinja2 is using Unicode internally which means that you have to pass Unicode objects to the render function or bytestrings that only consist of ASCII characters.
So wherever you set result.result\_str, you need to make it unicode, e.g.
```
result.result_str = unicode... |
Python - 'ascii' codec can't decode byte | 5,040,532 | 29 | 2011-02-18T11:07:41Z | 14,919,377 | 55 | 2013-02-17T08:41:54Z | [
"python",
"jinja2"
] | I'm using Python 2.6 and Jinja2 to create HTML reports. I provide the template with many results and the template loops through them and creates HTML tables
When calling template.render, I've suddenly started getting this error.
```
<td>{{result.result_str}}</td>
UnicodeDecodeError: 'ascii' codec can't decode byte 0x... | Try to add this:
```
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
```
It fixed my problem, good luck. |
Shuffling NumPy array along a given axis | 5,040,797 | 11 | 2011-02-18T11:35:59Z | 5,044,364 | 17 | 2011-02-18T17:15:43Z | [
"python",
"random",
"numpy"
] | Given the following NumPy array,
```
> a = array([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5],[1, 2, 3, 4, 5]])
```
it's simple enough to shuffle a single row,
```
> shuffle(a[0])
> a
array([[4, 2, 1, 3, 5],[1, 2, 3, 4, 5],[1, 2, 3, 4, 5]])
```
Is it possible to use indexing notation to shuffle each of the rows independently?... | You have to call `numpy.random.shuffle()` several times because you are shuffling several sequences independently. `numpy.random.shuffle()` works on any mutable sequence and is not actually a `ufunc`. The shortest and most efficient code to shuffle all rows of a two-dimensional array `a` separately probably is
```
map... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.