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 |
|---|---|---|---|---|---|---|---|---|---|
one-to-many inline select with django admin | 6,034,047 | 27 | 2011-05-17T16:26:40Z | 8,818,880 | 21 | 2012-01-11T12:01:20Z | [
"python",
"django",
"django-models",
"django-admin"
] | I have a standard many-to-one relationship set up. There are a bunch of fields, but for our purposes here, the relevant model is:
```
class Class(models.Model):
name = models.CharField(max_length=128)
class Student(models.Model):
class = models.ForeignKey(Class)
name = models.CharField(max_length=128)
... | Here is "custom form" solution as Luke Sneeringer suggested. Anyway, I'm suprised by absence of out-of-the-box Django solution to this (rather natural and probably common) problem. Am I missing something?
```
from django import forms
from django.db import models
from django.contrib import admin
class Foo(models.Model... |
Compiling with cython and mingw produces gcc: error: unrecognized command line option '-mno-cygwin' | 6,034,390 | 108 | 2011-05-17T16:59:16Z | 6,035,864 | 174 | 2011-05-17T19:11:10Z | [
"python",
"mingw",
"distutils",
"cython"
] | I'm trying to compile a python extension with cython in win 7 64-bit using mingw (64-bit).
I'm working with Python 2.6 (Active Python 2.6.6) and with the adequate distutils.cfg file (setting mingw as the compiler)
When executing
```
> C:\Python26\programas\Cython>python setup.py build_ext --inplace
```
I get an er... | It sounds like GCC 4.7.0 has finally removed the deprecated `-mno-cygwin` option, but distutils has not yet caught up with it. Either install a slightly older version of MinGW, or edit `distutils\cygwinccompiler.py` in your Python directory to remove all instances of `-mno-cygwin`. |
Compiling with cython and mingw produces gcc: error: unrecognized command line option '-mno-cygwin' | 6,034,390 | 108 | 2011-05-17T16:59:16Z | 15,185,029 | 11 | 2013-03-03T11:09:03Z | [
"python",
"mingw",
"distutils",
"cython"
] | I'm trying to compile a python extension with cython in win 7 64-bit using mingw (64-bit).
I'm working with Python 2.6 (Active Python 2.6.6) and with the adequate distutils.cfg file (setting mingw as the compiler)
When executing
```
> C:\Python26\programas\Cython>python setup.py build_ext --inplace
```
I get an er... | During the process of solving these and the following problems I found, I wrote a recipe in [this thread](http://comments.gmane.org/gmane.comp.python.cython.user/3488). I reproduce it here in case it could be of utility for others:
---
Step by step recipe to compile 64-bit cython extensions with python
2.6.6 with min... |
Compiling with cython and mingw produces gcc: error: unrecognized command line option '-mno-cygwin' | 6,034,390 | 108 | 2011-05-17T16:59:16Z | 19,853,092 | 9 | 2013-11-08T06:43:29Z | [
"python",
"mingw",
"distutils",
"cython"
] | I'm trying to compile a python extension with cython in win 7 64-bit using mingw (64-bit).
I'm working with Python 2.6 (Active Python 2.6.6) and with the adequate distutils.cfg file (setting mingw as the compiler)
When executing
```
> C:\Python26\programas\Cython>python setup.py build_ext --inplace
```
I get an er... | This bug has now been fixed in [Python 2.7.6 release candidate 1](http://www.python.org/download/releases/2.7.6/).
The patching commit is [here](http://hg.python.org/cpython/rev/7d9a1aa8d95e/).
The resolved issue tracker thread is [here](http://bugs.python.org/issue12641). |
Bad magic number error persists even after rebuilding the .pyc file | 6,034,621 | 7 | 2011-05-17T17:18:57Z | 6,034,978 | 11 | 2011-05-17T17:52:39Z | [
"python",
"python-3.x"
] | When running a Python 3 script of mine, I encounter a "Bad magic number" error (while the script tries to import another module). At first I imagined it's because there are .pyc files built by Python 2. I deleted the \_\_pycache\_\_ directory and reran the script, but the interpreter still gives me the same error when ... | The last line of the stack trace shows the path to the `pyc` file causing the error:
```
ImportError: Bad magic number in /home/mostafa/python/list.pyc
```
Assuming you have `list.py` in your PYTHONPATH, you can delete `/home/mostafa/python/list.pyc`. When you import `list`, Python3 will generate a new version of `li... |
Python Method overriding, does signature matter? | 6,034,662 | 11 | 2011-05-17T17:23:10Z | 6,034,715 | 15 | 2011-05-17T17:28:26Z | [
"python",
"inheritance",
"methods",
"override"
] | Lets say I have
```
class Super():
def method1():
pass
class Sub(Super):
def method1(param1, param2, param3):
stuff
```
Is this correct? Will calls to method1 always go to the sub class? My plan is to have 2 sub classes each override method1 with different params | Python will allow this, but if `method1()` is intended to be executed from external code then you may want to reconsider this, as it violates [LSP](http://en.wikipedia.org/wiki/Liskov_substitution_principle) and so won't always work properly. |
Python closure not working as expected | 6,035,848 | 11 | 2011-05-17T19:09:44Z | 6,035,865 | 22 | 2011-05-17T19:11:12Z | [
"python",
"lambda",
"closures"
] | When I run the following script, both lambda's run os.startfile() on the same file -- junk.txt. I would expect each lambda to use the value "f" was set to when the lambda was created. Is there a way to get this to function as I expect?
```
import os
def main():
files = [r'C:\_local\test.txt', r'C:\_local\junk.tx... | One way is to do this:
```
def main():
files = [r'C:\_local\test.txt', r'C:\_local\junk.txt']
funcs = []
for f in files:
# create a new lambda and store the current `f` as default to `path`
funcs.append(lambda path=f: os.stat(path))
print funcs
# calling the lambda without a parame... |
Call a python function from jinja2 | 6,036,082 | 82 | 2011-05-17T19:29:48Z | 6,038,550 | 55 | 2011-05-18T00:07:58Z | [
"python",
"jinja2"
] | I am using jinja2, and I want to call a python function as a helper, using a similar syntax as if I were calling a macro. jinja2 seems intent on preventing me from making a function call, and insists I repeat myself by copying the function into a template as a macro.
Is there any straightforward way to do this? And, i... | I think jinja deliberately makes it difficult to run 'arbitrary' python within a template. It tries to enforce the opinion that less logic in templates is a good thing.
You can manipulate the global namespace within an `Environment` instance to add references to your functions. It must be done *before* you load any te... |
Call a python function from jinja2 | 6,036,082 | 82 | 2011-05-17T19:29:48Z | 7,226,047 | 138 | 2011-08-29T04:26:11Z | [
"python",
"jinja2"
] | I am using jinja2, and I want to call a python function as a helper, using a similar syntax as if I were calling a macro. jinja2 seems intent on preventing me from making a function call, and insists I repeat myself by copying the function into a template as a macro.
Is there any straightforward way to do this? And, i... | For those using Flask, put this in your `__init__.py`:
```
def clever_function():
return u'HELLO'
app.jinja_env.globals.update(clever_function=clever_function)
```
and in your template call it with `{{ clever_function() }}` |
Call a python function from jinja2 | 6,036,082 | 82 | 2011-05-17T19:29:48Z | 22,966,127 | 51 | 2014-04-09T14:45:09Z | [
"python",
"jinja2"
] | I am using jinja2, and I want to call a python function as a helper, using a similar syntax as if I were calling a macro. jinja2 seems intent on preventing me from making a function call, and insists I repeat myself by copying the function into a template as a macro.
Is there any straightforward way to do this? And, i... | **Note: This is Flask specific!**
I know this post is quite old, but there are better methods of doing this in the newer versions of Flask using context processors.
**Variables can easily be created:**
```
@app.context_processor
def example():
return dict(myexample='This is an example')
```
The above can be use... |
Call a python function from jinja2 | 6,036,082 | 82 | 2011-05-17T19:29:48Z | 27,096,279 | 13 | 2014-11-24T00:42:11Z | [
"python",
"jinja2"
] | I am using jinja2, and I want to call a python function as a helper, using a similar syntax as if I were calling a macro. jinja2 seems intent on preventing me from making a function call, and insists I repeat myself by copying the function into a template as a macro.
Is there any straightforward way to do this? And, i... | ```
from jinja2 import Template
def custom_function(a):
return a.replace('o', 'ay')
template = 'Hey, my name is {{ custom_function(first_name) }}'
jinga_html_template = Template(template)
jinga_html_template.globals['custom_function'] = custom_function
fields = {'firstname': 'Jo'}
print jinga_html_template.rende... |
Platform-independent file paths? | 6,036,129 | 17 | 2011-05-17T19:33:10Z | 6,036,156 | 29 | 2011-05-17T19:36:23Z | [
"python",
"path",
"cross-platform"
] | How can I use a file inside my app folder in Python? Platform independent of course...
something similar to this:
```
#!/bin/sh
mypath=${0%/*}
LIBDIR=$mypath/modules
``` | You can use `os.path` and its functions, which take care of OS-specific paths:
```
>>> import os
>>> os.path.join('app', 'subdir', 'dir', 'filename.foo')
'app/subdir/dir/filename.foo'
```
On Windows, it should print out with backslashes. |
Platform-independent file paths? | 6,036,129 | 17 | 2011-05-17T19:33:10Z | 6,036,168 | 9 | 2011-05-17T19:36:52Z | [
"python",
"path",
"cross-platform"
] | How can I use a file inside my app folder in Python? Platform independent of course...
something similar to this:
```
#!/bin/sh
mypath=${0%/*}
LIBDIR=$mypath/modules
``` | ```
import os
os.path.join(os.path.curdir, 'file.name')
```
or
```
import os
os.path.join(os.path.dirname(__file__), 'file.name')
```
depending upon whether it's a module *(2)* or a single script *(1)*, and whether you're invoking it from the same directory *(1)*, or from a different one *(2)*.
## Edit
Looking at ... |
Bizarre error importing settings in django | 6,036,599 | 7 | 2011-05-17T20:19:40Z | 6,037,142 | 26 | 2011-05-17T21:06:15Z | [
"python",
"django",
"settings",
"importerror",
"django-settings"
] | I have many projects working in ubuntu with python2.7 and virtualenv/virtualenvwrapper, in my work some developers works with macosx and windows, generally I create the project as usual:
```
django-admin.py start project x
```
And we use svn for cvs, but in some point, without nothing rational for me, when I try some... | > I got this error:
>
> Error: Can't find the file 'settings.py' in the directory containing 'manage.py'. It appears you've customized things. You'll have to run django-admin.py, passing it your settings module. (If the file settings.py does indeed exist, it's causing an ImportError somehow.)
The `manage.py` script pr... |
best platform to draw curves and create JPEGs | 6,037,656 | 2 | 2011-05-17T21:58:35Z | 6,037,750 | 7 | 2011-05-17T22:09:12Z | [
".net",
"python",
"math",
"graph",
"curve"
] | i have an equation of a curve that i need to draw like:
```
((X^z)-1)/z = y
```
does anyone know how i can draw this curve and save it as an image using python or .net? | A good library for 2d plots in Python is <http://matplotlib.sourceforge.net/>. The resulting plot can be saved straight from the plot dialog. |
Finding the length of an mp3 file | 6,037,826 | 2 | 2011-05-17T22:18:30Z | 6,037,997 | 11 | 2011-05-17T22:41:24Z | [
"python",
"mp3"
] | So i have the code:
```
import glob,os
import random
path = 'C:\\Music\\'
aw=[]
for infile in glob.glob( os.path.join(path,'*.mp3') ):
libr = infile.split('Downloaded',1)
aw.append(infile)
aww = -1
while 1:
aww += 1
print len(aw),aww
random.shuffle(aw)
awww = aw[aww]
os.startfile(awww... | You can use [mutagen](https://bitbucket.org/lazka/mutagen) to get the length of the song (see the [tutorial](https://bitbucket.org/lazka/mutagen/src/b27f57a13d47bf861bf69e95c250d12a5d7db489/docs/tutorial.rst?at=default)):
```
from mutagen.mp3 import MP3
audio = MP3("example.mp3")
print audio.info.length
``` |
Pyramid and Chameleon ZPT | 6,037,850 | 4 | 2011-05-17T22:21:17Z | 6,039,912 | 7 | 2011-05-18T04:35:53Z | [
"python",
"pyramid",
"chameleon",
"template-tal"
] | I'm new to web development and am trying to make a simple webpage in python using Pyramid. I've run into a bit of a snag though when it comes to making template files using Chameleon. What I'm trying to do right now is very simple. The view callable returns a list of dictionaries (all dictionaries have same keys just d... | You need to use "tal:repeat". If you've passed in "people" to the template, which is a list of dictionaries:
```
<ul>
<li tal:repeat="person people">${person['firstname']} ${person['lastname']}</li>
</ul>
``` |
Project Euler problem number 4 | 6,037,973 | 4 | 2011-05-17T22:37:31Z | 6,037,998 | 7 | 2011-05-17T22:41:26Z | [
"python"
] | ```
n = 0
for a in xrange(999, 100, -1):
for b in xrange(a, 100, -1):
x = a * b
if x > n:
s = str(a * b)
if s == s[::-1]:
n = a * b
print n
```
I have a question about this solution to [the problem](http://projecteuler.net/index.php?section=problems&id=4).
I... | The third parameter to `xrange()` is the increment value. The default is 1, which means the counter will count in an increasing direction. To count in a decreasing direction, use -1. Your `a` counter will go from 999 to 101 (the `xrange()` iterator stops just *before* it reaches the second parameter value).
For future... |
python-oauth2 with Twitter's oauth_callback | 6,038,761 | 4 | 2011-05-18T00:52:54Z | 6,040,041 | 9 | 2011-05-18T04:55:02Z | [
"python",
"oauth",
"twitter",
"twitter-oauth",
"twython"
] | I'm using [Twython](https://github.com/ryanmcgrath/twython) as my Twitter API wrapper, and oauth2 to handle authentication. I'm trying to have a use login via twitter, and then redirecting him after the oauth dance to a dynamically generated oauth\_callback. This, however, appears to be impossible to do with these libr... | Found the answer [here](http://milindshakya.tumblr.com/post/4208580364/overriding-twitters-default-callback-url-using-oauth)
All you have to do is pass Twython the parameter callback\_url and replace line 205 in Twython.py with
`resp, content = client.request(request_token_url, "POST",body=urllib.urlencode({'oauth_ca... |
Counting "deepness" or the deepest level a nested list goes to | 6,039,103 | 14 | 2011-05-18T02:01:47Z | 6,039,138 | 16 | 2011-05-18T02:10:19Z | [
"python",
"list",
"nested",
"levels"
] | A have a real problem (and a headache) with an assigment...
I'm in an introductory programming class, and I have to write a function that, given a list, will return the "maximum" deepness it goes to...
For example: [1,2,3] will return 1, [1,[2,3]] will return 2...
I've written this piece of code (it's the best I coul... | Here is one way to write the function
```
depth = lambda L: isinstance(L, list) and max(map(depth, L))+1
```
I think the idea you are missing is to use `max()` |
Python + Arduino with Mac OS X | 6,039,367 | 5 | 2011-05-18T02:49:17Z | 6,039,411 | 13 | 2011-05-18T02:59:01Z | [
"python",
"osx",
"serial-port",
"arduino"
] | I'm having trouble communicating between my Arduino and Python. I have a couple of questions that I hope can be answered, but first and most importantly, I need to simply establish a connection.
For Windows, apparently the solution is rather convenient, but on Mac OS X, I apparently need to access some system files (w... | The easiest way to communicate in Python with the Arduino (or any microcontroller with serial) is using [pySerial](http://pyserial.sourceforge.net/).
Here's an example:
```
import serial
s = serial.Serial(port='/dev/tty.usbmodemfa141', baudrate=9600)
s.write('text')
s.read()
s.readline()
```
PS: If you're using Pyt... |
python sequence find function | 6,039,425 | 9 | 2011-05-18T03:02:29Z | 6,039,516 | 14 | 2011-05-18T03:23:02Z | [
"python",
"find",
"sequence"
] | How do I find an object in a sequence satisfying a particular criterion?
List comprehension and filter go through the entire list.
Is the only alternative a handmade loop ?
```
mylist = [10, 2, 20, 5, 50]
find(mylist, lambda x:x>10) # returns 20
``` | here's the pattern I use:
```
mylist = [10, 2, 20, 5, 50]
found = next(i for i in mylist if predicate(i))
```
Or, in python 2.4/2.5 and , `next()` is a not a builtin:
```
found = (i for i in mylist if predicate(i)).next()
```
Do note that `next()` raises `StopIteration` if no element was found. In most cases, that'... |
TypeError: 'str' object is not callable (Python) | 6,039,605 | 29 | 2011-05-18T03:41:01Z | 6,039,623 | 63 | 2011-05-18T03:43:48Z | [
"python"
] | My code:
```
import urllib2 as u
import os as o
inn = 'dword.txt'
w = open(inn)
z = w.readline()
b = w.readline()
c = w.readline()
x = w.readline()
m = w.readline()
def Dict(Let, Mod):
global str
inn = 'dword.txt'
den = 'definitions.txt'
print 'reading definitions...'
dell =open(den, 'w')
... | This is the problem:
```
global str
str = str(mar)
```
You are redefining what `str()` means. `str` is the built-in Python name of the string type, and you don't want to change it.
Use a different name for the local variable, and remove the `global` statement. |
TypeError: 'str' object is not callable (Python) | 6,039,605 | 29 | 2011-05-18T03:41:01Z | 14,936,426 | 61 | 2013-02-18T12:34:02Z | [
"python"
] | My code:
```
import urllib2 as u
import os as o
inn = 'dword.txt'
w = open(inn)
z = w.readline()
b = w.readline()
c = w.readline()
x = w.readline()
m = w.readline()
def Dict(Let, Mod):
global str
inn = 'dword.txt'
den = 'definitions.txt'
print 'reading definitions...'
dell =open(den, 'w')
... | While not in your code, another hard-to-spot error is when the `%` character is missing in an attempt of string formatting:
```
"foo %s bar %s coffee"("blah","asdf")
```
but it should be:
```
"foo %s bar %s coffee"%("blah","asdf")
```
The missing `%` would result in the same `TypeError: 'str' object is not callable... |
Executing assembler code with python | 6,040,932 | 12 | 2011-05-18T06:53:12Z | 6,041,026 | 10 | 2011-05-18T07:02:54Z | [
"python",
"pointers",
"assembly",
"memory-address"
] | I want to execute assembly code inside a python script. Is that possible?
In C programming would be like this
```
static inline getesp(){
__asm__("mov %esp, %eax");
}
```
But how to do that with Python? Is it possible? | One way you could do this would be to write a (C) extension for Python. You can take a look at [this](http://docs.python.org/extending/) documentation for full details of how to do that.
Another way of developing C-based Python extensions would be to interface directly with an external library using the [ctypes](http:... |
Executing assembler code with python | 6,040,932 | 12 | 2011-05-18T06:53:12Z | 6,043,004 | 12 | 2011-05-18T10:09:10Z | [
"python",
"pointers",
"assembly",
"memory-address"
] | I want to execute assembly code inside a python script. Is that possible?
In C programming would be like this
```
static inline getesp(){
__asm__("mov %esp, %eax");
}
```
But how to do that with Python? Is it possible? | You can look into using the `CorePy` package, available [here](http://www.corepy.org/). To use it on an amd64 for instance, per the documentation:
```
# Load the x86_64 instructions and environment
>>> import corepy.arch.x86_64.isa as x86
>>> import corepy.arch.x86_64.platform as x86_env
Platform: linux.spre_linux_x86... |
Python memory serialisation | 6,041,395 | 10 | 2011-05-18T07:42:25Z | 6,041,645 | 9 | 2011-05-18T08:09:16Z | [
"python",
"class",
"serialization",
"memory-management",
"pickle"
] | I was wondering whether someone might know the answer to the following.
I'm using Python to build a character-based suffix tree. There are over 11 million nodes in the tree which fits in to approximately 3GB of memory. This was down from 7GB by using the **slot** class method rather than the **Dict** method.
When I s... | If you try to pickle an empty list, you get:
```
>>> s = StringIO()
>>> pickle.dump([], s)
>>> s.getvalue()
'(l.'
```
and similarly `'(d.'` for an empty `dict`. That's three bytes. The [in-memory representation of a list](http://stackoverflow.com/questions/3917574/how-is-pythons-list-implemented/3958322#3958322), how... |
Python check if value is in a list of dicts | 6,041,981 | 3 | 2011-05-18T08:39:08Z | 6,042,088 | 11 | 2011-05-18T08:49:11Z | [
"python"
] | I have a list of dicts e.g.
```
[{'name':'Bernard','age':7},{'name':'George','age':4},{'name':'Reginald','age':6}]
```
I'd like to check to see if a string value is the same as the 'name' value in any of the dicts in the list. For example 'Harold' would be False, but 'George' would be True.
I realise I could do this... | No, there cannot be a more efficient way if you have just this list of dicts.
However, if you want to check frequently, you can extract a dictionary with name:age items:
```
l = [{'name':'Bernard','age':7},{'name':'George','age':4},{'name':'Reginald','age':6}]
d = dict((i['name'], i['age']) for i in l)
```
now you h... |
Calling Chrome web browser from the webbrowser.get() in Python | 6,042,335 | 6 | 2011-05-18T09:12:41Z | 6,042,407 | 8 | 2011-05-18T09:19:14Z | [
"python",
"google-chrome",
"browser",
"ubuntu-11.04"
] | How I should call webbrowser.get() function so I open the chrome web browser? I'm running Ubuntu 11.04 and Python version 2.7.
Using webbrowser.get('chrome') yields an error. | The quick workaround is to make Chrome the default browser in your system and then use simply webbrowser.get(). I've just checked that on ubuntu 10.10 and it worked just fine.
**EDIT**
Just reviewed the code of /usr/lib/python2.6/webbrowser.py. You should do like this:
```
In [5]: webbrowser.get('/usr/bin/google-chr... |
Session differences in Pylons and Pyramid | 6,042,681 | 7 | 2011-05-18T09:41:42Z | 6,044,925 | 10 | 2011-05-18T12:50:48Z | [
"python",
"session",
"sqlalchemy",
"pylons",
"pyramid"
] | As a Pylons user I'm trying to switch to Pyramid now trying to understand differences.
In Pylons I was used to define Session in `myproj.model.meta` as:
```
Session = scoped_session(sessionmaker())
```
then import it in `myproj.model` to define model and so on then in app refer to:
```
root = Session.query(MyModel)... | Actually the way you are looking up your sqlalchemy session instance for querying doesn't really have anything to do with pylons and/or pyramid. Pylons may have suggested one of the ways as being the "standard" pylons way but that's it. The only real difference between the ways you're getting your session is in the exa... |
Split unicode string into 300 byte chunks without destroying characters | 6,043,463 | 9 | 2011-05-18T10:48:46Z | 6,043,797 | 10 | 2011-05-18T11:16:21Z | [
"python",
"string",
"utf-8"
] | I want to split `u"an arbitrary unicode string"` into chunks of say 300 bytes without destroying any characters. The strings will be written to a socket that expects utf8 using `unicode_string.encode("utf8")`. I don't want to destroy any characters. How would I do this? | UTF-8 is designed for this.
```
def split_utf8(s, n):
"""Split UTF-8 s into chunks of maximum length n."""
while len(s) > n:
k = n
while (ord(s[k]) & 0xc0) == 0x80:
k -= 1
yield s[:k]
s = s[k:]
yield s
```
Not tested. But you find a place to split, then backtrac... |
sqlalchemy: how to join several tables by one query? | 6,044,309 | 24 | 2011-05-18T11:58:27Z | 6,045,131 | 20 | 2011-05-18T13:04:00Z | [
"python",
"sql",
"join",
"sqlalchemy"
] | I have the following SQLAlchemy mapped classes:
```
class User(Base):
__tablename__ = 'users'
email = Column(String, primary_key=True)
name = Column(String)
class Document(Base):
__tablename__ = "documents"
name = Column(String, primary_key=True)
author = Column(String, ForeignKey("users.email... | Try this
```
q = Session.query(User,Document,DocumentPermissions).filter(User.email == Document.author).\
filter(Document.name == DocumentPermissions.document).\
filter(User.email == 'someemail').all()
``` |
sqlalchemy: how to join several tables by one query? | 6,044,309 | 24 | 2011-05-18T11:58:27Z | 6,226,740 | 15 | 2011-06-03T11:50:11Z | [
"python",
"sql",
"join",
"sqlalchemy"
] | I have the following SQLAlchemy mapped classes:
```
class User(Base):
__tablename__ = 'users'
email = Column(String, primary_key=True)
name = Column(String)
class Document(Base):
__tablename__ = "documents"
name = Column(String, primary_key=True)
author = Column(String, ForeignKey("users.email... | A good style would be to setup some relations and a primary key for permissions (actually, usually it is good style to setup **integer** primary keys for everything, but whatever):
```
class User(Base):
__tablename__ = 'users'
email = Column(String, primary_key=True)
name = Column(String)
class Document(B... |
How to connect python to db2 | 6,044,326 | 11 | 2011-05-18T12:00:41Z | 6,060,101 | 7 | 2011-05-19T14:18:01Z | [
"python",
"db2"
] | Is there a way `to connect python to DB2` ? | ibm-db, the official DB2 driver for Python and Django is here:
* <https://code.google.com/p/ibm-db/>
Here's a recent tutorial for how to install everything on Ubuntu Linux:
* <http://programmingzen.com/2011/05/12/installing-python-django-and-db2-on-ubuntu-11-04/>
I should mention that there were several older unoff... |
Efficient way to get index of minimum value in long vector, python | 6,044,645 | 9 | 2011-05-18T12:26:47Z | 6,045,587 | 7 | 2011-05-18T13:34:05Z | [
"python",
"list",
"indexing",
"latitude-longitude",
"minimum"
] | I have a long list of longitude values (len(Lon) = 420481), and another one of latitude values. I want to find the corresponding latitude to the minimum of the longitude.
I tried:
```
SE_Lat = [Lat[x] for x,y in enumerate(Lon) if y == min(Lon)]
```
but this takes ages to finish.
Does anyone know a more efficient wa... | May I recommend numpy?
```
import numpy
nplats = numpy.array(lats)
nplons = numpy.array(lons)
# this part is 20x faster than using the built-in python functions
index = numpy.argmin(nplats)
print nplats[index], nplons[index]
```
this is way faster than the min(izip()) solution (~20x using my setup when using 420481... |
Implementing my own higher level test scripting language | 6,045,869 | 2 | 2011-05-18T13:54:27Z | 6,046,061 | 9 | 2011-05-18T14:07:32Z | [
"python",
"parsing"
] | I've inherited a bunch of test scripts which look something like this:
```
// make connection on standard port (FD)
ot 11 02 00 0F FD
// wait for ACK
in 12 ackValue
// wait for connection confirmation
in 13 ackValue 09 88
//send 5 bytes of arbitary data
ot 21 ackValue 05 01 02 03 04 05
```
And so on.
I would like to... | You don't need any special parsers for such simple tests. Just use Python. A simple solution could start like this:
```
class TestGen(object):
def __init__(self, filename):
self._filename = filename
def __enter__(self):
self._file = open(self._filename, 'w')
return self
def __exi... |
Counting occurrences in a Python list | 6,046,387 | 7 | 2011-05-18T14:29:13Z | 6,046,479 | 18 | 2011-05-18T14:35:53Z | [
"python"
] | I have a list of integers; for example:
```
l = [1, 2, 3, 4, 4, 4, 1, 1, 1, 2]
```
I am trying to make a list of the three elements in `l` with the highest number of occurrences, in descending order of frequency. So in this case I want the list `[1, 4, 2]`, because `1` occurs the most in `l` (four times), `4` is next... | Use a [collections.Counter](http://docs.python.org/library/collections.html#collections.Counter):
```
import collections
l= [1 ,2 ,3 ,4,4,4 , 1 ,1 ,1 ,2]
x=collections.Counter(l)
print(x.most_common())
# [(1, 4), (4, 3), (2, 2), (3, 1)]
print([elt for elt,count in x.most_common(3)])
# [1, 4, 2]
```
`collections.Cou... |
Render an xml to a view | 6,046,605 | 3 | 2011-05-18T14:44:07Z | 6,046,655 | 7 | 2011-05-18T14:46:54Z | [
"python",
"django",
"django-views"
] | The scenario goes like this.
I get an atom file from a website (say A). A third party will be request this atom file through my website (say B).
I am writing a Django app which will frequently poll website A and store it as a file. Now, when a third party requests for the file through website B, I will have to displa... | Do something like this.
```
return render(request, 'myapp/index.html', {"foo": "bar"} content_type="application/xhtml+xml")
``` |
Explain example from python subprocess module | 6,046,779 | 6 | 2011-05-18T14:54:36Z | 6,046,866 | 10 | 2011-05-18T15:01:11Z | [
"python",
"subprocess"
] | Section [17.1.4.2: Replacing shell pipeline](http://docs.python.org/library/subprocess.html#replacing-shell-pipeline) of the python subprocess module says to replace
```
output=`dmesg | grep hda`
```
with
```
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close... | You are closing `p1.stdout` in the *parent* process, thus leaving dmesg as the only process with that file descriptor open. If you didn't do this, even when dmesg closed its stdout, you would still have it open, and a `SIGPIPE` would not be generated. (The OS basically keeps a reference count, and generates `SIGPIPE` w... |
Pip: Specifying minor version | 6,047,670 | 23 | 2011-05-18T16:05:43Z | 6,047,897 | 32 | 2011-05-18T16:24:08Z | [
"python",
"pip",
"distribute"
] | In my `requirements.txt` file I want to specify that my app needs Django version 1.3.x. That is, either 1.3.0, or 1.3.1, or 1.3.2, etc. (When these come out.) But not 1.4, when it comes out.
What's the syntax for this? | According to [Ian Bicking](http://groups.google.com/group/python-virtualenv/msg/123b47b6e181ff9f):
```
Django>=1.3,<1.4
```
However, it's [apparently safer to do](http://groups.google.com/group/python-virtualenv/msg/07d88e8408fd86d7):
```
Django>=1.3,<1.3.99
``` |
Writing Unicode text to a text file? | 6,048,085 | 129 | 2011-05-18T16:39:46Z | 6,048,141 | 17 | 2011-05-18T16:44:35Z | [
"python",
"unicode",
"character-encoding"
] | I'm pulling data out of a Google doc, processing it, and writing it to a file (that eventually I will paste into a Wordpress page).
It has some non-ASCII symbols. How can I convert these safely to symbols that can be used in HTML source?
Currently I'm converting everything to Unicode on the way in, joining it all tog... | The file opened by `codecs.open` is a file that takes `unicode` data, encodes it in `iso-8859-1` and writes it to the file. However, what you try to write isn't `unicode`; you take `unicode` and encode it in `iso-8859-1` *yourself*. That's what the `unicode.encode` method does, and the result of encoding a unicode stri... |
Writing Unicode text to a text file? | 6,048,085 | 129 | 2011-05-18T16:39:46Z | 6,048,203 | 194 | 2011-05-18T16:49:01Z | [
"python",
"unicode",
"character-encoding"
] | I'm pulling data out of a Google doc, processing it, and writing it to a file (that eventually I will paste into a Wordpress page).
It has some non-ASCII symbols. How can I convert these safely to symbols that can be used in HTML source?
Currently I'm converting everything to Unicode on the way in, joining it all tog... | Deal exclusively with unicode objects as much as possible by decoding things to unicode objects when you first get them and encoding them as necessary on the way out.
If your string is actually a unicode object, you'll need to convert it to a unicode-encoded string object before writing it to a file:
```
foo = u'Î, ... |
Writing Unicode text to a text file? | 6,048,085 | 129 | 2011-05-18T16:39:46Z | 35,086,151 | 12 | 2016-01-29T13:49:08Z | [
"python",
"unicode",
"character-encoding"
] | I'm pulling data out of a Google doc, processing it, and writing it to a file (that eventually I will paste into a Wordpress page).
It has some non-ASCII symbols. How can I convert these safely to symbols that can be used in HTML source?
Currently I'm converting everything to Unicode on the way in, joining it all tog... | In Python 2.6+, you could [use `io.open()`](https://docs.python.org/2/library/io.html) that is default ([builtin `open()`](https://docs.python.org/3/library/functions.html#open)) on Python 3:
```
import io
with io.open(filename, 'w', encoding=character_encoding) as file:
file.write(unicode_text)
```
It might be ... |
How to generate a fixed-length hash based on current date and time in Python? | 6,048,576 | 4 | 2011-05-18T17:22:23Z | 6,048,639 | 17 | 2011-05-18T17:26:46Z | [
"python"
] | I want to generate a fixed-length (say 10 characters) hash based on current date & time. This hash will be append to names of the uploaded files from my users. How can I do that in Python? | Batteries included:
```
import hashlib
import time
hash = hashlib.sha1()
hash.update(str(time.time()))
print hash.hexdigest()
print hash.hexdigest()[:10]
``` |
Base36 Encode a String? | 6,049,657 | 3 | 2011-05-18T18:54:28Z | 6,050,072 | 7 | 2011-05-18T19:32:56Z | [
"java",
"python",
"ruby"
] | I've been looking online, but can't find a solution to this. In Python, Ruby, or Java, how can I base 36 encode the following string: nOrG9Eh0uyeilM8Nnu5pTywj3935kW+5= | ## Ruby
---
*To base 36:*
```
s.unpack('H*')[0].to_i(16).to_s 36
```
*From base 36:*
```
[s36.to_i(36).to_s(16)].pack 'H*'
``` |
ipython and fork() | 6,049,741 | 7 | 2011-05-18T19:02:19Z | 6,224,225 | 8 | 2011-06-03T07:29:33Z | [
"python",
"fork",
"process",
"ipython"
] | I am planning a Python script that'll use `os.fork()` to create a bunch of child processes to perform some computations. The parent process will block until the children terminate.
The twist is that I need to be able to run the script both from the Unix shell using `python` and from `ipython` using `%run`.
In what ma... | The following seems to work:
```
import os, sys
child_pid = os.fork()
if child_pid == 0:
print 'in child'
os._exit(os.EX_OK)
print 'hm... wasn''t supposed to get here'
else:
print 'in parent'
```
The trick is to use [`os._exit()`](http://docs.python.org/library/os.html#os._exit) instead of [`sys.exit()`](htt... |
Python: what does "import" prefer - modules or packages? | 6,049,825 | 13 | 2011-05-18T19:10:44Z | 6,050,009 | 12 | 2011-05-18T19:27:45Z | [
"python",
"module",
"package",
"python-import",
"precedence"
] | Suppose in the current directory there is a file named `somecode.py`, and a directory named `somecode` which contains an `__init__.py` file. Now I run some other Python script from this directory which executes `import somecode`. Which file will be imported - `somecode.py` or `somecode/__init__.py`?
Is there even a de... | Packages will be imported before modules. Illustrated:
```
% tree .
.
|-- foo
| |-- __init__.py
| `-- __init__.pyc
`-- foo.py
```
`foo.py`:
```
% cat foo.py
print 'you have imported foo.py'
```
`foo/__init__.py`:
```
% cat foo/__init__.py
print 'you have imported foo/__init__.py'
```
And from interactive int... |
django import error - No module named core.management | 6,049,933 | 126 | 2011-05-18T19:21:19Z | 6,050,037 | 14 | 2011-05-18T19:29:31Z | [
"python",
"django",
"python-import",
"pythonpath"
] | Ok, I see plenty of these errors around. I have tried everything I know to do and have yet to figure this out.
I am working on a development server running python 2.5 and Django 1.3. Django 1.3 was installed using python setup.py install after unpacking the tar.gz download.
All works well, I seldom have the need to r... | Please, reinstall django with pip:
```
sudo pip install --upgrade django==1.3
```
(Replace 1.3 to your django version) |
django import error - No module named core.management | 6,049,933 | 126 | 2011-05-18T19:21:19Z | 6,059,969 | 8 | 2011-05-19T14:08:05Z | [
"python",
"django",
"python-import",
"pythonpath"
] | Ok, I see plenty of these errors around. I have tried everything I know to do and have yet to figure this out.
I am working on a development server running python 2.5 and Django 1.3. Django 1.3 was installed using python setup.py install after unpacking the tar.gz download.
All works well, I seldom have the need to r... | As known this was a path issue.
the base of my custom packages shared a name with a directory set in a /etc/profile. The packages were in a different location however for the webserver. So I removed the offending entries from my $PYTHONPATH and was good to go!
Thanks for the help. |
django import error - No module named core.management | 6,049,933 | 126 | 2011-05-18T19:21:19Z | 10,756,446 | 135 | 2012-05-25T14:42:52Z | [
"python",
"django",
"python-import",
"pythonpath"
] | Ok, I see plenty of these errors around. I have tried everything I know to do and have yet to figure this out.
I am working on a development server running python 2.5 and Django 1.3. Django 1.3 was installed using python setup.py install after unpacking the tar.gz download.
All works well, I seldom have the need to r... | If, like me, you are running your django in a virtualenv, and getting this error, look at your `manage.py`.
The first line should define the python executable used to run the script.
This should be the path to your virtualenv's python, but it is something wrong like /usr/bin/python, which is not the same path and will ... |
django import error - No module named core.management | 6,049,933 | 126 | 2011-05-18T19:21:19Z | 12,512,229 | 7 | 2012-09-20T12:04:35Z | [
"python",
"django",
"python-import",
"pythonpath"
] | Ok, I see plenty of these errors around. I have tried everything I know to do and have yet to figure this out.
I am working on a development server running python 2.5 and Django 1.3. Django 1.3 was installed using python setup.py install after unpacking the tar.gz download.
All works well, I seldom have the need to r... | another possible reason for this problem is, that your OS runs python3 by default.
either you explicitely do: `python2 manage.py`
or you edit the shebang of manage.py, like so:
```
#!/usr/bin/env python2
``` |
django import error - No module named core.management | 6,049,933 | 126 | 2011-05-18T19:21:19Z | 17,050,797 | 32 | 2013-06-11T18:07:05Z | [
"python",
"django",
"python-import",
"pythonpath"
] | Ok, I see plenty of these errors around. I have tried everything I know to do and have yet to figure this out.
I am working on a development server running python 2.5 and Django 1.3. Django 1.3 was installed using python setup.py install after unpacking the tar.gz download.
All works well, I seldom have the need to r... | If you are in a virtualenv you need to activate it before you can run ./manage.py 'command'
```
source path/to/your/virtualenv/bin/activate
```
if you config workon in .bash\_profile or .bashrc
```
workon yourvirtualenvname
```
\*please dont edit your manage.py file maybe works by isnt the correct way and could giv... |
django import error - No module named core.management | 6,049,933 | 126 | 2011-05-18T19:21:19Z | 20,802,248 | 24 | 2013-12-27T14:19:04Z | [
"python",
"django",
"python-import",
"pythonpath"
] | Ok, I see plenty of these errors around. I have tried everything I know to do and have yet to figure this out.
I am working on a development server running python 2.5 and Django 1.3. Django 1.3 was installed using python setup.py install after unpacking the tar.gz download.
All works well, I seldom have the need to r... | I had the same problem because I was installing Django as a super user, thus not in my virtualenv. You should not do `sudo pip install Django`
Instead, install it this way:
```
$ source ./bin/activate
$ pip install Django
``` |
Determine if point is in polygon or passed through | 6,050,392 | 6 | 2011-05-18T20:05:48Z | 6,052,144 | 16 | 2011-05-18T23:20:37Z | [
"python",
"geometry",
"polygon",
"point-in-polygon"
] | I'm trying to figure out how best to do this, if I have a vector (a line consisting of 2 points) on a 2d plane how can I determine if it has passed through a polygon?
I know I can take each line which makes up the polygon and see if any intersect but is there a better way?
I've read this one post [Point in Polygon ak... | If you want a python library for geometric operations, have a look at [`shapely`](http://trac.gispython.org/lab/wiki/Shapely). It makes this as simple as `someline.intersects(somepolygon)`.
Here's a quick example of intersections, buffer, and clipping (with a nice plot... I'm using [`descartes`](http://pypi.python.org... |
Python eigenvalue computations run much slower than those of MATLAB on my computer. Why? | 6,051,678 | 12 | 2011-05-18T22:15:52Z | 6,052,231 | 14 | 2011-05-18T23:33:05Z | [
"python",
"matlab",
"numpy",
"eigenvalue"
] | I would like to compute the eigenvalues of large-ish matrices (about 1000x1000) using Python 2.6.5. I have been unable to do so quickly. I have not found any other threads addressing this question.
When I run
```
a = rand(1000,1000);
tic;
for i =1:10
eig(a);
end
toc;
```
in MATLAB it takes about 30 seconds. A si... | I think what you're seeing is the difference between the Intel Math Kernel Library (MKL) that's being used by Matlab and whatever LAPACK implementation you have on your system (ATLAS, maybe?) that scipy is linked against. You can see how much faster the MKL is in [these benchmarks](http://www.enthought.com/epd/mkl/).
... |
Loading Magnet LINK using Rasterbar libtorrent in Python | 6,051,877 | 5 | 2011-05-18T22:45:05Z | 6,053,350 | 13 | 2011-05-19T03:13:19Z | [
"python",
"bittorrent",
"magnet-uri"
] | How would one load a Magnet link via rasterbar libtorrent python binding? | ```
import libtorrent as lt
import time
ses = lt.session()
params = { 'save_path': '/home/downloads/'}
link = "magnet:?xt=urn:btih:4MR6HU7SIHXAXQQFXFJTNLTYSREDR5EI&tr=http://tracker.vodo.net:6970/announce"
handle = lt.add_magnet_uri(ses, link, params)
print 'downloading metadata...'
while (not handle.has_metadata()):... |
Purpose of else and finally in exception handling | 6,051,934 | 31 | 2011-05-18T22:53:23Z | 6,051,948 | 16 | 2011-05-18T22:55:40Z | [
"python"
] | Are the `else` and `finally` sections of exception handling redundant? For example, is there any difference between the following two code snippets?
```
try:
foo = open("foo.txt")
except IOError:
print("error")
else:
print(foo.read())
finally:
print("finished")
```
and
```
try:
foo = open("foo.tx... | `finally` is executed regardless of whether the statements in the try block fail or succeed. `else` is executed only if the statements in the try block don't raise an exception. |
Purpose of else and finally in exception handling | 6,051,934 | 31 | 2011-05-18T22:53:23Z | 6,051,952 | 8 | 2011-05-18T22:56:12Z | [
"python"
] | Are the `else` and `finally` sections of exception handling redundant? For example, is there any difference between the following two code snippets?
```
try:
foo = open("foo.txt")
except IOError:
print("error")
else:
print(foo.read())
finally:
print("finished")
```
and
```
try:
foo = open("foo.tx... | No matter what happens, the block in the `finally` **always** gets executed. Even if an exception wasn't handled or the exception handlers themselves generate new exceptions. |
Purpose of else and finally in exception handling | 6,051,934 | 31 | 2011-05-18T22:53:23Z | 6,051,978 | 31 | 2011-05-18T22:59:26Z | [
"python"
] | Are the `else` and `finally` sections of exception handling redundant? For example, is there any difference between the following two code snippets?
```
try:
foo = open("foo.txt")
except IOError:
print("error")
else:
print(foo.read())
finally:
print("finished")
```
and
```
try:
foo = open("foo.tx... | The idea is that you keep the code for which you are handling exceptions as small as possible. Anything in the `else` block *could* get moved into the `try`, yes, but then you might end up catching an exception when you really want it to be raised. You may have successfully opened the file, but if the `read` causes an ... |
Using a Django variable in a CSS file | 6,052,341 | 15 | 2011-05-18T23:51:52Z | 6,052,381 | 10 | 2011-05-18T23:58:56Z | [
"python",
"css",
"django",
"templates",
"django-templates"
] | I am trying to create a *dynamic* CSS file using the Django templating engine or any other means.
Currently, I have a CSS rule that looks like this:
```
background-image: url('http://static.example.com/example.png');
```
Where `http://static.example.com` corresponds to the `STATIC_URL` variable in Python. Using the ... | You basically have two options:
1. Serve your CSS dynamically, with an entry in urls.py, etc., just as if it were an HTML page. Your template file will simply be CSS instead of HTML, but will use normal Django template syntax, etc.
2. Shortcut: Reference your background image with a relative path. This may or may not ... |
Using a Django variable in a CSS file | 6,052,341 | 15 | 2011-05-18T23:51:52Z | 6,058,369 | 10 | 2011-05-19T12:07:14Z | [
"python",
"css",
"django",
"templates",
"django-templates"
] | I am trying to create a *dynamic* CSS file using the Django templating engine or any other means.
Currently, I have a CSS rule that looks like this:
```
background-image: url('http://static.example.com/example.png');
```
Where `http://static.example.com` corresponds to the `STATIC_URL` variable in Python. Using the ... | A very good solution here is to use [django-compressor](http://django_compressor.readthedocs.org/en/latest/). Firstly, if you are serving more than one CSS file, compressor is going to help improve page load times by dropping the number of requests.
A side effect of compressing / concatenating files is that compressor... |
What is the closest thing to WordPress in python instead of php? | 6,053,005 | 26 | 2011-05-19T02:01:18Z | 6,053,021 | 12 | 2011-05-19T02:05:16Z | [
"php",
"python",
"wordpress"
] | What is the closest thing to [WordPress](http://wordpress.org/) in python instead of php?
[WordPress](http://wordpress.org/) is known for its simplicity. You donwload it, throw it on your server, make some edits to a config file and you are done. Afterwords you can pick a nice theme and edit it a little bit and voilá... | I'm not sure what you are looking for, but here is a list of a bunch of blogging software written in python:
<http://wiki.python.org/moin/PythonBlogSoftware> |
What is the closest thing to WordPress in python instead of php? | 6,053,005 | 26 | 2011-05-19T02:01:18Z | 6,053,070 | 14 | 2011-05-19T02:14:27Z | [
"php",
"python",
"wordpress"
] | What is the closest thing to [WordPress](http://wordpress.org/) in python instead of php?
[WordPress](http://wordpress.org/) is known for its simplicity. You donwload it, throw it on your server, make some edits to a config file and you are done. Afterwords you can pick a nice theme and edit it a little bit and voilá... | There is another project worth mentioning not on the Python wiki blog software page, [mezzanine](http://mezzanine.jupo.org/). Built on top of Django, it certainly angles to be an all encompassing blog solution, and even lets you import your old wordpress posts (if you wanted to migrate). Django is a great project in ge... |
Python: efficiently check if integer is within *many* ranges | 6,053,974 | 28 | 2011-05-19T05:00:50Z | 6,054,040 | 10 | 2011-05-19T05:08:51Z | [
"python"
] | I am working on a postage application which is required to check an integer postcode against a number of postcode ranges, and return a different code based on which range the postcode matches against.
Each code has more than one postcode range. For example, the **M** code should be returned if the postcode is within t... | You can throw your ranges into tuples and put the tuples in a list. Then use `any()` to help you find if your value is within these ranges.
```
ranges = [(1000,2429), (2545,2575), (2640,2686), (2890, 2890)]
if any(lower <= postcode <= upper for (lower, upper) in ranges):
print('M')
``` |
python cherrypy - how to add header | 6,054,473 | 8 | 2011-05-19T06:02:55Z | 6,054,675 | 17 | 2011-05-19T06:29:58Z | [
"python",
"cherrypy"
] | How can I add retry-header in cherrypy?
```
import cherrypy
import os
class Root:
def index(self):
cherrypy.response.headers['Retry-After'] = 60
cherrypy.request.headers["Age"]= 20
cherrypy.config.update({'Retry-After': '60'})
raise cherrypy.HTTPError(503, 'Service Unavailable')
... | When you set a status code by raising `HTTPError`, the headers in `cherrypy.response.headers` are ignored. Set the HTTP status by setting `cherrypy.response.status` instead:
```
import cherrypy
class Root:
def index(self):
cherrypy.response.headers['Retry-After'] = 60
cherrypy.response.status = 50... |
Python: list to JSON | 6,056,418 | 3 | 2011-05-19T09:20:02Z | 6,056,453 | 9 | 2011-05-19T09:22:07Z | [
"python",
"django",
"jquery-ui-autocomplete"
] | I am trying to use Django with [jquery UI autocomplete](http://jqueryui.com/demos/autocomplete/) but having trouble sending response.
Here is my code:
```
def ajax_tags_autocomplete(request):
""" Autocomplete for tag list """
beginning_of_title = request.GET.get('term', '')
tags_found = Tag.objects.values... | Are you sure it's actually a list containing unicode objects and not a list containing some database objects? The `u"php"` might just be the `repr()` of the object.
Try `json.dumps([unicode(t) for t in tags_found])` or `json.dumps(map(unicode, tags_found))` |
Python: deleting a class attribute in a subclass | 6,057,130 | 22 | 2011-05-19T10:19:20Z | 6,057,409 | 15 | 2011-05-19T10:43:17Z | [
"python",
"class",
"inheritance",
"namespaces"
] | I have a subclass and I want it to *not* include a class attribute that's present on the base class.
I tried this, but it doesn't work:
```
>>> class A(object):
... x = 5
>>> class B(A):
... del x
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
class B(A):
File "<pyshell#1>"... | You don't need to delete it. Just override it.
```
class B(A):
x = None
```
or simply don't reference it.
Or consider a different design (instance attribute?). |
Python: deleting a class attribute in a subclass | 6,057,130 | 22 | 2011-05-19T10:19:20Z | 15,920,132 | 27 | 2013-04-10T07:58:15Z | [
"python",
"class",
"inheritance",
"namespaces"
] | I have a subclass and I want it to *not* include a class attribute that's present on the base class.
I tried this, but it doesn't work:
```
>>> class A(object):
... x = 5
>>> class B(A):
... del x
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
class B(A):
File "<pyshell#1>"... | You can use delattr(class,field\_name) to remove it from the class definition |
Python super() - should be working but isn't? | 6,057,540 | 6 | 2011-05-19T10:53:12Z | 6,057,743 | 7 | 2011-05-19T11:13:38Z | [
"python",
"multiple-inheritance"
] | As far as I can tell, and everything I've been finding online, this should work (but it doesn't, which is why I'm asking here ;) )
```
class Tigon(Crossbreeds, Predator, Lion):
def __init__(self):
super().__init__()
def printSize(self):
print("Huge")
```
Both "Crossbreeds" and "Predator" inhe... | Short answer: Don't inherit the same base class directly and indirectly, but inheriting directly *after* indirectly should work. So don't inherit `Predator` or inherit it *after* `Lion`.
Well, the [C3 MRO](http://www.python.org/download/releases/2.3/mro/) seems to not be able to find any order consistent with all cons... |
Storing user and password in a database | 6,058,019 | 10 | 2011-05-19T11:37:21Z | 6,058,506 | 10 | 2011-05-19T12:18:11Z | [
"python",
"security",
"passwords"
] | I am creating a software with user + password. After autentification, the user can access some semi public services, but also encrypt some files that only the user can access.
The user must be stored as is, without modification, if possible. After auth, the user and the password are kept in memory as long as the softw... | Crypto is hard to get right, it's good that you're asking questions.
**Storing passwords:** Passwords should be hashed using a *key stretching algorithm*. Typically, you want to use a library rather than implement it yourself. Key stretching algorithms are designed to chew up processor cycles, so it's nice to evaluate... |
I want to extract a .tgz file and extract any subdirectories that have files that are .tgz and .tar | 6,058,786 | 7 | 2011-05-19T12:45:05Z | 6,059,458 | 8 | 2011-05-19T13:30:44Z | [
"python",
"gzip",
"tar",
"decompression"
] | I'm using the code below to extract `.tgz` files. The type of log files (`.tgz`) that I need to extract have sub-directories that have other `.tgz` files and `.tar` files inside them. I want to extract those too.
Ultimately, I'm trying to search for certain strings in all `.log` files and `.txt` files that may appear ... | This should give you the desired result:
```
import os, sys, tarfile
def extract(tar_url, extract_path='.'):
print tar_url
tar = tarfile.open(tar_url, 'r')
for item in tar:
tar.extract(item, extract_path)
if item.name.find(".tgz") != -1 or item.name.find(".tar") != -1:
extract(... |
Evaluating a list of python lambda functions only evaluates the last list element | 6,059,205 | 11 | 2011-05-19T13:13:11Z | 6,059,389 | 12 | 2011-05-19T13:25:23Z | [
"python"
] | I have a list of lambda functions I want to evaluate in order. I'm not sure why, but only the last function gets evaluated. Example below:
```
>>> def f(x,z):
... print "x=",x,", z=",z
...
>>>
>>> g = lambda x : f(x,13)
>>> g(2)
x= 2 , z= 13 # As expected
>>>
>>> lst=[]
>>>
>>> for i i... | The lambda is just looking up the global value of 'i'.
Try the following instead:
```
for i in range(0,5):
lst.append(lambda x, z=i: f(x,z))
``` |
Cutting one image into multiple images using the Python Image Library | 6,059,217 | 8 | 2011-05-19T13:14:04Z | 14,252,471 | 22 | 2013-01-10T07:04:01Z | [
"python",
"image-manipulation",
"python-imaging-library",
"image-segmentation"
] | I need to cut this image into three parts using PIL and pick the middle part.
How do I do it?
<http://thedilbertstore.com/images/periodic_content/dilbert/dt110507dhct.jpg> | Say you have a really long picture like this.

And now you want to slice it up into smaller vertical bits, because it is so long.
Here is a Python script that will do that. This was useful to me for in preparing very long im... |
Cutting one image into multiple images using the Python Image Library | 6,059,217 | 8 | 2011-05-19T13:14:04Z | 22,964,916 | 8 | 2014-04-09T13:59:02Z | [
"python",
"image-manipulation",
"python-imaging-library",
"image-segmentation"
] | I need to cut this image into three parts using PIL and pick the middle part.
How do I do it?
<http://thedilbertstore.com/images/periodic_content/dilbert/dt110507dhct.jpg> | I wanted to up-vote [Gourneau's](http://stackoverflow.com/a/14252471/3447915) solution, but lack the sufficient reputation. However, I figured I would post the code that I developed as a result of his answer just in case it might be helpful to somebody else. I also added the ability to iterate through a file structure,... |
Simple counter example using mapreduce in Google App Engine | 6,060,095 | 9 | 2011-05-19T14:17:36Z | 6,062,045 | 9 | 2011-05-19T16:50:25Z | [
"python",
"google-app-engine",
"mapreduce"
] | I'm somewhat confused with the current state of mapreduce support in GAE. According to the docs <http://code.google.com/p/appengine-mapreduce/> reduce phase isn't supported yet, but in the description of the session from I/O 2011 ( <http://www.youtube.com/watch?v=EIxelKcyCC0> ) it's written "It is now possible to run f... | You don't really need a reduce phase. You can accomplish this with a linear task chain, more or less as follows:
```
def count_colors(limit=100, totals={}, cursor=None):
query = Car.all()
if cursor:
query.with_cursor(cursor)
cars = query.fetch(limit)
for car in cars:
try:
totals[car.color] += 1
... |
How to document fields and properties in Python? | 6,060,813 | 28 | 2011-05-19T15:10:32Z | 6,061,254 | 33 | 2011-05-19T15:41:16Z | [
"python",
"documentation"
] | It's easy to document a class or method in Python:
```
class Something:
""" Description of the class. """
def do_it(self):
""" Description of the method. """
pass
class_variable = 1 # How to comment?
@property
def give_me_some_special_dict(self):
""" doesn't work! Doc of general dict will be s... | Python has a PEP ([257](http://www.python.org/dev/peps/pep-0257/)) that defines Docstring Conventions. Regarding documentation of attributes, it states:
> String literals occurring immediately
> after a simple assignment at the top
> level of a module, class, or `__init__`
> method are called "attribute
> docstrings".... |
problems with easy_install pycrypto | 6,061,180 | 6 | 2011-05-19T15:35:42Z | 6,062,869 | 10 | 2011-05-19T17:59:47Z | [
"python",
"pycrypto"
] | I'm trying install pycrypto on osx with easy\_install and I'm getting the following error:
```
easy_install pycrypto
Searching for pycrypto
Reading http://pypi.python.org/simple/pycrypto/
Reading http://pycrypto.sourceforge.net
Reading http://www.pycrypto.org/
Reading http://www.amk.ca/python/code/crypto
Best match: p... | I have this in my `~/.bash_profile` to address this very issue:
```
# Set compile flags to not try to compile for PPC (no longer supported by xcode 4)
# (this is required for eg building pycrypto)
export ARCHFLAGS="-arch i386 -arch x86_64"
``` |
Why dictionary values aren't in the inserted order? | 6,061,380 | 8 | 2011-05-19T15:52:02Z | 6,061,395 | 12 | 2011-05-19T15:53:11Z | [
"python",
"dictionary",
"sequence"
] | When i declare a list 1,2,3,4 and i do something with it , even just print i get back the same sequence 1,2,3,4.
But when i do anything with dictionaries , they always change number sequence , like it is being sorted in a twisted way i can't understand .
```
test1 = [4,1,2,3,6,5]
print test1
test2 = {"c":3,"a":1,"b":... | Dictionaries in Python are *unordered by definition*. Use `OrderedDict` if you need the order in which values were inserted (it's available in Python 2.7 and 3.x). |
Is get_result() a required call for put_async() in Google App Engine | 6,061,681 | 14 | 2011-05-19T16:19:09Z | 6,288,109 | 7 | 2011-06-09T04:30:29Z | [
"python",
"google-app-engine",
"asynchronous",
"gae-datastore"
] | With the new release of GAE 1.5.0, we now have an easy way to do async datastore calls. Are we required to call `get_result()` after calling
'[put\_async](http://code.google.com/appengine/docs/python/datastore/functions.html#put_async)'?
For example, if I have an model called `MyLogData`, can I just call:
```
put_asy... | I don't think there is any sure way to know if `get_result()` is required unless someone on the GAE team verifies this, but I think it's not needed. Here is how I tested it.
I wrote a simple handler:
```
class DB_TempTestModel(db.Model):
data = db.BlobProperty()
class MyHandler(webapp.RequestHandler):
def ge... |
How to get value of arguments passed to functions on the stack? | 6,061,744 | 9 | 2011-05-19T16:24:21Z | 6,061,820 | 9 | 2011-05-19T16:30:52Z | [
"python",
"stack-trace",
"traceback"
] | Using:
```
traceback.print_stack()
```
I can get:
```
File "x.py", line 20, in <module>
y(x)
File "x.py", line 11, in y
fun(x)
File "x.py", line 8, in fun
traceback.print_stack()
```
I there any way to get something like this:
```
File "x.py", line 20, in <module>
y(x) WHERE x == 1
File "... | You can probably rig something up by using [`inspect.getargvalues()`](http://docs.python.org/library/inspect.html#inspect.getargvalues) and accessing the stack frame belonging to your traceback:
```
inspect.getargvalues(traceback.tb_frame)
```
You'll have to do some work to get the output exactly as desired. The abo... |
How to get value of arguments passed to functions on the stack? | 6,061,744 | 9 | 2011-05-19T16:24:21Z | 6,061,913 | 8 | 2011-05-19T16:38:53Z | [
"python",
"stack-trace",
"traceback"
] | Using:
```
traceback.print_stack()
```
I can get:
```
File "x.py", line 20, in <module>
y(x)
File "x.py", line 11, in y
fun(x)
File "x.py", line 8, in fun
traceback.print_stack()
```
I there any way to get something like this:
```
File "x.py", line 20, in <module>
y(x) WHERE x == 1
File "... | You can use the [inspect](http://docs.python.org/library/inspect.html) module for this:
```
>>> import inspect
... def fn(x):
... try:
... print(1/0)
... except ZeroDivisionError as e:
... frames = inspect.trace()
... argvalues = inspect.getargvalues(frames[0][0])
... print("Arg... |
How do you get the current text contents of a QComboBox? | 6,061,893 | 13 | 2011-05-19T16:37:24Z | 6,062,987 | 28 | 2011-05-19T18:09:20Z | [
"python",
"pyqt",
"pyqt4",
"python-2.6",
"qcombobox"
] | using pyqt4 and python 2.6, i am using a qcombobox to provide a list of options. i am having problems with using the selected option. i have been able to use a signal to trigger a method when the option is selected, but the problem is that when the use clicks run the contents of several of these comboboxes need to be t... | You can convert the QString type to python string by just using the `str`
function. Assuming you are not using any Unicode characters you can get a python
string as below:
```
text = str(combobox1.currentText())
```
If you are using any unicode characters, you can do:
```
text = unicode(combobox1.currentText())
``` |
How to find the comment tag <!--...--> with BeautifulSoup? | 6,062,210 | 16 | 2011-05-19T17:03:05Z | 6,062,252 | 23 | 2011-05-19T17:06:26Z | [
"python",
"html",
"tags",
"beautifulsoup"
] | I tried soup.find('!--') but it doesn't seem to work. Thanks in advance.
Edit: Thanks for the tip on how to find all comments. I have a follow up question. How do I specifically search out for a comment?
For example, I have the following comment tag:
`<!-- <span class="titlefont"> <i>Wednesday 110518</i>(05:00PM)<br... | You can find all the comments in a document with via the `findAll` method. See this example showing how to do exactly what you're trying to do [Removing elements](http://www.crummy.com/software/BeautifulSoup/documentation.html#Removing%20elements):
In brief, you want this:
```
comments = soup.findAll(text=lambda text... |
Python: efficient counting number of unique values of a key in a list of dictionaries | 6,062,212 | 4 | 2011-05-19T17:03:12Z | 6,062,244 | 11 | 2011-05-19T17:05:53Z | [
"python",
"list",
"dictionary",
"count",
"unique"
] | There must be a better way of writing this Python code where I have a list of people (people are dictionaries) and I am trying to find the number of unique values of a certain key (in this case the key is called Nationality and I am trying to find the number of unique nationalities in the list of people):
```
no_of_na... | A better way is to build the `set` directly from the dictionaries:
```
print len(set(p['Nationality'] for p in people))
``` |
Adding information to an exception? | 6,062,576 | 48 | 2011-05-19T17:34:35Z | 6,062,677 | 8 | 2011-05-19T17:43:35Z | [
"python",
"exception-handling"
] | EDIT: I am running python 2.6
I want to achieve something like this:
```
def foo():
try:
raise IOError('Stuff ')
except:
raise
def bar(arg1):
try:
foo()
except Exception as e:
e.message = e.message + 'happens at %s' % arg1
raise
bar('arg1')
```
```
Traceback...
IO... | Assuming you don't want to or can't modify foo(), you can try this:
```
try:
raise IOError('stuff')
except Exception as e:
e.args = (e.args[0] + ' happens',)
raise
``` |
Adding information to an exception? | 6,062,576 | 48 | 2011-05-19T17:34:35Z | 6,062,799 | 46 | 2011-05-19T17:53:45Z | [
"python",
"exception-handling"
] | EDIT: I am running python 2.6
I want to achieve something like this:
```
def foo():
try:
raise IOError('Stuff ')
except:
raise
def bar(arg1):
try:
foo()
except Exception as e:
e.message = e.message + 'happens at %s' % arg1
raise
bar('arg1')
```
```
Traceback...
IO... | I'd do it like this so changing its type in `foo()` won't require also changing it in `bar()`.
```
def foo():
try:
raise IOError('Stuff')
except:
raise
def bar(arg1):
try:
foo()
except Exception as e:
raise type(e)(e.message + ' happens at %s' % arg1)
bar('arg1')
```
... |
Remove (or hide) default Permissions from Django | 6,062,655 | 20 | 2011-05-19T17:42:14Z | 6,185,222 | 17 | 2011-05-31T08:59:52Z | [
"python",
"django"
] | I'm developing a Django app that will have two administration backends. One for daily use by "normal" users and the default one for more advanced tasks and for the developers.
The application uses some custom permissions but none of the default ones. So I'm currently looking for a way to remove the default permissions... | **UPDATE: Django 1.7 supports the customization of [default permissions](https://docs.djangoproject.com/en/1.8/ref/models/options/#default-permissions)**
**Original Answer**
*The following is valid for Django **prior to version 1.7***
This is a standard functionality of the [*auth*](https://docs.djangoproject.com/en... |
Remove (or hide) default Permissions from Django | 6,062,655 | 20 | 2011-05-19T17:42:14Z | 6,267,218 | 12 | 2011-06-07T15:00:07Z | [
"python",
"django"
] | I'm developing a Django app that will have two administration backends. One for daily use by "normal" users and the default one for more advanced tasks and for the developers.
The application uses some custom permissions but none of the default ones. So I'm currently looking for a way to remove the default permissions... | I struggled with this same problem for a while and I think I've come up with a clean solution. Here's how you hide the permissions for Django's auth app:
```
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from django import forms
from django.contrib.auth.models import Permissi... |
Remove (or hide) default Permissions from Django | 6,062,655 | 20 | 2011-05-19T17:42:14Z | 28,467,698 | 8 | 2015-02-12T01:23:05Z | [
"python",
"django"
] | I'm developing a Django app that will have two administration backends. One for daily use by "normal" users and the default one for more advanced tasks and for the developers.
The application uses some custom permissions but none of the default ones. So I'm currently looking for a way to remove the default permissions... | A new feature introduced in Django 1.7 is the ability to define the default permissions. As stated in the [documentation](https://docs.djangoproject.com/en/1.7/ref/models/options/ "documentation") if you set this to empty none of the default permissions will be created.
A working example would be:
```
class Blar1(mod... |
compare two python strings that contain numbers | 6,062,973 | 4 | 2011-05-19T18:08:33Z | 6,063,041 | 9 | 2011-05-19T18:14:06Z | [
"python",
"string",
"numbers"
] | UPDATE: I should have specified this sooner, but not all of the names are simply floats. For example, some of them are "prefixed" with "YT". So for example" YT1.1. so, you have the same problem YT1.9 < YT1.11 should be true. I'm really surprised that the string comparison fails....
hello,
this should be a pretty simpl... | Convert the names to tuples of integers and compare the tuples:
```
def splittedname(s):
return tuple(int(x) for x in s.split('.'))
splittedname(s1) > splittedname(s2)
```
**Update**: Since your names apparently can contain other characters than digits, you'll need to check for `ValueError` and leave any values ... |
Where to join threads created in an asynchronous tornado request handler? | 6,062,997 | 9 | 2011-05-19T18:09:51Z | 6,131,223 | 12 | 2011-05-25T21:32:53Z | [
"python",
"multithreading",
"join",
"tornado"
] | This one has me a bit baffled. Fairly new to tornado and threading in python, so I could be completely off the mark with what I'm trying to do here.
Probably best to start with some simplified code:
```
class Handler(tornado.web.RequestHandler):
def perform(self):
#do something cuz hey, we're in a thread!
... | I believe `Thread.join()` will block until the thread finishes, probably something you want to avoid. Rather than joining, you can have the thread callback to the handler.
When using threads, be aware that tornado isn't thread-safe, so you can't use any RequestHandler (for example) methods from threads.
This works fo... |
Google App Engine Versioning in the Datastore | 6,063,286 | 14 | 2011-05-19T18:35:37Z | 6,063,370 | 7 | 2011-05-19T18:41:30Z | [
"python",
"google-app-engine",
"gae-datastore"
] | Google App Engine has the concept of app versions. i.e., you can have multiple versions of your app running concurrently and accessible at different subdomains. For instance: `http://1.my-app-name.appspot.com`, `http://2.my-app-name.appspot.com`.
What aspects of the app are actually "versioned" by this? Is it only the... | Datastore has no concept of versions.
When you update a model definition, any entities you create in the future will be of the new type, and the old ones will be of the old type. This frequently leads to runtime errors if your code is not aware of these changes. |
Google App Engine Versioning in the Datastore | 6,063,286 | 14 | 2011-05-19T18:35:37Z | 6,063,861 | 25 | 2011-05-19T19:27:00Z | [
"python",
"google-app-engine",
"gae-datastore"
] | Google App Engine has the concept of app versions. i.e., you can have multiple versions of your app running concurrently and accessible at different subdomains. For instance: `http://1.my-app-name.appspot.com`, `http://2.my-app-name.appspot.com`.
What aspects of the app are actually "versioned" by this? Is it only the... | Correct, app version refers only to your uploaded files. Both versions use with the same datastore.
Note that the datastore itself is schema-less. Each entity is an independent collection of key/value pairs. Two entities of the same kind don't have to share the same set of properties, or property types. db.Model provi... |
Python efficiency: lists vs. tuples | 6,063,494 | 8 | 2011-05-19T18:52:44Z | 6,063,532 | 16 | 2011-05-19T18:55:32Z | [
"python",
"python-2.7",
"optimization",
"python-2.6"
] | I have a medium-amount of base objects.
These base objects will be put in collections, and these collections will be munged around: sorted, truncated, etc.
Unfortunately, the *n* is large enough that memory consumption is slightly worrisome, and speed is getting concerning.
My *understanding* is that tuples are slig... | If you have a tuple and a list with the same elements, the tuple takes less space. Since tuples are immutable, you can't sort them, add to them, etc. I recommend watching [this talk by Alex Gaynor](http://blip.tv/pycon-us-videos-2009-2010-2011/pycon-2011-the-data-structures-of-python-4898160) for a quick intro on when ... |
Python efficiency: lists vs. tuples | 6,063,494 | 8 | 2011-05-19T18:52:44Z | 6,063,647 | 9 | 2011-05-19T19:05:10Z | [
"python",
"python-2.7",
"optimization",
"python-2.6"
] | I have a medium-amount of base objects.
These base objects will be put in collections, and these collections will be munged around: sorted, truncated, etc.
Unfortunately, the *n* is large enough that memory consumption is slightly worrisome, and speed is getting concerning.
My *understanding* is that tuples are slig... | As others mentioned tuples are immutable. Sorting a tuple (e.g. `sorted(mytuple)`) returns a list, which you would then have to cast back to a tuple.
To sort a tuple (and keep it a tuple) you'd have to do this:
```
mytuple = (3,2,1)
mysortedtuple = tuple(sorted(mytuple))
```
To sort a list you'd have to do this:
``... |
Increment a python floating point value by the smallest possible amount | 6,063,755 | 40 | 2011-05-19T19:16:52Z | 6,064,066 | 8 | 2011-05-19T19:48:24Z | [
"python"
] | I'm using floating point values as dictionary keys.
Occasionally, *very* occasionally (and perhaps never, but not certainly never), there will be collisions. I would like to resolve these by incrementing the floating point value by as small an amount as possible. How can I do this?
In C, I would twiddle the bits of t... | First, this "respond to a collision" is a pretty bad idea.
If they collide, the values in the dictionary should have been lists of items with a common key, not individual items.
Your "hash probing" algorithm will have to loop through more than one "tiny increments" to resolve collisions.
And sequential hash probes a... |
Increment a python floating point value by the smallest possible amount | 6,063,755 | 40 | 2011-05-19T19:16:52Z | 6,163,157 | 57 | 2011-05-28T17:15:33Z | [
"python"
] | I'm using floating point values as dictionary keys.
Occasionally, *very* occasionally (and perhaps never, but not certainly never), there will be collisions. I would like to resolve these by incrementing the floating point value by as small an amount as possible. How can I do this?
In C, I would twiddle the bits of t... | > Increment a python floating point
> value by the smallest possible amount
You are not crazy and you should be able to do this. It is a current shortcoming of the Python math library, sadly, both in Python 2.X and Python3000. There should be a `math.nextafter(x,y)` in Python but there isn't. It would be trivial to ad... |
matplotlib colorbar for scatter | 6,063,876 | 28 | 2011-05-19T19:28:32Z | 6,065,493 | 77 | 2011-05-19T22:22:15Z | [
"python",
"colors",
"matplotlib"
] | I'm working with data that has the data has 3 plotting parameters: x,y,c. How do you create a custom color value for a scatter plot?
Extending this [example](http://stackoverflow.com/questions/2925806/fixing-color-in-scatter-plots-in-matplotlib) I'm trying to do:
```
import matplotlib
import matplotlib.pyplot as plt
... | From the matplotlib docs on scatter [1](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.scatter):
> cmap is only used if c is an array of floats
So colorlist needs to be a list of floats rather than a list of tuples as you have it now.
plt.colorbar() wants a mappable object, like the CircleCol... |
Django: MultiValueField and MultiWidget | 6,064,121 | 5 | 2011-05-19T19:53:01Z | 6,351,618 | 14 | 2011-06-15T00:09:00Z | [
"python",
"django",
"django-admin",
"django-forms"
] | Django's documentation doesn't do a very thorough job of explaining how to use MultiValueField and MultiWidget. I've tried dissecting the [one implementation](http://code.djangoproject.com/browser/django/trunk/django/forms/fields.py#L908) and haven't had good results. Would someone mind giving me a quick pointer in the... | Please notice that django.forms.MultiValueField is a [**form** field](https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#field-types) and not a **model** field (like django.db.models.CharField). Therefore, it is not treated as a model field in your Test model, and was not created in your database. (You can ... |
Making io.BufferedReader from sys.stdin in Python2 | 6,065,173 | 18 | 2011-05-19T21:39:26Z | 13,189,316 | 7 | 2012-11-02T04:27:24Z | [
"python",
"bufferedreader",
"python-2.x"
] | How can I make a BufferedReader object from a standard file object, like sys.stdin or what you get from 'open'?
(Background: I need a peek() method, which the standard file objects fail at having. Any suggestions to solve this issue are also welcome.)
I'd have sort of expected this to work, but it doesn't:
```
>>> i... | I was also looking for the same code for the same reason (using peek) awhile ago. And this works:
```
reader = io.open(sys.stdin.fileno())
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.