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 |
|---|---|---|---|---|---|---|---|---|---|
Adding model-wide help text to a django model's admin form | 3,728,617 | 32 | 2010-09-16T16:20:20Z | 3,729,995 | 21 | 2010-09-16T19:20:39Z | [
"python",
"django",
"django-models",
"django-admin"
] | In my django app, I would like to be able to add customized help text to the admin change form for some of my models. Note I'm not talking about the field specific `help_text` attribute that I can set on individual fields. For example, at the top of the change form for `My_Model` in `My_App` I'd like to be able to add ... | There is a fairly simple, yet underdocumented way of accomplishing this.
## Define render\_change\_form in the Admin class
First, you need to pass extra context to your admin. To do this, you can define a render\_change\_form function within your admin Class, e.g.:
```
# admin.py
class CustomAdmin(admin.ModelAdmin):... |
Python Titlecase a String with exceptions | 3,728,655 | 41 | 2010-09-16T16:25:36Z | 3,728,735 | 7 | 2010-09-16T16:34:53Z | [
"python",
"string",
"title-case"
] | Is there a standard way in Python to titlecase a string (i.e. words start with uppercase characters, all remaining cased characters have lowercase) but leaving articles like `and`, `in`, and `of` lowercased? | There are these methods:
```
>>> mytext = u'i am a foobar bazbar'
>>> print mytext.capitalize()
I am a foobar bazbar
>>> print mytext.title()
I Am A Foobar Bazbar
```
There's no lowercase article option. You'd have to code that yourself, probably by using a list of articles you want to lower. |
Python Titlecase a String with exceptions | 3,728,655 | 41 | 2010-09-16T16:25:36Z | 3,729,060 | 32 | 2010-09-16T17:18:05Z | [
"python",
"string",
"title-case"
] | Is there a standard way in Python to titlecase a string (i.e. words start with uppercase characters, all remaining cased characters have lowercase) but leaving articles like `and`, `in`, and `of` lowercased? | Use the [titlecase.py](http://muffinresearch.co.uk/archives/2008/05/27/titlecasepy-titlecase-in-python/) module! Works only for English.
```
>>> from titlecase import titlecase
>>> titlecase('i am a foobar bazbar')
'I Am a Foobar Bazbar'
``` |
Python Titlecase a String with exceptions | 3,728,655 | 41 | 2010-09-16T16:25:36Z | 3,729,957 | 75 | 2010-09-16T19:16:11Z | [
"python",
"string",
"title-case"
] | Is there a standard way in Python to titlecase a string (i.e. words start with uppercase characters, all remaining cased characters have lowercase) but leaving articles like `and`, `in`, and `of` lowercased? | There are a few problems with this. If you use split and join, some white space characters will be ignored. The built-in capitalize and title methods do not ignore white space.
```
>>> 'There is a way'.title()
'There Is A Way'
```
If a sentence starts with an article, you do not want the first word of a title... |
How can I programmatically change the argspec of a function in a python decorator? | 3,729,378 | 13 | 2010-09-16T17:59:17Z | 3,729,458 | 11 | 2010-09-16T18:09:45Z | [
"python",
"reflection",
"decorator",
"inspect"
] | Given a function:
```
def func(f1, kw='default'):
pass
bare_argspec = inspect.getargspec(func)
@decorator
def func2(f1, kw='default'):
pass
decorated_argspec = inspect.getargspec(func2)
```
How can I create a decorator such that `bare_argspec == decorated_argspec`?
(As to why, the framework that calls the d... | Michele Simionato's [decorator module](http://pypi.python.org/pypi/decorator) has a decorator called decorator which preserves function argspecs.
```
import inspect
import decorator
def func(f1, kw='default'):
pass
bare_argspec = inspect.getargspec(func)
print(bare_argspec)
# ArgSpec(args=['f1', 'kw'], varargs=No... |
Conditional Class Creation (Python) | 3,729,419 | 6 | 2010-09-16T18:03:46Z | 3,729,445 | 8 | 2010-09-16T18:08:04Z | [
"python"
] | From the tutorial: "A class definition is an executable statement."
Is the following recommended in a script?
```
my_switch = False
if my_switch:
class Hello:
def __init__(self):
self.greeting = "Hello!"
else:
class Hello:
def __init__(self):
self.greeting = "Salut!"
`... | You can even do
```
class Hello:
def __init__(self):
self.greeting = "Hello!"
class Salut:
def __init__(self):
self.greeting = "Salut!"
if my_switch:
Hello = Salut
```
(note that your code needs lower-case Class keywords...) |
a list of pygame sprites loses its first element, and gains a duplicate of the last | 3,729,648 | 3 | 2010-09-16T18:32:23Z | 3,729,961 | 7 | 2010-09-16T19:16:44Z | [
"python",
"list",
"pygame"
] | I have a function that loads a sprite sheet, finds a block of sprites, and then puts each individual sprite into a list. Before it appends a sprite into the list, it will blit it onto the screen. Once it's done loading sprites, it will then iterate through the list, blitting each sprite as it goes. The two sets of blit... | ```
image.blit(spritesheet, (0,0), rect)
```
You haven't re-initialised `image` each time around the loop, it's still the same surface you used in the previous iteration, a surface that is already in the list. Each time round the loop you overwrite the sprite you appended to the list in the previous step.
I suggest g... |
Issue with Django admin registering an inline user profile admin | 3,729,866 | 9 | 2010-09-16T19:03:52Z | 3,730,043 | 18 | 2010-09-16T19:26:23Z | [
"python",
"django",
"django-admin"
] | I'm currently working on a django project. I'm attempting to add a UserProfile model inline to my User model. In my models.py I have:
```
class UserProfile(models.Model):
'''
Extension to the User model in django admin.
'''
user = models.ForeignKey(User)
site_role = models.CharField(max_length=128,... | my guess is that you either are doing some crazy module importing... or... you have an ordering problem in your `settings.INSTALLED_APPS` list. Make sure that `'django.contrib.auth'` appears on your list before your app that is replacing the default admin. The list should look something like this:
```
INSTALLED_APPS =... |
Why can't I "save as" an Excel file from my Python code? | 3,730,428 | 4 | 2010-09-16T20:14:05Z | 3,730,512 | 12 | 2010-09-16T20:27:44Z | [
"python",
"save-as"
] | I have an Python `ExcelDocument` class that provides basic convenience methods for reading/writing/formatting Excel files, and I'm getting a strange error in seemingly simple Python code. I have a save and `saveAs` method:
```
def save(self):
''' Save the file '''
self.workbook.Save()
def saveAs(self, newFileNa... | I've found (the hard way) that `SaveAs` doesn't support slash `/`.
Try `saveAs("C:\\test.xlx")` instead. |
Passing 'None' as function parameter (where parameter is a function) | 3,730,831 | 7 | 2010-09-16T21:07:01Z | 3,731,084 | 7 | 2010-09-16T21:46:58Z | [
"python",
"lambda"
] | I am writing a small app that has to perform some 'sanity checks' before entering execution. (eg. of a sanity check: test if a certain path is readable / writable / exists)
The code:
```
import logging
import os
import shutil
import sys
from paths import PATH
logging.basicConfig(level=logging.DEBUG)
log = logging.ge... | What's with all the lambdas that serve no purpose? Well, maybe optional arguments will help you a bit:
```
def sanity_check( test, name='undefined', ontrue=None, onfalse=None ):
if test:
log.debug(name)
if ontrue is not None:
ontrue()
else:
log.warn( name )
if onfals... |
Python Script execute commands in Terminal | 3,730,964 | 24 | 2010-09-16T21:28:28Z | 3,731,000 | 55 | 2010-09-16T21:32:55Z | [
"python",
"terminal"
] | I read this somewhere a while ago but cant seem to find it. I am trying to find a command that will execute commands in the terminal and then output the result.
For example: the script will be:
```
command 'ls -l'
```
It will out the result of running that command in the terminal | There are several ways to do this:
A simple way is using the os module:
```
import os
os.system("ls -l")
```
More complex things can be achieved with the subprocess module:
for example:
```
import subprocess
test = subprocess.Popen(["ping","-W","2","-c", "1", "192.168.1.70"], stdout=subprocess.PIPE)
output = test.c... |
Python: binascii.a2b_hex gives "Odd-length string" | 3,731,278 | 4 | 2010-09-16T22:18:37Z | 3,731,300 | 7 | 2010-09-16T22:21:46Z | [
"python"
] | I have a hex value that I'm grabbing from a text file, then I'm passing it to a2b\_hex to convert it to the proper binary representation. Here is what I have:
```
k = open('./' + basefile + '.key', 'r')
k1 = k.read()
k.close()
my_key = binascii.a2b_hex(k1)
```
When I print k1, it is as expected: 81e3d6df
Here is the... | Are you sure the file doesn't have something extra in it? Whitespace, for instance?
Try `k1.strip()` |
How do I divide the members of a list by the corresponding members of another list in Python? | 3,731,426 | 4 | 2010-09-16T22:46:56Z | 3,731,439 | 14 | 2010-09-16T22:49:16Z | [
"python"
] | Let's say I have two data sets. I have a week-by-week tally of users who tried my service.
```
trials = [2,2,2,8,8,4]
```
And I have a week by week tally of trial users who signed up.
```
conversions = [1,0,2,4,8,3]
```
I can do it pretty quickly this way:
```
conversion_rate = []
for n in range(len(trials)):
c... | Use zip:
```
[c/t for c,t in zip(conversions, trials)]
```
The most elegant way to get floats is to upgrade to Python 3.x.
If you need to use Python 2.x then you could write this:
```
>>> [float(c)/t for c,t in zip(conversions, trials)]
[0.5, 0.0, 1.0, 0.5, 1.0, 0.75]
```
Alternatively you could add this at the st... |
Getting Started with PyQt | 3,731,558 | 4 | 2010-09-16T23:12:07Z | 3,731,580 | 8 | 2010-09-16T23:17:28Z | [
"python",
"qt",
"pyqt"
] | I'm testing out some of the examples in *Rapid GUI Programming with Python and Qt*, but running into a stumbling block here or where. When I copied to following exercise (verbatim, from the book):
```
import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
app = QApplication(sys.argv)
try:
du... | You probably forgot to add a shebang to your script, to tell your shell to actually run it with the Python interpreter. Try adding
```
#!/usr/bin/python
```
as the first line in your script, provided that's where your Python interpreter is installed. You might want to try
```
which python
```
in case you're not sur... |
How can I remove the axes in an Axes3D class? | 3,732,787 | 7 | 2010-09-17T05:09:07Z | 3,736,072 | 7 | 2010-09-17T14:12:14Z | [
"python",
"matplotlib"
] | I am using mplot3d like this:
```
fig = plt.figure(figsize=(14,10))
ax = Axes3D(fig,azim=azimuth,elev=elevation)
ax.grid(on=False)
# Additional axes
xspan = np.linspace(0,80+20)
yspan = np.linspace(0,60+20)
zspan = np.linspace(0,60+20)
ax.plot3D(xspan,np.zeros(xspan.shape[0]),np.zeros(xspan.shape[0]),'k--')
ax.pl... | If I understand your question correctly, all you need to do is call `ax.axis("off")` or equivalently, `ax.set_axis_off()`.
Just to make sure we're on the same page, your example code might produce something like this (if it could be executed as you posted it...):

While... |
Python subprocess timeout? | 3,733,270 | 15 | 2010-09-17T07:00:16Z | 3,733,348 | 8 | 2010-09-17T07:17:11Z | [
"python",
"timeout",
"pipe",
"subprocess",
"popen"
] | Is there any argument or options to setup a timeout for Python's subprocess.Popen method?
Something like this:
`subprocess.Popen(['..'], ..., timeout=20)` ? | subprocess.Popen doesn't block so you can do something like this:
```
import time
p = subprocess.Popen(['...'])
time.sleep(20)
if p.poll() is None:
p.kill()
print 'timed out'
else:
print p.communicate()
```
It has a drawback in that you must always wait at least 20 seconds for it to finish. |
Python subprocess timeout? | 3,733,270 | 15 | 2010-09-17T07:00:16Z | 13,362,505 | 12 | 2012-11-13T14:29:22Z | [
"python",
"timeout",
"pipe",
"subprocess",
"popen"
] | Is there any argument or options to setup a timeout for Python's subprocess.Popen method?
Something like this:
`subprocess.Popen(['..'], ..., timeout=20)` ? | I would advise taking a look at the [Timer class](http://docs.python.org/2/library/threading.html#threading.Timer) in the threading module. I used it to implement a timeout for a Popen.
First, create a callback:
```
def timeout( p ):
if p.poll() is None:
print 'Error: process taking too long t... |
Howto Format dict string outputs nicely | 3,733,554 | 21 | 2010-09-17T07:54:47Z | 3,733,570 | 24 | 2010-09-17T07:56:55Z | [
"python",
"string",
"formatting"
] | I wonder if there is an easy way to format Strings of dict-outputs such as this:
```
{
'planet' : {
'name' : 'Earth',
'has' : {
'plants' : 'yes',
'animals' : 'yes',
'cryptonite' : 'no'
}
}
}
```
..., where a simple str(dict) just would give you a quite unreadable ...
```
{'planet' :... | Use pprint
```
import pprint
x = {
'planet' : {
'name' : 'Earth',
'has' : {
'plants' : 'yes',
'animals' : 'yes',
'cryptonite' : 'no'
}
}
}
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(x)
```
This outputs
```
{ 'planet': { 'has': { 'animals': 'yes',
... |
Howto Format dict string outputs nicely | 3,733,554 | 21 | 2010-09-17T07:54:47Z | 3,735,164 | 34 | 2010-09-17T12:08:16Z | [
"python",
"string",
"formatting"
] | I wonder if there is an easy way to format Strings of dict-outputs such as this:
```
{
'planet' : {
'name' : 'Earth',
'has' : {
'plants' : 'yes',
'animals' : 'yes',
'cryptonite' : 'no'
}
}
}
```
..., where a simple str(dict) just would give you a quite unreadable ...
```
{'planet' :... | Depending on what you're doing with the output, one option is to use JSON for the display.
```
import json
x = {'planet' : {'has': {'plants': 'yes', 'animals': 'yes', 'cryptonite': 'no'}, 'name': 'Earth'}}
print json.dumps(x, indent=2)
```
Output:
```
{
"planet": {
"has": {
"plants": "yes",
"anim... |
Python RegEx Matching Newline | 3,734,023 | 6 | 2010-09-17T09:14:00Z | 3,734,076 | 9 | 2010-09-17T09:23:18Z | [
"python",
"regex"
] | I have the following regular expression:
```
[0-9]{8}.*\n.*\n.*\n.*\n.*
```
Which I have tested in Expresso against the file I am working and the match is sucessfull.
I want to match the following:
* Reference number 8 numbers long
* Any character, any number of times
* New Line
* Any character, any number of times... | Don't use `re.DOTALL` or the dot will match newlines, too. Also use raw strings (`r"..."`) for regexes:
```
for m in re.findall(r'[0-9]{8}.*\n.*\n.*\n.*\n.*', l):
print m
```
However, your version still should have worked (although very inefficiently) *if* you have read the entire file as binary into memory *as on... |
Getting pdb in Emacs to use Python process from current virtualenv | 3,734,880 | 18 | 2010-09-17T11:27:58Z | 3,735,490 | 8 | 2010-09-17T12:59:37Z | [
"python",
"emacs",
"virtualenv",
"pdb"
] | I am debugging some python code in emacs using pdb and getting some import issues. The dependencies are installed in one of my bespoked virtualenv environments.
Pdb is stubbornly using /usr/bin/python and not the python process from my virtualenv.
I use virtualenv.el to support switching of environments within emacs ... | `python-shell` uses variable `python-default-interpreter` to determine which python interpreter to use. When the value of this variable is `cpython`, the variables `python-python-command` and `python-python-command-args` are consulted to determine the interpreter
and arguments to use. Those two variables are manipulate... |
Getting pdb in Emacs to use Python process from current virtualenv | 3,734,880 | 18 | 2010-09-17T11:27:58Z | 10,313,090 | 7 | 2012-04-25T09:43:02Z | [
"python",
"emacs",
"virtualenv",
"pdb"
] | I am debugging some python code in emacs using pdb and getting some import issues. The dependencies are installed in one of my bespoked virtualenv environments.
Pdb is stubbornly using /usr/bin/python and not the python process from my virtualenv.
I use virtualenv.el to support switching of environments within emacs ... | Invoke pdb like this:
```
python -m pdb myscript.py
```
Instead of
```
pdb myscript.py
``` |
Linear feedback shift register? | 3,735,217 | 8 | 2010-09-17T12:16:11Z | 9,876,780 | 7 | 2012-03-26T17:26:12Z | [
"python",
"language-agnostic",
"digital-logic"
] | Lately I bumped repeatedly into the concept of LFSR, that I find quite interesting because of its links with different fields and also fascinating in itself. It took me some effort to understand, the final help was this really good [page](http://homepage.mac.com/afj/lfsr.html), much better than the (at first) cryptic [... | Since I was looking for a LFSR-implementation in Python, I stumbled upon this topic. I found however that the following was a bit more accurate according to my needs:
```
def lfsr(seed, mask):
result = seed
nbits = mask.bit_length()-1
while True:
result = (result << 1)
xor = result >> nbits... |
Python lxml and stdin | 3,735,364 | 4 | 2010-09-17T12:40:53Z | 3,735,416 | 10 | 2010-09-17T12:48:29Z | [
"python",
"xml",
"lxml"
] | I have a xml file, book.xml (<http://msdn.microsoft.com/en-us/library/ms762271(VS.85).aspx>)
I would like to cat books.xml and get all book ids and genres for the book id.
Similar to
```
cat books.xml | python reader.py
```
Any tips or help would be appreciated. Thanks. | To read an XML file from stdin, just use `etree.parse`. This function accepts a file object, which can be `sys.stdin`.
```
import sys
from lxml import etree
tree = etree.parse(sys.stdin)
print ( [(b.get('id'), b.findtext('genre')) for b in tree.iterfind('book')] )
``` |
mixing super and classic calls in Python | 3,735,569 | 8 | 2010-09-17T13:10:40Z | 3,735,726 | 8 | 2010-09-17T13:30:32Z | [
"python"
] | firstly, let me quote a bit an essay from "Expert Python Programming" book:
> In the following example, a C class that calls its base classes using the \_*init*\_ method will
> make B class be called twice!
```
class A(object):
def __init__(self):
print "A"
super(A, self).__init__()
class B(objec... | To understand this behaviour, you have to understand that `super` calls not the base class, but searches the next matching method along the order in the `__mro__`. So, the call `super(A, self).__init__()` looks at the `__mro__ == ['C', 'A', 'B', 'object']`, sees `B` as the next class with a matching method and calls th... |
Check for a key pattern in a dictionary in python | 3,735,814 | 5 | 2010-09-17T13:42:24Z | 3,735,866 | 15 | 2010-09-17T13:49:22Z | [
"python",
"dictionary"
] | ```
dict1=({"EMP$$1":1,"EMP$$2":2,"EMP$$3":3})
```
How to check if EMP exists in the dictionary using python
```
dict1.get("EMP##") ??
``` | It's not entirely clear what you want to do.
You can loop through the keys in the `dict` selecting keys using [the `startswith()` method](http://docs.python.org/library/stdtypes.html#str.startswith):
```
>>> for key in dict1:
... if key.startswith("EMP$$"):
... print "Found",key
...
Found EMP$$1
Found EMP... |
Split with single colon but not double colon using regex | 3,735,841 | 8 | 2010-09-17T13:46:24Z | 3,735,896 | 9 | 2010-09-17T13:52:07Z | [
"python",
"regex",
"split"
] | I have a string like this
```
"yJdz:jkj8h:jkhd::hjkjh"
```
I want to split it using colon as a separator, but not a double colon. Desired result:
```
("yJdz", "jkj8h", "jkhd::hjkjh")
```
I'm trying with:
```
re.split(":{1}", "yJdz:jkj8h:jkhd::hjkjh")
```
but I got a wrong result.
In the meanwhile I'm escaping `"... | You can do this with [lookahead and lookbehind](http://www.regular-expressions.info/lookaround.html), if you want:
```
>>> s = "yJdz:jkj8h:jkhd::hjkjh"
>>> l = re.split("(?<!:):(?!:)", s)
>>> print l
['yJdz', 'jkj8h', 'jkhd::hjkjh']
```
This regex essentially says "match a `:` that is not followed by a `:` or precede... |
Split with single colon but not double colon using regex | 3,735,841 | 8 | 2010-09-17T13:46:24Z | 3,735,908 | 17 | 2010-09-17T13:53:11Z | [
"python",
"regex",
"split"
] | I have a string like this
```
"yJdz:jkj8h:jkhd::hjkjh"
```
I want to split it using colon as a separator, but not a double colon. Desired result:
```
("yJdz", "jkj8h", "jkhd::hjkjh")
```
I'm trying with:
```
re.split(":{1}", "yJdz:jkj8h:jkhd::hjkjh")
```
but I got a wrong result.
In the meanwhile I'm escaping `"... | You could split on `(?<!:):(?!:)`. This uses two [negative lookarounds](http://www.regular-expressions.info/lookaround.html) (a lookbehind and a lookahead) which assert that a valid match only has one colon, without a colon before or after it.
To explain the pattern:
```
(?<!:) # assert that the previous character i... |
Django Query using .order_by() and .latest() | 3,736,964 | 30 | 2010-09-17T16:02:06Z | 3,737,410 | 50 | 2010-09-17T17:04:08Z | [
"python",
"django",
"sql-order-by"
] | I have a model:
```
class MyModel(models.Model):
creation_date = models.DateTimeField(auto_now_add = True, editable=False)
class Meta:
get_latest_by = 'creation_date'
```
I had a query in my view that did the following:
```
instances = MyModel.objects.all().order_by('creation_date')
```
And then later ... | > I would have expected .latest() to always return the most recent instance based on a (date)(time) field.
The [documentation](http://docs.djangoproject.com/en/dev/ref/models/querysets/#latest-field-name-none) says that
> If your model's `Meta` specifies `get_latest_by`, you can leave off the `field_name` argument to... |
Can I prevent fabric from prompting me for a sudo password? | 3,737,003 | 43 | 2010-09-17T16:06:17Z | 3,737,441 | 31 | 2010-09-17T17:07:45Z | [
"python",
"sudo",
"fabric"
] | I am using [Fabric](http://docs.fabfile.org/0.9.2/) to run commands on a remote server. The user with which I connect on that server has some sudo privileges, and does not require a password to use these privileges. When SSH'ing into the server, I can run `sudo blah` and the command executes without prompting for a pas... | Try passing `shell=False` to sudo. That way /bin/bash won't be added to the sudo command. `sudo('some_command', shell=False)`
From line 503 of [fabric/operations.py](http://code.fabfile.org/repositories/entry/fabric/0.9/fabric/operations.py#L503):
```
if (not env.use_shell) or (not shell):
real_command = "%s %s" ... |
Can I prevent fabric from prompting me for a sudo password? | 3,737,003 | 43 | 2010-09-17T16:06:17Z | 20,080,546 | 11 | 2013-11-19T19:39:27Z | [
"python",
"sudo",
"fabric"
] | I am using [Fabric](http://docs.fabfile.org/0.9.2/) to run commands on a remote server. The user with which I connect on that server has some sudo privileges, and does not require a password to use these privileges. When SSH'ing into the server, I can run `sudo blah` and the command executes without prompting for a pas... | This is the most direct answer to your question:
You do not actually have a problem; you misunderstand how Fabric run() and sudo() work.
Your "workaround" is NOT a workaround it is the 100% valid answer to the problem.
Here's a simple set of rules:
1) Use "run()" when you don't expect a prompt.
2) use "sudo()" when y... |
use the system monospace font in gtk textview | 3,737,021 | 11 | 2010-09-17T16:08:21Z | 3,737,156 | 8 | 2010-09-17T16:26:53Z | [
"python",
"gtk"
] | I would like to have a GtkTextView in my (Python) program which shows text with the system monospace font. I found many ways which use an expicit font family name and size. However, I would like to use the system specified monospace font (e.g. from the ubuntu font preferences panel).
My program should be able to run o... | You can just use "monospace 18" as your font and it will use the system monospaced font. |
How do you convert a stringed dictionary to a Python dictionary? | 3,737,900 | 4 | 2010-09-17T18:21:14Z | 3,737,969 | 11 | 2010-09-17T18:31:48Z | [
"python"
] | I have the following string which is a Python dictionary stringified:
```
some_string = '{123: False, 456: True, 789: False}'
```
How do I get the Python dictionary out of the above string? | Use [**`ast.literal_eval`**](http://docs.python.org/library/ast.html#ast.literal_eval):
> Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
>... |
Why does PyUSB / libusb require root (sudo) permissions on Linux? | 3,738,173 | 9 | 2010-09-17T19:03:03Z | 8,582,398 | 8 | 2011-12-20T21:46:46Z | [
"python",
"usb",
"libusb",
"pyusb"
] | I have been toying around with [PyUSB](http://pyusb.berlios.de/) lately, and found that it works beautifully on Linux (Ubuntu has [libusb](http://www.libusb.org/) 0.1 and 1.0, as well as [OpenUSB](http://sourceforge.net/projects/openusb/develop))... but only if I run the program with root privileges (with `sudo`, of co... | You can change the permissions of your usb device node by creating a udev rule.
e.g. I added the following line to a file in `/etc/udev/rules.d/`
```
SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", MODE="0664", GROUP="usbusers"
```
This sets the owner of the device node to `root:usbusers` rather than `root:root`
After... |
How to insert arrays into a database? | 3,738,269 | 11 | 2010-09-17T19:16:31Z | 3,738,402 | 8 | 2010-09-17T19:33:09Z | [
"python",
"database-design",
"numpy"
] | [In my previous question](http://stackoverflow.com/questions/3684484) a lot of users wanted me to give some more data to toy with. So I got working on exporting all my data and processing it with Python, but then I realized: where do I leave all this data?
Well I decided the best thing would be to stick them in a data... | You'll probably want to start out with a `dogs` table containing all the flat (non array) data for each dog, things which each dog has *one* of, like a name, a sex, and an age:
```
CREATE TABLE `dogs` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(64),
`age` INT UNSIGNED,
`sex` ENUM('M... |
What do I do when I need a self referential dictionary? | 3,738,381 | 21 | 2010-09-17T19:30:13Z | 3,738,400 | 7 | 2010-09-17T19:33:01Z | [
"python",
"dictionary"
] | I'm new to Python, and am sort of surprised I cannot do this.
```
dictionary = {
'a' : '123',
'b' : dictionary['a'] + '456'
}
```
I'm wondering what the Pythonic way to correctly do this in my script, because I feel like I'm not the only one that has tried to do this.
**EDIT:** Enough people were wondering w... | ```
>>> dictionary = {
... 'a':'123'
... }
>>> dictionary['b'] = dictionary['a'] + '456'
>>> dictionary
{'a': '123', 'b': '123456'}
```
It works fine but when you're trying to use `dictionary` it hasn't been defined yet (because it has to evaluate that literal dictionary first).
But be careful because this assigns to... |
What do I do when I need a self referential dictionary? | 3,738,381 | 21 | 2010-09-17T19:30:13Z | 3,740,096 | 31 | 2010-09-18T02:08:14Z | [
"python",
"dictionary"
] | I'm new to Python, and am sort of surprised I cannot do this.
```
dictionary = {
'a' : '123',
'b' : dictionary['a'] + '456'
}
```
I'm wondering what the Pythonic way to correctly do this in my script, because I feel like I'm not the only one that has tried to do this.
**EDIT:** Enough people were wondering w... | No fear of creating new classes -
You can take advantage of Python's string formating capabilities
and simply do:
```
class MyDict(dict):
def __getitem__(self, item):
return dict.__getitem__(self, item) % self
dictionary = MyDict({
'user' : 'gnucom',
'home' : '/home/%(user)s',
'bin' : '%(home)s... |
How to strip all whitespace from string | 3,739,909 | 61 | 2010-09-18T00:42:10Z | 3,739,928 | 21 | 2010-09-18T00:48:21Z | [
"python",
"python-3.x",
"spaces",
"strip"
] | How do I strip all the spaces in a python string? For example, I want a string like `strip my spaces` to be turned into `stripmyspaces`, but I cannot seem to accomplish that with `strip()`:
```
>>> 'strip my spaces'.strip()
'strip my spaces'
``` | ```
>>> import re
>>> re.sub(r'\s+', '', 'strip my spaces')
'stripmyspaces'
```
Also handles any whitespace characters that you're not thinking of (believe me, there are plenty). |
How to strip all whitespace from string | 3,739,909 | 61 | 2010-09-18T00:42:10Z | 3,739,939 | 124 | 2010-09-18T00:54:26Z | [
"python",
"python-3.x",
"spaces",
"strip"
] | How do I strip all the spaces in a python string? For example, I want a string like `strip my spaces` to be turned into `stripmyspaces`, but I cannot seem to accomplish that with `strip()`:
```
>>> 'strip my spaces'.strip()
'strip my spaces'
``` | Taking advantage of str.split's behavior with no sep parameter:
```
>>> s = " \t foo \n bar "
>>> "".join(s.split())
'foobar'
```
If you just want to remove spaces instead of all whitespace:
```
>>> s.replace(" ", "")
'\tfoo\nbar'
```
## Premature optimization
Even though efficiency isn't the primary goalâwritin... |
How to strip all whitespace from string | 3,739,909 | 61 | 2010-09-18T00:42:10Z | 16,653,798 | 14 | 2013-05-20T16:16:31Z | [
"python",
"python-3.x",
"spaces",
"strip"
] | How do I strip all the spaces in a python string? For example, I want a string like `strip my spaces` to be turned into `stripmyspaces`, but I cannot seem to accomplish that with `strip()`:
```
>>> 'strip my spaces'.strip()
'strip my spaces'
``` | Alternatively,
```
"strip my spaces".translate( None, string.whitespace )
``` |
Python Dbus : How to export Interface property | 3,740,903 | 3 | 2010-09-18T08:29:22Z | 3,791,563 | 9 | 2010-09-24T22:48:25Z | [
"python",
"dbus"
] | In all python dbus documentations there are info on how to export objects, interfaces, signals, but there is nothing how to export interface property.
Any ideas how to do that ? | It's definitely possible to implement D-Bus properties in Python! D-Bus properties are just methods on a particular interface, namely `org.freedesktop.DBus.Properties`. The interface is defined [in the D-Bus specification](http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-properties); you can ... |
Python print works differently on different servers | 3,742,167 | 6 | 2010-09-18T15:05:39Z | 3,742,195 | 7 | 2010-09-18T15:12:32Z | [
"python",
"unicode",
"twisted"
] | When I try to print an unicode string on my dev server it works correctly but production server raises exception.
```
File "/home/user/twistedapp/server.py", line 97, in stringReceived
print "sent:" + json
File "/usr/lib/python2.6/dist-packages/twisted/python/log.py", line 555, in write
d = (self.buf + data).s... | `print`ing of Unicode strings relies on `sys.stdout` (the process's standard output) having a correct `.encoding` attribute that Python can use to encode the unicode string into a byte string to perform the required printing -- and that setting depends on the way the OS is set up, where standard output is directed to, ... |
How do I convert datetime to date (in Python)? | 3,743,222 | 270 | 2010-09-18T19:44:01Z | 3,743,238 | 70 | 2010-09-18T19:47:09Z | [
"python",
"datetime"
] | How do I convert a `datetime.datetime` object (for example, the return value of `datetime.datetime.now())` to a `datetime.date object` in Python? | From the documentation:
> [`datetime.datetime.date()`](http://docs.python.org/library/datetime.html#datetime.datetime.date)
>
> Return date object with same year, month and day. |
How do I convert datetime to date (in Python)? | 3,743,222 | 270 | 2010-09-18T19:44:01Z | 3,743,240 | 409 | 2010-09-18T19:47:40Z | [
"python",
"datetime"
] | How do I convert a `datetime.datetime` object (for example, the return value of `datetime.datetime.now())` to a `datetime.date object` in Python? | Use the `date()` method:
```
datetime.datetime.now().date()
``` |
How do I convert datetime to date (in Python)? | 3,743,222 | 270 | 2010-09-18T19:44:01Z | 3,954,926 | 35 | 2010-10-17T19:38:06Z | [
"python",
"datetime"
] | How do I convert a `datetime.datetime` object (for example, the return value of `datetime.datetime.now())` to a `datetime.date object` in Python? | You use the `datetime.datetime.date()` method:
```
datetime.datetime.now().date()
```
Obviously, the expression above can (and should IMHO :) be written as:
```
datetime.date.today()
``` |
How do I convert datetime to date (in Python)? | 3,743,222 | 270 | 2010-09-18T19:44:01Z | 16,673,715 | 24 | 2013-05-21T15:25:30Z | [
"python",
"datetime"
] | How do I convert a `datetime.datetime` object (for example, the return value of `datetime.datetime.now())` to a `datetime.date object` in Python? | You can convert a datetime object to a date with the date() method of the date time object, as follows:
```
<datetime_object>.date()
``` |
Is there a Python equivalent to Ruby symbols? | 3,743,532 | 48 | 2010-09-18T21:14:17Z | 3,743,555 | 57 | 2010-09-18T21:19:14Z | [
"python",
"ruby",
"dictionary",
"key",
"symbols"
] | Is there a Python equivalent to Ruby symbols?
* If so then what is it?
* If not then are we stuck with using **strings** as our **keys** in dictionaries only? | No, python doesn't have a symbol type.
However string literals are interned by default and other strings can be interned using the `intern` function. So using string literals as keys in dictionaries is not less performant than using symbols in ruby. |
Is there a Python equivalent to Ruby symbols? | 3,743,532 | 48 | 2010-09-18T21:14:17Z | 3,743,919 | 12 | 2010-09-18T23:21:41Z | [
"python",
"ruby",
"dictionary",
"key",
"symbols"
] | Is there a Python equivalent to Ruby symbols?
* If so then what is it?
* If not then are we stuck with using **strings** as our **keys** in dictionaries only? | As others have said, there is no symbol in Python, but strings work well.
To avoid quoting strings as keys, use the dict() constructor syntax:
```
d = dict(
a = 1,
b = 2,
c = "Hello there",
)
``` |
Python - Best GUI library for the job? | 3,743,572 | 15 | 2010-09-18T21:25:34Z | 3,743,578 | 7 | 2010-09-18T21:28:12Z | [
"python",
"user-interface"
] | I've been using WxPython and I've tried Tk, but it seems that, while both are good and I'll likely use them for other projects, neither of those appear to be capable of accomplishing the things that I want for my current project (which is fine, they're good at what they do).
Basically what I'm looking for is something... | How about PyQt?
<http://www.riverbankcomputing.co.uk/software/pyqt/intro> |
Making Python script accessible system wide | 3,743,812 | 2 | 2010-09-18T22:43:12Z | 3,744,248 | 11 | 2010-09-19T01:55:34Z | [
"python",
"linux",
"windows",
"shell",
"osx-leopard"
] | Can someone tell me how to make my script callable in any directory?
My script simply returns the number of files in a directory. I would like it to work in any directory by invoking it, instead of first being copied there and then typing `python myscript.py`
I am using Mac OS X, but is there a common way to get it i... | If your script starts with a suitable shebang line, such as:
```
#!/usr/bin/env python
```
And your script has the executable bit set (for Linux, OS X, and other Unix-like systems):
```
chmod +x myscript.py
```
And the path to your script is in your PATH environment variable:
```
export PATH=${PATH}:`pwd` # on Uni... |
Why does java/javascript/python force the use of () after a method name, even if it takes no arguments? | 3,744,180 | 5 | 2010-09-19T01:30:17Z | 3,744,198 | 13 | 2010-09-19T01:38:20Z | [
"java",
"javascript",
"python",
"methods",
"properties"
] | One of my most common bugs is that I can never remember whether something is a method or a property, so I'm constantly adding or removing parentheses.
So I was wondering if there was good logic behind making the difference between calling on an object's properties and methods explicit.
Obviously, it allows you to hav... | All modern languages require this because *referencing* a function and *calling* a function are separate actions.
For example,
```
def func():
print "hello"
return 10
a = func
a()
```
Clearly, `a = func` and `a = func()` have very different meanings.
Ruby--the most likely language you're thinking of in cont... |
Why does java/javascript/python force the use of () after a method name, even if it takes no arguments? | 3,744,180 | 5 | 2010-09-19T01:30:17Z | 3,744,207 | 8 | 2010-09-19T01:42:41Z | [
"java",
"javascript",
"python",
"methods",
"properties"
] | One of my most common bugs is that I can never remember whether something is a method or a property, so I'm constantly adding or removing parentheses.
So I was wondering if there was good logic behind making the difference between calling on an object's properties and methods explicit.
Obviously, it allows you to hav... | In languages like Python and JavaScript, functions are firstâclass objects. This means that you can pass functions around, just like you can pass around any other value. The parentheses after the function name (the `()` in `myfunc()`) actually constitute an operator, just like `+` or `*`. Instead of meaning "add this... |
pythonic way to rewrite an assignment in an if statement | 3,744,382 | 5 | 2010-09-19T03:09:09Z | 3,744,903 | 10 | 2010-09-19T07:38:44Z | [
"python",
"syntax",
"if-statement"
] | Is there a pythonic preferred way to do this that I would do in C++:
```
for s in str:
if r = regex.match(s):
print r.groups()
```
I really like that syntax, imo it's a lot cleaner than having temporary variables everywhere. The only other way that's not overly complex is
```
for s in str:
r = regex.... | How about
```
for r in [regex.match(s) for s in str]:
if r:
print r.groups()
```
or a bit more functional
```
for r in filter(None, map(regex.match, str)):
print r.groups()
``` |
Is this how you paginate, or is there a better algorithm? | 3,744,451 | 6 | 2010-09-19T03:39:25Z | 3,744,524 | 9 | 2010-09-19T04:37:53Z | [
"python",
"pagination",
"paging",
"data-paging"
] | I want to be able to take a sequence like:
```
my_sequence = ['foo', 'bar', 'baz', 'spam', 'eggs', 'cheese', 'yogurt']
```
Use a function like:
```
my_paginated_sequence = get_rows(my_sequence, 3)
```
To get:
```
[['foo', 'bar', 'baz'], ['spam', 'eggs', 'cheese'], ['yogurt']]
```
This is what I came up with by ju... | If you know you have a sliceable sequence (list or tuple),
```
def getrows_byslice(seq, rowlen):
for start in xrange(0, len(seq), rowlen):
yield seq[start:start+rowlen]
```
This of course is a generator, so if you absolutely need a list as the result, you'll use `list(getrows_byslice(seq, 3))` or the like... |
Why do you have to call .iteritems() when iterating over a dictionary in python? | 3,744,568 | 125 | 2010-09-19T05:03:33Z | 3,744,636 | 9 | 2010-09-19T05:36:02Z | [
"python",
"loops",
"dictionary"
] | Why do you have to call `iteritems()` to iterate over key, value pairs in a dictionary? ie
```
dic = {'one':'1', 'two':'2'}
for k, v in dic.iteritems():
print k, v
```
Why isn't that the default behavior of iterating over a dictionary
```
for k, v in dic:
print k, v
``` | **My guess:** Using the full tuple would be more intuitive for looping, but perhaps less so for testing for membership using `in`.
```
if key in counts:
counts[key] += 1
else:
counts[key] = 1
```
That code wouldn't really work if you had to specify both key and value for `in`. I am having a hard time imaginin... |
Why do you have to call .iteritems() when iterating over a dictionary in python? | 3,744,568 | 125 | 2010-09-19T05:03:33Z | 3,744,713 | 164 | 2010-09-19T06:13:03Z | [
"python",
"loops",
"dictionary"
] | Why do you have to call `iteritems()` to iterate over key, value pairs in a dictionary? ie
```
dic = {'one':'1', 'two':'2'}
for k, v in dic.iteritems():
print k, v
```
Why isn't that the default behavior of iterating over a dictionary
```
for k, v in dic:
print k, v
``` | For every python container C, the expectation is that
```
for item in C:
assert item in C
```
will pass just fine -- wouldn't *you* find it astonishing if one sense of `in` (the loop clause) had a completely different meaning from the other (the presence check)? I sure would! It naturally works that way for lists... |
urllib.request in Python 2.7 | 3,745,771 | 8 | 2010-09-19T13:00:49Z | 3,745,811 | 13 | 2010-09-19T13:13:08Z | [
"python",
"twitter",
"tweepy"
] | I can use urllib.request module with Python 3.1. But when I execute the same program using Python 2.7, an error comes along the lines of;
```
AttributeError: 'module' object has no attribute 'request'.
```
I believe this error is because theres no request module in urllib for Python 2.7. Because I need to use [tweepy... | use [`urllib2.urlopen`](http://docs.python.org/library/urllib2.html#urllib2.urlopen) |
Flask for Python - architectural question regarding the system | 3,746,844 | 7 | 2010-09-19T18:05:27Z | 3,748,267 | 7 | 2010-09-20T01:56:04Z | [
"python",
"django",
"web-applications",
"wsgi",
"flask"
] | I've been using Django and Django passes in a request object to a view when it's run. It looks like (from first glance) in Flask the application owns the request and it's imported (as if it was a static resource). I don't understand this and I'm just trying to wrap my brain around WSGI and Flask, etc. Any help is appre... | In Flask request is a thread-safe global, so you actually do import it:
```
from flask import request
```
I'm not sure this feature is related to WSGI as other WSGI micro-frameworks do pass request as a view function argument. "Global" request object is a feature of Flask. Flask also encourages to store user's data w... |
reload (update) a module file in the interpreter | 3,747,679 | 13 | 2010-09-19T22:10:08Z | 3,747,686 | 7 | 2010-09-19T22:12:53Z | [
"python",
"module"
] | Let's say I have this python script `script.py` and I load it in the interpreter by typing
```
import script
```
and then I execute my function by typing:
```
script.testFunction(testArgument)
```
OK so far so good, but when I change `script.py`, if I try to import again the script doesn't update. I have to exit fr... | <http://docs.python.org/library/functions.html#reload>
> ### reload(module)
>
> Reload a previously imported module. The argument must
> be a module object, so it must have been successfully imported before.
> This is useful if you have edited the module source file using an
> external editor and want to try out the n... |
reload (update) a module file in the interpreter | 3,747,679 | 13 | 2010-09-19T22:10:08Z | 3,747,692 | 11 | 2010-09-19T22:15:29Z | [
"python",
"module"
] | Let's say I have this python script `script.py` and I load it in the interpreter by typing
```
import script
```
and then I execute my function by typing:
```
script.testFunction(testArgument)
```
OK so far so good, but when I change `script.py`, if I try to import again the script doesn't update. I have to exit fr... | You can issue a `reload script`, but that will not update your existing objects and will not go deep inside other modules.
**Fortunately this is solved by `IPython` - a better python shell which supports auto-reloading.**
To use autoreloading in `IPython`, you'll have to type `import ipy_autoreload` first, or put it ... |
What is the syntax to insert one list into another list in python? | 3,748,063 | 94 | 2010-09-20T00:41:13Z | 3,748,067 | 21 | 2010-09-20T00:43:50Z | [
"python",
"list",
"append",
"extend"
] | Given two lists:
```
x = [1,2,3]
y = [4,5,6]
```
What is the syntax to:
1. Insert `x` into `y` such that `y` now looks like `[1, 2, 3, [4, 5, 6]]`?
2. Insert all the items of `x` into `y` such that `y` now looks like `[1, 2, 3, 4, 5, 6]`? | ```
foo = [1, 2, 3]
bar = [4, 5, 6]
foo.append(bar) --> [1, 2, 3, [4, 5, 6]]
foo.extend(bar) --> [1, 2, 3, 4, 5, 6]
```
<http://docs.python.org/tutorial/datastructures.html> |
What is the syntax to insert one list into another list in python? | 3,748,063 | 94 | 2010-09-20T00:41:13Z | 3,748,071 | 168 | 2010-09-20T00:46:01Z | [
"python",
"list",
"append",
"extend"
] | Given two lists:
```
x = [1,2,3]
y = [4,5,6]
```
What is the syntax to:
1. Insert `x` into `y` such that `y` now looks like `[1, 2, 3, [4, 5, 6]]`?
2. Insert all the items of `x` into `y` such that `y` now looks like `[1, 2, 3, 4, 5, 6]`? | Do you mean `append`?
```
>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x.append(y)
>>> x
[1, 2, 3, [4, 5, 6]]
```
Or merge?
```
>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x + y
[1, 2, 3, 4, 5, 6]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 5, 6]
``` |
What is the syntax to insert one list into another list in python? | 3,748,063 | 94 | 2010-09-20T00:41:13Z | 3,748,092 | 9 | 2010-09-20T00:51:48Z | [
"python",
"list",
"append",
"extend"
] | Given two lists:
```
x = [1,2,3]
y = [4,5,6]
```
What is the syntax to:
1. Insert `x` into `y` such that `y` now looks like `[1, 2, 3, [4, 5, 6]]`?
2. Insert all the items of `x` into `y` such that `y` now looks like `[1, 2, 3, 4, 5, 6]`? | The question does not make clear what exactly you want to achieve.
List has the `append` method, which appends its argument to the list:
```
>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.append(list_two)
>>> list_one
[1, 2, 3, [4, 5, 6]]
```
There's also the `extend` method, which appends *items* from t... |
how to bold csv data in excel? | 3,749,020 | 6 | 2010-09-20T06:10:21Z | 3,749,026 | 12 | 2010-09-20T06:13:11Z | [
"python"
] | I work on a python(django) project. I write csv code as follows,
```
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=DueDateWiseSearch.csv'
writer = csv.writer(response)
writer.writerow(['Infant Name','Mother Name','Mother Address',
'Next Vaccine D... | There's no way to do that in CSV. You could all caps the output, or you could use another format that supports text styles. |
Python group by | 3,749,512 | 50 | 2010-09-20T07:50:01Z | 3,749,537 | 74 | 2010-09-20T07:54:40Z | [
"python",
"group-by"
] | Assume that I have a such set of pair datas where index 0 is the value and the index 1 is the type:
```
input = [
('11013331', 'KAT'),
('9085267', 'NOT'),
('5238761', 'ETH'),
('5349618', 'ETH'),
('11788544', 'NOT'),
('962142', 'ETH'),
('7... | Do it in 2 steps. First, create a dictionary.
```
>>> input = [('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'), ('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH')]
>>> from collections import default... |
Python group by | 3,749,512 | 50 | 2010-09-20T07:50:01Z | 3,749,740 | 30 | 2010-09-20T08:28:14Z | [
"python",
"group-by"
] | Assume that I have a such set of pair datas where index 0 is the value and the index 1 is the type:
```
input = [
('11013331', 'KAT'),
('9085267', 'NOT'),
('5238761', 'ETH'),
('5349618', 'ETH'),
('11788544', 'NOT'),
('962142', 'ETH'),
('7... | Python's built-in `itertools` module actually has a [`groupby`](https://docs.python.org/3.5/library/itertools.html#itertools.groupby) function that you could use, but the elements to be grouped must first be sorted such that the elements to be grouped are contiguous in the list:
```
sortkeyfn = key=lambda s:s[1]
input... |
Type safety in Python | 3,749,796 | 17 | 2010-09-20T08:36:48Z | 3,749,823 | 13 | 2010-09-20T08:41:50Z | [
"python",
"type-safety"
] | I've defined a `Vector` class which has three property variables: `x`, `y` and `z`. Coordinates have to be real numbers, but there's nothing to stop one from doing the following:
```
>>> v = Vector(8, 7.3, -1)
>>> v.x = "foo"
>>> v.x
"foo"
```
I could implement "type safety" like this:
```
import numbers
class Vect... | You have to ask yourself why you want to test type on setting these values. Just raise a `TypeError` in any calculation which happens to stumble over the wrong value type. Bonus: standard operations already do this.
```
>>> 3.0 / 'abc'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupp... |
Type safety in Python | 3,749,796 | 17 | 2010-09-20T08:36:48Z | 3,749,837 | 10 | 2010-09-20T08:44:24Z | [
"python",
"type-safety"
] | I've defined a `Vector` class which has three property variables: `x`, `y` and `z`. Coordinates have to be real numbers, but there's nothing to stop one from doing the following:
```
>>> v = Vector(8, 7.3, -1)
>>> v.x = "foo"
>>> v.x
"foo"
```
I could implement "type safety" like this:
```
import numbers
class Vect... | [Duck Typing](http://en.wikipedia.org/wiki/Duck_typing) is the usual way in Python. It should work with anything that **behaves** like a number, but not necessarily **is** a real number.
In most cases in Python one should not explicitly check for types. You gain flexibility because your code can be used with custom da... |
Why does adding a trailing comma after a variable name make it a tuple? | 3,750,632 | 15 | 2010-09-20T10:43:50Z | 3,750,731 | 24 | 2010-09-20T10:56:23Z | [
"python",
"syntax",
"tuples"
] | I want to know that why adding a trailing comma after a variable name (in this case a string) makes it a `tuple`. i.e.
```
>>> abc = 'mystring',
>>> print(abc)
('mystring',)
```
When I print `abc` it returns the `tuple` `('mystring',)`. | It is the commas, not the parentheses, which are significant. The Python tutorial says:
> A tuple consists of a number of values separated by commas
Parentheses are used for disambiguation in other places where commas are used, for example, enabling you to nest or enter a tuple as part of an argument list.
See the [... |
Create file path from variables | 3,751,900 | 15 | 2010-09-20T13:27:41Z | 3,751,917 | 34 | 2010-09-20T13:29:53Z | [
"python",
"path"
] | I am looking for some advice as to the best way to generate a file path using variables, currently my code looks similar to the following:
```
path = /my/root/directory
for x in list_of_vars:
if os.path.isdir(path + '/' + x): # line A
print(x + ' exists.')
else:
os.mkdir(path +... | Yes there is such a built-in function: [`os.path.join`](http://docs.python.org/library/os.path.html#os.path.join).
```
>>> import os.path
>>> os.path.join('/my/root/directory', 'in', 'here')
'/my/root/directory/in/here'
``` |
Create file path from variables | 3,751,900 | 15 | 2010-09-20T13:27:41Z | 3,751,926 | 7 | 2010-09-20T13:31:06Z | [
"python",
"path"
] | I am looking for some advice as to the best way to generate a file path using variables, currently my code looks similar to the following:
```
path = /my/root/directory
for x in list_of_vars:
if os.path.isdir(path + '/' + x): # line A
print(x + ' exists.')
else:
os.mkdir(path +... | You want the path.join() function from os.path.
```
>>> from os import path
>>> path.join('foo', 'bar')
'foo/bar'
```
This builds your path with os.sep (instead of the less portable `'/'`) and does it more efficiently (in general) than using `+`.
However, this won't actually create the path. For that, you have to do... |
Can Python be made to generate tracing similar to bash's set -x? | 3,751,927 | 6 | 2010-09-20T13:31:07Z | 3,752,246 | 7 | 2010-09-20T14:09:24Z | [
"python",
"bash",
"debugging",
"set",
"trace"
] | Is there a similar mechanism in Python, to the effect `set -x` has on bash?
Here's some example output from bash in this mode:
```
+ for src in cpfs.c log.c popcnt.c ssse3_popcount.c blkcache.c context.c types.c device.c
++ my_mktemp blkcache.c.o
+++ mktemp -t blkcache.c.o.2160.XXX
++ p=/tmp/blkcache.c.o.2160.IKA
++ ... | Perhaps use [sys.settrace](http://docs.python.org/library/sys.html#sys.settrace):
Use `traceit()` to turn on tracing, use `traceit(False)` to turn off tracing.
```
import sys
import linecache
def _traceit(frame, event, arg):
'''
http://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_... |
Python string formatting + UTF-8 strange behaviour | 3,751,968 | 3 | 2010-09-20T13:35:46Z | 3,752,057 | 7 | 2010-09-20T13:46:34Z | [
"python",
"string",
"utf-8"
] | When printing a formatted string with a fixed length (e.g, `%20s`), the width differs from UTF-8 string to a normal string:
```
>>> str1="Adam Matan"
>>> str2="××× ×ת×"
>>> print "X %20s X" % str1
X Adam Matan X
>>> print "X %20s X" % str2
X ××× ××ª× X
```
Note the difference:
```
X ... | You need to specify that the second string is Unicode by putting `u` in front of the string:
```
>>> str1="Adam Matan"
>>> str2=u"××× ×ת×"
>>> print "X %20s X" % str1
X Adam Matan X
>>> print "X %20s X" % str2
X ××× ××ª× X
```
Doing this lets Python know that it's counting Unicode ch... |
Join string and None/string using optional delimiter | 3,752,240 | 6 | 2010-09-20T14:08:53Z | 3,752,273 | 7 | 2010-09-20T14:12:25Z | [
"python",
"string"
] | I am basically looking for the Python equivalent to this VB/VBA string operation:
```
FullName = LastName & ", " + FirstName
```
In VB/VBA `+` and `&` are both concatenation operators, but they differ in how they handle a Null value:
```
"Some string" + Null ==> Null
"Some string" & Null ==> "Some string"
```
This ... | ```
FullName = LastName + (", " + FirstName if FirstName else "")
``` |
Join string and None/string using optional delimiter | 3,752,240 | 6 | 2010-09-20T14:08:53Z | 3,752,317 | 35 | 2010-09-20T14:17:05Z | [
"python",
"string"
] | I am basically looking for the Python equivalent to this VB/VBA string operation:
```
FullName = LastName & ", " + FirstName
```
In VB/VBA `+` and `&` are both concatenation operators, but they differ in how they handle a Null value:
```
"Some string" + Null ==> Null
"Some string" & Null ==> "Some string"
```
This ... | The following line can be used to concatenate more not-None elements:
```
FullName = ', '.join(filter(None, (LastName, FirstName)))
``` |
How do I get a list of all parent tags in BeautifulSoup? | 3,752,327 | 3 | 2010-09-20T14:18:34Z | 3,753,929 | 7 | 2010-09-20T17:39:48Z | [
"python",
"html-parsing",
"beautifulsoup",
"xml-parsing"
] | Let's say I have a structure like this:
```
<folder name="folder1">
<folder name="folder2">
<bookmark href="link.html">
</folder>
</folder>
```
If I point to bookmark, what would be the command to just extract all of the folder lines?
For example,
```
bookmarks = soup.findAll('bookmark')
```
the... | Here is my stab at it:
```
>>> from BeautifulSoup import BeautifulSoup
>>> html = """<folder name="folder1">
<folder name="folder2">
<bookmark href="link.html">
</folder>
</folder>
"""
>>> bookmarks = soup.findAll('bookmark')
>>> [p.get('name') for p in bookmarks[0].findAllPrevious(name = 'folder')... |
Python: PIL replace a single RGBA color | 3,752,476 | 11 | 2010-09-20T14:37:19Z | 3,753,428 | 24 | 2010-09-20T16:26:33Z | [
"python",
"colors",
"python-imaging-library"
] | I have already taken a look at this question: [SO question](http://stackoverflow.com/questions/1616767/pil-best-way-to-replace-color) and seem to have implemented a very similar technique for replacing a single color including the alpha values:
```
c = Image.open(f)
c = c.convert("RGBA")
w, h = c.size
cnt = 0
for px i... | If you have numpy, it provides a much, much faster way to operate on PIL images.
E.g.:
```
import Image
import numpy as np
im = Image.open('test.png')
im = im.convert('RGBA')
data = np.array(im) # "data" is a height x width x 4 numpy array
red, green, blue, alpha = data.T # Temporarily unpack the bands for readab... |
Is django-piston mature enough? | 3,752,607 | 7 | 2010-09-20T14:52:18Z | 6,232,130 | 13 | 2011-06-03T20:10:40Z | [
"python",
"django",
"web-services",
"rest",
"django-piston"
] | I'm developing an advertising site and want to use web services for the requests. I mean, a publisher site will put a JavaScript snippet and it will pull a banner through a REST GET.
Is the [django-piston](http://pypi.python.org/pypi/django-piston) framework mature enough to implement this functionality? | I've been looking into finding the "best" Django REST package and came across this table, which is useful:
<http://www.djangopackages.com/grids/g/api/>
At this point (mid-2011) Django-Tastypie is the clear winner for number of authors, updated codebase, documentation, and overall activity.
EDIT, Jan.2012: I think th... |
Python: Adding element to list while iterating | 3,752,618 | 22 | 2010-09-20T14:54:23Z | 3,752,697 | 14 | 2010-09-20T15:00:53Z | [
"python",
"iteration"
] | I know that it is not allowed to remove elements while iterating a list, but is it allowed to add elements to a python list while iterating. Here is an example:
```
for a in myarr:
if somecond(a):
myarr.append(newObj())
```
I have tried this in my code and it seems to works fine, however i dont kn... | well, according to <http://docs.python.org/tutorial/controlflow.html>
> It is not safe to modify the sequence
> being iterated over in the loop (this
> can only happen for mutable sequence
> types, such as lists). If you need to
> modify the list you are iterating over
> (for example, to duplicate selected
> items) yo... |
Python: Adding element to list while iterating | 3,752,618 | 22 | 2010-09-20T14:54:23Z | 5,677,451 | 22 | 2011-04-15T13:23:14Z | [
"python",
"iteration"
] | I know that it is not allowed to remove elements while iterating a list, but is it allowed to add elements to a python list while iterating. Here is an example:
```
for a in myarr:
if somecond(a):
myarr.append(newObj())
```
I have tried this in my code and it seems to works fine, however i dont kn... | Why don't you just do it the idiomatic C way? This ought to be bullet-proof, but it won't be fast. I'm pretty sure indexing into a list in Python walks the linked list, so this is a "Shlemiel the Painter" algorithm. But I tend not to worry about optimization until it becomes clear that a particular section of code is r... |
Using NLTK and WordNet; how do I convert simple tense verb into its present, past or past participle form? | 3,753,021 | 18 | 2010-09-20T15:36:30Z | 3,761,041 | 14 | 2010-09-21T13:58:05Z | [
"python",
"nlp",
"nltk",
"wordnet"
] | Using NLTK and [WordNet](https://en.wikipedia.org/wiki/WordNet), how do I convert simple tense verb into its present, past or past participle form?
**For example:**
I want to write a function which would give me verb in expected form as follows.
```
v = 'go'
present = present_tense(v)
print present # prints "going"
... | I think what you're looking for is the [NodeBox::Linguistics](http://nodebox.net/code/index.php/Linguistics#verb_conjugation) library. It does exactly that:
```
print en.verb.present("gave")
>>> give
``` |
Using NLTK and WordNet; how do I convert simple tense verb into its present, past or past participle form? | 3,753,021 | 18 | 2010-09-20T15:36:30Z | 26,802,243 | 9 | 2014-11-07T13:21:53Z | [
"python",
"nlp",
"nltk",
"wordnet"
] | Using NLTK and [WordNet](https://en.wikipedia.org/wiki/WordNet), how do I convert simple tense verb into its present, past or past participle form?
**For example:**
I want to write a function which would give me verb in expected form as follows.
```
v = 'go'
present = present_tense(v)
print present # prints "going"
... | With the help of NLTK this can also be done. It can give the base form of the verb. But not the exact tense, but it still can be useful. Try the following code.
```
from nltk.stem.wordnet import WordNetLemmatizer
words = ['gave','went','going','dating']
for word in words:
print word+"-->"+WordNetLemmatizer().lemma... |
Serializing Foreign Key objects in Django | 3,753,359 | 25 | 2010-09-20T16:16:04Z | 3,753,769 | 22 | 2010-09-20T17:14:19Z | [
"python",
"django",
"django-orm"
] | I have been working on developing some RESTful Services in Django to be used with both Flash and Android apps.
Developing the services interface has been quite simple, but I have been running into an issue with serializing objects that have foreign key and many to many relationships.
I have a model like this:
```
cl... | I had a similar requirement although not for RESTful purposes. I was able to achieve what I needed by using a "full" serializing module, in my case [`Django Full Serializers`](http://code.google.com/p/wadofstuff/wiki/DjangoFullSerializers). This is part of [wadofstuff](http://code.google.com/p/wadofstuff/) and is distr... |
packing and unpacking variable length array/string using the struct module in python | 3,753,589 | 18 | 2010-09-20T16:48:24Z | 3,753,685 | 15 | 2010-09-20T17:01:44Z | [
"python",
"binary",
"struct",
"python-3.x"
] | I am trying to get a grip around the packing and unpacking of binary data in Python 3. Its actually not that hard to understand, except one problem:
what if I have a variable length textstring and want to pack and unpack this in the most elegant manner?
As far as I can tell from the manual I can only unpack fixed siz... | The `struct` module does only support fixed-length structures. For variable-length strings, your options are either:
* Dynamically construct your format string (a `str` will have to be converted to a `bytes` before passing it to `pack()`):
```
s = bytes(s, 'utf-8') # Or other appropriate encoding
struct.pack... |
Python: tree structure and numerical codes? | 3,753,665 | 6 | 2010-09-20T16:58:25Z | 3,753,796 | 9 | 2010-09-20T17:17:33Z | [
"python"
] | I'm using Python and I have some data that I want to put into a tree format and assign codes to. Here's some example data:
```
Africa North Africa Algeria
Africa North Africa Morocco
Africa West Africa Ghana
Africa West Africa Sierra Leone
```
What would be an appropriate tree structure for ... | I would recommend, assuming you can count on there being no duplication among the names, something like:
```
class Node(object):
byname = {}
def __init__(self, name, parent=None):
self.name = name
self.parent = parent
self.children = []
self.byname[name] = self
if paren... |
Declare function at end of file in Python | 3,754,240 | 36 | 2010-09-20T18:21:08Z | 3,754,284 | 53 | 2010-09-20T18:27:08Z | [
"python",
"function",
"formatting"
] | Is it possible to call a function without first fully defining it? When attempting this I get the error: "*function\_name* is not defined". I am coming from a C++ background so this issue stumps me.
Declaring the function before works:
```
def Kerma():
return "energy / mass"
print Kerma()
```
However, a... | One way that is sort of idiomatic in Python is writing:
```
def main():
print Kerma()
def Kerma():
return "energy / mass"
if __name__ == '__main__':
main()
```
This allows you to write you code in the order you like as long as you keep calling the function `main` at the end. |
Declare function at end of file in Python | 3,754,240 | 36 | 2010-09-20T18:21:08Z | 3,756,598 | 8 | 2010-09-21T00:58:45Z | [
"python",
"function",
"formatting"
] | Is it possible to call a function without first fully defining it? When attempting this I get the error: "*function\_name* is not defined". I am coming from a C++ background so this issue stumps me.
Declaring the function before works:
```
def Kerma():
return "energy / mass"
print Kerma()
```
However, a... | When a Python module (file) is run, the top level statements in it are executed in the order they appear from top to bottom (beginning to end). This means you can't reference something until you've defined it. For example the following will generate the error shown:
```
c = a + b # NameError: name 'a' is not defined
... |
running PIL on 64bit | 3,754,574 | 11 | 2010-09-20T19:00:03Z | 3,757,358 | 23 | 2010-09-21T04:41:36Z | [
"python",
"64bit",
"python-imaging-library"
] | Is there any way of running PIL(Python Imaging Library) on a 64bit OS?
it is windows 7 64bit | PIL-1.1.7.win-amd64-py2.x installers are available at <http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil> |
a basic question about "while true" | 3,754,620 | 32 | 2010-09-20T19:06:08Z | 3,754,632 | 64 | 2010-09-20T19:07:16Z | [
"python",
"syntax"
] | level: beginner
```
def play_game(word_list):
hand = deal_hand(HAND_SIZE) # random init
while True:
cmd = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
if cmd == 'n':
hand = deal_hand(HAND_SIZE)
play_hand(hand.copy(), word_list)
... | `while True` means loop forever. The `while` statement takes an expression and executes the loop body while the expression evaluates to (boolean) "true". `True` always evaluates to boolean "true" and thus executes the loop body indefinitely. It's an idiom that you'll just get used to eventually! Most languages you're l... |
a basic question about "while true" | 3,754,620 | 32 | 2010-09-20T19:06:08Z | 3,754,685 | 26 | 2010-09-20T19:12:33Z | [
"python",
"syntax"
] | level: beginner
```
def play_game(word_list):
hand = deal_hand(HAND_SIZE) # random init
while True:
cmd = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
if cmd == 'n':
hand = deal_hand(HAND_SIZE)
play_hand(hand.copy(), word_list)
... | > my question: while WHAT is True?
While `True` is `True`.
The while loop will run as long as the conditional expression evaluates to `True`.
Since `True` always evaluates to `True`, the loop will run indefinitely, until something within the loop `return`s or `break`s. |
Pythonic way to check if a list is sorted or not | 3,755,136 | 53 | 2010-09-20T20:15:14Z | 3,755,153 | 29 | 2010-09-20T20:18:09Z | [
"python",
"algorithm",
"list",
"sorted"
] | Is there a pythonic way to check if a list is already sorted in ASC or DESC.
```
listtimestamps=[1,2,3,5,6,7]
```
something like `isttimestamps.isSorted()` that returns `True` or `False`.
EDIT: I want to input a list of timestamps for some messages and check if the the transactions appeared in the correct order.
an... | I would just use
```
if sorted(lst) == lst:
# code here
```
unless it's a very big list in which case you might want to create a custom function.
if you are just going to sort it if it's not sorted, then forget the check and sort it.
```
lst.sort()
```
and don't think about it too much.
if you want a custom f... |
Pythonic way to check if a list is sorted or not | 3,755,136 | 53 | 2010-09-20T20:15:14Z | 3,755,251 | 89 | 2010-09-20T20:33:03Z | [
"python",
"algorithm",
"list",
"sorted"
] | Is there a pythonic way to check if a list is already sorted in ASC or DESC.
```
listtimestamps=[1,2,3,5,6,7]
```
something like `isttimestamps.isSorted()` that returns `True` or `False`.
EDIT: I want to input a list of timestamps for some messages and check if the the transactions appeared in the correct order.
an... | Actually we are not giving the answer anijhaw is looking for. Here is the one liner:
```
all(l[i] <= l[i+1] for i in xrange(len(l)-1))
``` |
Pythonic way to check if a list is sorted or not | 3,755,136 | 53 | 2010-09-20T20:15:14Z | 3,755,410 | 18 | 2010-09-20T20:53:53Z | [
"python",
"algorithm",
"list",
"sorted"
] | Is there a pythonic way to check if a list is already sorted in ASC or DESC.
```
listtimestamps=[1,2,3,5,6,7]
```
something like `isttimestamps.isSorted()` that returns `True` or `False`.
EDIT: I want to input a list of timestamps for some messages and check if the the transactions appeared in the correct order.
an... | This iterator form is 10-15% faster than using integer indexing:
```
# from itertools import izip as zip # python 2 only!
def is_sorted(l):
return all(a <= b for a, b in zip(l[:-1], l[1:]))
``` |
Pythonic way to check if a list is sorted or not | 3,755,136 | 53 | 2010-09-20T20:15:14Z | 17,224,104 | 12 | 2013-06-20T21:28:02Z | [
"python",
"algorithm",
"list",
"sorted"
] | Is there a pythonic way to check if a list is already sorted in ASC or DESC.
```
listtimestamps=[1,2,3,5,6,7]
```
something like `isttimestamps.isSorted()` that returns `True` or `False`.
EDIT: I want to input a list of timestamps for some messages and check if the the transactions appeared in the correct order.
an... | A beautiful way to implement this is to use the `imap` function from `itertools`:
```
from itertools import imap, tee
import operator
def is_sorted(iterable, compare=operator.le):
a, b = tee(iterable)
next(b, None)
return all(imap(compare, a, b))
```
This implementation is fast and works on any iterables. |
Python Reportlab PDF - Centering Text on page | 3,755,851 | 5 | 2010-09-20T21:59:14Z | 3,755,880 | 7 | 2010-09-20T22:04:21Z | [
"python",
"pdf-generation",
"reportlab"
] | I am using [ReportLab](http://www.reportlab.com/software/opensource/) to generate a pdf dynamically with python.
I would like a line of text to be centered on a page. Here is the specific code I currently have, but do not know how to center the text horizontally.
```
header = p.beginText(190, 740)
header.textOut("Tit... | The reportlab canvas has a [drawCentredString](http://www.reportlab.com/apis/reportlab/dev/pdfgen.html#reportlab.pdfgen.canvas.Canvas.drawCentredString) method. And yes, they spell it like that.
> Weâre British, dammit, and proud of
> our spelling!
**Edit**:
As for text objects, I'm afraid you don't. You can do som... |
Trying to use my subnet address in python code | 3,755,863 | 3 | 2010-09-20T22:01:02Z | 3,756,002 | 8 | 2010-09-20T22:32:42Z | [
"python",
"linux",
"networking"
] | I'm trying to get my ip subnet address (192.168.1.xxx) into my python code. I'm running linux/osx. How do I do this/ What is the best way to do this? | The easiest way to to this in my experience is to use two third party packages:
* [python-netifaces](http://pypi.python.org/pypi/netifaces/): Portable network interface information
* [python-netaddr](http://pypi.python.org/pypi/netaddr): Pythonic manipulation of IPv4, IPv6, CIDR, EUI and MAC network addresses
So inst... |
Python multiprocessing : progress report from processes | 3,756,533 | 9 | 2010-09-21T00:37:24Z | 3,756,572 | 14 | 2010-09-21T00:49:01Z | [
"python",
"multiprocessing"
] | I have some tasks in an application that are CPU bound and I want to use the multiprocessing module to use the multi-cores processors.
I take a big task (a video file analysis) and I split it into several smaller tasks which are put in a queue and done by worker processes.
What I want to know is how to report progress ... | I would recommend a [multiprocessing.Queue](http://docs.python.org/library/multiprocessing.html#multiprocessing.Queue): nothing easier than for the worker processes to post their updates (presumably as tuples with the various aspect of their progress updates) there, while the main process just wait for such messages an... |
Connect Sphinx autodoc-skip-member to my function | 3,757,500 | 24 | 2010-09-21T05:22:08Z | 3,757,526 | 34 | 2010-09-21T05:28:07Z | [
"python",
"python-sphinx"
] | I want to use [sphinx's autodoc-skip-member](http://sphinx.pocoo.org/ext/autodoc.html#event-autodoc-skip-member) event to select a portion of the members on a certain python class for documentation.
But it isn't clear from the sphinx docs, and I can't find any examples that illustrate: where do I put the code to conne... | Aha, last ditch effort on a little googling turned up [this example](http://trac.sagemath.org/sage_trac/attachment/ticket/7813/conf.py), scroll down to the bottom. Apparently a setup() function in conf.py will get called with the app. I was able to define the following at the bottom of my conf.py:
```
def maybe_skip_m... |
Connect Sphinx autodoc-skip-member to my function | 3,757,500 | 24 | 2010-09-21T05:22:08Z | 21,449,475 | 10 | 2014-01-30T06:36:51Z | [
"python",
"python-sphinx"
] | I want to use [sphinx's autodoc-skip-member](http://sphinx.pocoo.org/ext/autodoc.html#event-autodoc-skip-member) event to select a portion of the members on a certain python class for documentation.
But it isn't clear from the sphinx docs, and I can't find any examples that illustrate: where do I put the code to conne... | This answer expands upon the [answer by bstpierre](http://stackoverflow.com/a/3757526/832230). Below is the relevant portion from my `conf.py`:
```
autodoc_default_flags = ['members', 'private-members', 'special-members',
#'undoc-members',
'show-inheritance']
def auto... |
Changing the behaviour of a Django model with __getattr__ | 3,757,951 | 4 | 2010-09-21T06:59:28Z | 3,758,206 | 7 | 2010-09-21T07:37:51Z | [
"python",
"django",
"class"
] | I'm trying to change the behaviour of a Django model to allow me to access a foreign key's properties directly from the parent, e.g.
```
cache.part_number
vs
cache.product.part_number
```
I've tried overriding the `__getattr__` method as follows, but I get a recursion error when I try to access the foreign key's ... | Consider the code inside your `__getattr__` method:
```
value = getattr(self.product, name, None)
```
Try guessing what happens when `self.product` is invoked. I'll give you a clue: it involves a call to `__getattr__`. The [documentation](http://docs.python.org/reference/datamodel.html#object.__getattr__) has the det... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.