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 |
|---|---|---|---|---|---|---|---|---|---|
python tracing a segmentation fault | 2,663,841 | 30 | 2010-04-18T20:35:04Z | 2,664,232 | 41 | 2010-04-18T22:23:37Z | [
"python",
"c",
"debugging"
] | I'm developing C extensions from python ad I obtain some segfaults (inevitable during the development...).
I'm searching a way to display at which line of code the segfault happens (an idea is like tracing every single line of code), how I can do that? | If you are on linux, run python under gdb
```
gdb python
(gdb) run /path/to/script.py
## wait for segfault ##
(gdb) backtrace
## stack trace of the c code
``` |
python tracing a segmentation fault | 2,663,841 | 30 | 2010-04-18T20:35:04Z | 2,667,467 | 12 | 2010-04-19T12:48:16Z | [
"python",
"c",
"debugging"
] | I'm developing C extensions from python ad I obtain some segfaults (inevitable during the development...).
I'm searching a way to display at which line of code the segfault happens (an idea is like tracing every single line of code), how I can do that? | Segfaults from C extensions are very frequently a result of not incrementing a reference count when you create a new reference to an object. That makes them very hard to track down as the segfault occurs only after the last reference is removed from the object, and even then often only when some other object is being a... |
Counting longest occurence of repeated sequence in Python | 2,664,150 | 7 | 2010-04-18T22:00:59Z | 2,664,198 | 7 | 2010-04-18T22:15:25Z | [
"python",
"string"
] | What's the easiest way to count the longest consecutive repeat of a certain character in a string? For example, the longest consecutive repeat of "b" in the following string:
```
my_str = "abcdefgfaabbbffbbbbbbfgbb"
```
would be 6, since other consecutive repeats are shorter (3 and 2, respectively.) How can I do this... | How about a regex example:
```
import re
my_str = "abcdefgfaabbbffbbbbbbfgbb"
len(max(re.compile("(b+b)*").findall(my_str))) #changed the regex from (b+b) to (b+b)*
# max([len(i) for i in re.compile("(b+b)").findall(my_str)]) also works
```
**Edit, Mine vs. interjays**
```
x=timeit.Timer(stmt='import itertools;my_st... |
Why use Python interactive mode? | 2,664,785 | 17 | 2010-04-19T01:39:15Z | 2,664,798 | 12 | 2010-04-19T01:43:01Z | [
"python",
"interactive-mode",
"python-interactive"
] | When I first started reading about Python, all of the tutorials have you use Python's Interactive Mode. It is difficult to save, write long programs, or edit your existing lines (for me at least). It seems like a far more difficult way of writing Python code than opening up a code.py file and running the interpreter on... | [**REPL Loops**](http://en.wikipedia.org/wiki/Read-eval-print_loop) (like Python's interactive mode) provide immediate feedback to the programmer. As such, you can rapidly write and test small pieces of code, and assemble those pieces into a larger program. |
Why use Python interactive mode? | 2,664,785 | 17 | 2010-04-19T01:39:15Z | 2,665,150 | 31 | 2010-04-19T04:07:51Z | [
"python",
"interactive-mode",
"python-interactive"
] | When I first started reading about Python, all of the tutorials have you use Python's Interactive Mode. It is difficult to save, write long programs, or edit your existing lines (for me at least). It seems like a far more difficult way of writing Python code than opening up a code.py file and running the interpreter on... | Let's see:
* If you want to know how something works, you can just try it. There is no need to write up a file. I almost always scratch write my programs in the interpreter before coding them. It's not just for things that you don't know how they work in the programming language. I never remember what the correct argu... |
Reading CSV files in numpy where delimiter is "," | 2,664,790 | 9 | 2010-04-19T01:40:51Z | 2,664,880 | 11 | 2010-04-19T02:17:43Z | [
"python",
"csv",
"numpy",
"delimiter"
] | I've got a CSV file with a format that looks like this:
> "FieldName1", "FieldName2", "FieldName3", "FieldName4"
> "04/13/2010 14:45:07.008", "7.59484916392", "10", "6.552373"
> "04/13/2010 14:45:22.010", "6.55478493312", "9", "3.5378543"
> ...
Note that there are double quote characters at the start and end of... | The basic problem is that NumPy doesn't understand the concept of stripping quotes (whereas the `csv` module does). When you say `delimiter='","'`, you're telling NumPy that the column delimiter is literally a quoted comma, i.e. the quotes are around the comma, not the value, so the extra quotes you get on he first and... |
How can I use Perl's s/// in an expression? | 2,664,812 | 7 | 2010-04-19T01:47:58Z | 2,664,843 | 11 | 2010-04-19T01:57:47Z | [
"python",
"regex",
"perl",
"variable-assignment",
"substitution"
] | I got a headache looking for this:
How do you use s/// in an expression as opposed to an assignment. To clarify what I mean, I'm looking for a perl equivalent of python's **re.sub(...)** when used in the following context:
```
newstring = re.sub('ab', 'cd', oldstring)
```
The only way I know how to do this in perl so... | You can use `($new = $old) =~ s/whatever/whateverelse/;` for an exactly same functionality you are looking for:
```
use strict;
my $old = "OLD";
my $new;
($new = $old) =~ s/OLD/NEW/;
print "old=$old, new=$new";
```
Produces:
```
old=OLD, new=NEW
```
Exactly what you want
If you're looking for a function, you can j... |
How can I use Perl's s/// in an expression? | 2,664,812 | 7 | 2010-04-19T01:47:58Z | 2,664,849 | 7 | 2010-04-19T02:00:32Z | [
"python",
"regex",
"perl",
"variable-assignment",
"substitution"
] | I got a headache looking for this:
How do you use s/// in an expression as opposed to an assignment. To clarify what I mean, I'm looking for a perl equivalent of python's **re.sub(...)** when used in the following context:
```
newstring = re.sub('ab', 'cd', oldstring)
```
The only way I know how to do this in perl so... | Perl's regular expression substitution always happens 'in-place'. So you need to copy the string to a new variable and operate on the new variable:
```
(my $newstring = $oldstring) =~ s/ab/cd/;
``` |
How can I use Perl's s/// in an expression? | 2,664,812 | 7 | 2010-04-19T01:47:58Z | 2,665,963 | 7 | 2010-04-19T07:59:07Z | [
"python",
"regex",
"perl",
"variable-assignment",
"substitution"
] | I got a headache looking for this:
How do you use s/// in an expression as opposed to an assignment. To clarify what I mean, I'm looking for a perl equivalent of python's **re.sub(...)** when used in the following context:
```
newstring = re.sub('ab', 'cd', oldstring)
```
The only way I know how to do this in perl so... | You seem to have a misconception about how `=~` works. `=~` is a binding operator that associates a variable with a regexp operator. It does not do any assignment.
The regexp operators all work by default with the topic variable `$_`, so `s/foo/bar/;` is the same as `$_ =~ s/foo/bar/;`. No assignment occurs. The topic... |
How should I extract % delimited tags | 2,665,400 | 2 | 2010-04-19T05:53:54Z | 2,665,404 | 7 | 2010-04-19T05:55:54Z | [
"python",
"text-extraction"
] | I want to get the `%tagname%` from a file and copy them to a dictionary only `tagname` in python. | this will get you a list of tags
```
re.findall("%([^%]+)%", text)
``` |
What is the 'wb' mean in this code, using Python? | 2,665,866 | 26 | 2010-04-19T07:43:06Z | 2,665,873 | 28 | 2010-04-19T07:44:22Z | [
"python",
"file",
"syntax"
] | Code:
```
file('pinax/media/a.jpg', 'wb')
``` | [File mode](http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files), write and binary. Since you are writing a .jpg file, it looks fine.
But if you supposed to read that jpg file you need to use `'rb'`
More info
> On Windows, 'b' appended to the mode
> opens the file in binary mode, so
> there ar... |
What is the 'wb' mean in this code, using Python? | 2,665,866 | 26 | 2010-04-19T07:43:06Z | 2,665,922 | 17 | 2010-04-19T07:52:34Z | [
"python",
"file",
"syntax"
] | Code:
```
file('pinax/media/a.jpg', 'wb')
``` | The `wb` indicates that the file is opened for writing in binary mode.
On Unix systems (Linux, Mac OS X, etc.), binary mode does nothing - they treat text files the same way that any other files are treated. On Windows, however, text files are written with slightly modified line endings. This causes a serious problem ... |
Any better way to generate a tuple of all possible tuples in form of (x1,y1,x2,y2)? | 2,666,253 | 2 | 2010-04-19T08:58:16Z | 2,666,299 | 7 | 2010-04-19T09:04:14Z | [
"python"
] | I want to generate a tuple of tuple in form of ((x1,y1,x2,y2),...(x1,y1,x2,y2)) where x1,y1,x2,y2 are all in range of (0,8).
Is there any other way rather than the following?
```
S = list()
for x1 in range(0, 8):
for y1 in range(0, 8):
for x2 in range(0, 8):
for y2 in range(0, 8):
... | ```
tuple([x1, y1, x2, y2] for x1 in range(0, 8) for x2 in range(0, 8) for y1 in range(0, 8) for y2 in range(0, 8))
```
Or
```
import itertools
a = [range(0,8)]*4
print tuple(itertools.product(*a))
```
Note that this returns a tuple of tuples. If you need a tuple of lists, use `tuple(itertools.imap(list, itertools.p... |
python while loop | 2,666,614 | 2 | 2010-04-19T10:31:04Z | 2,666,624 | 11 | 2010-04-19T10:32:44Z | [
"python",
"syntax"
] | ```
def merge(l1,l2):
i=0;
while((l1[i]!=none)||(l2[i]!=none)):
```
SyntaxError: invalid syntax
being a newbie i can't figure out whats wrong with the abouve code. | Replace `||` with `or`, make `None` upper-case (and lose the semi-colon):
```
def merge(l1, l2):
i = 0
while l1[i] != None or l2[i] != None:
pass
```
(As you can see, the parentheses were also redundant.)
Furthermore, `!= None` can be changed to `is not None`:
```
while l1[i] is not None or l2[i] is not Non... |
Cannot find vcvarsall.bat when running a Python script | 2,667,069 | 53 | 2010-04-19T11:48:15Z | 6,500,422 | 13 | 2011-06-28T00:28:04Z | [
"python",
"visual-studio-2010"
] | I am working on Vista, and using Python 2.6.4. I am using a software that utilizes a Python script, but bumped into the message:
```
cannot find vcvarsall.bat
```
So, I installed visual c++ 2010. Still the file is not found - though, it is there. My guess (a very uneducated one...) is that somewhere the path is wrong... | The solution to this problem is to set the following environment variable:
```
VS90COMNTOOLS
```
For instance:
```
set VS90COMNTOOLS=C:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools
```
This error can be caused by not rebooting after installing Visual Studios, or not starting a new command prompt after in... |
Cannot find vcvarsall.bat when running a Python script | 2,667,069 | 53 | 2010-04-19T11:48:15Z | 8,884,982 | 39 | 2012-01-16T19:04:10Z | [
"python",
"visual-studio-2010"
] | I am working on Vista, and using Python 2.6.4. I am using a software that utilizes a Python script, but bumped into the message:
```
cannot find vcvarsall.bat
```
So, I installed visual c++ 2010. Still the file is not found - though, it is there. My guess (a very uneducated one...) is that somewhere the path is wrong... | It seems that Python is looking explicitly for Visual Studio 2008. I encountered this problem where it couldn't find vcvarsall.bat even though it was on the path.
It turns out that Visual Studio 2010 creates the following environment variable:
```
SET VS100COMNTOOLS=C:\Program Files\Microsoft Visual Studio 10.0\Commo... |
Cannot find vcvarsall.bat when running a Python script | 2,667,069 | 53 | 2010-04-19T11:48:15Z | 27,210,430 | 20 | 2014-11-30T05:45:22Z | [
"python",
"visual-studio-2010"
] | I am working on Vista, and using Python 2.6.4. I am using a software that utilizes a Python script, but bumped into the message:
```
cannot find vcvarsall.bat
```
So, I installed visual c++ 2010. Still the file is not found - though, it is there. My guess (a very uneducated one...) is that somewhere the path is wrong... | Here's a **simple solution**. I'm using Python 2.7 and Windows 7.
What you're trying to install requires a C/C++ compiler but Python isn't finding it. A lot of Python packages are actually written in C/C++ and need to be compiled. vcvarsall.bat is needed to compile C++ and pip is assuming your machine can do that.
1.... |
Cannot find vcvarsall.bat when running a Python script | 2,667,069 | 53 | 2010-04-19T11:48:15Z | 29,402,715 | 8 | 2015-04-01T23:38:03Z | [
"python",
"visual-studio-2010"
] | I am working on Vista, and using Python 2.6.4. I am using a software that utilizes a Python script, but bumped into the message:
```
cannot find vcvarsall.bat
```
So, I installed visual c++ 2010. Still the file is not found - though, it is there. My guess (a very uneducated one...) is that somewhere the path is wrong... | In **2015**, if you still getting this confusing error, ***blame python default setuptools*** that PIP uses.
1. Download and install minimal *Microsoft Visual C++ Compiler for Python 2.7* required to compile python 2.7 modules from <http://www.microsoft.com/en-in/download/details.aspx?id=44266>
2. Update your setuptoo... |
CURL alternative in Python | 2,667,509 | 94 | 2010-04-19T12:55:12Z | 2,667,545 | 20 | 2010-04-19T12:59:48Z | [
"python",
"curl"
] | I have a cURL call that I use in PHP:
> curl -i -H 'Accept: application/xml' -u login:key "https://app.streamsend.com/emails"
I need a way to do the same thing in Python. Is there an alternative to cURL in Python. I know of urllib but I'm a Python noob and have no idea how to use it. | If you are using a command to just call curl like that, you can do the same thing in Python with `subprocess`. Example:
```
subprocess.call(['curl', '-i', '-H', '"Accept: application/xml"', '-u', 'login:key', '"https://app.streamsend.com/emails"'])
```
Or you could try [PycURL](http://pycurl.sourceforge.net/) if you ... |
CURL alternative in Python | 2,667,509 | 94 | 2010-04-19T12:55:12Z | 2,668,139 | 62 | 2010-04-19T14:24:02Z | [
"python",
"curl"
] | I have a cURL call that I use in PHP:
> curl -i -H 'Accept: application/xml' -u login:key "https://app.streamsend.com/emails"
I need a way to do the same thing in Python. Is there an alternative to cURL in Python. I know of urllib but I'm a Python noob and have no idea how to use it. | ```
import urllib2
manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, 'https://app.streamsend.com/emails', 'login', 'key')
handler = urllib2.HTTPBasicAuthHandler(manager)
director = urllib2.OpenerDirector()
director.add_handler(handler)
req = urllib2.Request('https://app.streamsend.com/em... |
CURL alternative in Python | 2,667,509 | 94 | 2010-04-19T12:55:12Z | 8,131,577 | 31 | 2011-11-15T04:38:51Z | [
"python",
"curl"
] | I have a cURL call that I use in PHP:
> curl -i -H 'Accept: application/xml' -u login:key "https://app.streamsend.com/emails"
I need a way to do the same thing in Python. Is there an alternative to cURL in Python. I know of urllib but I'm a Python noob and have no idea how to use it. | Here's a simple example using urllib2 that does a basic authentication against GitHub's API.
```
import urllib2
u='username'
p='userpass'
url='https://api.github.com/users/username'
# simple wrapper function to encode the username & pass
def encodeUserData(user, password):
return "Basic " + (user + ":" + passwor... |
CURL alternative in Python | 2,667,509 | 94 | 2010-04-19T12:55:12Z | 10,093,587 | 111 | 2012-04-10T17:32:49Z | [
"python",
"curl"
] | I have a cURL call that I use in PHP:
> curl -i -H 'Accept: application/xml' -u login:key "https://app.streamsend.com/emails"
I need a way to do the same thing in Python. Is there an alternative to cURL in Python. I know of urllib but I'm a Python noob and have no idea how to use it. | You can use HTTP Requests that are described in the [Requests: HTTP for Humans](http://docs.python-requests.org/en/latest/index.html) user guide. |
Simple python oo issue | 2,667,688 | 4 | 2010-04-19T13:22:40Z | 2,667,701 | 12 | 2010-04-19T13:24:25Z | [
"python",
"arguments",
"mutable"
] | Have a look a this simple example. I don't quite understand why o1 prints "Hello Alex" twice. I would think that because of the default self.a is always reset to the empty list. Could someone explain to me what's the rationale here? Thank you so much.
```
class A(object):
def __init__(self, a=[]):
... | Read this Pitfall about mutable default function arguments:
<http://www.ferg.org/projects/python_gotchas.html>
In short, when you define
```
def __init__(self,a=[])
```
The list referenced by self.a by default is defined only once, at definition-time, not run-time. So each time you call `o.a.append` or `o1.a.append`... |
Make Sphinx generate RST class documentation from pydoc | 2,668,187 | 7 | 2010-04-19T14:28:46Z | 2,712,413 | 11 | 2010-04-26T09:46:07Z | [
"python",
"python-sphinx",
"pydoc"
] | I'm currently migrating all existing (incomplete) documentation to [Sphinx](http://sphinx.pocoo.org/).
The problem is that the documentation uses [Python docstrings](http://epydoc.sourceforge.net/docstrings.html) (the module is written in C, but it probably does not matter) and the class documentation must be converte... | The autodoc does generate RST only there is no official way to get it out of it. The easiest hack to get it was by changing `sphinx.ext.autodoc.Documenter.add_line` method to emit me the line it gets.
As all I want is one time migration, output to stdout is good enough for me:
```
def add_line(self, line, source, *li... |
shuffle string in python | 2,668,312 | 28 | 2010-04-19T14:41:31Z | 2,668,325 | 33 | 2010-04-19T14:42:36Z | [
"python",
"string"
] | I am looking for a function or short program that recieves a string (up to 10 letters) and shuffles it.
thanks Ariel | There is a function [shuffle](http://docs.python.org/library/random.html) in the random module. Note that it shuffles in-place so you first have to convert your string to a list of characters, shuffle it, then join the result again.
```
import random
l = list(s)
random.shuffle(l)
result = ''.join(l)
``` |
shuffle string in python | 2,668,312 | 28 | 2010-04-19T14:41:31Z | 2,668,366 | 58 | 2010-04-19T14:49:44Z | [
"python",
"string"
] | I am looking for a function or short program that recieves a string (up to 10 letters) and shuffles it.
thanks Ariel | ```
>>> import random
>>> s="abcdef123"
>>> ''.join(random.sample(s,len(s)))
'1f2bde3ac'
``` |
Detect and record a sound with python | 2,668,442 | 10 | 2010-04-19T15:00:10Z | 2,669,341 | 9 | 2010-04-19T17:03:25Z | [
"python",
"audio",
"detect",
"record"
] | I'm using this program to record a sound in python:
<http://stackoverflow.com/questions/892199/detect-record-audio-in-python/892293#892293>
I want to change the program to start recording when sound is detected by the sound card input. Probably should compare the input sound level in chunk, but how do this? | You could try something like this:
*based on [this question/answer](http://stackoverflow.com/questions/892199/detect-record-audio-in-python/892293#892293)*
```
# this is the threshold that determines whether or not sound is detected
THRESHOLD = 0
#open your audio stream
# wait until the sound data breaks some l... |
Python Glade could not create GladeXML Object | 2,668,618 | 13 | 2010-04-19T15:24:56Z | 2,668,968 | 23 | 2010-04-19T16:08:07Z | [
"python",
"user-interface",
"exception",
"glade"
] | I've created a simple window GUI in Glade 3.6.7 and I am trying to import it into Python. Every time I try to do so I get the following error:
```
(queryrelevanceevaluation.py:8804): libglade-WARNING **: Expected <glade-interface>. Got <interface>.
(queryrelevanceevaluation.py:8804): libglade-WARNING **: did not f... | You have created a GtkBuilder file instead of Glade file.
You can use GtkBuilder as follow:
```
builder = gtk.Builder()
builder.add_from_string(string, len(string))
builder.connect_signals(anobject)
builder.get_object(name)
```
**EDIT**:
When you start a new project in glade it asks you if you want create a glade f... |
redefine __and__ operator | 2,668,667 | 4 | 2010-04-19T15:29:54Z | 2,668,697 | 9 | 2010-04-19T15:33:41Z | [
"python",
"operators",
"redefine",
"and-operator"
] | Why I can't redefine the `__and__` operator?
```
class Cut(object):
def __init__(self, cut):
self.cut = cut
def __and__(self, other):
return Cut("(" + self.cut + ") && (" + other.cut + ")")
a = Cut("a>0")
b = Cut("b>0")
c = a and b
print c.cut()
```
I want `(a>0) && (b>0)`, but I got b... | `__and__` is the binary (bitwise) `&` operator, not the logical `and` operator.
Because the `and` operator is a short-circuit operator, it can't be implemented as a function. That is, if the first argument is false, the second argument isn't evaluated at all. If you try to implement that as a function, both arguments ... |
How to find the real user home directory using python? | 2,668,909 | 33 | 2010-04-19T15:59:03Z | 2,668,952 | 40 | 2010-04-19T16:05:40Z | [
"python",
"linux",
"windows",
"directory",
"home-directory"
] | I see that if we change the HOME(linux) or USERPROFILE(windows) environmental variable and run a python script, it returns the new value as the user home when I tried,
os.environ['HOME']
os.exp
Is there any way to find the real user home directory without relying on the environmental variable?. Thanx.
**edit:**
He... | I think [`os.path.expanduser(path)`](http://docs.python.org/library/os.path.html#os.path.expanduser) could be helpful.
> On Unix and Windows, return the argument with an initial component of `~` or `~user` replaced by that userâs home directory.
>
> On Unix, an initial `~` is replaced by the environment variable HOM... |
How to find the real user home directory using python? | 2,668,909 | 33 | 2010-04-19T15:59:03Z | 3,085,545 | 7 | 2010-06-21T14:33:53Z | [
"python",
"linux",
"windows",
"directory",
"home-directory"
] | I see that if we change the HOME(linux) or USERPROFILE(windows) environmental variable and run a python script, it returns the new value as the user home when I tried,
os.environ['HOME']
os.exp
Is there any way to find the real user home directory without relying on the environmental variable?. Thanx.
**edit:**
He... | I think `os.path.expanduser(path)` is the best answer to your question, but there's an alternative that may be worth mentioning in the Unix world: the [`pwd`](http://docs.python.org/library/pwd.html) package. e.g.
```
import os, pwd
pwd.getpwuid(os.getuid()).pw_dir
``` |
How to sort alpha numeric set in python | 2,669,059 | 38 | 2010-04-19T16:21:05Z | 2,669,120 | 70 | 2010-04-19T16:31:58Z | [
"python",
"sorting"
] | I have a set
```
set(['booklet', '4 sheets', '48 sheets', '12 sheets'])
```
After sorting I want it to look like
```
4 sheets,
12 sheets,
48 sheets,
booklet
```
Any idea please | [Jeff Atwood](http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html) talks about natural sort and gives an example of one way to do it in Python. Here is my variation on it:
```
import re
def sorted_nicely( l ):
""" Sort the given iterable in the way that humans expect."""
con... |
How to sort alpha numeric set in python | 2,669,059 | 38 | 2010-04-19T16:21:05Z | 2,669,523 | 38 | 2010-04-19T17:32:57Z | [
"python",
"sorting"
] | I have a set
```
set(['booklet', '4 sheets', '48 sheets', '12 sheets'])
```
After sorting I want it to look like
```
4 sheets,
12 sheets,
48 sheets,
booklet
```
Any idea please | Short and sweet:
```
sorted(data, key=lambda item: (int(item.partition(' ')[0])
if item[0].isdigit() else float('inf'), item))
```
This version:
* Works in Python 2 and Python 3, because:
+ It does not assume you compare strings and integers (which won't work in Python 3)
+ It does... |
rpy2: Converting a data.frame to a numpy array | 2,669,427 | 7 | 2010-04-19T17:18:19Z | 2,669,874 | 7 | 2010-04-19T18:32:01Z | [
"python",
"numpy",
"bioconductor",
"rpy2"
] | I have a data.frame in R. It contains a lot of data : gene expression levels from many (125) arrays. I'd like the data in Python, due mostly to my incompetence in R and the fact that this was supposed to be a 30 minute job.
I would like the following code to work. To understand this code, know that the variable `path`... | This is the most straightforward and reliable way i've found to to transfer a data frame from R to Python.
To begin with, I think exchanging the data through the R bindings is an unnecessary complication. R provides a simple method to export data, likewise, NumPy has decent methods for data import. The file format is ... |
Python Wildcard Import Vs Named Import | 2,669,627 | 4 | 2010-04-19T17:48:51Z | 2,669,707 | 8 | 2010-04-19T18:02:45Z | [
"python",
"import",
"wildcard",
"named"
] | Ok, I have some rather odd behavior in one of my Projects and I'm hoping someone can tell me why. My file structure looks like this:
```
MainApp.py
res/
__init__.py
elements/
__init__.py
MainFrame.py
```
Inside of MainFrame.py I've defined a class named RPMWindow which extends wx.Frame.
In MainApp.py thi... | You have circular imports:
MainFrame.py is indirectly importing MainApp.py, and MainApp.py is importing MainFrame.py. As a result, when MainApp.py is importing MainFrame.py, the RPMWindow class hasn't been defined yet and you get the ImportError. |
Avoiding accidentally catching KeyboardInterrupt and SystemExit in Python 2.4 | 2,669,750 | 16 | 2010-04-19T18:09:08Z | 2,669,767 | 12 | 2010-04-19T18:11:49Z | [
"python",
"python-2.4"
] | In Python scripts, there are many cases where a keyboard interrupt (Ctrl-C) fails to kill the process because of a bare `except` clause somewhere in the code:
```
try:
foo()
except:
bar()
```
The standard solution in Python 2.5 or higher is to catch `Exception` rather than using bare `except` clauses:
```
tr... | According to the [Python documentation](http://docs.python.org/whatsnew/2.5.html#pep-352-exceptions-as-new-style-classes), the right way to handle this in Python versions earlier than 2.5 is:
```
try:
foo()
except (KeyboardInterrupt, SystemExit):
raise
except:
bar()
```
That's very wordy, but at least it'... |
Large Django application layout | 2,670,031 | 25 | 2010-04-19T19:02:20Z | 2,670,177 | 32 | 2010-04-19T19:27:53Z | [
"python",
"django",
"conventions"
] | I am in a team developing a web-based university portal, which will be based on Django. We are still in the exploratory stages, and I am trying to find the best way to lay the project/development environment out.
My initial idea is to develop the system as a Django "app", which contains sub-applications to separate ou... | The best way that I have found to go about this is to create applications and then a project to glue them together. Most of my projects have similar apps which are included in each. Emails, notes, action reminders, user auth, etc. My preferred layout is like so:
* project/
+ settings.py
+ urls.py
+ views.py
+ ... |
Web Security: Worst-Case Situation | 2,670,346 | 3 | 2010-04-19T19:49:27Z | 2,670,597 | 7 | 2010-04-19T20:26:45Z | [
"python",
"security"
] | I currently have built a system that checks user IP, browser, and a random-string cookie to determine if he is an admin.
In the worst case, someone steals my cookie, uses the same browser I do, and masks his IP to appear as mine. Is there another layer of security I should add onto my script to make it more secure?
E... | Checking the browser is a complete and absolute waste of code. There is no point in writing a secuirty system that is [trivial](https://addons.mozilla.org/en-US/firefox/addon/59) for an attacker to bypass. If the attacker obtains the session id via xss or sniffing the line then they will also have your "user-agent".
C... |
printing to the screen on the same line at different times | 2,671,004 | 6 | 2010-04-19T21:23:14Z | 2,671,016 | 9 | 2010-04-19T21:25:12Z | [
"python"
] | My code looks like this:
```
print "Doing Something...",
do_some_function_that_takes_a_long_time()
print "Done"
```
I want it to print that statement at the top to the screen first, then do the function, and then print the "Done" line. Currently it waits until the "Done" line is executed before it prints the top part... | You have to [flush the output](http://stackoverflow.com/questions/230751/how-to-flush-output-of-python-print) after your first `print`. |
Create a dictionary in python which is indexed by lists | 2,671,211 | 5 | 2010-04-19T21:59:06Z | 2,671,270 | 14 | 2010-04-19T22:10:31Z | [
"python",
"dictionary"
] | I would like to create a dictionary which is indexed by lists. For instance, my dictionary should look like:
```
D = {[1,2,3]:1, [2,3]:3}
```
Anyone know how to do this? If I just type `D([1,2,3]) = 1` it returns an error. | dict keys must be *hashable*, which lists are not becase they are *mutable*. You can change a list after you make it. Think of how tricky it would be to try to keep a dict when the data used as keys changes; it doesn't make any sense. Imagine this scenario
```
>>> foo = [1, 2]
>>> bar = {foo: 3}
>>> foo.append(4)
```
... |
Python: How can I use Twisted as the transport for SUDS? | 2,671,228 | 12 | 2010-04-19T22:01:05Z | 2,671,843 | 13 | 2010-04-20T00:48:02Z | [
"python",
"soap",
"twisted",
"suds",
"transport"
] | I have a project that is based on Twisted used to
communicate with network devices and I am adding support for a new
vendor ([Citrix NetScaler](http://www.citrix.com/netscaler)) whose API is SOAP. Unfortunately the
support for SOAP in Twisted still relies on `SOAPpy`, which is badly out
of date. In fact as of this ques... | The default interpretation of *transport* in the context of Twisted is probably an implementation of `twisted.internet.interfaces.ITransport`. At this layer, you're basically dealing with raw bytes being sent and received over a socket of some sort (UDP, TCP, and SSL being the most commonly used three). This isn't real... |
Hashable, immutable | 2,671,376 | 49 | 2010-04-19T22:32:07Z | 2,671,398 | 52 | 2010-04-19T22:39:41Z | [
"python",
"data-structures",
"hash",
"immutability"
] | From a recent SO question (see [Create a dictionary in python which is indexed by lists](http://stackoverflow.com/questions/2671211/create-a-dictionary-in-python-which-is-indexed-by-lists)) I realized I probably had a wrong conception of the meaning of hashable and immutable objects in python.
* What does hashable mea... | [Hashing](http://en.wikipedia.org/wiki/Hash_function) is the process of converting some large amount of data into a much smaller amount (typically a single integer) in a repeatable way so that it can be looked up in a table in constant-time (`O(1)`), which is important for high-performance algorithms and data structure... |
Appengine filter inequality and ordering fails | 2,671,587 | 22 | 2010-04-19T23:26:46Z | 2,671,672 | 19 | 2010-04-19T23:52:42Z | [
"python",
"google-app-engine",
"google-cloud-datastore"
] | I think I'm overlooking something simple here, I can't imagine this is impossible to do.
I want to filter by a datetime attribute and then order the result by a ranking integer attribute. When I try to do this:
```
query.filter("submitted >=" thisweek).order("ranking")
```
I get the following:
```
BadArgumentError:... | The datastore isn't capable of ordering a query that contains an inequality by any property other than the one used in the inequality.
This can often be worked around by adding a property that can be filtered with an equality; in this case, it may be possible to have a BooleanProperty tracking whether an entity is fro... |
Calling Python from Java through scripting engine (jython)? | 2,671,768 | 9 | 2010-04-20T00:23:26Z | 2,671,799 | 14 | 2010-04-20T00:31:53Z | [
"java",
"python",
"jython",
"javax.script"
] | I'm trying to call Jython from a Java 6 application using `javax.script`:
```
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class jythonEx
{
public static void main (String args[]) throws ScriptException
{
ScriptEngineManager mgr... | You have to register your engine first.
From: [ScriptEngineManager.getEngineByName](http://java.sun.com/javase/6/docs/api/javax/script/ScriptEngineManager.html#getEngineByName%28java.lang.String%29):
> *[...] first searches for a ScriptEngineFactory that has been registered as a handle [...] Returns null if no such f... |
Twisted Python getPage | 2,671,780 | 3 | 2010-04-20T00:26:57Z | 2,671,812 | 14 | 2010-04-20T00:36:49Z | [
"python",
"twisted"
] | I tried to get support on this but I am TOTALLY confused.
Here's my code:
```
from twisted.internet import reactor
from twisted.web.client import getPage
from twisted.web.error import Error
from twisted.internet.defer import DeferredList
from sys import argv
class GrabPage:
def __init__(self, page):
self.page = p... | You're missing the basics of how Twisted operates. It all revolves around the `reactor`, which you're never even running. Think of the reactor like this:

Until you start the reactor, by setting up deferreds all you're doing is chaining t... |
How should I rewrite my database execute/commit to make it amenable to unit testing? | 2,671,947 | 6 | 2010-04-20T01:17:15Z | 2,672,132 | 8 | 2010-04-20T02:13:52Z | [
"python",
"database",
"unit-testing"
] | I've been trying to get started with unit-testing while working on a little cli program.
My program basically parses the command line arguments and options, and decides which function to call. Each of the functions performs some operation on a database.
So, for instance, I might have a create function:
```
def creat... | Alex's answer covers the dependency injection approach. Another is to factor your method. As it stands, it has two phases: construct a SQL statement, and execute the SQL statement. You don't want to test the second phase: you didn't write the SQL engine or the database, you can assume they work properly. Phase 1 is you... |
Why do I get a TypeError: 'module' object is not callable when trying to import the random module? | 2,672,270 | 4 | 2010-04-20T03:04:18Z | 2,672,288 | 14 | 2010-04-20T03:09:31Z | [
"python"
] | I am using Python 2.6 and am trying to run a simple random number generator program (random.py):
```
import random
for i in range(5):
# random float: 0.0 <= number < 1.0
print random.random(),
# random float: 10 <= number < 20
print random.uniform(10, 20),
# random integer: 100 <= number <= 100... | Name your file something else. In Python a script *is* a module, whose name is determined by the filename. So when you start out your file `random.py` with `import random` you are creating a loop in the module structure. |
What does a leading `\x` mean in a Python string `\xaa` | 2,672,326 | 27 | 2010-04-20T03:25:16Z | 2,672,338 | 31 | 2010-04-20T03:28:35Z | [
"python",
"string",
"escaping"
] | What is difference between `'aa'` and `'\xaa'`? What does the `\x` part mean? And which chapter of the Python documentation covers this topic? | The leading `\x` escape sequence means the next two characters are interpreted as hex digits for the character code, so `\xaa` equals `chr(0xaa)`, i.e., `chr(16 * 10 + 10)` -- a small raised lowercase `'a'` character.
Escape sequences are documented in a short table [here](http://docs.python.org/reference/lexical_anal... |
Testing for the existence of a field in a class | 2,672,801 | 6 | 2010-04-20T05:37:10Z | 2,672,824 | 18 | 2010-04-20T05:41:39Z | [
"python",
"class",
"exists"
] | i have a quick question. I have a 2D array that stores an instance of a class. The elements of the array are assigned a particular class based on a text file that is read earlier in the program. Since i do not know without looking in the file what class is stored at a particular element i could refer to a field that do... | `hasattr(x, 'foo')` is a built-in binary function that checks whether object `x` has an attribute `x.foo` (whether it gets it from its class or not), which seems close to what you're asking. Whether what you're asking is actually what you *should* be asking is a different issue -- as @Eli's answer suggests, your design... |
Multiple counters in a single for loop : Python | 2,672,936 | 11 | 2010-04-20T06:12:48Z | 2,672,942 | 8 | 2010-04-20T06:14:28Z | [
"python",
"for-loop"
] | Is it possible in Python to run multiple counters in a single for loop as in C/C++?
I would want something like -- `for i,j in x,range(0,len(x)):` I know Python interprets this differently and why, but how would I run two loop counters concurrently in a single for loop? | You might want to use [zip](http://docs.python.org/library/functions.html#zip)
```
for i,j in zip(x,range(0,len(x))):
```
Example,
```
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> print zipped
[(1, 4), (2, 5), (3, 6)]
>>> for a,b in zipped:
... print a,b
...
1 4
2 5
3 6
>>>
```
**Note**: The c... |
Multiple counters in a single for loop : Python | 2,672,936 | 11 | 2010-04-20T06:12:48Z | 2,672,958 | 24 | 2010-04-20T06:17:20Z | [
"python",
"for-loop"
] | Is it possible in Python to run multiple counters in a single for loop as in C/C++?
I would want something like -- `for i,j in x,range(0,len(x)):` I know Python interprets this differently and why, but how would I run two loop counters concurrently in a single for loop? | You want `zip` in general, which combines two iterators, as @S.Mark says. But in this case `enumerate` does exactly what you need, which means you don't have to use `range` directly:
```
for j, i in enumerate(x):
```
Note that this gives the index of `x` first, so I've reversed `j, i`. |
Django BigInteger auto-increment field as primary key? | 2,672,975 | 19 | 2010-04-20T06:19:55Z | 7,448,366 | 12 | 2011-09-16T17:32:27Z | [
"python",
"django",
"primary-key",
"auto-increment",
"biginteger"
] | I'm currently building a project which involves a lot of collective intelligence. Every user visiting the web site gets created a unique profile and their data is later used to calculate best matches for themselves and other users.
By default, Django creates an INT(11) `id` field to handle models primary keys. I'm con... | > NOTE: This answer as modified, according to Larry's code. Previous solution extended fields.BigIntegerField, but better to extend fields.AutoField
I had the same problem and solved with following code:
```
from django.db.models import fields
from south.modelsinspector import add_introspection_rules
class BigAutoFi... |
Django BigInteger auto-increment field as primary key? | 2,672,975 | 19 | 2010-04-20T06:19:55Z | 17,035,822 | 15 | 2013-06-11T02:51:53Z | [
"python",
"django",
"primary-key",
"auto-increment",
"biginteger"
] | I'm currently building a project which involves a lot of collective intelligence. Every user visiting the web site gets created a unique profile and their data is later used to calculate best matches for themselves and other users.
By default, Django creates an INT(11) `id` field to handle models primary keys. I'm con... | Inspired by lfagundes but with a small but important correction:
```
class BigAutoField(fields.AutoField):
def db_type(self, connection): # pylint: disable=W0621
if 'mysql' in connection.__class__.__module__:
return 'bigint AUTO_INCREMENT'
return super(BigAutoField, self).db_type(conne... |
Getting and trapping HTTP response using Mechanize in Python | 2,673,022 | 11 | 2010-04-20T06:27:12Z | 2,673,402 | 12 | 2010-04-20T07:40:52Z | [
"python",
"mechanize"
] | I am trying to get the response codes from Mechanize in python. While I am able to get a 200 status code anything else isn't returned (404 throws and exception and 30x is ignored). Is there a way to get the original status code?
Thanks | Errors will throw an exception, so just use try:...except:... to handle them.
Your Mechanize browser object has a method set\_handle\_redirect() that you can use to turn 30x redirection on or off. Turn it off and you get an error for redirects that you handle just like you handle any other error:
```
>>> from mechani... |
How to generate random number with the specific length in python | 2,673,385 | 35 | 2010-04-20T07:38:19Z | 2,673,399 | 69 | 2010-04-20T07:40:35Z | [
"python",
"random"
] | Let say I need a 3 digit number, so it would be something like:
```
>>> random(3)
563
or
>>> random(5)
26748
>> random(2)
56
``` | To get a random 3-digit number:
```
from random import randint
randint(100, 999) # randint is inclusive at both ends
```
(assuming you really meant three digits, rather than "up to three digits".)
To use an arbitrary number of digits:
```
from random import randint
def random_with_N_digits(n):
range_start = 1... |
How to generate random number with the specific length in python | 2,673,385 | 35 | 2010-04-20T07:38:19Z | 15,439,939 | 11 | 2013-03-15T18:44:10Z | [
"python",
"random"
] | Let say I need a 3 digit number, so it would be something like:
```
>>> random(3)
563
or
>>> random(5)
26748
>> random(2)
56
``` | If you want it as a string (for example, a 10-digit phone number) you can use this:
```
n = 10
''.join(["%s" % randint(0, 9) for num in range(0, n)])
``` |
Enforce unique upload file names using django? | 2,673,647 | 33 | 2010-04-20T08:30:56Z | 2,677,474 | 90 | 2010-04-20T18:00:37Z | [
"python",
"django",
"pinax",
"file-rename"
] | What's the best way to rename photos with a unique filename on the server as they are uploaded, using django? I want to make sure each name is used only once. Are there any pinax apps that can do this, perhaps with GUID? | Use uuid. To tie that into your model see [Django documentation](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload_to) for FileField upload\_to.
For example in your models.py define the following function:
```
import uuid
import os
def get_file_path(instance, filename):
ex... |
inheritance from str or int | 2,673,651 | 29 | 2010-04-20T08:31:59Z | 2,673,863 | 39 | 2010-04-20T09:11:14Z | [
"python",
"string",
"inheritance",
"int",
"new-operator"
] | Why I have problem creating a class inheriting from str (or also from int)
```
class C(str):
def __init__(self, a, b):
str.__init__(self,a)
self.b = b
C("a", "B")
TypeError: str() takes at most 1 argument (2 given)
```
tha same happens if I try to use `int` instead of `str`, but it works with custom cl... | ```
>>> class C(str):
... def __new__(cls, *args, **kw):
... return str.__new__(cls, *args, **kw)
...
>>> c = C("hello world")
>>> type(c)
<class '__main__.C'>
>>> c.__class__.__mro__
(<class '__main__.C'>, <type 'str'>, <type 'basestring'>, <type 'object'>)
```
Since `__init__` is called after the objec... |
inheritance from str or int | 2,673,651 | 29 | 2010-04-20T08:31:59Z | 2,676,367 | 10 | 2010-04-20T15:24:19Z | [
"python",
"string",
"inheritance",
"int",
"new-operator"
] | Why I have problem creating a class inheriting from str (or also from int)
```
class C(str):
def __init__(self, a, b):
str.__init__(self,a)
self.b = b
C("a", "B")
TypeError: str() takes at most 1 argument (2 given)
```
tha same happens if I try to use `int` instead of `str`, but it works with custom cl... | Inheriting built-in types is very seldom worth while. You have to deal with several issues and you don't really get much benefit.
It is almost always better to use composition. Instead of inheriting `str`, you would keep a `str` object as an attribute.
```
class EnhancedString(object):
def __init__(self, *args, ... |
How to handle the pylint message: Warning: Method could be a function | 2,674,035 | 36 | 2010-04-20T09:46:19Z | 2,674,052 | 42 | 2010-04-20T09:49:52Z | [
"python",
"oop",
"pylint"
] | I have a python class and ran pylint against it. One message it gave was:
```
Warning: Method could be a function
```
Is this telling me that it would be better to move this method out of the class because it doesn't use any instance variables?
In C# I would make this a static method. What's the most pythonic thing ... | Moving it to a function is common, if it doesn't touch the class at all.
If it manipulates class attributes, use the `classmethod` decorator:
```
@classmethod
def spam(cls, ...):
# cls is the class, you can use it to get class attributes
```
`classmethod` and `staticmethod` (which is the same as the former, excep... |
Several numpy arrays with SWIG | 2,674,046 | 4 | 2010-04-20T09:48:46Z | 2,678,816 | 8 | 2010-04-20T21:32:17Z | [
"c++",
"python",
"numpy",
"swig"
] | I am using SWIG to pass numpy arrays from Python to C++ code:
```
%include "numpy.i"
%init %{
import_array();
%}
%apply (float* INPLACE_ARRAY1, int DIM1) {(float* data, int n)};
class Class
{
public:
void test(float* data, int n)
{
//...
}
};
```
and in Python:
```
c = Class()
a = zeros(5)
c.test(a)
... | I found out the answer from a collegue of mine:
```
%apply (float* INPLACE_ARRAY1, int DIM1) {(float* data1, int n1), (float* data2, int n2)};
class Class
{
public:
void test(float* data1, int n1, float* data2, int n2)
{
//...
}
};
```
Now two numpy arrays are passed to Class::test. |
Objects array with numpy | 2,674,139 | 5 | 2010-04-20T10:05:10Z | 2,675,859 | 9 | 2010-04-20T14:20:47Z | [
"python",
"arrays",
"numpy"
] | are there any way to create an object form any class inside a numpy array?. Something like:
```
a = zeros(4)
for i in range(4):
a[i]=Register()
```
Thanks | Yes, you can do this:
```
a = numpy.array([Register() for _ in range(4)])
```
Here, `a.dtype` is `dtype('object')`.
Alternatively, if you really need to reserve memory for your array and then build it element by element, you can do:
```
a = numpy.empty(shape=(4,), dtype=object)
a[0] = Register() # etc.
``` |
Python - Locating the position of a regex match in a string? | 2,674,391 | 13 | 2010-04-20T10:49:00Z | 2,674,405 | 24 | 2010-04-20T10:50:54Z | [
"python",
"regex"
] | I'm currently using regular expressions to search through RSS feeds to find if certain words and phrases are mentioned, and would then like to extract the text on either side of the match as well. For example:
```
String = "This is an example sentence, it is for demonstration only"
re.search("is", String)
```
I'd lik... | You could use `.find("is")`, it would return position of "is" in the string
or use .start() from re
```
>>> re.search("is", String).start()
2
```
Actually its match "is" from "Th**is**"
If you need to match per word, you should use `\b` before and after "is", `\b` is the word boundary.
```
>>> re.search(r"\bis\b",... |
Python - Locating the position of a regex match in a string? | 2,674,391 | 13 | 2010-04-20T10:49:00Z | 2,674,416 | 9 | 2010-04-20T10:52:59Z | [
"python",
"regex"
] | I'm currently using regular expressions to search through RSS feeds to find if certain words and phrases are mentioned, and would then like to extract the text on either side of the match as well. For example:
```
String = "This is an example sentence, it is for demonstration only"
re.search("is", String)
```
I'd lik... | [`re.Match` objects have a number of methods](http://docs.python.org/library/re.html#match-objects) to help you with this:
```
>>> m = re.search("is", String)
>>> m.span()
(2, 4)
>>> m.start()
2
>>> m.end()
4
``` |
Python - Locating the position of a regex match in a string? | 2,674,391 | 13 | 2010-04-20T10:49:00Z | 16,360,404 | 11 | 2013-05-03T13:44:14Z | [
"python",
"regex"
] | I'm currently using regular expressions to search through RSS feeds to find if certain words and phrases are mentioned, and would then like to extract the text on either side of the match as well. For example:
```
String = "This is an example sentence, it is for demonstration only"
re.search("is", String)
```
I'd lik... | I don't think this question has been completely answered yet because all of the answers only give single match examples. The OP's question demonstrates the nuances of having 2 matches as well as a substring match which should not be reported because it is not a word/token.
To match multiple occurrences, one might do s... |
Django view security and best-practices | 2,674,479 | 5 | 2010-04-20T11:03:02Z | 2,674,820 | 11 | 2010-04-20T11:57:33Z | [
"python",
"django",
"security",
"django-views"
] | I've recently begun working on Django and now my app is nearing completion and i've begun to wonder about security and best-practices.
I have view that generates a page and different functions in the page post AJAX requests to individual views. For example, I have a view called show\_employees and I can delete and upd... | Well, instead of only using @login\_required, I suggest you take a look at the [permissions framework](http://docs.djangoproject.com/en/dev/topics/auth/#id1) and the associated [permission required decorator](http://docs.djangoproject.com/en/dev/topics/auth/#the-permission-required-decorator). This way you can fine tun... |
Django CMS malfunction: Site matching query does not exist | 2,674,615 | 17 | 2010-04-20T11:27:27Z | 2,674,688 | 14 | 2010-04-20T11:38:46Z | [
"python",
"django"
] | I've installed all apps in a project, then added a site in the sites section, and deleted example.com. Now Pages section in Django CMS 2.0 isn't working: it raises a DoesNotExist exception: `Site matching query does not exist.` at <http://127.0.0.1:8000/admin/cms/page/>
The section worked normally before I deleted the... | From <http://docs.djangoproject.com/en/dev/ref/contrib/sites/#ref-contrib-sites>
The SITE\_ID setting specifies the database ID of the Site object associated with that particular settings file.
So, check the django\_site table and make sure you are using the correct SITE\_ID for your site. |
Twisted: how-to bind a server to a specified IP address? | 2,674,799 | 10 | 2010-04-20T11:53:40Z | 2,674,872 | 13 | 2010-04-20T12:05:11Z | [
"python",
"twisted"
] | I want to have a twisted service (started via twistd) which listens to TCP/POST request on a specified port on a specified IP address. By now I have a twisted application which listens to port 8040 on localhost. It is running fine, but I want it to only listen to a certain IP address, say 10.0.0.78.
How-to manage that... | What you're looking for is the `interface` argument to `twisted.application.internet.TCPServer`:
```
smsInboundServer = internet.TCPServer(8001, webserver.Site(smsInbound),
interface='10.0.0.78')
```
(Which it inherits from `reactor.listenTCP()`, since all the `t.a.i.*Server` classes really just forward to `react... |
List attributes of an object | 2,675,028 | 69 | 2010-04-20T12:28:35Z | 2,675,148 | 91 | 2010-04-20T12:44:42Z | [
"python",
"class",
"python-3.x"
] | Is there a way to grab a list of attributes that exist on instances of a class? (This class is just an bland example, it is not my task at hand.)
```
class new_class():
def __init__(self, number):
self.multi = int(number) * 2
self.str = str(number)
a = new_class(2)
print(', '.join(a.SOMETHING))
``... | ```
>>> class new_class():
... def __init__(self, number):
... self.multi = int(number) * 2
... self.str = str(number)
...
>>> a = new_class(2)
>>> a.__dict__
{'multi': 4, 'str': '2'}
>>> a.__dict__.keys()
dict_keys(['multi', 'str'])
```
You may also find [pprint](http://docs.python.org/py3k/library/pprint.... |
List attributes of an object | 2,675,028 | 69 | 2010-04-20T12:28:35Z | 2,675,542 | 45 | 2010-04-20T13:43:30Z | [
"python",
"class",
"python-3.x"
] | Is there a way to grab a list of attributes that exist on instances of a class? (This class is just an bland example, it is not my task at hand.)
```
class new_class():
def __init__(self, number):
self.multi = int(number) * 2
self.str = str(number)
a = new_class(2)
print(', '.join(a.SOMETHING))
``... | ```
dir(instance)
# or
instance.__dict__
```
Then you can test what type is with type() or if is a method with callable(). |
List attributes of an object | 2,675,028 | 69 | 2010-04-20T12:28:35Z | 31,967,014 | 15 | 2015-08-12T13:43:16Z | [
"python",
"class",
"python-3.x"
] | Is there a way to grab a list of attributes that exist on instances of a class? (This class is just an bland example, it is not my task at hand.)
```
class new_class():
def __init__(self, number):
self.multi = int(number) * 2
self.str = str(number)
a = new_class(2)
print(', '.join(a.SOMETHING))
``... | `vars(obj)` returns the attributes of an object. |
What is Ruby's analog to Python Metaclasses? | 2,676,007 | 9 | 2010-04-20T14:39:53Z | 2,678,233 | 23 | 2010-04-20T20:02:48Z | [
"python",
"ruby",
"metaprogramming",
"metaclass"
] | Python has the idea of metaclasses that, if I understand correctly, allow you to modify an object of a class at the moment of construction. You are not modifying the class, but instead the object that is to be created then initialized.
Python (at least as of 3.0 I believe) also has the idea of class decorators. Again ... | Ruby doesn't have metaclasses. There are some constructs in Ruby which some people sometimes wrongly call metaclasses but they aren't (which is a source of *endless* confusion).
However, there's a lot of ways to achieve the same results in Ruby that you would do with metaclasses. But without telling us what exactly yo... |
What is Ruby's analog to Python Metaclasses? | 2,676,007 | 9 | 2010-04-20T14:39:53Z | 2,679,158 | 12 | 2010-04-20T22:29:16Z | [
"python",
"ruby",
"metaprogramming",
"metaclass"
] | Python has the idea of metaclasses that, if I understand correctly, allow you to modify an object of a class at the moment of construction. You are not modifying the class, but instead the object that is to be created then initialized.
Python (at least as of 3.0 I believe) also has the idea of class decorators. Again ... | Your updated question looks quite different now. If I understand you correctly, you want to hook into object allocation and initialization, which has absolutely nothing whatsoever to do with metaclasses. (But you *still* don't write what it is that you actually want to do, so I might still be off.)
In some object-orie... |
Best way to do enum in Sqlalchemy? | 2,676,133 | 20 | 2010-04-20T14:54:42Z | 2,676,213 | 15 | 2010-04-20T15:07:49Z | [
"python",
"sqlalchemy"
] | im reading sqlalchemy and i see the code
```
employees_table = Table('employees', metadata,
Column('employee_id', Integer, primary_key=True),
Column('name', String(50)),
Column('manager_data', String(50)),
Column('engineer_info', String(50)),
Column('type', String(20), nullable=False)
)
employee_m... | SQLAlchemy has an Enum type since 0.6:
<http://docs.sqlalchemy.org/en/latest/core/type_basics.html?highlight=enum#sqlalchemy.types.Enum>
Although I would only recommend it's usage if your database has a native enum type. Otherwise I would personally just use an int. |
Best way to do enum in Sqlalchemy? | 2,676,133 | 20 | 2010-04-20T14:54:42Z | 6,104,825 | 31 | 2011-05-24T01:23:12Z | [
"python",
"sqlalchemy"
] | im reading sqlalchemy and i see the code
```
employees_table = Table('employees', metadata,
Column('employee_id', Integer, primary_key=True),
Column('name', String(50)),
Column('manager_data', String(50)),
Column('engineer_info', String(50)),
Column('type', String(20), nullable=False)
)
employee_m... | I wrote a post which extends the Enum type into Python-land as well, and is my preferred approach to enumerations: <http://techspot.zzzeek.org/2011/01/14/the-enum-recipe/> |
Best way to do enum in Sqlalchemy? | 2,676,133 | 20 | 2010-04-20T14:54:42Z | 7,927,363 | 9 | 2011-10-28T09:19:41Z | [
"python",
"sqlalchemy"
] | im reading sqlalchemy and i see the code
```
employees_table = Table('employees', metadata,
Column('employee_id', Integer, primary_key=True),
Column('name', String(50)),
Column('manager_data', String(50)),
Column('engineer_info', String(50)),
Column('type', String(20), nullable=False)
)
employee_m... | I like zzzeek's recipe at <http://techspot.zzzeek.org/2011/01/14/the-enum-recipe/>, but I changed two things:
* I'm using the Python name of the EnumSymbol also as the name in the database, instead of using its value. I think that's less confusing. Having a separate value is still useful, e.g. for creating popup menus... |
Best way to do enum in Sqlalchemy? | 2,676,133 | 20 | 2010-04-20T14:54:42Z | 17,297,515 | 10 | 2013-06-25T12:35:42Z | [
"python",
"sqlalchemy"
] | im reading sqlalchemy and i see the code
```
employees_table = Table('employees', metadata,
Column('employee_id', Integer, primary_key=True),
Column('name', String(50)),
Column('manager_data', String(50)),
Column('engineer_info', String(50)),
Column('type', String(20), nullable=False)
)
employee_m... | I'm not really knowledgeable in SQLAlchemy but [this approach by Paulo](http://pau.io/journal/2013-01-01/sqlalchemy-enum-python-namedtuple.html) seemed much simpler to me.
I didn't need user-friendly descriptions, so I went with it.
Quoting Paulo (I hope he doesn't mind my reposting it here):
> Pythonâs `namedtup... |
In which scenario it is useful to use Disassembly on python? | 2,676,154 | 3 | 2010-04-20T14:57:18Z | 2,676,343 | 7 | 2010-04-20T15:21:59Z | [
"python",
"assembly"
] | The dis module can be effectively used to disassemble Python methods, functions and classes into low-level interpreter instructions.
I know that `dis` information can be used for:
1. Find race condition in programs that use threads
2. Find possible optimizations
From your experience, do you know any other scenari... | `dis` is useful, for example, when you have different code doing the same thing and you wonder where the performance difference lies in.
## Example: `list += [item]` vs `list.append(item)`
```
def f(x): return 2*x
def f1(func, nums):
result = []
for item in nums:
result += [fun(item)]
return result
def f2... |
What version of Visual Studio is Python on my computer compiled with? | 2,676,763 | 70 | 2010-04-20T16:17:01Z | 2,676,791 | 12 | 2010-04-20T16:19:40Z | [
"python",
"windows",
"visual-studio",
"visual-c++"
] | I am trying to find out the version of Visual Studio that is used to compile the Python on my computer
It says
```
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32
```
What I do not understand is this `MSC V.1500` designation. Does it mean it is compiled with Visual Studio 2005? ... | `MSC v.1500` appears to be Visual C++ 2008 according to [this thread on the OpenCobol forums](http://www.opencobol.org/modules/newbb/viewtopic.php?topic_id=743&forum=1) (of all places).
The [MSDN page on Predefined Macros](http://msdn.microsoft.com/en-us/library/b0084kay.aspx) indicates 1500 to be the result of the `_... |
What version of Visual Studio is Python on my computer compiled with? | 2,676,763 | 70 | 2010-04-20T16:17:01Z | 2,676,904 | 117 | 2010-04-20T16:34:00Z | [
"python",
"windows",
"visual-studio",
"visual-c++"
] | I am trying to find out the version of Visual Studio that is used to compile the Python on my computer
It says
```
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32
```
What I do not understand is this `MSC V.1500` designation. Does it mean it is compiled with Visual Studio 2005? ... | ```
For this version of Visual C++ Use this compiler version
Visual C++ 4.x MSC_VER=1000
Visual C++ 5 MSC_VER=1100
Visual C++ 6 MSC_VER=1200
Visual C++ .NET MSC_VER=1300
Visual C++ .NET 2003 MSC_VER=1310
Visual C++ 2005 (8.0) M... |
Google App Engine: JSON module | 2,676,767 | 8 | 2010-04-20T16:17:25Z | 2,676,851 | 16 | 2010-04-20T16:27:07Z | [
"python",
"django",
"json",
"google-app-engine"
] | I'm using JSON with [Google App Engine](http://en.wikipedia.org/wiki/Google_App_Engine).
I'm using JSON for comunication, so on the Python side I have:
```
import json
```
The error I'm getting is this:
> <class 'django.core.exceptions.ViewDoesNotExist'>: Could not import views.ganttapp. Error was: No module named ... | Maybe you can import the [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) [simplejson](http://docs.nullpobug.com/django/trunk/django.utils.simplejson-module.html) wrapper:
```
from django.utils import simplejson
``` |
How to parse malformed HTML in python, using standard libraries | 2,676,872 | 27 | 2010-04-20T16:29:21Z | 2,680,724 | 39 | 2010-04-21T06:18:17Z | [
"python",
"html",
"dom",
"parsing",
"html-parsing"
] | There are so many [html and xml libraries built into python](http://docs.python.org/library/markup.html), that it's hard to believe there's no support for real-world HTML parsing.
I've found plenty of great third-party libraries for this task, but this question is about the python standard library.
Requirements:
* U... | Parsing HTML reliably is a relatively modern development (weird though that may seem). As a result there is definitely nothing in the standard library. [HTMLParser](http://docs.python.org/library/htmlparser.html) may *appear* to be a way to handle HTML, but it's not -- it fails on lots of very common HTML, and though y... |
How can I read a function's signature including default argument values? | 2,677,185 | 45 | 2010-04-20T17:17:24Z | 2,677,263 | 72 | 2010-04-20T17:29:04Z | [
"python",
"arguments",
"inspect"
] | Given a function object, how can I get its signature? For example, for:
```
def myMethod(firt, second, third='something'):
pass
```
I would like to get `"myMethod(firt, second, third='something')"`. | ```
import inspect
def foo(a,b,x='blah'):
pass
print(inspect.getargspec(foo))
# ArgSpec(args=['a', 'b', 'x'], varargs=None, keywords=None, defaults=('blah',))
```
However, note that `inspect.getargspec()` is deprecated since Python 3.0.
3.0 - 3.4 recommends `inspect.getfullargspec()`. See: <https://docs.python.... |
How can I read a function's signature including default argument values? | 2,677,185 | 45 | 2010-04-20T17:17:24Z | 11,202,399 | 8 | 2012-06-26T07:15:34Z | [
"python",
"arguments",
"inspect"
] | Given a function object, how can I get its signature? For example, for:
```
def myMethod(firt, second, third='something'):
pass
```
I would like to get `"myMethod(firt, second, third='something')"`. | ```
#! /usr/bin/env python
import inspect
from collections import namedtuple
DefaultArgSpec = namedtuple('DefaultArgSpec', 'has_default default_value')
def _get_default_arg(args, defaults, arg_index):
""" Method that determines if an argument has default value or not,
and if yes what is the default value for... |
How can I read a function's signature including default argument values? | 2,677,185 | 45 | 2010-04-20T17:17:24Z | 25,076,824 | 11 | 2014-08-01T09:17:03Z | [
"python",
"arguments",
"inspect"
] | Given a function object, how can I get its signature? For example, for:
```
def myMethod(firt, second, third='something'):
pass
```
I would like to get `"myMethod(firt, second, third='something')"`. | Arguably the easiest way to find the signature for a function would be `help(function)`:
```
>>> def function(arg1, arg2="foo", *args, **kwargs): pass
>>> help(function)
Help on function function in module __main__:
function(arg1, arg2='foo', *args, **kwargs)
```
Also, in Python 3 a method was added to the `inspect`... |
Reading a client's header from Python CGI script? | 2,677,325 | 11 | 2010-04-20T17:39:24Z | 2,677,423 | 11 | 2010-04-20T17:51:21Z | [
"python",
"cgi",
"http-headers"
] | I'm writing a very simple web service, written in Python and run as CGI on an Apache server.
According to Python docs (somewhere... I forgot where), I can use sys.stdin to read the data POSTed by a random client, and this has been working fine. However, I would like to be able to read the HTTP header information as we... | If you are running as a CGI, you can't read the HTTP header directly, but the web server put much of that information into environment variables for you. You can just pick it out of os.environ[]
The list of environment variables that might be there is pretty long. You can find it by doing a web search for "common gate... |
python variable scope | 2,677,545 | 7 | 2010-04-20T18:11:58Z | 2,677,580 | 9 | 2010-04-20T18:18:59Z | [
"python",
"scope",
"rationale"
] | I'm teaching my self python and I was translating some sample code into this
```
class Student(object):
def __init__( self, name, a,b,c ):
self.name = name
self.a = a
self.b = b
self.c = c
def average(self):
return ( a+b+c ) / 3.0
```
Which is pretty much my intended c... | Barenames (like `a`, `b`, `c`) are always scoped as local or global (save for nested functions, which are nowhere around in your code). The rationale is that adding further scopes would needlessly make things more complicated -- e.g, if in your `self.a = a` the barename `a` could be scoped to mean what you appear to wa... |
Python f.write() at beginning of file? | 2,677,617 | 15 | 2010-04-20T18:25:46Z | 2,677,852 | 9 | 2010-04-20T19:02:16Z | [
"python",
"file-io"
] | I'm doing it like this now, but i want it to write at the beginning of the file instead.
```
f = open('out.txt', 'a') # or 'w'?
f.write("string 1")
f.write("string 2")
f.write("string 3")
f.close()
```
so that the contenst of out.txt will be:
```
string 3
string 2
string 1
```
and not (like this code does):
```
st... | Take a look at [this question](http://stackoverflow.com/questions/125703/how-do-i-modify-a-text-file-in-python). There are some solutions there.
Though I would probably go that same way Daniel and MAK suggest -- maybe make a lil' class to make things a little more flexible and explicit:
```
class Prepender:
def ... |
Canât download youtube video | 2,678,051 | 7 | 2010-04-20T19:34:12Z | 2,679,042 | 15 | 2010-04-20T22:08:39Z | [
"python",
"file",
"python-3.x",
"urllib"
] | Iâm having trouble retrieving the Youtube video automatically. Hereâs the code. The problem is the last part. `download = urllib.request.urlopen(download_url).read()`
```
# Youtube video download script
# 10n1z3d[at]w[dot]cn
import urllib.request
import sys
print("\n--------------------------... | The code on the original question relies on several assumptions about the content of youtube pages and urls (expressed in constructs such as "url.split('something=')[1]") which may not always be true. I tested it and it might depend even on which related videos show on the page. You might have tripped on any of those s... |
How does Dropbox use Python on Windows and OS X? | 2,678,180 | 37 | 2010-04-20T19:53:53Z | 2,679,695 | 35 | 2010-04-21T01:08:32Z | [
"python",
"windows",
"osx",
"dropbox"
] | In Windows the Dropbox client uses python25.dll and the MS C runtime libraries (msvcp71.dll, etc). On OS X the Python code is compiled bytecode (pyc).
My guess is they are using a common library they have written then just have to use different hooks for the different platforms.
What method of development is this? It... | Dropbox uses a combination of wxPython and PyObjC on the Mac (less wxPython in the 0.8 series). It looks like they've built a bit of a UI abstraction layer but nothing overwhelmingâi.e., they're doing their cross-platform app the right way.
They include their own Python mainly because the versions of Python included... |
How does Dropbox use Python on Windows and OS X? | 2,678,180 | 37 | 2010-04-20T19:53:53Z | 6,492,960 | 18 | 2011-06-27T12:39:06Z | [
"python",
"windows",
"osx",
"dropbox"
] | In Windows the Dropbox client uses python25.dll and the MS C runtime libraries (msvcp71.dll, etc). On OS X the Python code is compiled bytecode (pyc).
My guess is they are using a common library they have written then just have to use different hooks for the different platforms.
What method of development is this? It... | For **WINDOWS**, Dropbox have employed a module similar to **py2exe** to package all their .py scripts, required libraries, resources etc into the distribution that you have mentioned above (`.exe`, `library.zip`, `MS C runtime library` and `python25.dll`) so that they can be run **without requiring Python installation... |
How do I construct a slightly more complex filter using or_ or and_ in sqlalchemy | 2,678,600 | 16 | 2010-04-20T21:02:14Z | 2,679,134 | 10 | 2010-04-20T22:25:03Z | [
"python",
"filter",
"sqlalchemy"
] | I'm trying to do a very simple search from a list of terms
```
terms = ['term1', 'term2', 'term3']
```
How do I programmatically go through the list of terms and construct the "conditions" from the list of terms so that I can make the query using filter and or\_ or \_and?
```
e.g. query.filter(or_(#something constru... | Assuming that your `terms` variable contains valid SQL statement fragments, you can simply pass `terms` preceded by an asterisk to `or_` or `and_`:
```
>>> from sqlalchemy.sql import and_, or_
>>> terms = ["name='spam'", "email='spam@eggs.com'"]
>>> print or_(*terms)
name='spam' OR email='spam@eggs.com'
>>> print and_... |
How do I construct a slightly more complex filter using or_ or and_ in sqlalchemy | 2,678,600 | 16 | 2010-04-20T21:02:14Z | 2,682,019 | 20 | 2010-04-21T10:21:46Z | [
"python",
"filter",
"sqlalchemy"
] | I'm trying to do a very simple search from a list of terms
```
terms = ['term1', 'term2', 'term3']
```
How do I programmatically go through the list of terms and construct the "conditions" from the list of terms so that I can make the query using filter and or\_ or \_and?
```
e.g. query.filter(or_(#something constru... | If you have a list of terms and want to find rows where a field matches one of them, then you could use the in\_() method:
```
terms = ['term1', 'term2', 'term3']
query.filter(Cls.field.in_(terms))
```
If you want to do something more complex, then `or_()` and `and_()` take `ClauseElement` objects as parameters. Clau... |
How do I construct a slightly more complex filter using or_ or and_ in sqlalchemy | 2,678,600 | 16 | 2010-04-20T21:02:14Z | 2,683,552 | 8 | 2010-04-21T14:01:41Z | [
"python",
"filter",
"sqlalchemy"
] | I'm trying to do a very simple search from a list of terms
```
terms = ['term1', 'term2', 'term3']
```
How do I programmatically go through the list of terms and construct the "conditions" from the list of terms so that I can make the query using filter and or\_ or \_and?
```
e.g. query.filter(or_(#something constru... | well I had quite the same issue here:
<http://stackoverflow.com/questions/2640628/sqlalchemy-an-efficient-better-select-by-primary-keys>
```
terms = ['one', 'two', 'three']
clauses = or_( * [Table.field == x for x in terms] )
query = Session.query(Table).filter(clauses)
```
Do you like this? |
Install Python 2.6 without using installer on Win32 | 2,678,702 | 16 | 2010-04-20T21:16:34Z | 2,678,726 | 25 | 2010-04-20T21:20:02Z | [
"python",
"installation",
"install"
] | I need to run a Python script on a machine that doesn't have Python installed. I use Python as a part of a software package, and Python runs behind the curtain without the user's notice of it.
What I did was as follows.
1. Copy python.exe, python26.dll, msvcr90.dll and Microsoft.VC90.CRT.manifest
2. Zip all the direc... | I have been using [PortablePython](http://www.portablepython.com/) for a year now, and I find it great as it is working on my locked-down work-notebook.
There is a Python 2.5.4, 2.6.1 and a 3.0.1 version. |
Install Python 2.6 without using installer on Win32 | 2,678,702 | 16 | 2010-04-20T21:16:34Z | 2,684,631 | 10 | 2010-04-21T16:11:55Z | [
"python",
"installation",
"install"
] | I need to run a Python script on a machine that doesn't have Python installed. I use Python as a part of a software package, and Python runs behind the curtain without the user's notice of it.
What I did was as follows.
1. Copy python.exe, python26.dll, msvcr90.dll and Microsoft.VC90.CRT.manifest
2. Zip all the direc... | I looked into the Python interpreter source code, and I did some experiments. And I found that the Python interpreter prepend the "THE DIRECTORY OF PYTHONXXX.DLL + pythonXXX.zip" no matter what. XXX is the version of the Python interpreter.
As a result, if there is a python26.zip in the same directory as the python26.... |
Python 3 Template Engine | 2,678,710 | 4 | 2010-04-20T21:17:24Z | 2,678,743 | 7 | 2010-04-20T21:22:16Z | [
"python",
"templates",
"python-3.x",
"template-engine"
] | Is there a template engine for Python 3? It should be flexible (not HTML/XML centric) and fast. | There is [Jinja](http://pypi.python.org/pypi/Jinja2/) |
Can I debug with python debugger when using py.test somehow? | 2,678,792 | 24 | 2010-04-20T21:28:14Z | 3,254,078 | 38 | 2010-07-15T09:09:50Z | [
"python",
"unit-testing",
"pdb"
] | I am using py.test for unit testing my python program. I wish to debug my test code with the python debugger the normal way (by which i mean pdb.set\_trace() in the code) but I can't make it work.
Putting pdb.set\_trace() in the code doesn't work (raises IOError: reading from stdin while output is captured). I have al... | it's real simple: put an `assert 0` where you want to start debugging in your code and run your tests with:
```
py.test --pdb
```
done :)
Alternatively, if you are using pytest-2.0.1 or above, there also is the `pytest.set_trace()` helper which you can put anywhere in your test code. Here are the [docs](http://pytes... |
Can I debug with python debugger when using py.test somehow? | 2,678,792 | 24 | 2010-04-20T21:28:14Z | 3,418,597 | 15 | 2010-08-05T19:49:50Z | [
"python",
"unit-testing",
"pdb"
] | I am using py.test for unit testing my python program. I wish to debug my test code with the python debugger the normal way (by which i mean pdb.set\_trace() in the code) but I can't make it work.
Putting pdb.set\_trace() in the code doesn't work (raises IOError: reading from stdin while output is captured). I have al... | I found that I can run py.test with capture disabled, then use pdb.set\_trace() as usual.
```
> py.test --capture=no
============================= test session starts ==============================
platform linux2 -- Python 2.5.2 -- pytest-1.3.3
test path 1: project/lib/test/test_facet.py
project/lib/test/test_facet.... |
Can I debug with python debugger when using py.test somehow? | 2,678,792 | 24 | 2010-04-20T21:28:14Z | 17,582,472 | 7 | 2013-07-10T23:08:49Z | [
"python",
"unit-testing",
"pdb"
] | I am using py.test for unit testing my python program. I wish to debug my test code with the python debugger the normal way (by which i mean pdb.set\_trace() in the code) but I can't make it work.
Putting pdb.set\_trace() in the code doesn't work (raises IOError: reading from stdin while output is captured). I have al... | The easiest way is using the py.test mechanism to create breakpoint
<http://pytest.org/latest/usage.html#setting-a-breakpoint-aka-set-trace>
```
import pytest
def test_function():
...
pytest.set_trace() # invoke PDB debugger and tracing
```
Or if you want `pytest`'s debugger as a one-liner, change your `i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.