content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Searching and capturing a character using regular expressions Python
While going through one of the problems in Python Challenge, I am trying to solve it as follows:
Read the input in a text file with characters as follows:
DQheAbsaMLjTmAOKmNsLziVMenFxQdATQIjItwtyCHyeMwQTNxbbLXWZnGmDqHhXnLHfEyvzxMhSXzd
BEBaxeaPgQPttvqRvxHPEOUtIsttPDeeuGFgmDkKQcEYjuSuiGROGfYpzkQgvcCDBKrcYwHFlvPzDMEk
MyuPxvGtgSvWgrybKOnbEGhqHUXHhnyjFwSfTfaiWtAOMBZEScsOSumwPssjCPlLbLsPIGffDLpZzMKz
jarrjufhgxdrzywWosrblPRasvRUpZLaUbtDHGZQtvZOvHeVSTBHpitDllUljVvWrwvhpnVzeWVYhMPs
kMVcdeHzFZxTWocGvaKhhcnozRSbWsIEhpeNfJaRjLwWCvKfTLhuVsJczIYFPCyrOJxOPkXhVuCqCUgE
luwLBCmqPwDvUPuBRrJZhfEXHXSBvljqJVVfEGRUWRSHPeKUJCpMpIsrV.......
What I need is to go through this text file and pick all lower case letters that are enclosed by only three upper-case letters on each side.
The python script that I wrote to do the above is as follows:
import re
pattern = re.compile("[a-z][A-Z]{3}([a-z])[A-Z]{3}[a-z]")
f = open('/Users/Dev/Sometext.txt','r')
for line in f:
result = pattern.search(line)
if result:
print result.groups()
f.close()
The above given script, instead of returning the capture(list of lower case characters), returns all the text blocks that meets the regular expression criteria, like
aXCSdFGHj
vCDFeTYHa
nHJUiKJHo
.........
.........
Can somebody tell me what exactly I am doing wrong here? And instead of looping through the entire file, is there an alternate way to run the regular expression search on the entire file?
Thanks
A:
I'd suggest using lookaround:
(?<=[A-Z]{3})(?<![A-Z].{3})([a-z])(?=[A-Z]{3})(?!.{3}[A-Z])
This will have no problem with overlapping matches.
Explanation:
(?<=[A-Z]{3}) # assert that there are 3 uppercase letters before the current position
(?<![A-Z].{3}) # assert that there is no uppercase letter 4 characters before the current position
([a-z]) # match a lowercase character (all characters in the example are ASCII)
(?=[A-Z]{3}) # assert that there are 3 uppercase letter after the current position
(?!.{3}[A-Z]) # assert that there is no uppercase letter 4 characters after the current position
A:
Change result.groups() to result.group(1) and you will get just the single letter match.
A second problem with your code is that it will not find multiple results on one line. So instead of using re.search you'll need re.findall or re.finditer. findall will return strings or tuples of strings, whereas finditer returns match objects.
Here's where I approached the same problem:
import urllib
import re
pat = re.compile('[a-z][A-Z]{3}([a-z])[A-Z]{3}[a-z]')
print ''.join(pat.findall(urllib.urlopen(
"http://www.pythonchallenge.com/pc/def/equality.html").read()))
Note that re.findall and re.finditer return non-overlapping results. So when using the above pattern with re.findall searching against string 'aBBBcDDDeFFFg', your only match will be 'c', but not 'e'. Fortunately, this Python Challenge problem contains no such such examples.
A:
import re
with open('/Users/Dev/Sometext.txt','r') as f:
tokens = re.findall(r'[a-z][A-Z]{3}([a-z])[A-Z]{3}[a-z]', f.read())
for token ins tokens:
print token
What findall does:
Return all non-overlapping matches of
pattern in string, as a list of
strings. The string is scanned
left-to-right, and matches are
returned in the order found. If one or
more groups are present in the
pattern, return a list of groups; this
will be a list of tuples if the
pattern has more than one group. Empty
matches are included in the result
unless they touch the beginning of
another match.
Maybe the most useful function in the re module.
The read() function reads the whole file into on big string. This is especially useful if you need to match a regular expression against the whole file.
Warning: Depending on the size of the file, you may prefer iterating over the file line by line as you did in your first approach.
| Searching and capturing a character using regular expressions Python | While going through one of the problems in Python Challenge, I am trying to solve it as follows:
Read the input in a text file with characters as follows:
DQheAbsaMLjTmAOKmNsLziVMenFxQdATQIjItwtyCHyeMwQTNxbbLXWZnGmDqHhXnLHfEyvzxMhSXzd
BEBaxeaPgQPttvqRvxHPEOUtIsttPDeeuGFgmDkKQcEYjuSuiGROGfYpzkQgvcCDBKrcYwHFlvPzDMEk
MyuPxvGtgSvWgrybKOnbEGhqHUXHhnyjFwSfTfaiWtAOMBZEScsOSumwPssjCPlLbLsPIGffDLpZzMKz
jarrjufhgxdrzywWosrblPRasvRUpZLaUbtDHGZQtvZOvHeVSTBHpitDllUljVvWrwvhpnVzeWVYhMPs
kMVcdeHzFZxTWocGvaKhhcnozRSbWsIEhpeNfJaRjLwWCvKfTLhuVsJczIYFPCyrOJxOPkXhVuCqCUgE
luwLBCmqPwDvUPuBRrJZhfEXHXSBvljqJVVfEGRUWRSHPeKUJCpMpIsrV.......
What I need is to go through this text file and pick all lower case letters that are enclosed by only three upper-case letters on each side.
The python script that I wrote to do the above is as follows:
import re
pattern = re.compile("[a-z][A-Z]{3}([a-z])[A-Z]{3}[a-z]")
f = open('/Users/Dev/Sometext.txt','r')
for line in f:
result = pattern.search(line)
if result:
print result.groups()
f.close()
The above given script, instead of returning the capture(list of lower case characters), returns all the text blocks that meets the regular expression criteria, like
aXCSdFGHj
vCDFeTYHa
nHJUiKJHo
.........
.........
Can somebody tell me what exactly I am doing wrong here? And instead of looping through the entire file, is there an alternate way to run the regular expression search on the entire file?
Thanks
| [
"I'd suggest using lookaround:\n(?<=[A-Z]{3})(?<![A-Z].{3})([a-z])(?=[A-Z]{3})(?!.{3}[A-Z])\n\nThis will have no problem with overlapping matches.\nExplanation:\n(?<=[A-Z]{3}) # assert that there are 3 uppercase letters before the current position\n(?<![A-Z].{3}) # assert that there is no uppercase letter 4 charac... | [
2,
2,
1
] | [] | [] | [
"python",
"regex",
"search",
"text_files"
] | stackoverflow_0004186249_python_regex_search_text_files.txt |
Q:
Invoke python callable with an arg list
Simple question: How can I pass an arbitrary list of args to a python callable?
Let's say I want to invoke a function from the command line, like so:
my_script.py foo hello world
with the following script:
import myfuncs
f = getattr(myfuncs, sys.args[1])
if f and callable(f):
# This is the bit I don't know. I effectively want f(sys.args[2:])
I'm sure there's a way to do this, but I must be overlooking it.
A:
You are looking for sequence unpacking. I.e. f(*sys.argv[2:])
A:
Yep, check out the section Unpacking argument lists in the docs.
For your particular use, it could be something like this
def f(a, b, c):
print a, b, c
stuff = ['f',2,3,4]
f(*stuff[1:]) ### equivalent to f(2,3,4)
| Invoke python callable with an arg list | Simple question: How can I pass an arbitrary list of args to a python callable?
Let's say I want to invoke a function from the command line, like so:
my_script.py foo hello world
with the following script:
import myfuncs
f = getattr(myfuncs, sys.args[1])
if f and callable(f):
# This is the bit I don't know. I effectively want f(sys.args[2:])
I'm sure there's a way to do this, but I must be overlooking it.
| [
"You are looking for sequence unpacking. I.e. f(*sys.argv[2:])\n",
"Yep, check out the section Unpacking argument lists in the docs.\nFor your particular use, it could be something like this\ndef f(a, b, c): \n print a, b, c\n\nstuff = ['f',2,3,4]\n\nf(*stuff[1:]) ### equivalent to f(2,3,4)\n\n"
] | [
7,
4
] | [] | [] | [
"callable",
"python"
] | stackoverflow_0004186679_callable_python.txt |
Q:
How to display database query results of 100,000 rows or more with HTML?
We're rewriting a website used by one of our clients. The user traffic on it is very low, less than 100 unique visitors a week. It's basically just a nice interface to their data in our databases. It allows them to query and filter on different sets of data of theirs.
We're rewriting the site in Python, re-using the same Oracle database that the data is currently on. The current version is written in an old, old version of Coldfusion. One of the things that Coldfusion does well though is displays tons of database records on a single page. It's capable of displaying hundreds of thousands of rows at once without crashing the browser. It uses a Java applet, and it looks like the contents of the rows are perhaps compressed and passed in through the HTML or something. There is a large block of data in the HTML but it's not displayed - it's just rendered by the Java applet.
I've tried several JavaScript solutions but they all hinge on the fact that the data will be present in an HTML table or something along those lines. This causes browsers to freeze and run out of memory.
Does anyone know of any solutions to this situation? Our client loves the ability to scroll through all of this data without clicking a "next page" link.
A:
I have done just what you are describing using the following (which works very well):
jQuery Datatables
It enables you to do 'fetch as you scroll' pagination, so you can disable the pagination arrows in favor of a 'forever' scroll.
A:
Give a try with Jquery scroll.
Instead of image scroll , you need to have data scroll.
You should poulate data in the divs , instead of images.
http://www.smoothdivscroll.com/#quickdemo
It should work. I wish.
You gotta great client anyway :-)
Something related to your Q
http://www.9lessons.info/2009/07/load-data-while-scroll-with-jquery-php.html
http://api.jquery.com/scroll/
A:
I'm using Open Rico's LiveGrid in a project to display a table with thousands of rows in a page as an endless scrolling table. It has been working really fine so far. The table requests data on demand when you scroll through the rows. The parameters are send as simple GET parameters and the response you have to create on the serverside is simple XML. It should be possible to implement a data backend for a Rico LiveGrid in Python.
A:
Most people, in this case, would use a framework. The best documented and most popular framework in Python is Django. It has good database support (including Oracle), and you'll have the easiest time getting help using it since there's such an active Django community.
You can try some other frameworks, but if you're tied to Python I'd recommend Django.
Of course, Jython (if it's an option), would make your job very easy. You could take the existing Java framework you have and just use Jython to build a frontend (and continue to use your Java applet and Java classes and Java server).
The memory problem is an interesting one; I'd be curious to see what you come up with.
A:
Have you tried jqGrid? It can be buggy at times, but overall it's one of the better JavaScript grids. It's fairly efficient in dealing with large datasets. It also has a feature whereby the grid retrieves data asynchronously in chunks, but still allows continuous scrolling. It just asks for more data as the user scrolls down to it.
A:
I did something like this a while ago and successfully implemented YUI's data table combined with Django
http://developer.yahoo.com/yui/datatable/
This gives you column sorting, pagination, scrolling and so on. It also allows you to use a variety of data sources such as JSON or XML.
| How to display database query results of 100,000 rows or more with HTML? | We're rewriting a website used by one of our clients. The user traffic on it is very low, less than 100 unique visitors a week. It's basically just a nice interface to their data in our databases. It allows them to query and filter on different sets of data of theirs.
We're rewriting the site in Python, re-using the same Oracle database that the data is currently on. The current version is written in an old, old version of Coldfusion. One of the things that Coldfusion does well though is displays tons of database records on a single page. It's capable of displaying hundreds of thousands of rows at once without crashing the browser. It uses a Java applet, and it looks like the contents of the rows are perhaps compressed and passed in through the HTML or something. There is a large block of data in the HTML but it's not displayed - it's just rendered by the Java applet.
I've tried several JavaScript solutions but they all hinge on the fact that the data will be present in an HTML table or something along those lines. This causes browsers to freeze and run out of memory.
Does anyone know of any solutions to this situation? Our client loves the ability to scroll through all of this data without clicking a "next page" link.
| [
"I have done just what you are describing using the following (which works very well):\njQuery Datatables\nIt enables you to do 'fetch as you scroll' pagination, so you can disable the pagination arrows in favor of a 'forever' scroll.\n",
"Give a try with Jquery scroll.\nInstead of image scroll , you need to have... | [
8,
3,
2,
1,
1,
1
] | [] | [] | [
"coldfusion",
"html",
"oracle",
"python"
] | stackoverflow_0004186384_coldfusion_html_oracle_python.txt |
Q:
Django running wrong version
Although running "python" from the shell runs Python v2.7, Django is loading files for python2.4, as shown in the error when I load a django site:
Mod_python error: "PythonHandler django.core.handlers.modpython"
Traceback (most recent call last):
File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 287, in HandlerDispatch
log=debug)
File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 461, in import_module
f, p, d = imp.find_module(parts[i], path)
ImportError: No module named django
I think Django is installed for version 2.7 and that's why the bottom says "No module named django"
This is my first django install (it's on a mediatemple DV server) so I wouldn't be surprised if I'm doing something stupid. Thanks!
A:
mod_python is built for 2.4, but Django is installed for 2.7. Either build mod_python for 2.7, install Django under 2.4, or put a local copy of Django with your project so that the version of Python doesn't matter.
| Django running wrong version | Although running "python" from the shell runs Python v2.7, Django is loading files for python2.4, as shown in the error when I load a django site:
Mod_python error: "PythonHandler django.core.handlers.modpython"
Traceback (most recent call last):
File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 287, in HandlerDispatch
log=debug)
File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 461, in import_module
f, p, d = imp.find_module(parts[i], path)
ImportError: No module named django
I think Django is installed for version 2.7 and that's why the bottom says "No module named django"
This is my first django install (it's on a mediatemple DV server) so I wouldn't be surprised if I'm doing something stupid. Thanks!
| [
"mod_python is built for 2.4, but Django is installed for 2.7. Either build mod_python for 2.7, install Django under 2.4, or put a local copy of Django with your project so that the version of Python doesn't matter.\n"
] | [
2
] | [] | [] | [
"django",
"mediatemple",
"python"
] | stackoverflow_0004186099_django_mediatemple_python.txt |
Q:
Problems with variable referenced before assignment when using os.path.walk
OK. I have some background in Matlab and I'm now switching to Python.
I have this bit of code under Pythnon 2.6.5 on 64-bit Linux which scrolls through directories, finds files named 'GeneralData.dat', retrieves some data from them and stitches them into a new data set:
import pylab as p
import os, re
import linecache as ln
def LoadGenomeMeanSize(arg, dirname, files):
for file in files:
filepath = os.path.join(dirname, file)
if filepath == os.path.join(dirname,'GeneralData.dat'):
data = p.genfromtxt(filepath)
if data[-1,4] != 0.0: # checking if data set is OK
data_chopped = data[1000:-1,:] # removing some of data
Grand_mean = data_chopped[:,2].mean()
Grand_STD = p.sqrt((sum(data_chopped[:,4]*data_chopped[:,3]**2) + sum((data_chopped[:,2]-Grand_mean)**2))/sum(data_chopped[:,4]))
else:
break
if filepath == os.path.join(dirname,'ModelParams.dat'):
l = re.split(" ", ln.getline(filepath, 6))
turb_param = float(l[2])
arg.append((Grand_mean, Grand_STD, turb_param))
GrandMeansData = []
os.path.walk(os.getcwd(), LoadGenomeMeanSize, GrandMeansData)
GrandMeansData = sorted(GrandMeansData, key=lambda data_sort: data_sort[2])
TheMeans = p.zeros((len(GrandMeansData), 3 ))
i = 0
for item in GrandMeansData:
TheMeans[i,0] = item[0]
TheMeans[i,1] = item[1]
TheMeans[i,2] = item[2]
i += 1
print TheMeans # just checking...
# later do some computation on TheMeans in NumPy
And it throws me this (though I would swear it was working a month ego):
Traceback (most recent call last):
File "/home/User/01_PyScripts/TESTtest.py", line 29, in <module>
os.path.walk(os.getcwd(), LoadGenomeMeanSize, GrandMeansData)
File "/usr/lib/python2.6/posixpath.py", line 233, in walk
walk(name, func, arg)
File "/usr/lib/python2.6/posixpath.py", line 225, in walk
func(arg, top, names)
File "/home/User/01_PyScripts/TESTtest.py", line 26, in LoadGenomeMeanSize
arg.append((Grand_mean, Grand_STD, turb_param))
UnboundLocalError: local variable 'Grand_mean' referenced before assignment
All right... so I went and did some reading and came up with this global variable:
import pylab as p
import os, re
import linecache as ln
Grand_mean = p.nan
Grand_STD = p.nan
def LoadGenomeMeanSize(arg, dirname, files):
for file in files:
global Grand_mean
global Grand_STD
filepath = os.path.join(dirname, file)
if filepath == os.path.join(dirname,'GeneralData.dat'):
data = p.genfromtxt(filepath)
if data[-1,4] != 0.0: # checking if data set is OK
data_chopped = data[1000:-1,:] # removing some of data
Grand_mean = data_chopped[:,2].mean()
Grand_STD = p.sqrt((sum(data_chopped[:,4]*data_chopped[:,3]**2) + sum((data_chopped[:,2]-Grand_mean)**2))/sum(data_chopped[:,4]))
else:
break
if filepath == os.path.join(dirname,'ModelParams.dat'):
l = re.split(" ", ln.getline(filepath, 6))
turb_param = float(l[2])
arg.append((Grand_mean, Grand_STD, turb_param))
GrandMeansData = []
os.path.walk(os.getcwd(), LoadGenomeMeanSize, GrandMeansData)
GrandMeansData = sorted(GrandMeansData, key=lambda data_sort: data_sort[2])
TheMeans = p.zeros((len(GrandMeansData), 3 ))
i = 0
for item in GrandMeansData:
TheMeans[i,0] = item[0]
TheMeans[i,1] = item[1]
TheMeans[i,2] = item[2]
i += 1
print TheMeans # just checking...
# later do some computation on TheMeans in NumPy
It does not give error massages. Even gives a file with data... but data are bloody wrong! I checked some of them manually by running commands:
import pylab as p
data = p.genfromtxt(filepath)
data_chopped = data[1000:-1,:]
Grand_mean = data_chopped[:,2].mean()
Grand_STD = p.sqrt((sum(data_chopped[:,4]*data_chopped[:,3]**2) \
+ sum((data_chopped[:,2]-Grand_mean)**2))/sum(data_chopped[:,4]))
on selected files. They are different :-(
1) Can anyone explain me what's wrong?
2) Does anyone know a solution to that?
I'll be grateful for help :-)
Cheers,
PTR
A:
I would say this condition is not passing:
if filepath == os.path.join(dirname,'GeneralData.dat'):
which means you are not getting GeneralData.dat before ModelParams.dat. Maybe you need to sort alphabetically or the file is not there.
A:
I see one issue with the code and the solution that you have provided.
Never hide the issue of "variable referencing before assignment" by just making the variable visible.
Try to understand why it happened?
Prior to creating a global variable "Grand_mean", you were getting an issue that you are accessing Grand_mean before any value is assigned to it. In such a case, by initializing the variable outside the function and marking it as global, only serves to hide the issue.
You see erroneous result because now you have made the variable visible my making it global but the issue continues to exist. You Grand_mean was never equalized to some correct data.
This means that section of code under "if filepath == os.path.join(dirname,..." was never executed.
A:
Using global is not the right solution. That only makes sense if you do in fact want to reference and assign to the global "Grand_mean" name. The need for disambiguation comes from the way the interpreter prescans for assignment operators in function declarations.
You should start by assigning a default value to Grand_mean within the scope of LoadGenomeMeanSize(). You have 1 of 4 branches to actually assign a value to Grand_mean that has correct semantic meaning within one loop iteration. You are likely running into a case where
if filepath == os.path.join(dirname,'ModelParams.dat'): is true, but either
if filepath == os.path.join(dirname,'GeneralData.dat'): or if data[-1,4] != 0.0: is not. It's likely the second condition that is failing for you. Move the
The quick and dirty answer is you probably need to rearrange your code like this:
...
if filepath == os.path.join(dirname,'GeneralData.dat'):
data = p.genfromtxt(filepath)
if data[-1,4] != 0.0: # checking if data set is OK
data_chopped = data[1000:-1,:] # removing some of data
Grand_mean = data_chopped[:,2].mean()
Grand_STD = p.sqrt((sum(data_chopped[:,4]*data_chopped[:,3]**2) + sum((data_chopped[:,2]-Grand_mean)**2))/sum(data_chopped[:,4]))
if filepath == os.path.join(dirname,'ModelParams.dat'):
l = re.split(" ", ln.getline(filepath, 6))
turb_param = float(l[2])
arg.append((Grand_mean, Grand_STD, turb_param))
else:
break
...
| Problems with variable referenced before assignment when using os.path.walk | OK. I have some background in Matlab and I'm now switching to Python.
I have this bit of code under Pythnon 2.6.5 on 64-bit Linux which scrolls through directories, finds files named 'GeneralData.dat', retrieves some data from them and stitches them into a new data set:
import pylab as p
import os, re
import linecache as ln
def LoadGenomeMeanSize(arg, dirname, files):
for file in files:
filepath = os.path.join(dirname, file)
if filepath == os.path.join(dirname,'GeneralData.dat'):
data = p.genfromtxt(filepath)
if data[-1,4] != 0.0: # checking if data set is OK
data_chopped = data[1000:-1,:] # removing some of data
Grand_mean = data_chopped[:,2].mean()
Grand_STD = p.sqrt((sum(data_chopped[:,4]*data_chopped[:,3]**2) + sum((data_chopped[:,2]-Grand_mean)**2))/sum(data_chopped[:,4]))
else:
break
if filepath == os.path.join(dirname,'ModelParams.dat'):
l = re.split(" ", ln.getline(filepath, 6))
turb_param = float(l[2])
arg.append((Grand_mean, Grand_STD, turb_param))
GrandMeansData = []
os.path.walk(os.getcwd(), LoadGenomeMeanSize, GrandMeansData)
GrandMeansData = sorted(GrandMeansData, key=lambda data_sort: data_sort[2])
TheMeans = p.zeros((len(GrandMeansData), 3 ))
i = 0
for item in GrandMeansData:
TheMeans[i,0] = item[0]
TheMeans[i,1] = item[1]
TheMeans[i,2] = item[2]
i += 1
print TheMeans # just checking...
# later do some computation on TheMeans in NumPy
And it throws me this (though I would swear it was working a month ego):
Traceback (most recent call last):
File "/home/User/01_PyScripts/TESTtest.py", line 29, in <module>
os.path.walk(os.getcwd(), LoadGenomeMeanSize, GrandMeansData)
File "/usr/lib/python2.6/posixpath.py", line 233, in walk
walk(name, func, arg)
File "/usr/lib/python2.6/posixpath.py", line 225, in walk
func(arg, top, names)
File "/home/User/01_PyScripts/TESTtest.py", line 26, in LoadGenomeMeanSize
arg.append((Grand_mean, Grand_STD, turb_param))
UnboundLocalError: local variable 'Grand_mean' referenced before assignment
All right... so I went and did some reading and came up with this global variable:
import pylab as p
import os, re
import linecache as ln
Grand_mean = p.nan
Grand_STD = p.nan
def LoadGenomeMeanSize(arg, dirname, files):
for file in files:
global Grand_mean
global Grand_STD
filepath = os.path.join(dirname, file)
if filepath == os.path.join(dirname,'GeneralData.dat'):
data = p.genfromtxt(filepath)
if data[-1,4] != 0.0: # checking if data set is OK
data_chopped = data[1000:-1,:] # removing some of data
Grand_mean = data_chopped[:,2].mean()
Grand_STD = p.sqrt((sum(data_chopped[:,4]*data_chopped[:,3]**2) + sum((data_chopped[:,2]-Grand_mean)**2))/sum(data_chopped[:,4]))
else:
break
if filepath == os.path.join(dirname,'ModelParams.dat'):
l = re.split(" ", ln.getline(filepath, 6))
turb_param = float(l[2])
arg.append((Grand_mean, Grand_STD, turb_param))
GrandMeansData = []
os.path.walk(os.getcwd(), LoadGenomeMeanSize, GrandMeansData)
GrandMeansData = sorted(GrandMeansData, key=lambda data_sort: data_sort[2])
TheMeans = p.zeros((len(GrandMeansData), 3 ))
i = 0
for item in GrandMeansData:
TheMeans[i,0] = item[0]
TheMeans[i,1] = item[1]
TheMeans[i,2] = item[2]
i += 1
print TheMeans # just checking...
# later do some computation on TheMeans in NumPy
It does not give error massages. Even gives a file with data... but data are bloody wrong! I checked some of them manually by running commands:
import pylab as p
data = p.genfromtxt(filepath)
data_chopped = data[1000:-1,:]
Grand_mean = data_chopped[:,2].mean()
Grand_STD = p.sqrt((sum(data_chopped[:,4]*data_chopped[:,3]**2) \
+ sum((data_chopped[:,2]-Grand_mean)**2))/sum(data_chopped[:,4]))
on selected files. They are different :-(
1) Can anyone explain me what's wrong?
2) Does anyone know a solution to that?
I'll be grateful for help :-)
Cheers,
PTR
| [
"I would say this condition is not passing:\nif filepath == os.path.join(dirname,'GeneralData.dat'):\nwhich means you are not getting GeneralData.dat before ModelParams.dat. Maybe you need to sort alphabetically or the file is not there.\n",
"I see one issue with the code and the solution that you have provided.\... | [
0,
0,
0
] | [] | [] | [
"function",
"global_variables",
"python",
"variable_assignment"
] | stackoverflow_0004186764_function_global_variables_python_variable_assignment.txt |
Q:
python vlc.py or vlcwidget.py unable to open the MRL
I am encountering the following error. The mpg file is in the same directory where vlcwidget.py is located. Could some one point it out the issue or share thier experience?
C:\workspace\python-HEAD\python>vlcwidget.py trn_anaglyph_adj.mpg
libdvdnav: Using dvdnav version 4.1.4
libdvdread: Using libdvdcss version 1.2.10 for DVD access
libdvdread: Can't stat trn_anaglyph_adj.mpg
No such file or directory
libdvdread: Could not open trn_anaglyph_adj.mpg
libdvdnav: vm: failed to open/read the DVD
[01bbd45c] filesystem access error: cannot open file trn_anaglyph_adj.mpg (No su
ch file or directory)
[01bbd45c] main access error: File reading failed
[01bbd45c] main access error: VLC could not open the file "trn_anaglyph_adj.mpg"
.
[0095fd8c] main input error: open of `trn_anaglyph_adj.mpg' failed: (null)
[0095fd8c] main input error: Your input can't be opened
[0095fd8c] main input error: VLC is unable to open the MRL 'trn_anaglyph_adj.mpg
'. Check the log for details.
C:\workspace\python-HEAD\python>vlcwidget.py trn_anaglyph_adj.mpg
A:
use full path? (maybe libvlc is running from wherever libvlc.dll is located or what not)...
| python vlc.py or vlcwidget.py unable to open the MRL | I am encountering the following error. The mpg file is in the same directory where vlcwidget.py is located. Could some one point it out the issue or share thier experience?
C:\workspace\python-HEAD\python>vlcwidget.py trn_anaglyph_adj.mpg
libdvdnav: Using dvdnav version 4.1.4
libdvdread: Using libdvdcss version 1.2.10 for DVD access
libdvdread: Can't stat trn_anaglyph_adj.mpg
No such file or directory
libdvdread: Could not open trn_anaglyph_adj.mpg
libdvdnav: vm: failed to open/read the DVD
[01bbd45c] filesystem access error: cannot open file trn_anaglyph_adj.mpg (No su
ch file or directory)
[01bbd45c] main access error: File reading failed
[01bbd45c] main access error: VLC could not open the file "trn_anaglyph_adj.mpg"
.
[0095fd8c] main input error: open of `trn_anaglyph_adj.mpg' failed: (null)
[0095fd8c] main input error: Your input can't be opened
[0095fd8c] main input error: VLC is unable to open the MRL 'trn_anaglyph_adj.mpg
'. Check the log for details.
C:\workspace\python-HEAD\python>vlcwidget.py trn_anaglyph_adj.mpg
| [
"use full path? (maybe libvlc is running from wherever libvlc.dll is located or what not)...\n"
] | [
0
] | [] | [] | [
"python",
"vlc"
] | stackoverflow_0003887972_python_vlc.txt |
Q:
Python+ubuntu error
Am trying to run the following python program
import re
regex=re.compile("http...imgs.xkcd.com.comics.[\\S]*.[jpg|png]")
f=open('out.txt')
for a in f:
print regex.findall(a)
print '\n'
when I type the code into the interpreter manually, it works as expected
but when i save it as a file and try to run it , it gives errors.
The command i used to run it is
chmod +x
sudo ./pymod.py
ERROR:
./pymod.py: 2: Syntax error: "(" unexpected
if i dont use sudo, the error i get is
./pymod.py: line 2: syntax error near unexpected token `('
./pymod.py: line 2: `regex=re.compile("http...imgs.xkcd.com.comics.[\\S]*.[jpg|png]")'
am using ubuntu 10.04 with everything on default
it takes about 10-15 seconds for the error to appear
A:
Your file should start with shebang. You should include the path to the python interpreter
#!/usr/bin/env python
import re
regex=re.compile("http...imgs.xkcd.com.comics.[\\S]*.[jpg|png]")
Check out : http://en.wikipedia.org/wiki/Shebang_(Unix)
A:
This is probably executing as a bash script instead of in Python. Put
#!/usr/bin/env python
at the beginning of your script.
A:
When you set something as executable, you have to specify what you want it to run it with, or Linux will consider it to be a bash script.
Add this as the first line of the file:
#!/usr/bin/python
Or run it like:
python pymod.py
Cheers!
A:
Either use the "shebang". I.e. put
#! /usr/bin/python
as the first line of your script.
Or teach your ubuntu how to treat python scripts without it
as described here: http://www.daniweb.com/code/snippet241988.html
| Python+ubuntu error | Am trying to run the following python program
import re
regex=re.compile("http...imgs.xkcd.com.comics.[\\S]*.[jpg|png]")
f=open('out.txt')
for a in f:
print regex.findall(a)
print '\n'
when I type the code into the interpreter manually, it works as expected
but when i save it as a file and try to run it , it gives errors.
The command i used to run it is
chmod +x
sudo ./pymod.py
ERROR:
./pymod.py: 2: Syntax error: "(" unexpected
if i dont use sudo, the error i get is
./pymod.py: line 2: syntax error near unexpected token `('
./pymod.py: line 2: `regex=re.compile("http...imgs.xkcd.com.comics.[\\S]*.[jpg|png]")'
am using ubuntu 10.04 with everything on default
it takes about 10-15 seconds for the error to appear
| [
"Your file should start with shebang. You should include the path to the python interpreter\n#!/usr/bin/env python\nimport re\nregex=re.compile(\"http...imgs.xkcd.com.comics.[\\\\S]*.[jpg|png]\")\n\nCheck out : http://en.wikipedia.org/wiki/Shebang_(Unix)\n",
"This is probably executing as a bash script instead of... | [
3,
2,
1,
0
] | [] | [] | [
"python",
"ubuntu"
] | stackoverflow_0004187470_python_ubuntu.txt |
Q:
How can I check if my python object is a number?
In Java the numeric types all descend from Number so I would use
(x instanceof Number).
What is the python equivalent?
A:
Test if your variable is an instance of numbers.Number:
>>> import numbers
>>> import decimal
>>> [isinstance(x, numbers.Number) for x in (0, 0.0, 0j, decimal.Decimal(0))]
[True, True, True, True]
This uses ABCs and will work for all built-in number-like classes, and also for all third-party classes if they are worth their salt (registered as subclasses of the Number ABC).
However, in many cases you shouldn't worry about checking types manually - Python is duck typed and mixing somewhat compatible types usually works, yet it will barf an error message when some operation doesn't make sense (4 - "1"), so manually checking this is rarely really needed. It's just a bonus. You can add it when finishing a module to avoid pestering others with implementation details.
This works starting with Python 2.6. On older versions you're pretty much limited to checking for a few hardcoded types.
A:
Python 3:
isinstance(x, (int, float, complex)) and not isinstance(x, bool)
Python 2:
isinstance(x, (int, long, float, complex)) and not isinstance(x, bool)
Note that this answer works incorrectly for Numpy objects.
A:
Use Number from the numbers module to test isinstance(n, Number) (available since 2.6).
isinstance(n, numbers.Number)
Here it is in action with various kinds of numbers and one non-number:
>>> from numbers import Number
... from decimal import Decimal
... from fractions import Fraction
... for n in [2, 2.0, Decimal('2.0'), complex(2,0), Fraction(2,1), '2']:
... print '%15s %s' % (n.__repr__(), isinstance(n, Number))
2 True
2.0 True
Decimal('2.0') True
(2+0j) True
Fraction(2, 1) True
'2' False
This is, of course, contrary to duck typing. If you are more concerned about how an object acts rather than what it is, perform your operations as if you have a number and use exceptions to tell you otherwise.
A:
Sure you can use isinstance, but be aware that this is not how Python works. Python is a duck typed language. You should not explicitly check your types. A TypeError will be raised if the incorrect type was passed.
So just assume it is an int. Don't bother checking.
| How can I check if my python object is a number? | In Java the numeric types all descend from Number so I would use
(x instanceof Number).
What is the python equivalent?
| [
"Test if your variable is an instance of numbers.Number:\n>>> import numbers\n>>> import decimal\n>>> [isinstance(x, numbers.Number) for x in (0, 0.0, 0j, decimal.Decimal(0))]\n[True, True, True, True]\n\nThis uses ABCs and will work for all built-in number-like classes, and also for all third-party classes if they... | [
322,
223,
60,
0
] | [
"That's not really how python works. Just use it like you would a number, and if someone passes you something that's not a number, fail. It's the programmer's responsibility to pass in the correct types.\n"
] | [
-7
] | [
"numbers",
"python",
"types"
] | stackoverflow_0004187185_numbers_python_types.txt |
Q:
How to handle button states efficiently in Tkinter
I've done a few searches but I couldn't find anything about this topic. Perhaps because it is common programmer knowledge (I'm not a programmer, I've learned from necessity), or because I'm going about it the wrong way.
I would like ideas/suggestions on how to manage button states for a GUI. For example, if I have a program which allows the user to import and process data, then certain functions should be inaccessible until the data has been imported successfully, or if they want to graph certain data, they need to select which data to graph before hitting the 'graph' or 'export' button. Even in the simple programs I've built these relationships seems to get complicated quickly. It seems simple to say "User shouldn't be able to hit button 'A' until 'B' and 'C' have been completed, then 'A' should be disabled if button 'D' or the 'Cancel' button. But that's a lot to track for one button. Thus far, I've tried two things:
Changing/Checking button states in the callback functions for the button. So in the above example, I would have code in buttons B's and C's callback to check if A should be enabled. And in buttons D's and Cancel's callbacks I would have code to disable button A. This gets complicated quickly and is difficult to maintain as code changes.
Setting boolean variables in every buttons callback (or just checking the states later using cget()) and checking the variables in a polling function to determine which buttons should be enabled or disabled.
I'm just not sure about this. I would like to make code as short and easy to understand as possible (and easy to edit later), but I don't like the idea of polling all the button states every few hundred milliseconds just for button 'management'. You can extend the same idea to check boxes, menu items, etc... but I'd like to here what others have done and why they do it the way they do.
A:
You are only changing button states based on events, right? There is no reason to 'poll' to see if a button state has changed. What you can do is build a function which does all of the calling for you, then call it with something like disable_buttons([okButton, graphButton, printButton]). When an event takes place that modifies the appropriate user interface options (such as importing data), have another function that turns them on: enable_buttons([graphButton]). You could do this with each object's methods, of course, but making a wrapper allows you to be consistent throughout your application.
| How to handle button states efficiently in Tkinter | I've done a few searches but I couldn't find anything about this topic. Perhaps because it is common programmer knowledge (I'm not a programmer, I've learned from necessity), or because I'm going about it the wrong way.
I would like ideas/suggestions on how to manage button states for a GUI. For example, if I have a program which allows the user to import and process data, then certain functions should be inaccessible until the data has been imported successfully, or if they want to graph certain data, they need to select which data to graph before hitting the 'graph' or 'export' button. Even in the simple programs I've built these relationships seems to get complicated quickly. It seems simple to say "User shouldn't be able to hit button 'A' until 'B' and 'C' have been completed, then 'A' should be disabled if button 'D' or the 'Cancel' button. But that's a lot to track for one button. Thus far, I've tried two things:
Changing/Checking button states in the callback functions for the button. So in the above example, I would have code in buttons B's and C's callback to check if A should be enabled. And in buttons D's and Cancel's callbacks I would have code to disable button A. This gets complicated quickly and is difficult to maintain as code changes.
Setting boolean variables in every buttons callback (or just checking the states later using cget()) and checking the variables in a polling function to determine which buttons should be enabled or disabled.
I'm just not sure about this. I would like to make code as short and easy to understand as possible (and easy to edit later), but I don't like the idea of polling all the button states every few hundred milliseconds just for button 'management'. You can extend the same idea to check boxes, menu items, etc... but I'd like to here what others have done and why they do it the way they do.
| [
"You are only changing button states based on events, right? There is no reason to 'poll' to see if a button state has changed. What you can do is build a function which does all of the calling for you, then call it with something like disable_buttons([okButton, graphButton, printButton]). When an event takes plac... | [
1
] | [] | [] | [
"button",
"python",
"state",
"tkinter"
] | stackoverflow_0004172426_button_python_state_tkinter.txt |
Q:
How to use refresh_access_token in the Yahoo Social Python SDK
I'm trying to use the Yahoo Social Python SDK to get a users contacts through oAuth. This is for a webapp running on App Engine. SO, I have everything set up to run through the oAuth dance, exchanging consumer keys and verifiers and all that jazz. I store the token and can reuse it to retrieve a users contacts until the token the expires an hour later. So, is there anyone out there who has used the Python SDK and can tell me what is wrong with this simple code:
import yahoo.application
CONSUMER_KEY = '####'
CONSUMER_SECRET = '##'
APPLICATION_ID = '##'
CALLBACK_URL = '##'
oauthapp = yahoo.application.OAuthApplication(CONSUMER_KEY, CONSUMER_SECRET, APPLICATION_ID, CALLBACK_URL)
oauthapp.token = yahoo.oauth.AccessToken.from_string(access_token) #access_token is legit string pulled from datastore
oauthapp.token = oauthapp.refresh_access_token(oauthapp.token)
contacts = oauthapp.getContacts()
Running this throws the following error:
'oauth_token'<br>
Traceback (most recent call last):<br>
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 513, in __call__<br>
handler.post(*groups)<br>
File "/base/data/home/apps/testproj/2.345270664321958961/scripteditor.py", line 1249, in post<br>
oauthapp.token = oauthapp.refresh_access_token(oauthapp.token)<br>
File "/base/data/home/apps/testproj/2.345270664321958961/yahoo/application.py", line 90, in refresh_access_token<br>
self.token = self.client.fetch_access_token(request)<br>
File "/base/data/home/apps/testproj/2.345270664321958961/yahoo/oauth.py", line 165, in fetch_access_token<br>
return AccessToken.from_string(self.connection.getresponse().read().strip())<br>
File "/base/data/home/apps/testproj/2.345270664321958961/yahoo/oauth.py", line 130, in from_string<br>
key = params['oauth_token'][0]<br>
KeyError: 'oauth_token'<br>
Basically, if I comment out the line with refresh_access_token, and the token has not expired, this code works and I get the users contacts. But with refresh_acces_token, it fails at that line. Can anyone give a hand?
A:
Looks like something wrong with passing params. Try to debug oauth_token variable.
A:
Solved. For reasons I can't understand, the above code now just works. It might have been a problem on yahoo's end, but I really can't be sure. It's been running fine for two weeks.
| How to use refresh_access_token in the Yahoo Social Python SDK | I'm trying to use the Yahoo Social Python SDK to get a users contacts through oAuth. This is for a webapp running on App Engine. SO, I have everything set up to run through the oAuth dance, exchanging consumer keys and verifiers and all that jazz. I store the token and can reuse it to retrieve a users contacts until the token the expires an hour later. So, is there anyone out there who has used the Python SDK and can tell me what is wrong with this simple code:
import yahoo.application
CONSUMER_KEY = '####'
CONSUMER_SECRET = '##'
APPLICATION_ID = '##'
CALLBACK_URL = '##'
oauthapp = yahoo.application.OAuthApplication(CONSUMER_KEY, CONSUMER_SECRET, APPLICATION_ID, CALLBACK_URL)
oauthapp.token = yahoo.oauth.AccessToken.from_string(access_token) #access_token is legit string pulled from datastore
oauthapp.token = oauthapp.refresh_access_token(oauthapp.token)
contacts = oauthapp.getContacts()
Running this throws the following error:
'oauth_token'<br>
Traceback (most recent call last):<br>
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 513, in __call__<br>
handler.post(*groups)<br>
File "/base/data/home/apps/testproj/2.345270664321958961/scripteditor.py", line 1249, in post<br>
oauthapp.token = oauthapp.refresh_access_token(oauthapp.token)<br>
File "/base/data/home/apps/testproj/2.345270664321958961/yahoo/application.py", line 90, in refresh_access_token<br>
self.token = self.client.fetch_access_token(request)<br>
File "/base/data/home/apps/testproj/2.345270664321958961/yahoo/oauth.py", line 165, in fetch_access_token<br>
return AccessToken.from_string(self.connection.getresponse().read().strip())<br>
File "/base/data/home/apps/testproj/2.345270664321958961/yahoo/oauth.py", line 130, in from_string<br>
key = params['oauth_token'][0]<br>
KeyError: 'oauth_token'<br>
Basically, if I comment out the line with refresh_access_token, and the token has not expired, this code works and I get the users contacts. But with refresh_acces_token, it fails at that line. Can anyone give a hand?
| [
"Looks like something wrong with passing params. Try to debug oauth_token variable.\n",
"Solved. For reasons I can't understand, the above code now just works. It might have been a problem on yahoo's end, but I really can't be sure. It's been running fine for two weeks.\n"
] | [
0,
0
] | [] | [] | [
"google_app_engine",
"oauth",
"python",
"yahoo_api"
] | stackoverflow_0003946093_google_app_engine_oauth_python_yahoo_api.txt |
Q:
Streaming pipes in Python
I'm trying to convert the output of vmstat into a CSV file using Python, so I use something like this to convert to CSV and add the date and time as coloumns:
vmstat 5 | python myscript.py >> vmstat.log
The problem I'm having is it blocks while trying to iterate sys.stdin. It seems like the input buffer doesn't get flushed. I don't want to endlessly loop around and burn processor time as I'm trying to measure this. Here's a simple demonstration which blocks on line 3:
import sys
for line in sys.stdin:
sys.stdout.write(line)
sys.stdout.flush()
Is there an easy way to access the stream immediately like grep does, without pausing while the input buffer fills up?
A:
VMstat 5,does not close the stdout, so the python buffer is still waiting for more data.
Use this instead:
for line in iter(sys.stdin.readline, ""):
print line
| Streaming pipes in Python | I'm trying to convert the output of vmstat into a CSV file using Python, so I use something like this to convert to CSV and add the date and time as coloumns:
vmstat 5 | python myscript.py >> vmstat.log
The problem I'm having is it blocks while trying to iterate sys.stdin. It seems like the input buffer doesn't get flushed. I don't want to endlessly loop around and burn processor time as I'm trying to measure this. Here's a simple demonstration which blocks on line 3:
import sys
for line in sys.stdin:
sys.stdout.write(line)
sys.stdout.flush()
Is there an easy way to access the stream immediately like grep does, without pausing while the input buffer fills up?
| [
"VMstat 5,does not close the stdout, so the python buffer is still waiting for more data.\nUse this instead:\nfor line in iter(sys.stdin.readline, \"\"):\n print line\n\n"
] | [
7
] | [] | [] | [
"python"
] | stackoverflow_0004187785_python.txt |
Q:
How to find total amount of memory used by python process/object in windows
I have some script that loads a lot of data to memory.
I want to know how efficient the data stored in memory.
So, I want to be able to know how many memory was used by python before I loaded data, and after I loaded data.
Also I wondering, if it is some way to check memory usage of complex object.
Let say i have nested dictionary with different types of data inside. How can i know how many memory used by all data in this dictionary.
Thanks,
Alex
A:
As far as I know there is no easy way to see what the memory consumption of a certain object is. It would be a non-trivial thing to do because references could be shared among objects.
Here are my two favourite workarounds:
Use the process manager. Have the program pause for before allocation. Write down the memory used before allocation. Allocate. Write down memory after allocation. It's a low-tech method but it works.
Alternatively you can use pickle.dump to serialize your data structure. The resulting pickle will be comparable (not identical!) in size to the space needed to store the data structure in memory. For better results, use the binary pickle protocol.
A:
You can take a look at the guppy package, which can give you informations about memory used by every loaded object. Unfortunately, it doesn't seem to work under python>=2.6, but it's good if you are using at most python 2.5.
Its usage is really simple, just put these lines in your code, where you want to collect memory informations:
from guppy import hpy
hp = hpy()
print hp.heap()
Which will give you an output like this:
Partition of a set of 25961 objects. Total size = 1894868 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 11901 46 775408 41 775408 41 str
1 6040 23 219964 12 995372 53 tuple
2 1718 7 116824 6 1112196 59 types.CodeType
3 73 0 113608 6 1225804 65 dict of module
4 348 1 107232 6 1333036 70 dict (no owner)
5 196 1 100192 5 1433228 76 dict of type
6 1643 6 92008 5 1525236 80 function
7 209 1 90572 5 1615808 85 type
8 144 1 76800 4 1692608 89 dict of class
9 984 4 35424 2 1728032 91 __builtin__.wrapper_descriptor
A:
In order to analyze how much memory an object uses, you could use Pympler:
>>> from pympler import asizeof
>>> obj = dict(nested=dict(trash=[1,2,3]))
>>> asizeof.asizeof(obj)
800
>>> asizeof.asizeof(obj['nested'])
480
>>> asizeof.asizeof(obj['nested']['trash'])
160
>>> asizeof.asizeof(obj['nested']['trash'][0])
24
A:
An alternative is that you could use windows's performance counters through pywin32
| How to find total amount of memory used by python process/object in windows | I have some script that loads a lot of data to memory.
I want to know how efficient the data stored in memory.
So, I want to be able to know how many memory was used by python before I loaded data, and after I loaded data.
Also I wondering, if it is some way to check memory usage of complex object.
Let say i have nested dictionary with different types of data inside. How can i know how many memory used by all data in this dictionary.
Thanks,
Alex
| [
"As far as I know there is no easy way to see what the memory consumption of a certain object is. It would be a non-trivial thing to do because references could be shared among objects.\nHere are my two favourite workarounds:\n\nUse the process manager. Have the program pause for before allocation. Write down the m... | [
5,
2,
2,
0
] | [] | [] | [
"memory_management",
"python",
"windows"
] | stackoverflow_0004155126_memory_management_python_windows.txt |
Q:
How can I inspect a linux process to determine how/when a process dies/terminates?
I have a python irc bot which I start up as root by doing /etc/init.d/phenny start. Sometimes it dies, though and it seems to happen overnight.
What can I do to inspect it and see the status of the process in a text file?
A:
If you're interested in really low level process activity, you can run the python interpreter under strace with standard error redirected to a file.
If you're only interested in inspecting the python code when your bot crashes, and you have the location in the source where the crash happens, you can wrap that location with try/except and break into the debugger in theexcept clause:
import pdb; pdb.set_trace()
You'll probably need to run your bot in non-daemon mode for that to work, though.
A:
If you know it's still running, you can pstack it to see it's walkback. I'm not sure how useful that will be because you will see the call stack of the interpreter. You could also try strace or ltrace as someone else mentioned.
I would also make sure that in whatever environment the script runs in, you have set ulimit -c unlimited so that a core is generated in case python it is outright crashing.
Another thing I might try is to have this job executed by a parent that does not wait it's child. This should cause the proc table entry to stick around as a zombie even when the underlying job has exited.
A:
You might want to try Python psutils, it is something that I have used and works.
A:
A cheap way to get some extra clues about the problem would be to start phenny with
/etc/init.d/phenny start 2>/tmp/phenny.out 1>&2
When it crashes, check the tail of /tmp/phenny.out for the Python traceback.
A:
If you only need to verify that the process is running you could just run a script that checks the output of command
ps ax | grep [p]henny
every few seconds. If it's empty, then obviously the process is dead.
| How can I inspect a linux process to determine how/when a process dies/terminates? | I have a python irc bot which I start up as root by doing /etc/init.d/phenny start. Sometimes it dies, though and it seems to happen overnight.
What can I do to inspect it and see the status of the process in a text file?
| [
"If you're interested in really low level process activity, you can run the python interpreter under strace with standard error redirected to a file.\nIf you're only interested in inspecting the python code when your bot crashes, and you have the location in the source where the crash happens, you can wrap that loc... | [
1,
1,
0,
0,
0
] | [] | [] | [
"linux",
"process",
"python"
] | stackoverflow_0004070369_linux_process_python.txt |
Q:
Connecting and Saving Data With Redis Inside Celery Task
I have an object that saves data to Redis. It needs to block as less as possible, so I've decided to use Celery to offload the task. When I try to .save() the object outside of celery, it connects to Redis and stores the data just fine. However, when I try to do the exact same thing from a Celery task, it looks like it runs, but there is no connection to Redis, no exception, no error output and nothing gets saves to the Redis server. I replicated the problem with the small bit of code below. test.py:
from celery.decorators import task
import redis
class A(object):
def __init__(self):
print "init"
def save(self):
self.r = self.connect()
self.r.set('foo', 'bar')
print "saved"
def connect(self):
return redis.Redis(host="localhost", port=6379)
a = A()
@task
def something(a):
a.save()
Here is the Python console output:
>>> from test import *
init
>>> a
<test.A object at 0x1010e3c10>
>>> result = something.delay(a)
>>> result.ready()
True
>>> result.successful()
True
And here is the celeryd output:
[2010-11-15 12:05:33,672: INFO/MainProcess] Got task from broker: test.something[d1d71ee5-7206-4fa7-844c-04445fd8bead]
[2010-11-15 12:05:33,688: WARNING/PoolWorker-2] saved
[2010-11-15 12:05:33,694: INFO/MainProcess] Task test.something[d1d71ee5-7206-4fa7-844c-04445fd8bead] succeeded in 0.00637984275818s: None
Any help would be awesome! I've replicated the issue on multiple computers, with multiple python versions.
A:
The problem was being caused by a misconfiguration in the celeryconfig.py. CELERY_IMPORTS needed to include the task module. This is resolved.
| Connecting and Saving Data With Redis Inside Celery Task | I have an object that saves data to Redis. It needs to block as less as possible, so I've decided to use Celery to offload the task. When I try to .save() the object outside of celery, it connects to Redis and stores the data just fine. However, when I try to do the exact same thing from a Celery task, it looks like it runs, but there is no connection to Redis, no exception, no error output and nothing gets saves to the Redis server. I replicated the problem with the small bit of code below. test.py:
from celery.decorators import task
import redis
class A(object):
def __init__(self):
print "init"
def save(self):
self.r = self.connect()
self.r.set('foo', 'bar')
print "saved"
def connect(self):
return redis.Redis(host="localhost", port=6379)
a = A()
@task
def something(a):
a.save()
Here is the Python console output:
>>> from test import *
init
>>> a
<test.A object at 0x1010e3c10>
>>> result = something.delay(a)
>>> result.ready()
True
>>> result.successful()
True
And here is the celeryd output:
[2010-11-15 12:05:33,672: INFO/MainProcess] Got task from broker: test.something[d1d71ee5-7206-4fa7-844c-04445fd8bead]
[2010-11-15 12:05:33,688: WARNING/PoolWorker-2] saved
[2010-11-15 12:05:33,694: INFO/MainProcess] Task test.something[d1d71ee5-7206-4fa7-844c-04445fd8bead] succeeded in 0.00637984275818s: None
Any help would be awesome! I've replicated the issue on multiple computers, with multiple python versions.
| [
"The problem was being caused by a misconfiguration in the celeryconfig.py. CELERY_IMPORTS needed to include the task module. This is resolved. \n"
] | [
0
] | [] | [] | [
"celery",
"python",
"redis"
] | stackoverflow_0004188350_celery_python_redis.txt |
Q:
Plotting 3D scatter with python?
Is there any module that could aid me in producing something like this?
A:
Like this, say?
(source: sourceforge.net)
The matplotlib examples gallery is a wonderful thing to behold.
Code copied from the linked example.
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
def randrange(n, vmin, vmax):
return (vmax-vmin)*np.random.rand(n) + vmin
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 100
for c, m, zl, zh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
xs = randrange(n, 23, 32)
ys = randrange(n, 0, 100)
zs = randrange(n, zl, zh)
ax.scatter(xs, ys, zs, c=c, marker=m)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
A:
Adapted from the Cookbook
from numpy import *
import pylab as p
import mpl_toolkits.mplot3d.axes3d as p3
x=random.randn(100)
y=random.randn(100)
z=random.randn(100)
fig=p.figure()
ax = p3.Axes3D(fig)
ax.scatter3D(ravel(x),ravel(y),ravel(z))
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
p.show()
A:
I think matplotlib should be able to do something like that.
| Plotting 3D scatter with python? |
Is there any module that could aid me in producing something like this?
| [
"Like this, say?\n\n(source: sourceforge.net) \nThe matplotlib examples gallery is a wonderful thing to behold.\n\nCode copied from the linked example.\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\n\ndef randrange(n, vmin, vmax):\n return (vmax-vmin)*np.random.ran... | [
6,
3,
1
] | [] | [] | [
"3d",
"python"
] | stackoverflow_0004188482_3d_python.txt |
Q:
Force locale for one function to be UK/English in just one function so that datetime.strftime always returns an English format
I need to write a very simple python function which accepts a date in Excel format (an integer of days elapsed since 1st Jan 1900). I convert that to a python datetime.date object, and finally I'd like to format that as a shortened string date (e.g. "Jan10" or "Mar11") - basically the date in MmmYY format.
dt.strftime( fmt )
This function works just fine on UK & US workstations, however I've noticed that on some colleagues PCs which are set to a French locale we get the wrong anser:
>>> locale.getdefaultlocale()
('fr_FR', 'cp1252')
On these machines the function above returns the formatted date-string in French which is not the desired output.
I understand that I could use the locale.setlocale function to globally re-define the locale, however this is not something which is desirable. Elsewhere in the system there is likely to be scripts which require a native-language locale. I do not wish to break somebody else's component by re-defining a global locale.
So what can I do? Short of re-writing the string-formatting function, is there a way I can make the strftime function produce it's output in the UK/US locale without affecting anything else?
Platform = Python2.4.4 on Windows 32bit
FYI, this solution does not apply - it changes the locale globally which is exactly what I want to avoid doing:
Locale date formatting in Python
A:
If you need fixed strings then it's probably best to create a mapping of month number to month name and just use that.
months = {1: 'Jan', 2: 'Feb', ...}
printf '%s%02d' % (months[somedt.month], somedt.year % 100)
A:
Yes, this is possible to do. I've had this same problem when implementing a web server. I wanted the date/time to appear in the client web browser's locale, not the server's local.
In the standard library, there is a locale module. Check out the setlocale() and getlocale()
methods, specifically wit the category LC_TIME. You'll probably want to use getlocale() to get the existing locale, then setlocale to set it to something like 'EN_US' or 'C", then call the strftime method, and finally restore the previous local with another setlocale() call.
| Force locale for one function to be UK/English in just one function so that datetime.strftime always returns an English format | I need to write a very simple python function which accepts a date in Excel format (an integer of days elapsed since 1st Jan 1900). I convert that to a python datetime.date object, and finally I'd like to format that as a shortened string date (e.g. "Jan10" or "Mar11") - basically the date in MmmYY format.
dt.strftime( fmt )
This function works just fine on UK & US workstations, however I've noticed that on some colleagues PCs which are set to a French locale we get the wrong anser:
>>> locale.getdefaultlocale()
('fr_FR', 'cp1252')
On these machines the function above returns the formatted date-string in French which is not the desired output.
I understand that I could use the locale.setlocale function to globally re-define the locale, however this is not something which is desirable. Elsewhere in the system there is likely to be scripts which require a native-language locale. I do not wish to break somebody else's component by re-defining a global locale.
So what can I do? Short of re-writing the string-formatting function, is there a way I can make the strftime function produce it's output in the UK/US locale without affecting anything else?
Platform = Python2.4.4 on Windows 32bit
FYI, this solution does not apply - it changes the locale globally which is exactly what I want to avoid doing:
Locale date formatting in Python
| [
"If you need fixed strings then it's probably best to create a mapping of month number to month name and just use that.\nmonths = {1: 'Jan', 2: 'Feb', ...}\n\nprintf '%s%02d' % (months[somedt.month], somedt.year % 100)\n\n",
"Yes, this is possible to do. I've had this same problem when implementing a web server.... | [
0,
0
] | [] | [] | [
"internationalization",
"python",
"windows"
] | stackoverflow_0004186023_internationalization_python_windows.txt |
Q:
Problem running compiled Python script
So I have compiled a python script with py2exe according to this answer. There were no errors during compilation, everything went fine.
When I run the script from a cmd like this:
C:\Users\Richard\Dist\backprop3.exe 60
This is the output I get:
C:\Users\Richard>C:\Users\Richard\Dist\backprop3.exe 60
Traceback (most recent call last):
File "backprop3.py", line 209, in <module>
File "backprop3.py", line 175, in demo
NameError: global name '__file__' is not defined
C:\Users\Richard>
Which is referring to this line:
image = Image.open( os.path.dirname( os.path.abspath( __file__ ) )+"/backprop-input.bmp" )
That line just loads an image from a current directory. Where is the problem?
A:
__file__ will not work within py2exe. This is because the module is inside the .exe and thus there is nothing to set __file__ to which will give you the python file.
See http://www.py2exe.org/index.cgi/WhereAmI for techniques of dealing with this.
| Problem running compiled Python script | So I have compiled a python script with py2exe according to this answer. There were no errors during compilation, everything went fine.
When I run the script from a cmd like this:
C:\Users\Richard\Dist\backprop3.exe 60
This is the output I get:
C:\Users\Richard>C:\Users\Richard\Dist\backprop3.exe 60
Traceback (most recent call last):
File "backprop3.py", line 209, in <module>
File "backprop3.py", line 175, in demo
NameError: global name '__file__' is not defined
C:\Users\Richard>
Which is referring to this line:
image = Image.open( os.path.dirname( os.path.abspath( __file__ ) )+"/backprop-input.bmp" )
That line just loads an image from a current directory. Where is the problem?
| [
"__file__ will not work within py2exe. This is because the module is inside the .exe and thus there is nothing to set __file__ to which will give you the python file.\nSee http://www.py2exe.org/index.cgi/WhereAmI for techniques of dealing with this.\n"
] | [
8
] | [] | [] | [
"python"
] | stackoverflow_0004188708_python.txt |
Q:
How can I force urllib2 to time out?
I want to to test my application's handling of timeouts when grabbing data via urllib2, and I want to have some way to force the request to timeout.
Short of finding a very very slow internet connection, what method can I use?
I seem to remember an interesting application/suite for simulating these sorts of things. Maybe someone knows the link?
A:
I usually use netcat to listen on port 80 of my local machine:
nc -l 80
Then I use http://localhost/ as the request URL in my application. Netcat will answer at the http port but won't ever give a response, so the request is guaranteed to time out provided that you have specified a timeout in your urllib2.urlopen() call or by calling socket.setdefaulttimeout().
A:
You could set the default timeout as shown above, but you could use a mix of both since Python 2.6 in there is a timeout option in the urlopen method:
import urllib2
import socket
try:
response = urllib2.urlopen("http://google.com", None, 2.5)
except URLError, e:
print "Oops, timed out?"
except socket.timeout:
print "Timed out!"
The default timeout for urllib2 is infinite, and importing socket ensures you that you'll catch the timeout as socket.timeout exception
A:
import socket
socket.setdefaulttimeout(2) # set time out to 2 second.
If you want to set the timeout for each request you can use the timeout argument for urlopen
A:
why not write a very simple CGI script in bash that just sleeps for the required timeout period?
A:
If you're running on a Mac, speedlimit is very cool.
There's also dummynet. It's a lot more hardcore, but it also lets you do some vastly more interesting things. Here's a pre-configured VM image.
If you're running on a Linux box already, there's netem.
I believe I've heard of a Windows-based tool called TrafficShaper, but that one I haven't verified.
| How can I force urllib2 to time out? | I want to to test my application's handling of timeouts when grabbing data via urllib2, and I want to have some way to force the request to timeout.
Short of finding a very very slow internet connection, what method can I use?
I seem to remember an interesting application/suite for simulating these sorts of things. Maybe someone knows the link?
| [
"I usually use netcat to listen on port 80 of my local machine:\nnc -l 80\n\nThen I use http://localhost/ as the request URL in my application. Netcat will answer at the http port but won't ever give a response, so the request is guaranteed to time out provided that you have specified a timeout in your urllib2.url... | [
10,
6,
3,
0,
0
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0004188723_python_urllib2.txt |
Q:
multiple layouts/layout transitions in a python plasmoid
I'm doing a little python plasmoid that deals with remote resources.
Here's the code : glpoid
It offers a view of tickets (the default one), a view that let the user filling and sending a new ticket, and a last one to see a ticket detail...
My problem is that i don't know how to "close" the current layout when i'm passing to another view (or make it disappear).
For each layout, i define items that i add to the layout definition and last i display the new layout :
Initially, i display the default view with self.view_tickets_ui().
Each layout is definied in name_ui() methods which each redefine the layout and pass it to the applet.
To resume it's defined like this:
class GLPIApplet(plasmascript.Applet):
def __init__(self,parent,args=None):
plasmascript.Applet.__init__(self,parent)
def init(self):
self.setHasConfigurationInterface(False)
self.setAspectRatioMode(Plasma.Square)
self.resize(400,650)
# new ticket button
self.new = Plasma.PushButton()
self.new.setText('Nouveau Ticket')
self.connect(self.new, SIGNAL('clicked()'), self.new_ticket_ui)
# refresh button
self.refresh = Plasma.PushButton()
self.refresh.setText('Rafraichir')
self.connect(self.refresh, SIGNAL('clicked()'), self.view_tickets_ui)
# initialize
self.view_tickets_ui()
def view_tickets_ui(self, message=None):
# layout of ticket view
self.layout = QGraphicsLinearLayout(Qt.Vertical)
self.layout.itemSpacing(3)
self.layout.addItem(self.new)
self.view_tickets()
self.layout.addItem(self.refresh)
self.applet.setLayout(self.layout)
def new_ticket_ui(self, message=None):
# layout of a new ticket
self.layout = QGraphicsLinearLayout(Qt.Vertical)
self.layout.itemSpacing(3)
message_label = Plasma.Label()
message_label.setText('the message:')
self.layout.addItem(message_label)
self.applet.setLayout(self.layout)
Here init just defines some buttons, and then call view_tickets_ui() that put some items and display the layout.
If i call new_ticket_ui() after, it will add elements to the current layout... so both are displayed on the same place.
How can i manage that please??
A:
You could use a Plasma.TabBar with hidden tabs and switch between them, as mentioned on IRC. Connect the clicked signals to slots that switch among tabs and everything should be fine.
Also, a note on style: you should use the new signal/slot API whenever possible:
self.connect(self.refresh, SIGNAL('clicked()'), self.view_tickets_ui)
should become
self.refresh.clicked.connect(self.view_tickets_ui).
| multiple layouts/layout transitions in a python plasmoid | I'm doing a little python plasmoid that deals with remote resources.
Here's the code : glpoid
It offers a view of tickets (the default one), a view that let the user filling and sending a new ticket, and a last one to see a ticket detail...
My problem is that i don't know how to "close" the current layout when i'm passing to another view (or make it disappear).
For each layout, i define items that i add to the layout definition and last i display the new layout :
Initially, i display the default view with self.view_tickets_ui().
Each layout is definied in name_ui() methods which each redefine the layout and pass it to the applet.
To resume it's defined like this:
class GLPIApplet(plasmascript.Applet):
def __init__(self,parent,args=None):
plasmascript.Applet.__init__(self,parent)
def init(self):
self.setHasConfigurationInterface(False)
self.setAspectRatioMode(Plasma.Square)
self.resize(400,650)
# new ticket button
self.new = Plasma.PushButton()
self.new.setText('Nouveau Ticket')
self.connect(self.new, SIGNAL('clicked()'), self.new_ticket_ui)
# refresh button
self.refresh = Plasma.PushButton()
self.refresh.setText('Rafraichir')
self.connect(self.refresh, SIGNAL('clicked()'), self.view_tickets_ui)
# initialize
self.view_tickets_ui()
def view_tickets_ui(self, message=None):
# layout of ticket view
self.layout = QGraphicsLinearLayout(Qt.Vertical)
self.layout.itemSpacing(3)
self.layout.addItem(self.new)
self.view_tickets()
self.layout.addItem(self.refresh)
self.applet.setLayout(self.layout)
def new_ticket_ui(self, message=None):
# layout of a new ticket
self.layout = QGraphicsLinearLayout(Qt.Vertical)
self.layout.itemSpacing(3)
message_label = Plasma.Label()
message_label.setText('the message:')
self.layout.addItem(message_label)
self.applet.setLayout(self.layout)
Here init just defines some buttons, and then call view_tickets_ui() that put some items and display the layout.
If i call new_ticket_ui() after, it will add elements to the current layout... so both are displayed on the same place.
How can i manage that please??
| [
"You could use a Plasma.TabBar with hidden tabs and switch between them, as mentioned on IRC. Connect the clicked signals to slots that switch among tabs and everything should be fine.\nAlso, a note on style: you should use the new signal/slot API whenever possible:\nself.connect(self.refresh, SIGNAL('clicked()'), ... | [
1
] | [] | [] | [
"kde_plasma",
"plasmoid",
"python"
] | stackoverflow_0004173771_kde_plasma_plasmoid_python.txt |
Q:
Parsing HTML Tables with BeautifulSoup
I have used BeautifulSoup in the past but I am up against something new; incredibly generic/minimal HTML table markup... My goal is to grab each value and it's label (each in there own td) and print them out... They can be merged, I don't care, I just want to make sure each label is applied to the correct value. Here is an example table:
<tbody><tr>
<td class="labels">Dawn:</td>
<td class="site_data" style="text-align: left;">07:01</td>
<td class="labels">Sunrise:</td>
<td class="site_data" style="text-align: left;">07:26</td>
<td class="labels">Moonrise:</td>
<td class="site_data" style="text-align: left;">14:29</td>
<td rowspan="3"><img src="images/moon.bmp" alt="Moon" width="64" align="left" border="0" height="64" style="margin: 0px 10px" /></td>
</tr>
<tr>
<td class="labels">Dusk:</td>
<td class="site_data" style="text-align: left;">18:27</td>
<td class="labels">Sunset: </td>
<td class="site_data" style="text-align: left;">18:02</td>
<td class="labels">Moonset:</td>
<td class="site_data" style="text-align: left;">01:55</td>
</tr>
<tr>
<td class="labels">Daylight:</td>
<td class="site_data" style="text-align: left;">11:26</td>
<td class="labels">Day length:</td>
<td class="site_data" style="text-align: left;">10:36</td>
<td class="labels">Moon Phase:</td>
<td class="site_data" style="text-align: left;">Waxing Gibbous</td>
</tr>
</tbody>
I know how to grab these values...
for td in soup.findAll('table')[0]: # theres more than one table on the page
print td.renderContents().strip()
but this only gives me....
'Dawn:'
'07:01'
'Sunrise:'
'07:26'
'Moonrise:'
'14:29'
'<img src="images/moon.bmp" alt="Moon" width="64" align="left" border="0" height="64" style="margin: 0px 10px" />'
'Dusk:'
'18:27'
'Sunset: '
'18:02'
'Moonset:'
'01:55'
'Daylight:'
'11:26'
'Day length:'
'10:36'
'Moon Phase:'
'Waxing Gibbous'
I guess I could grab onto those class values "labels" and "site_data" but how do I make sure the labels and data are grouped correctly?
A:
I'm not a BeautifulSoup expert, but you could try something like this:
for label in soup.findAll('table')[0].findAll('td', attrs={'class' : 'labels'}):
data_sibs = label.findNextSiblings(attrs={'class' : 'site_data'})
if len(data_sibs) > 0:
print label.renderContents().strip() + " " + data_sibs[0].renderContents().strip()
Edit:
Tested and produces the following:
Dawn: 07:01
Sunrise: 07:26
Moonrise: 14:29
etc..
A:
The following should be simpler and easier to follow:
import pprint
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(docTxt)
groupedData = []
for row in soup.findAll("tr"):
data = {}
allTDs = row.findAll("td")
for x in range(0, len(allTDs)-1, 2):
data[allTDs[x].renderContents().strip()] = allTDs[x+1].renderContents().strip()
groupedData.append(data)
pprint.pprint(groupedData)
output:
[{'Dawn:': '07:01', 'Moonrise:': '14:29', 'Sunrise:': '07:26'},
{'Dusk:': '18:27', 'Moonset:': '01:55', 'Sunset: ': '18:02'},
{'Day length:': '10:36',
'Daylight:': '11:26',
'Moon Phase:': 'Waxing Gibbous'}]
| Parsing HTML Tables with BeautifulSoup | I have used BeautifulSoup in the past but I am up against something new; incredibly generic/minimal HTML table markup... My goal is to grab each value and it's label (each in there own td) and print them out... They can be merged, I don't care, I just want to make sure each label is applied to the correct value. Here is an example table:
<tbody><tr>
<td class="labels">Dawn:</td>
<td class="site_data" style="text-align: left;">07:01</td>
<td class="labels">Sunrise:</td>
<td class="site_data" style="text-align: left;">07:26</td>
<td class="labels">Moonrise:</td>
<td class="site_data" style="text-align: left;">14:29</td>
<td rowspan="3"><img src="images/moon.bmp" alt="Moon" width="64" align="left" border="0" height="64" style="margin: 0px 10px" /></td>
</tr>
<tr>
<td class="labels">Dusk:</td>
<td class="site_data" style="text-align: left;">18:27</td>
<td class="labels">Sunset: </td>
<td class="site_data" style="text-align: left;">18:02</td>
<td class="labels">Moonset:</td>
<td class="site_data" style="text-align: left;">01:55</td>
</tr>
<tr>
<td class="labels">Daylight:</td>
<td class="site_data" style="text-align: left;">11:26</td>
<td class="labels">Day length:</td>
<td class="site_data" style="text-align: left;">10:36</td>
<td class="labels">Moon Phase:</td>
<td class="site_data" style="text-align: left;">Waxing Gibbous</td>
</tr>
</tbody>
I know how to grab these values...
for td in soup.findAll('table')[0]: # theres more than one table on the page
print td.renderContents().strip()
but this only gives me....
'Dawn:'
'07:01'
'Sunrise:'
'07:26'
'Moonrise:'
'14:29'
'<img src="images/moon.bmp" alt="Moon" width="64" align="left" border="0" height="64" style="margin: 0px 10px" />'
'Dusk:'
'18:27'
'Sunset: '
'18:02'
'Moonset:'
'01:55'
'Daylight:'
'11:26'
'Day length:'
'10:36'
'Moon Phase:'
'Waxing Gibbous'
I guess I could grab onto those class values "labels" and "site_data" but how do I make sure the labels and data are grouped correctly?
| [
"I'm not a BeautifulSoup expert, but you could try something like this:\nfor label in soup.findAll('table')[0].findAll('td', attrs={'class' : 'labels'}):\n data_sibs = label.findNextSiblings(attrs={'class' : 'site_data'})\n if len(data_sibs) > 0:\n print label.renderContents().strip() + \" \" + data_sibs[0].re... | [
2,
2
] | [] | [] | [
"beautifulsoup",
"html_table",
"python"
] | stackoverflow_0004188950_beautifulsoup_html_table_python.txt |
Q:
Admin search not working for my fields - Django
I have a model with an encrypted field.
So fields are encrypted and decrypted as they enter and leave the database.
The problem:
within the admin panel
?q='item' does not seem to find any rows
?field_name='item' does find them all!!
Any ideas? :)
A:
If I understand your question correctly you would have to encrypt the search term as well to fit to the entries in the database. This will most probably fail with the standard admin functionality, since all the fields specified as search fields will be handled in the same fashion. You would have to create your own ChangeList class and override its get_query_set method, so that it can handle your field in a special way!
| Admin search not working for my fields - Django | I have a model with an encrypted field.
So fields are encrypted and decrypted as they enter and leave the database.
The problem:
within the admin panel
?q='item' does not seem to find any rows
?field_name='item' does find them all!!
Any ideas? :)
| [
"If I understand your question correctly you would have to encrypt the search term as well to fit to the entries in the database. This will most probably fail with the standard admin functionality, since all the fields specified as search fields will be handled in the same fashion. You would have to create your own... | [
1
] | [] | [] | [
"django",
"django_admin",
"django_models",
"django_queryset",
"python"
] | stackoverflow_0004187576_django_django_admin_django_models_django_queryset_python.txt |
Q:
bisect and lists of user defined objects (python 3)
Before python 3, I used bisect to insert user-defined objects into a list. bisect was happy with this because my user-defined object had a def __cmp__ that defined how to compare the objects. I've read the rationale for not supporting cmp in python 3 and I'm fine with that. I thought a fix for my old code would be to 'decorate' my user-defined object by turning it into a tuple
(integer, user-defined object).
However, if I have a list of my tuples, and try ...
i = bisect_left([list_of_tuples], (integer, user-defined object))
then I get an error "builtins.TypeError: unorderable types ..."
So, (in python 3) how do I use bisect for lists of items that aren't made entirely of things with a natural sort order?
A:
You need to add an __lt__ method; this is now what is used for comparisons instead of __cmp__
| bisect and lists of user defined objects (python 3) | Before python 3, I used bisect to insert user-defined objects into a list. bisect was happy with this because my user-defined object had a def __cmp__ that defined how to compare the objects. I've read the rationale for not supporting cmp in python 3 and I'm fine with that. I thought a fix for my old code would be to 'decorate' my user-defined object by turning it into a tuple
(integer, user-defined object).
However, if I have a list of my tuples, and try ...
i = bisect_left([list_of_tuples], (integer, user-defined object))
then I get an error "builtins.TypeError: unorderable types ..."
So, (in python 3) how do I use bisect for lists of items that aren't made entirely of things with a natural sort order?
| [
"You need to add an __lt__ method; this is now what is used for comparisons instead of __cmp__\n"
] | [
17
] | [] | [] | [
"bisect",
"cmp",
"python",
"python_3.x"
] | stackoverflow_0004189505_bisect_cmp_python_python_3.x.txt |
Q:
Python subprocess produced output or not
This question is in relation to:
python, subprocess: reading output from subprocess
If P is a subprocess started with a command along the lines of
import subprocess
P = subprocess.Popen ("command", stdout=subprocess.PIPE)
we can read the output P produces by P.stdout.readline (). This is a blocking read though. How can I check if there is output ready for reading (without blocking)?
A:
If you are using *nix, then you can use the select module to poll the stdout file descriptor
import subprocess
import select
poller = select.epoll()
P = subprocess.Popen ("command", stdout=subprocess.PIPE)
poller.register(P.stdout, select.EPOLLHUP)
while True:
#block indefinitely: timeout = -1
#return immediately: timeout = 0
for fd, flags in poller.poll(timeout=0)
foo = P.stdout.readline()
#do something else before the next poll
| Python subprocess produced output or not | This question is in relation to:
python, subprocess: reading output from subprocess
If P is a subprocess started with a command along the lines of
import subprocess
P = subprocess.Popen ("command", stdout=subprocess.PIPE)
we can read the output P produces by P.stdout.readline (). This is a blocking read though. How can I check if there is output ready for reading (without blocking)?
| [
"If you are using *nix, then you can use the select module to poll the stdout file descriptor\nimport subprocess\nimport select\npoller = select.epoll()\n\nP = subprocess.Popen (\"command\", stdout=subprocess.PIPE)\npoller.register(P.stdout, select.EPOLLHUP)\n\nwhile True:\n #block indefinitely: timeout = -1\n ... | [
0
] | [] | [] | [
"communication",
"python",
"subprocess"
] | stackoverflow_0004189551_communication_python_subprocess.txt |
Q:
How to find the set of entities more recent than the last one with children
I have two SQLAlchemy model objects designated thus:
class SpecInstance(Base):
spec_id = Column(Integer, ForeignKey('spec.spec_id'))
details = Column(String)
class Spec(Base):
spec_id = Column(Integer)
spec_date = Column(DateTime)
instances = relationship(SpecInstance, backref="spec", cascade="all, delete, delete-orphan")
I am looking for a query that will return only those Spec objects that have a spec_date greater than the most recent one with instances. For example, given objects like these:
Spec(spec_id=1, spec_date='2010-10-01')
Spec(spec_id=2, spec_date='2010-10-02')
Spec(spec_id=3, spec_date='2010-10-03')
SpecInstance(spec_id=2, details='whatever')
I want my query to return only Spec 3. Spec 2 is ineligible because it has instances. Spec 1 is ineligible because it's older than Spec 2.
How do I do this?
A:
I'm not testing this code since I'm pretty sure it will work and setting up the env is an overhead.
In plain SQL, one will do this with a subquery. In sqlalchemy, subqueries are created in this manner:
sq = session.query(Spec.spec_date.label('most_recent'))\
.join((SpecInstance, SpecInstance.spec_id==Spec.spec_id))\
.order_by(desc(Spec.spec_date))\
.limit(1).subquery()
Here, we joined the two tables so only the Spec with SpecInstances are taken into account, then we order them by date so the latest are on top, and take only the first - the youngest with instances - and we only need its date. This will not be executed - it will be prepared as subquery in:
session.query(Spec)\
.join((sq, Spec.spec_date>sq.c.most_recent))
which is pretty straightforward. Be careful to put double parentheses on the join constructs, and to include .c in the second query on sq, since 'most_recent' will be a dynamic column lookup.
| How to find the set of entities more recent than the last one with children | I have two SQLAlchemy model objects designated thus:
class SpecInstance(Base):
spec_id = Column(Integer, ForeignKey('spec.spec_id'))
details = Column(String)
class Spec(Base):
spec_id = Column(Integer)
spec_date = Column(DateTime)
instances = relationship(SpecInstance, backref="spec", cascade="all, delete, delete-orphan")
I am looking for a query that will return only those Spec objects that have a spec_date greater than the most recent one with instances. For example, given objects like these:
Spec(spec_id=1, spec_date='2010-10-01')
Spec(spec_id=2, spec_date='2010-10-02')
Spec(spec_id=3, spec_date='2010-10-03')
SpecInstance(spec_id=2, details='whatever')
I want my query to return only Spec 3. Spec 2 is ineligible because it has instances. Spec 1 is ineligible because it's older than Spec 2.
How do I do this?
| [
"I'm not testing this code since I'm pretty sure it will work and setting up the env is an overhead.\nIn plain SQL, one will do this with a subquery. In sqlalchemy, subqueries are created in this manner:\nsq = session.query(Spec.spec_date.label('most_recent'))\\\n .join((SpecInstance, SpecInstance.spec_i... | [
0
] | [] | [] | [
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0004188312_orm_python_sqlalchemy.txt |
Q:
Why is save not working in Django?
I'm using manage.py shell and run something like this:
d=Document.objects.get(pk=1)
d.scores
{1:0,2:0,3:0}
d.scores[1]=5
d.scores
{1:5,2:0,3:0}
d.save()
But viewing d in the database reveals that it hasn't been updated. What am I doing wrong?? I checked out what's here, but d is definitely a Document instance.
If it helps, models.py looks like this:
from django.db import models
class Document(models.Model):
fileName=models.CharField(max_length=200)
fileUrl=models.CharField(max_length=200)
scores={1:0,2:0,3:0}
A:
Your 'scores' class variable isn't an instance of any of Django's *Field classes. I would imagine the 'scores' field isn't even on the table in the DB, since the field classes are what defines all of that, and what gets saved to the DB, among other things.
| Why is save not working in Django? | I'm using manage.py shell and run something like this:
d=Document.objects.get(pk=1)
d.scores
{1:0,2:0,3:0}
d.scores[1]=5
d.scores
{1:5,2:0,3:0}
d.save()
But viewing d in the database reveals that it hasn't been updated. What am I doing wrong?? I checked out what's here, but d is definitely a Document instance.
If it helps, models.py looks like this:
from django.db import models
class Document(models.Model):
fileName=models.CharField(max_length=200)
fileUrl=models.CharField(max_length=200)
scores={1:0,2:0,3:0}
| [
"Your 'scores' class variable isn't an instance of any of Django's *Field classes. I would imagine the 'scores' field isn't even on the table in the DB, since the field classes are what defines all of that, and what gets saved to the DB, among other things.\n"
] | [
6
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004189700_django_python.txt |
Q:
Python: RE vs. Query
I am building a website using Django, and this website uses blocks which are enabled for a certain page.
Right now I use a textfield containing paths were a block is enabled. When a page is requested, Django retrieves all blocks from database and does re.search on the TextField.
However, I was wondering if it is not a better idea to use a separate DB table for block/paths, were each row contains a single path and reference to a block, in terms of overhead.
A:
A seperate DB table is definitely the "right" way to do it, because mysql has to send all the data from your TEXT fields every time you query. As you add more rows and the TEXT fields get bigger, you'll start to notice performance issues and eventually crash the server. Also, you'll be able to use VARCHAR and add a unique index to the paths, making lookups lightning fast.
A:
I am not exactly familiar with Django, but if I am understanding the situation correctly, you should use a table.
In fact this is exactly the kind of use that DB software is designed and optimized for.
No worries. It will actually be faster.
By doing the search yourself, you are trying to implement part of the DB logic on your own. Fun, certainly, but not so fast. :)
Here are some nice links on designing a database:
http://dev.mysql.com/tech-resources/articles/intro-to-normalization.html
http://en.wikipedia.org/wiki/Third_normal_form
Hope this helps. Good luck. :-)
| Python: RE vs. Query | I am building a website using Django, and this website uses blocks which are enabled for a certain page.
Right now I use a textfield containing paths were a block is enabled. When a page is requested, Django retrieves all blocks from database and does re.search on the TextField.
However, I was wondering if it is not a better idea to use a separate DB table for block/paths, were each row contains a single path and reference to a block, in terms of overhead.
| [
"A seperate DB table is definitely the \"right\" way to do it, because mysql has to send all the data from your TEXT fields every time you query. As you add more rows and the TEXT fields get bigger, you'll start to notice performance issues and eventually crash the server. Also, you'll be able to use VARCHAR and ad... | [
2,
1
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0004183554_django_mysql_python.txt |
Q:
Python SQL DB string literals and escaping
Anyone know if the MySQLdb will automatically escape string literals for SQL statements?
For instance I am trying to execute the following:
cursor.execute("""SELECT * FROM `accounts` WHERE `account_name` = 'Blah'""")
Will this escape the account name automatically? Or will it only escape if I do the following?:
x = 'Blah'
cursor.execute("""SELECT * FROM `accounts` WHERE `account_name` = %s""", (x))
Or will it do it for both? Can anyone clarify this as I can't find any information on it.
A:
There is no escaping in the first example, it is a raw SQL query. It's valid, it'll work, but obviously it only makes sense if you always want to search for account Blah.
When you need to get an account from a name in a variable, you will need the parameterised version. However your example may not work as expected as (x) isn't a tuple, it's just the value x. x in a tuple sequence would be (x,). To avoid confusion you may prefer to use the list [x].
A:
Escaping is only done when you give the query and data to MySQLdb separately. That's how it knows what to escape. :-)
Thus, only your 2nd example will escape:
x = ('Blah',)
cursor.execute("""SELECT * FROM `accounts` WHERE `account_name` = %s""", x)
Note how I changed x to to tuple. That is what MySQLdb expects. It sort of makes sense since you may need to pass in multiple variables. Like:
x = ('Blah','Foo23')
cursor.execute("""SELECT * FROM `accounts` WHERE `account_name` = %s OR `account_code` = %s""", x)
Let me know if this answers your question.
Good Luck. :-)
| Python SQL DB string literals and escaping | Anyone know if the MySQLdb will automatically escape string literals for SQL statements?
For instance I am trying to execute the following:
cursor.execute("""SELECT * FROM `accounts` WHERE `account_name` = 'Blah'""")
Will this escape the account name automatically? Or will it only escape if I do the following?:
x = 'Blah'
cursor.execute("""SELECT * FROM `accounts` WHERE `account_name` = %s""", (x))
Or will it do it for both? Can anyone clarify this as I can't find any information on it.
| [
"There is no escaping in the first example, it is a raw SQL query. It's valid, it'll work, but obviously it only makes sense if you always want to search for account Blah.\nWhen you need to get an account from a name in a variable, you will need the parameterised version. However your example may not work as expect... | [
2,
1
] | [] | [] | [
"literals",
"mysql",
"python",
"sql",
"string"
] | stackoverflow_0004189808_literals_mysql_python_sql_string.txt |
Q:
What does [:] do?
return self.var[:]
What will that return?
A:
Python permits you to "slice" various container types; this is a shorthand notation for taking some subcollection of an ordered collection. For instance, if you have a list
foo = [1,2,3,4,5]
and you want the second, third, and fourth elements, you can do:
foo[1:4]
If you omit one of the numbers in the slice, it defaults to the start of the list. So for instance
foo[1:] == [2,3,4,5]
foo[:4] == [1,2,3,4]
Naturally, if you omit both numbers in the slice you will get the entire list back! However, you will get a copy of the list instead of the original; in fact, this is the standard notation for copying a list. Note the difference:
>>> a = [1,2,3,4]
>>> b = a
>>> b.append(5)
>>> a
[1, 2, 3, 4, 5]
>>>
>>> a = [1,2,3,4]
>>> b = a[:]
>>> b.append(5)
>>> a
[1, 2, 3, 4]
This occurs because b = a tells b to point to the same object as a, so appending to b is the same as appending to a. Copying the list a avoids this. Notice that this only runs one level of indirection deep -- if a contained a list, say, and you appended to that list in b, you would still change a.
By the way, there is an optional third argument to the slice, which is a step parameter -- it lets you move through the list in jumps of greater than 1. So you could write range(100)[0::2] for all the even numbers up to 100.
A:
If self.var is a mutable sequence, it will return a shallow copy of that sequence.
If self.var is an immutable built-in sequence such as a string or a tuple, most implementations will return self.var itself.
A:
That will create a shallow copy of the list, and return it.
"Shallow copy", as opposed to "deep copy", means the list will only create new copies of the references in it, not the actual objects. That is, a new list with the same object references will be created, but the objects themselves will remain the same.
If you remove an item from the original the new list won't be affected, but if you alter one of the elements inside the original list (by calling a method or setting an object property, for example), the element will also change on the new list, because although they are different lists, they point to the same objects.
A:
It's called list slicing:
[from:to:skip]
[from:to]
So if I say:
list = range(20)
print list[1:3] #returns [2, 3]
print list[1:12:3] #returns [2, 5, 8, 11]
print list[14:] #because theres no end: [15, 16, 17, 18, 19]
print list[14:-2] #-2 from the end: [15, 16, 17]
A:
you can use the operators with a list the following ways:
list=[1,2,3,4,5,6,7,8,9]
with a single : in the middle of the brackets you define the range from which position to what position to choose (starting position is 0. so I have the following options
list[0:3] shows [1,2,3], cause it starts from the position of the first number and it ends on the position previous to the second number
list[:3] shows the same than before, the first number is absent so there is no beginning limit
list[5:] shows the list from the fifth position to the end [6,7,8,9]
Now if x or y from list[x,y] is negative then it starts if is x from the x position and if it is y it ends from len(list)-2 position
For example: list[-1:3]= [2,3]
Now you can have 2 : like [x:y:z] here x indicates the starting cell, y the last cell (which is not included in the range returned) and z the step at which the sequence advances
list[0:5:2]=[0,2,4]
| What does [:] do? | return self.var[:]
What will that return?
| [
"Python permits you to \"slice\" various container types; this is a shorthand notation for taking some subcollection of an ordered collection. For instance, if you have a list\nfoo = [1,2,3,4,5]\n\nand you want the second, third, and fourth elements, you can do:\nfoo[1:4]\n\nIf you omit one of the numbers in the sl... | [
9,
5,
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004189446_python.txt |
Q:
Python script opening a bash prompt terminating the script
I want to write a chroot wrapper in python. The script will be copying some files, setting up some other stuff and then executing chroot and should land me in a chroot shell.
The tricky part is that I want no python processes running after I am in the chroot.
In other words, python should do the setup work, call chroot and terminate itself, leaving me in a chroot shell. When I exit the chroot, I should be in a directory where I was when I invoked the python script.
Is this possible?
A:
My first thought would be to use one of the os.exec* functions. These will replace the Python process with the chroot process (or whatever you decide to run with exec*).
# ... do setup work
os.execl('/bin/chroot', '/bin/chroot', directory_name, shell_path)
(or something like that)
A:
Alternatively, you can use a new thread for the popen command to avoid blocking the main code then pass the command results back.
import popen2
import time
result = '!'
running = False
class pinger(threading.Thread):
def __init__(self,num,who):
self.num = num
self.who = who
threading.Thread.__init__(self)
def run(self):
global result
cmd = "ping -n %s %s"%(self.num,self.who)
fin,fout = popen2.popen4(cmd)
while running:
result = fin.readline()
if not result:
break
fin.close()
if __name__ == "__main__":
running = True
ping = pinger(5,"127.0.0.1")
ping.start()
now = time.time()
end = now+300
old = result
while True:
if result != old:
print result.strip()
old = result
if time.time() > end:
print "Timeout"
running = False
break
if not result:
print "Finished"
break
| Python script opening a bash prompt terminating the script | I want to write a chroot wrapper in python. The script will be copying some files, setting up some other stuff and then executing chroot and should land me in a chroot shell.
The tricky part is that I want no python processes running after I am in the chroot.
In other words, python should do the setup work, call chroot and terminate itself, leaving me in a chroot shell. When I exit the chroot, I should be in a directory where I was when I invoked the python script.
Is this possible?
| [
"My first thought would be to use one of the os.exec* functions. These will replace the Python process with the chroot process (or whatever you decide to run with exec*).\n# ... do setup work\nos.execl('/bin/chroot', '/bin/chroot', directory_name, shell_path)\n\n(or something like that)\n",
"Alternatively, you ca... | [
2,
0
] | [] | [] | [
"bash",
"chroot",
"process",
"python",
"terminate"
] | stackoverflow_0004189878_bash_chroot_process_python_terminate.txt |
Q:
Why does Sqlite tell me no such column exists when I plainly created it?
in Python 2.6.5 with sqlite3.version 2.4.1, I use the following code:
c = conn.cursor()
# Create table
c.execute('''create table stocks
(date text, trans text, symbol text,
qty real, price real)''')
# Insert a row of data
c.execute("""insert into stocks
values ('2006-01-05','BUY','RHAT',100,35.14)""")
# Save (commit) the changes
conn.commit()
c.execute('''insert into stocks values(date=?, trans=?, symbol=?, qty=?, price=?
)''', ('08-26-1984', 'SELL', 'GOGL', 3, 400.00))
# We can also close the cursor
if we are done with it
c.close()
And it throws an error:
Traceback (most recent call last):
File "dbtest.py", line 18, in <module>
c.execute('''insert into stocks values(date=?, trans=?, symbol=?, qty=?, price=?)''', ('08-26-1984', 'SELL', 'GOGL', 3, 400.00))
sqlite3.OperationalError: no such column: date
My question - what the heck??? I created a column with the name "date"! I've spend the last two hours trying to figure out what in the world is wrong and I'm getting really frustrated. Also, when I try to open it by command line, I'm told:
Unable to open database "orders": file
is encrypted or is not a database
ANY help would be greatly appreciated as I'm about to put my computer through a wall.
Thanks!
A:
Incorrect syntax for that insert statement. This will work:
>>> c.execute('''insert into stocks
(date, trans, symbol, qty, price)values(?,?,?,?,?)''',
('08-26-1984', 'SELL', 'GOGL', 3, 400.00))
| Why does Sqlite tell me no such column exists when I plainly created it? | in Python 2.6.5 with sqlite3.version 2.4.1, I use the following code:
c = conn.cursor()
# Create table
c.execute('''create table stocks
(date text, trans text, symbol text,
qty real, price real)''')
# Insert a row of data
c.execute("""insert into stocks
values ('2006-01-05','BUY','RHAT',100,35.14)""")
# Save (commit) the changes
conn.commit()
c.execute('''insert into stocks values(date=?, trans=?, symbol=?, qty=?, price=?
)''', ('08-26-1984', 'SELL', 'GOGL', 3, 400.00))
# We can also close the cursor
if we are done with it
c.close()
And it throws an error:
Traceback (most recent call last):
File "dbtest.py", line 18, in <module>
c.execute('''insert into stocks values(date=?, trans=?, symbol=?, qty=?, price=?)''', ('08-26-1984', 'SELL', 'GOGL', 3, 400.00))
sqlite3.OperationalError: no such column: date
My question - what the heck??? I created a column with the name "date"! I've spend the last two hours trying to figure out what in the world is wrong and I'm getting really frustrated. Also, when I try to open it by command line, I'm told:
Unable to open database "orders": file
is encrypted or is not a database
ANY help would be greatly appreciated as I'm about to put my computer through a wall.
Thanks!
| [
"Incorrect syntax for that insert statement. This will work:\n>>> c.execute('''insert into stocks \n (date, trans, symbol, qty, price)values(?,?,?,?,?)''', \n ('08-26-1984', 'SELL', 'GOGL', 3, 400.00))\n\n"
] | [
8
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0004190476_python_sqlite.txt |
Q:
python: how to create persistent in-memory structure for debugging
[Python 3.1]
My program takes a long time to run just because of the pickle.load method on a huge data structure. This makes debugging very annoying and time-consuming: every time I make a small change, I need to wait for a few minutes to see if the regression tests passed.
I would like replace pickle with an in-memory data structure.
I thought of starting a python program in one process, and connecting to it from another; but I am afraid the inter-process communication overhead will be huge.
Perhaps I could run a python function from the interpreter to load the structure in memory. Then as I modify the rest of the program, I can run it many times (without exiting the interpreter in between). This seems like it would work, but I'm not sure if I will suffer any overhead or other problems.
A:
You can use mmap to open a view on the same file in multiple processes, with access at almost the speed of memory once the file is loaded.
A:
First you can pickle different parts of the hole object using this method:
# gen_objects.py
import random
import pickle
class BigBadObject(object):
def __init__(self):
self.a_dictionary={}
for x in xrange(random.randint(1, 1000)):
self.a_dictionary[random.randint(1,98675676)]=random.random()
self.a_list=[]
for x in xrange(random.randint(1000, 10000)):
self.a_list.append(random.random())
self.a_string=''.join([chr(random.randint(65, 90))
for x in xrange(random.randint(100, 10000))])
if __name__=="__main__":
output=open('lotsa_objects.pickled', 'wb')
for i in xrange(10000):
pickle.dump(BigBadObject(), output, pickle.HIGHEST_PROTOCOL)
output.close()
Once you generated the BigFile in various separate parts you can read it with a python program with several running at the same time reading each one different parts.
# reader.py
from threading import Thread
from Queue import Queue, Empty
import cPickle as pickle
import time
import operator
from gen_objects import BigBadObject
class Reader(Thread):
def __init__(self, filename, q):
Thread.__init__(self, target=None)
self._file=open(filename, 'rb')
self._queue=q
def run(self):
while True:
try:
one_object=pickle.load(self._file)
except EOFError:
break
self._queue.put(one_object)
class uncached(object):
def __init__(self, filename, queue_size=100):
self._my_queue=Queue(maxsize=queue_size)
self._my_reader=Reader(filename, self._my_queue)
self._my_reader.start()
def __iter__(self):
while True:
if not self._my_reader.is_alive():
break
# Loop until we get something or the thread is done processing.
try:
print "Getting from the queue. Queue size=", self._my_queue.qsize()
o=self._my_queue.get(True, timeout=0.1) # Block for 0.1 seconds
yield o
except Empty:
pass
return
# Compute an average of all the numbers in a_lists, just for show.
list_avg=0.0
list_count=0
for x in uncached('lotsa_objects.pickled'):
list_avg+=reduce(operator.add, x.a_list)
list_count+=len(x.a_list)
print "Average: ", list_avg/list_count
This way of reading the pickle file will take 1% of the time it takes in the other way. This is because you are running 100 parallel threads at the same time.
| python: how to create persistent in-memory structure for debugging | [Python 3.1]
My program takes a long time to run just because of the pickle.load method on a huge data structure. This makes debugging very annoying and time-consuming: every time I make a small change, I need to wait for a few minutes to see if the regression tests passed.
I would like replace pickle with an in-memory data structure.
I thought of starting a python program in one process, and connecting to it from another; but I am afraid the inter-process communication overhead will be huge.
Perhaps I could run a python function from the interpreter to load the structure in memory. Then as I modify the rest of the program, I can run it many times (without exiting the interpreter in between). This seems like it would work, but I'm not sure if I will suffer any overhead or other problems.
| [
"You can use mmap to open a view on the same file in multiple processes, with access at almost the speed of memory once the file is loaded.\n",
"First you can pickle different parts of the hole object using this method:\n# gen_objects.py\n\nimport random\nimport pickle\n\nclass BigBadObject(object):\n def __ini... | [
1,
0
] | [] | [] | [
"debugging",
"persistence",
"python",
"python_3.x"
] | stackoverflow_0004189721_debugging_persistence_python_python_3.x.txt |
Q:
Accessing the name that an object being created is assigned to
I'm writing some code to determine the name that an object is assigned to. This is for general debugging work and to further familiarize myself with python internals.
I have it structured as a class decorator so that all instances of that class will have their names recorded if it is possible to do. The code is fairly long so I won't post it unless asked. The general technique is as follows though
decorate the class' __init__ method with the code to do what I want
set caller = inspect.currentframe().f_back and open inspect.getframeinfo(caller).filename and send it to ast.parse. I don't do any error checking here because (1) this is just for debugging/profiling/hacking (2) this exact process was 'just' completed or the code wouldn't be running. Is there a problem with this?
find the ast.Assignment instance that causes the currently executing __init__ method to run
if len(assignment.targets) == 1 then there is only one item on the left hand side, and I can get the name out of targets[0].id. In a simple form like a = Foo(), then the assignment.value is an instance of ast.Call. if it's a literal (e.g. list), then value will be that list and bail because the object I'm interested in isn't being assigned to a name.
What is the best way to confirm that assignment.value.func is in fact type(obj).__call__ of the object that I'm interested in. I'm pretty sure that I'm guaranteed that It's "in there somewhere" or the code wouldn't even be running. I just need for it to be at the top level. The obvious thing to do is walk it and make sure that it doesn't contain any interior calls. Then I'm guaranteed that I have the name. (My reasoning is correct, I'm not sure if its assumptions are). This is not ideal though because if I'm interested in Foo, this could lead me to toss away a = Foo(Bar()) because I don't know if it's a = Bar(Foo()).
Of course I can just check assignment.value.func.id but then somebody could have done Foobar = Foo or something so I don't want to rely on this too heavily
Any help would be greatly appreciated. As always, I'm interested in any other suggestions or problems that I might be overlooking.
Also, I'm really surprised that I just had to invent the 'python-internals' tag.
A:
The AST can't give you that answer. Try using frame.f_lasti and then peeking into the bytecode. If the next line isn't a STORE_FAST, you've got interior calls or something else
going on other than the simple assignment you're looking for.
def f():
f = sys._getframe()
i = f.f_lasti + 3 # capture current point of execution, advance to expected store
print dis.disco(f.f_code, i)
A:
I don't know of how much help this is, but have you considered using the call to locals()? It returns a dict that contains the name and value of all the local variables.
For example:
s = ''
locals()
>>> {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 's': '', '__name__': '__main__', '__doc__': None}
t = s # I think this is what is of most importance to you
locals()
>>> {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 's': '', 't': '', '__name__': '__main__', '__doc__': None}
So you could traverse this dictionary and check which variables have (as their value) an object of the type that you are looking for.
Like I said, I don't know of how much help this answer is, but if you need clarification on anything, then do leave a comment and I will try to respond as best as I can.
A:
I don't do any error checking here because (1) this is just for debugging/profiling/hacking (2) this exact process was 'just' completed or the code wouldn't be running. Is there a problem with this?
Yes:
Start a program
Wait unit it imports a particular module foo.py
Edit foo.py
Now code that's loaded in a Python process doesn't match code found on disk.
Yet another reason why disassembling the bytecode may be a better technique.
A:
Here's how it's done. Much thanks to the anonymous clue giver. Much luck in your quest to rack up rep for your alt account.
import inspect
import opcode
def get_name(f):
"""Gets the name that the return value of a function is
assigned to.
This could be modified for classes as well. This is a
basic version for illustration that only prints out
the assignment instead of trying to do anything with it.
A more flexible way would be to pass it a callback for when
it identified an assignment.
It does nothing for assignment to attributes. The solution
for that isn't much more complicated though. If the
instruction after the function call is a a `LOAD_GLOBAL`,
`LOAD_FAST` or `LOAD_DEREF`, then it should be followed by
a chain of `LOAD_ATTR`'s. The last one is the attribute
assigned to.
"""
def inner(*args, **kwargs):
name = None
frame = inspect.currentframe().f_back
i = frame.f_lasti + 3
# get the name if it exists
code = frame.f_code
instr = ord(code.co_code[i])
arg = ord(code.co_code[i+1]) # no extended arg here.
if instr == opcode.opmap['STORE_FAST']:
name = code.co_varnames[arg]
elif instr in (opcode.opmap['STORE_GLOBAL'],
opcode.opmap['STORE_NAME']):
name = code.co_names[arg]
elif instr == opcode.opmap['STORE_DEREF']:
try:
name = code.co_cellvars[arg]
except IndexError:
name = code.co_freevars[arg - len(code.co_cellvars)]
ret = f(*args, **kwargs)
print opcode.opname[instr]
if name:
print "{0} = {1}".format(name, ret)
return ret
return inner
@get_name
def square(x):
return x**2
def test_local():
x = square(2)
def test_deref():
x = square(2)
def closure():
y = x
return closure
x = square(2)
test_local()
test_deref()()
It shouldn't be too hard to figure out assignments of the for list_[i] = foo() either, including the value of i by using frame.f_locals. The tricky ones are going to be literals and when it's passed as an argument. Both of those cases should be pretty challenging.
| Accessing the name that an object being created is assigned to | I'm writing some code to determine the name that an object is assigned to. This is for general debugging work and to further familiarize myself with python internals.
I have it structured as a class decorator so that all instances of that class will have their names recorded if it is possible to do. The code is fairly long so I won't post it unless asked. The general technique is as follows though
decorate the class' __init__ method with the code to do what I want
set caller = inspect.currentframe().f_back and open inspect.getframeinfo(caller).filename and send it to ast.parse. I don't do any error checking here because (1) this is just for debugging/profiling/hacking (2) this exact process was 'just' completed or the code wouldn't be running. Is there a problem with this?
find the ast.Assignment instance that causes the currently executing __init__ method to run
if len(assignment.targets) == 1 then there is only one item on the left hand side, and I can get the name out of targets[0].id. In a simple form like a = Foo(), then the assignment.value is an instance of ast.Call. if it's a literal (e.g. list), then value will be that list and bail because the object I'm interested in isn't being assigned to a name.
What is the best way to confirm that assignment.value.func is in fact type(obj).__call__ of the object that I'm interested in. I'm pretty sure that I'm guaranteed that It's "in there somewhere" or the code wouldn't even be running. I just need for it to be at the top level. The obvious thing to do is walk it and make sure that it doesn't contain any interior calls. Then I'm guaranteed that I have the name. (My reasoning is correct, I'm not sure if its assumptions are). This is not ideal though because if I'm interested in Foo, this could lead me to toss away a = Foo(Bar()) because I don't know if it's a = Bar(Foo()).
Of course I can just check assignment.value.func.id but then somebody could have done Foobar = Foo or something so I don't want to rely on this too heavily
Any help would be greatly appreciated. As always, I'm interested in any other suggestions or problems that I might be overlooking.
Also, I'm really surprised that I just had to invent the 'python-internals' tag.
| [
"The AST can't give you that answer. Try using frame.f_lasti and then peeking into the bytecode. If the next line isn't a STORE_FAST, you've got interior calls or something else\ngoing on other than the simple assignment you're looking for.\ndef f():\n f = sys._getframe()\n i = f.f_lasti + 3 # capture current p... | [
2,
0,
0,
0
] | [] | [] | [
"python",
"python_internals"
] | stackoverflow_0003744792_python_python_internals.txt |
Q:
How to fix a Python elif?
Okay I have the below code performing something I don't want it to do. If you run the program it will ask you "How are you?" (obviously), but when you give a answer to the question that applies to the elif statement, I still get a if statement response. Why is this?
talk = raw_input("How are you?")
if "good" or "fine" in talk:
print "Glad to here it..."
elif "bad" or "sad" or "terrible" in talk:
print "I'm sorry to hear that!"
A:
The problem is that the or operator does not do what you want here. What you're really saying is if the value of "good" is True or "fine" is in talk. The value of "good" is always True, since it's a non-empty string, which is why that branch always gets executed.
A:
if "good" in talk or "fine" in talk is what you meant. What you wrote is equivalent to if "good" or ("fine" in talk).
A:
talk = raw_input("How are you?")
if any(x in talk for x in ("good", "fine")):
print "Glad to here it..."
elif any(x in talk for x in ("bad", "sad", "terrible")):
print "I'm sorry to hear that!"
Note:
In [46]: "good" or "fine" in "I'm feeling blue"
Out[46]: 'good'
Python is grouping the condition like this:
("good") or ("fine" in "I'm feeling blue")
In terms of boolean values, that's equivalent to:
True or False
which is equal to
True
That's why the if-block is always getting executed.
A:
Use a regular expression. What if the input is "I'm good. Well, i'm more fine. Sorry, i feel terrible, my bad."
Then you'll have all conditions fulfilled and the output won't be what you expect.
A:
You have to test each string separately, or test for inclusion in a list or tuple.
In your code, Python will take the value of your strings and test them for truth ("good"',"bad"' and "sad"' will returnTrue' as they're not empty), and then it will check if `"fine"' is in the characters of talk (because of the way the in operator works with strings).
You should do something like this:
talk = raw_input("How are you?")
if talk in ("good", "fine"):
print "Glad to here it..."
elif talk in ("bad", "sad", "terrible"):
print "I'm sorry to hear that!"
A:
This worked for me:
talk = raw_input("How are you? ")
words = re.split("\\s+", talk)
if 'fine' in words:
print "Glad to hear it..."
elif 'terrible' in words:
print "I'm sorry to hear that!"
else:
print "Huh?"
From reading the other answers, we'd have to expand the predicates for other words.
| How to fix a Python elif? | Okay I have the below code performing something I don't want it to do. If you run the program it will ask you "How are you?" (obviously), but when you give a answer to the question that applies to the elif statement, I still get a if statement response. Why is this?
talk = raw_input("How are you?")
if "good" or "fine" in talk:
print "Glad to here it..."
elif "bad" or "sad" or "terrible" in talk:
print "I'm sorry to hear that!"
| [
"The problem is that the or operator does not do what you want here. What you're really saying is if the value of \"good\" is True or \"fine\" is in talk. The value of \"good\" is always True, since it's a non-empty string, which is why that branch always gets executed.\n",
"if \"good\" in talk or \"fine\" in tal... | [
8,
4,
2,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004190701_python.txt |
Q:
Fixing an Or Statement With Variables
How would I change the below code so Python reads the list which is inside the two variables and then perform an action after that without reeving an error? My code:
bad = ['bad','terrible', 'dumb']
good = ['good','happy','awesome']
talk = raw_input("type:")
if (bad) in talk:
print "I'm sorry to hear that :("
elif (good) in talk:
print "That's good!"
A:
Try this:
bad = set(['bad','terrible', 'dumb'])
good = set(['good','happy','awesome'])
talk = raw_input("type:")
if bad & set(talk.lower().split()):
print "I'm sorry to hear that :("
elif good & set(talk.lower().split()):
print "That's good!"
A:
Does this get you what you want?
bad = ['bad','terrible', 'dumb']
good = ['good','happy','awesome']
talk = raw_input("type:")
talk_list = talk.lower().split()
is_bad = any(w in bad for w in talk_list)
is_good = any(w in good for w in talk_list)
if is_bad:
print "I'm sorry to hear that :("
elif is_good:
print "That's good!"
A:
Use for loop and apply the same logic for 'good' too.
for badStr in bad:
if badStr in talk:
print "I'm sorry to hear that :("
break
for goodStr in good:
if goodStr in talk:
print "That's good!"
break
| Fixing an Or Statement With Variables | How would I change the below code so Python reads the list which is inside the two variables and then perform an action after that without reeving an error? My code:
bad = ['bad','terrible', 'dumb']
good = ['good','happy','awesome']
talk = raw_input("type:")
if (bad) in talk:
print "I'm sorry to hear that :("
elif (good) in talk:
print "That's good!"
| [
"Try this:\nbad = set(['bad','terrible', 'dumb'])\ngood = set(['good','happy','awesome'])\ntalk = raw_input(\"type:\")\nif bad & set(talk.lower().split()):\n print \"I'm sorry to hear that :(\"\nelif good & set(talk.lower().split()):\n print \"That's good!\"\n\n",
"Does this get you what you want?\nbad = ... | [
6,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004190841_python.txt |
Q:
Tracing Python warnings/errors to a line number in numpy and scipy
I am getting the error:
Warning: invalid value encountered in log
From Python and I believe the error is thrown by numpy (using version 1.5.0). However, since I am calling the "log" function in several places, I'm not sure where the error is coming from. Is there a way to get numpy to print the line number that generated this error?
I assume the warning is caused by taking the log of a number that is small enough to be rounded to 0 or smaller (negative). Is that right? What is the usual origin of these warnings?
A:
Putting np.seterr(invalid='raise') in your code (before the errant log call)
will cause numpy to raise an exception instead of issuing a warning.
That will give you a traceback error message and tell you the line Python was executing when the error occurred.
A:
If you have access to the numpy source, you should be able to find the line that prints that warning (using grep, etc) and edit the corresponding file to force an error (using an assertion, for example) when an invalid value is passed. That will give you a stack trace pointing to the place in your code that called log with the improper value.
I had a brief look in my numpy source, and couldn't find anything that matches the warning you described though (my version of numpy is older than yours, though).
>>> import numpy
>>> numpy.log(0)
-inf
>>> numpy.__version__
'1.3.0'
Is it possible that you're calling some other log function that isn't in numpy? For example, here is one that actually throws an exception when given invalid input.
>>> import math
>>> math.log(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
| Tracing Python warnings/errors to a line number in numpy and scipy | I am getting the error:
Warning: invalid value encountered in log
From Python and I believe the error is thrown by numpy (using version 1.5.0). However, since I am calling the "log" function in several places, I'm not sure where the error is coming from. Is there a way to get numpy to print the line number that generated this error?
I assume the warning is caused by taking the log of a number that is small enough to be rounded to 0 or smaller (negative). Is that right? What is the usual origin of these warnings?
| [
"Putting np.seterr(invalid='raise') in your code (before the errant log call)\nwill cause numpy to raise an exception instead of issuing a warning.\nThat will give you a traceback error message and tell you the line Python was executing when the error occurred.\n",
"If you have access to the numpy source, you sho... | [
22,
0
] | [] | [] | [
"numeric",
"numpy",
"python",
"scientific_computing",
"scipy"
] | stackoverflow_0004190817_numeric_numpy_python_scientific_computing_scipy.txt |
Q:
Python: open and display a text file at a specific line
I don't use Python very often, but I sometimes develop simple tools in it to make my life easier. My most frequently used is a log checker/crude debugger for SAS. It reads the SAS log line by line checking for any errors in my list and dumps anything it finds into standard out (I'm running Python 2.6 in a RedHat Linux environment) - along with the error, it prints the line number of that error (not that that's super useful).
What I'd really like to do is to optionally feed the script a line number and have it open the SAS log itself in GVIM and display it scrolled down to the line number I've specified. I haven't had any luck finding a way to do this - I've looked pretty thoroughly on Google to no avail. Any ideas would be greatly appreciated. Thanks!
Jeremy
A:
Once you've got the line number, you can run gvim filename -c 12 and it will go to line 12 (this is because -c <command> is "Execute <command> after loading the first file", so -c 12 is just saying run :12 after loading the file).
So I'm not sure if you really need Python at all in this case; just sending the line number direct to gvim may be all you need.
A:
If you want line 10
>>> f = open('thefile.log')
>>> lines = f.readlines()
>>> lines[10]
Or all at once
>>> open('thefile.log').readlines()[10]
Open in gvim
>>> import subprocess
>>> subprocess.call(['gvim', '-c', '10', 'thefile.log'])
A:
Depending on how frequently you inspect these logs and how noisy they are, it may be worth your time to put together an errorformat so you can use Vim's quickfix list to quickly jump between errors.
| Python: open and display a text file at a specific line | I don't use Python very often, but I sometimes develop simple tools in it to make my life easier. My most frequently used is a log checker/crude debugger for SAS. It reads the SAS log line by line checking for any errors in my list and dumps anything it finds into standard out (I'm running Python 2.6 in a RedHat Linux environment) - along with the error, it prints the line number of that error (not that that's super useful).
What I'd really like to do is to optionally feed the script a line number and have it open the SAS log itself in GVIM and display it scrolled down to the line number I've specified. I haven't had any luck finding a way to do this - I've looked pretty thoroughly on Google to no avail. Any ideas would be greatly appreciated. Thanks!
Jeremy
| [
"Once you've got the line number, you can run gvim filename -c 12 and it will go to line 12 (this is because -c <command> is \"Execute <command> after loading the first file\", so -c 12 is just saying run :12 after loading the file).\nSo I'm not sure if you really need Python at all in this case; just sending the l... | [
3,
2,
1
] | [] | [] | [
"python",
"vim"
] | stackoverflow_0004190695_python_vim.txt |
Q:
Is there a Ruby site like this python.mirocommunity.org (python)?
Is there a Ruby site like this http://python.mirocommunity.org (python videos). This is a great Python site, love to find a equivalent RUBY site any ideas? Maybe someone should start one?
Thankyou in advance ;-)
A:
For Rails this site is very popular: http://railscasts.com/
A:
Something like those:
http://rubyreflector.com/
http://rubycorner.com/
A:
Not as organized as "http://python.mirocommunity.org" but you may find this useful
http://confreaks.net/events
| Is there a Ruby site like this python.mirocommunity.org (python)? | Is there a Ruby site like this http://python.mirocommunity.org (python videos). This is a great Python site, love to find a equivalent RUBY site any ideas? Maybe someone should start one?
Thankyou in advance ;-)
| [
"For Rails this site is very popular: http://railscasts.com/\n",
"Something like those:\n\nhttp://rubyreflector.com/\nhttp://rubycorner.com/\n\n",
"Not as organized as \"http://python.mirocommunity.org\" but you may find this useful\n\nhttp://confreaks.net/events\n\n"
] | [
3,
1,
1
] | [] | [] | [
"jruby",
"python",
"ruby",
"ruby_on_rails",
"rubygems"
] | stackoverflow_0004185063_jruby_python_ruby_ruby_on_rails_rubygems.txt |
Q:
Python xml etree DTD from a StringIO source?
I'm adapting the following code (created via advice in this question), that took an XML file and it's DTD and converted them to a different format. For this problem only the loading section is important:
xmldoc = open(filename)
parser = etree.XMLParser(dtd_validation=True, load_dtd=True)
tree = etree.parse(xmldoc, parser)
This worked fine, whilst using the file system, but I'm converting it to run via a web framework, where the two files are loaded via a form.
Loading the xml file works fine:
tree = etree.parse(StringIO(data['xml_file'])
But as the DTD is linked to in the top of the xml file, the following statement fails:
parser = etree.XMLParser(dtd_validation=True, load_dtd=True)
tree = etree.parse(StringIO(data['xml_file'], parser)
Via this question, I tried:
etree.DTD(StringIO(data['dtd_file'])
tree = etree.parse(StringIO(data['xml_file'])
Whilst the first line doesn't cause an error, the second falls over on unicode entities the DTD is meant to pick up (and does so in the file system version):
XMLSyntaxError: Entity 'eacute' not
defined, line 4495, column 46
How do I go about correctly loading this DTD?
A:
Here's a short but complete example, using the custom resolver technique @Steven mentioned.
from StringIO import StringIO
from lxml import etree
data = dict(
xml_file = '''<?xml version="1.0"?>
<!DOCTYPE x SYSTEM "a.dtd">
<x><y>ézz</y></x>
''',
dtd_file = '''<!ENTITY eacute "é">
<!ELEMENT x (y)>
<!ELEMENT y (#PCDATA)>
''')
class DTDResolver(etree.Resolver):
def resolve(self, url, id, context):
return self.resolve_string(data['dtd_file'], context)
xmldoc = StringIO(data['xml_file'])
parser = etree.XMLParser(dtd_validation=True, load_dtd=True)
parser.resolvers.add(DTDResolver())
try:
tree = etree.parse(xmldoc, parser)
except etree.XMLSyntaxError as e:
# handle xml and validation errors
A:
You could probably use a custom resolver. The docs actually give an example of doing this to provide a dtd.
| Python xml etree DTD from a StringIO source? | I'm adapting the following code (created via advice in this question), that took an XML file and it's DTD and converted them to a different format. For this problem only the loading section is important:
xmldoc = open(filename)
parser = etree.XMLParser(dtd_validation=True, load_dtd=True)
tree = etree.parse(xmldoc, parser)
This worked fine, whilst using the file system, but I'm converting it to run via a web framework, where the two files are loaded via a form.
Loading the xml file works fine:
tree = etree.parse(StringIO(data['xml_file'])
But as the DTD is linked to in the top of the xml file, the following statement fails:
parser = etree.XMLParser(dtd_validation=True, load_dtd=True)
tree = etree.parse(StringIO(data['xml_file'], parser)
Via this question, I tried:
etree.DTD(StringIO(data['dtd_file'])
tree = etree.parse(StringIO(data['xml_file'])
Whilst the first line doesn't cause an error, the second falls over on unicode entities the DTD is meant to pick up (and does so in the file system version):
XMLSyntaxError: Entity 'eacute' not
defined, line 4495, column 46
How do I go about correctly loading this DTD?
| [
"Here's a short but complete example, using the custom resolver technique @Steven mentioned.\nfrom StringIO import StringIO\nfrom lxml import etree\n\ndata = dict(\n xml_file = '''<?xml version=\"1.0\"?>\n<!DOCTYPE x SYSTEM \"a.dtd\">\n<x><y>ézz</y></x>\n''',\n dtd_file = '''<!ENTITY eacute \"é\">... | [
5,
1
] | [] | [] | [
"dtd",
"lxml",
"python",
"xml"
] | stackoverflow_0003817137_dtd_lxml_python_xml.txt |
Q:
How can I store my atom data so my IRC bot can access it? Should I use SQL at all?
I want to add feeds such as ajaxian, smashingmagazine and store feeds starting today on my server, in order so that I can push the new items to my irc bot so it can echo them in my channel.
I will get ATOM data from this service: http://superfeedr.com/subscriber .. so I'm wondering which of the NoSQL storage mechanisms is ideal for storing ATOM data?
The atom data is xml, so they are documents, so perhaps something like CouchDB is suitable? Or MongoDb/Cassandra/Redis?
I'm aware that there are different kinds of no sql databases such as document oriented vs key/store, but as I don't have much experience I'd appreciate some insight from someone way more experienced. Thanks.
Additional things to consider
These won't be displayed on a website, or any publically viewable URL.
The only way to view them is to either a) wait for the bot to post new ones every hour or b) manually query the bot and give a time range or something like 0,20 and 20,40 through PM on IRC.
I won't really need to scale, I just have 15-20 people in the IRC chat room and only 1-3 people on average would probably query the bot at a given hour.
The bot will spit out new links every hour. The bot will never spit out old links.
A:
I would say that you will have to use the database you are most comfortable with.
Also look at the CAP Theorem to clarify better what exactly you need.
Couple of minutes ago I replied to a similar question. So you can have a look.
A:
I want to store external rss feed data - is this a good reason to use NoSQL?
No
A:
If the content you're storing is natively XML, and you have need to be able to run queries against it (say, using XPath), you might consider a native XML database such as eXist.
That said, it sounds like your needs are basic enough that any halfway-reasonable datastore will do.
| How can I store my atom data so my IRC bot can access it? Should I use SQL at all? | I want to add feeds such as ajaxian, smashingmagazine and store feeds starting today on my server, in order so that I can push the new items to my irc bot so it can echo them in my channel.
I will get ATOM data from this service: http://superfeedr.com/subscriber .. so I'm wondering which of the NoSQL storage mechanisms is ideal for storing ATOM data?
The atom data is xml, so they are documents, so perhaps something like CouchDB is suitable? Or MongoDb/Cassandra/Redis?
I'm aware that there are different kinds of no sql databases such as document oriented vs key/store, but as I don't have much experience I'd appreciate some insight from someone way more experienced. Thanks.
Additional things to consider
These won't be displayed on a website, or any publically viewable URL.
The only way to view them is to either a) wait for the bot to post new ones every hour or b) manually query the bot and give a time range or something like 0,20 and 20,40 through PM on IRC.
I won't really need to scale, I just have 15-20 people in the IRC chat room and only 1-3 people on average would probably query the bot at a given hour.
The bot will spit out new links every hour. The bot will never spit out old links.
| [
"I would say that you will have to use the database you are most comfortable with.\nAlso look at the CAP Theorem to clarify better what exactly you need.\nCouple of minutes ago I replied to a similar question. So you can have a look.\n",
"I want to store external rss feed data - is this a good reason to use NoSQL... | [
0,
0,
0
] | [] | [] | [
"atom_feed",
"nosql",
"python",
"rss",
"sql"
] | stackoverflow_0004189691_atom_feed_nosql_python_rss_sql.txt |
Q:
"Unsupported hash type" error w/ Python 2.6.5 and django framework
My registration form is throwing a ValueError during form.save() in my custom registration form's password field.
Here are the exception details (copied from http://www.pastie.org/1299144):
Environment:
Request Method: POST
Request URL: http://192.168.2.206:8080/register/
Django Version: 1.1.1
Python Version: 2.6.5
Installed Applications:
['django.contrib.auth',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.markup',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.comments',
'mysite.registration',
'mysite.profiles',
'mysite.epw',
'mysite.remember_me',
'mysite.avatar',
'mysite.django_documents',
'mysite.inlines',
'mysite.blog',
'mysite.forum',
'tagging']
Installed Middleware:
('django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'mysite.remember_me.views.AutoLogout')
Traceback:
File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/pymodules/python2.6/django/utils/decorators.py" in _wrapped_view
48. response = view_func(request, *args, **kwargs)
File "/home/karthik/Desktop/EPW_LOCAL/mysite/../mysite/epw/views.py" in register
1538. new_user = form.save(request)
File "/home/karthik/Desktop/EPW_LOCAL/mysite/../mysite/epw/form.py" in save
169. profile_callback=profile_callback)
File "/home/karthik/Desktop/EPW_LOCAL/mysite/../mysite/registration/models.py" in create_inactive_user
110. registration_profile = self.create_profile(new_user)
File "/home/karthik/Desktop/EPW_LOCAL/mysite/../mysite/registration/models.py" in create_profile
145. salt = hashlib.new(str(random.random())).hexdigest()[:5]
File "/usr/lib/python2.6/hashlib.py" in __hash_new
101. return __get_builtin_constructor(name)(string)
File "/usr/lib/python2.6/hashlib.py" in __get_builtin_constructor
80. raise ValueError, "unsupported hash type"
Exception Type: ValueError at /register/
Exception Value: unsupported hash type
pls could any one resolve this.
thanks
A:
It looks like you're trying to implement your own registration framework with it. What's wrong with the existing one? I think you should read more about the Django framework generally and go through the tutorial.
Looking at that traceback, the problem is in the line hashlib.new(str(random.random())).hexdigest()[:5]. (Get familiar with looking at tracebacks and working out what the issue is, you'll find you need to often when you make a mistake.)
help(hashlib.new) shows this:
__hash_new(name, string='')
new(name, string='') - Return a new hashing object using the named algorithm;
optionally initialized with a string.
The "named algorithm" should be md5, sha1, sha256, etc. (See help(hashlib) for the list, and also how you should use e.g. hashlib.md5() instead of hashlib.new('md5').)
A:
haslib.new() expects a hashing algorithm name (e.g. "md5", "sha1" etc.) as the first parameter. You're passing in a random string.
A:
when the password is saving at the time instead of hashlib i use sha cryptographic alog that works fine
| "Unsupported hash type" error w/ Python 2.6.5 and django framework | My registration form is throwing a ValueError during form.save() in my custom registration form's password field.
Here are the exception details (copied from http://www.pastie.org/1299144):
Environment:
Request Method: POST
Request URL: http://192.168.2.206:8080/register/
Django Version: 1.1.1
Python Version: 2.6.5
Installed Applications:
['django.contrib.auth',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.markup',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.comments',
'mysite.registration',
'mysite.profiles',
'mysite.epw',
'mysite.remember_me',
'mysite.avatar',
'mysite.django_documents',
'mysite.inlines',
'mysite.blog',
'mysite.forum',
'tagging']
Installed Middleware:
('django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'mysite.remember_me.views.AutoLogout')
Traceback:
File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/pymodules/python2.6/django/utils/decorators.py" in _wrapped_view
48. response = view_func(request, *args, **kwargs)
File "/home/karthik/Desktop/EPW_LOCAL/mysite/../mysite/epw/views.py" in register
1538. new_user = form.save(request)
File "/home/karthik/Desktop/EPW_LOCAL/mysite/../mysite/epw/form.py" in save
169. profile_callback=profile_callback)
File "/home/karthik/Desktop/EPW_LOCAL/mysite/../mysite/registration/models.py" in create_inactive_user
110. registration_profile = self.create_profile(new_user)
File "/home/karthik/Desktop/EPW_LOCAL/mysite/../mysite/registration/models.py" in create_profile
145. salt = hashlib.new(str(random.random())).hexdigest()[:5]
File "/usr/lib/python2.6/hashlib.py" in __hash_new
101. return __get_builtin_constructor(name)(string)
File "/usr/lib/python2.6/hashlib.py" in __get_builtin_constructor
80. raise ValueError, "unsupported hash type"
Exception Type: ValueError at /register/
Exception Value: unsupported hash type
pls could any one resolve this.
thanks
| [
"It looks like you're trying to implement your own registration framework with it. What's wrong with the existing one? I think you should read more about the Django framework generally and go through the tutorial.\nLooking at that traceback, the problem is in the line hashlib.new(str(random.random())).hexdigest()[:... | [
4,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004183016_django_python.txt |
Q:
python itertools skipping ahead
I have a list of lists. Using itertools, I am basically doing
for result in product([A,B],[C,D],[E,F,G]):
# test each result
and the result is the desired product, with each result containing one element from each of the lists. My code tests each of the results element-by-element, looking for the first (and best) 'good' one. There can be a very very large number to test.
Let's say I'm testing the first result 'ACE'. Let's say when I test the second element 'C' I find that 'ACE' is a bad result. There is no need to test 'ACF' or 'ACG'. I would want to skip from the failed ACE directly to trying ADE. Anyway to do this without just throwing the unwanted results on the floor?
If I was implementing this with nested for loops, I would be trying to manipulate the for loop indexes inside the loop and that would not be very nice ... but I do want to skip testing a lot of results. Can I skip ahead efficiently in itertools?
A:
itertools is not the best way to go with the concern you have.
If you just have 3 sets to combine, just loop over and when you fail, break the loops. (If you code is complex, set a variable and break right outside.
for i1 in [A, B]:
for i2 in [C, D]:
for i3 in [E, F, G]:
if not test(i1, i2, i3):
break
However, if the number of sets that you have is variable, then use a recursive function (backtrack):
inp_sets = ([A,B],[C,D],[E,F,G])
max_col = len(inp_sets)
def generate(col_index, current_set):
if col_index == max_col:
if test(current_set):
return current_set
else:
return None
else:
found = False
for item in inp_sets[col_index]:
res = generate(col_index+1, current_set + [item]):
if res:
return res
elif (col_index == max_col - 1):
# Here we are skipping the rest of the checks for last column
# Change the condition if you want to skip for more columns
return None
result = generate(0, [])
| python itertools skipping ahead | I have a list of lists. Using itertools, I am basically doing
for result in product([A,B],[C,D],[E,F,G]):
# test each result
and the result is the desired product, with each result containing one element from each of the lists. My code tests each of the results element-by-element, looking for the first (and best) 'good' one. There can be a very very large number to test.
Let's say I'm testing the first result 'ACE'. Let's say when I test the second element 'C' I find that 'ACE' is a bad result. There is no need to test 'ACF' or 'ACG'. I would want to skip from the failed ACE directly to trying ADE. Anyway to do this without just throwing the unwanted results on the floor?
If I was implementing this with nested for loops, I would be trying to manipulate the for loop indexes inside the loop and that would not be very nice ... but I do want to skip testing a lot of results. Can I skip ahead efficiently in itertools?
| [
"itertools is not the best way to go with the concern you have.\nIf you just have 3 sets to combine, just loop over and when you fail, break the loops. (If you code is complex, set a variable and break right outside.\nfor i1 in [A, B]:\n for i2 in [C, D]:\n for i3 in [E, F, G]:\n if not test(i1, i2, i... | [
1
] | [] | [] | [
"python",
"python_itertools"
] | stackoverflow_0004190966_python_python_itertools.txt |
Q:
Python string replace for UTF-16-LE file
Python 2.6
Using Python string.replace() seems not working for UTF-16-LE file. I think of 2 ways:
Find a Python module that can handle Unicode string manipulate.
Convert the target Unicode file to ASCII, use string.replace(), then convert it back. But I am worry about this may cause loss data.
Can the community suggest me a good way to solve this? Thanks.
EDIT:
My code looks like this:
infile = open(inputfilename)
for s in infile:
outfile.write(s.replace(targetText, replaceText))
Looks like the for loop can parse the line correct. Did I make any mistakes here?
EDIT2:
I've read the Python Unicode tutorial and tried below code, and get it worked. However, just wondering if there's any better way to do this. Can anyone help? Thanks.
infile = codecs.open(infilename,'r', encoding='utf-16-le')
newlines = []
for line in infile:
newlines.append(line.replace(originalText,replacementText))
outfile = codecs.open(outfilename, 'w', encoding='utf-16-le')
outfile.writelines(newlines)
Do I need to close infile or outfile?
A:
You don't have a Unicode file. There is no such thing (unless you are the author of NotePad, which conflates "Unicode" and "UTF-16LE").
Please read the Python Unicode HOWTO and Joel on Unicode.
Update I'm glad the suggested reading helped you. Here's a better version of your code:
infile = codecs.open(infilename,'r', encoding='utf-16-le')
outfile = codecs.open(outfilename, 'w', encoding='utf-16-le')
for line in infile:
fixed_line = line.replace(originalText,replacementText)
# no need to save up all the output lines in a list
outfile.write(fixed_line)
infile.close()
outfile.close()
It's always a good habit to release resources (e.g. close files) immediately when you are finished with them. More importantly, with output files, the directory is usually not updated until you close the file.
Read up on the "with" statement to find out about even better practice with file handling.
A:
Python 3
Looks like Python 3.6 will assume your file is UTF-8 by default if you open it in text mode (default):
>>> open('/etc/hosts')
<_io.TextIOWrapper name='/etc/hosts' mode='r' encoding='UTF-8'>
A function like file.readlines() will return str objects and in Python 3 strings are unicode. If you open the file in binary mode, it will be almost like Python 2 behavior:
>>> open('/etc/hosts', 'rb)
<_io.BufferedReader name='/etc/hosts'>
In this case readlines will return bytes objects and you must decode in order to get unicode:
>>> type(open('/etc/hosts', 'rb').readline())
bytes
>>> type(open('/etc/hosts', 'rb').readline().decode('utf-8'))
str
You can open your file using another encoding using the encoding argument:
>>> open('/etc/hosts', encoding='ascii')
<_io.TextIOWrapper name='/etc/hosts' mode='r' encoding='ascii'>
Python 2 (this is a very old answer)
Python 2 does not care about encoding, a file is just a stream of bytes. A function like file.readlines() will return str objects, not unicode even if you open the file in text mode. You can convert each line to an unicode object using str.decode('your-file-encoding').
>>> f = open('/etc/issue')
>>> l = f.readline()
>>> l
'Ubuntu 10.04.1 LTS \\n \\l\n'
>>> type(l)
<type 'str'>
>>> u = l.decode('utf-8')
>>> type(u)
<type 'unicode'>
You can get results similar to Python 3 using codecs.open instead of just open.
| Python string replace for UTF-16-LE file | Python 2.6
Using Python string.replace() seems not working for UTF-16-LE file. I think of 2 ways:
Find a Python module that can handle Unicode string manipulate.
Convert the target Unicode file to ASCII, use string.replace(), then convert it back. But I am worry about this may cause loss data.
Can the community suggest me a good way to solve this? Thanks.
EDIT:
My code looks like this:
infile = open(inputfilename)
for s in infile:
outfile.write(s.replace(targetText, replaceText))
Looks like the for loop can parse the line correct. Did I make any mistakes here?
EDIT2:
I've read the Python Unicode tutorial and tried below code, and get it worked. However, just wondering if there's any better way to do this. Can anyone help? Thanks.
infile = codecs.open(infilename,'r', encoding='utf-16-le')
newlines = []
for line in infile:
newlines.append(line.replace(originalText,replacementText))
outfile = codecs.open(outfilename, 'w', encoding='utf-16-le')
outfile.writelines(newlines)
Do I need to close infile or outfile?
| [
"You don't have a Unicode file. There is no such thing (unless you are the author of NotePad, which conflates \"Unicode\" and \"UTF-16LE\").\nPlease read the Python Unicode HOWTO and Joel on Unicode.\nUpdate I'm glad the suggested reading helped you. Here's a better version of your code:\ninfile = codecs.open(infil... | [
11,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0004190683_python_string.txt |
Q:
Where is the entry-point of the C code generating by pypy
I'm using PyPy to translate some python code to C code. I wrote a very simple script as below:
def main():
print "hello world!"
def entry_point(argv):
main()
return 0
def target(*args):
return entry_point, None
Then I used translate.py --source test.py. It did generate C code successful. When I make those code, it generated a executable file test-c. However I cannot find the main function in those code using grep, so I'm wondering where is the entry-point of the code generating by pypy.
Thank you for your reading.
A:
that's incorrect. Grep for pypy_g_entry_point. main() function is likely to be inlined in this example, so you won't get it. If you want it to be rendered use --inline-threshold=0 as a translation parameter.
A:
PyPy is probably not giving you a "main" function because you actually don't have an entry point in your Python code. You should probably just add
main()
at the end of the file.
| Where is the entry-point of the C code generating by pypy | I'm using PyPy to translate some python code to C code. I wrote a very simple script as below:
def main():
print "hello world!"
def entry_point(argv):
main()
return 0
def target(*args):
return entry_point, None
Then I used translate.py --source test.py. It did generate C code successful. When I make those code, it generated a executable file test-c. However I cannot find the main function in those code using grep, so I'm wondering where is the entry-point of the code generating by pypy.
Thank you for your reading.
| [
"that's incorrect. Grep for pypy_g_entry_point. main() function is likely to be inlined in this example, so you won't get it. If you want it to be rendered use --inline-threshold=0 as a translation parameter.\n",
"PyPy is probably not giving you a \"main\" function because you actually don't have an entry point i... | [
2,
1
] | [] | [] | [
"c",
"entry_point",
"pypy",
"python"
] | stackoverflow_0004190481_c_entry_point_pypy_python.txt |
Q:
How to compile a svn python binding for windows from the source?
I'm setting up a new svn+trac environment, the svn server's version is 1.6.11, then I can't find any corresponding pre-compiled svn-python binding, finally I found the following thread:
Python SVN bindings for Windows
so, my question is: how to compile from these source?
http://svn.apache.org/viewvc/subversion/trunk/subversion/bindings/swig/python/
A:
The win32svn project, Subversion for Windows, by alagazam,
is a win32 build of subversion.
As of November 2010, the latest build is 1.6.13 dated 2010-10-05,
including python 2.6 bindings.
Builds of earlier SVN versions on the same page include 1.6.11.
| How to compile a svn python binding for windows from the source? | I'm setting up a new svn+trac environment, the svn server's version is 1.6.11, then I can't find any corresponding pre-compiled svn-python binding, finally I found the following thread:
Python SVN bindings for Windows
so, my question is: how to compile from these source?
http://svn.apache.org/viewvc/subversion/trunk/subversion/bindings/swig/python/
| [
"The win32svn project, Subversion for Windows, by alagazam,\nis a win32 build of subversion.\nAs of November 2010, the latest build is 1.6.13 dated 2010-10-05,\nincluding python 2.6 bindings.\nBuilds of earlier SVN versions on the same page include 1.6.11.\n"
] | [
3
] | [] | [] | [
"python",
"svn",
"windows"
] | stackoverflow_0002894744_python_svn_windows.txt |
Q:
How to fix Python error importing ElementTree?
I'm beginning to learn python and here I'm trying to read from an xml file using ElementTree:
import sys
from elementtree.ElementTree import ElementTree
doc = ElementTree(file="test.xml")
doc.write(sys.stdout)
However I get this error:
File "my_xml.py", line 2, in
from elementtree.ElementTree import ElementTree
ImportError: No module named elementtree.ElementTree
I do have lib files in /usr/lib/python2.6/xml/etree/...
What am I doing wrong?
Thanks a lot for your help :)
A:
It should be:
from xml.etree.ElementTree import ElementTree
More information on this can be found at the Python docs.
| How to fix Python error importing ElementTree? | I'm beginning to learn python and here I'm trying to read from an xml file using ElementTree:
import sys
from elementtree.ElementTree import ElementTree
doc = ElementTree(file="test.xml")
doc.write(sys.stdout)
However I get this error:
File "my_xml.py", line 2, in
from elementtree.ElementTree import ElementTree
ImportError: No module named elementtree.ElementTree
I do have lib files in /usr/lib/python2.6/xml/etree/...
What am I doing wrong?
Thanks a lot for your help :)
| [
"It should be:\nfrom xml.etree.ElementTree import ElementTree\n\nMore information on this can be found at the Python docs.\n"
] | [
14
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0004192410_python_xml.txt |
Q:
What does django resolve_variable do? (template.Variable)
What does resolve_variable do? And could I use it for accessing the request outside of the view?
Edit
So template.Variable is the correct way to go - but I'm still unsure of its purpose. The documentation doesn't really help.
Cheers guys.
A:
I'm assuming your trying to write a custom template tag here, so here's what you do.
In your compilation function, you bind the variable like so:
@register.tag
def my_tag(parser, token):
# This version uses a regular expression to parse tag contents.
try:
# Splitting by None == splitting by spaces.
tag_name, var_name = token.contents.split(None, 1)
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents.split()[0]
#this will "bind" the variable in the template to the actual_var object
actual_var = template.Variable(var_name)
return MyNode(template_variable)
class MyNode(template.Node):
def __init__(self, actual_var):
self.actual_var = actual_var
def render(self, context):
actual_var_value = self.actual_var.resolve(context)
#do something with it
return result
If you only want access the request, you bind against the variable directly in the node. Make sure you have the request in the context:
from django.template import RequestContext
def my_view(request):
#request stuff
return render_to_response("mytemplate.html", {'extra context': None,}, context_instance=RequestContext(request))
Then in your template tag code.
@register.tag
def simple_request_aware_tag(parser, token):
return SimpleRequestAwareNode()
class SimpleRequestAwareNode(template.Node):
def render(self, context):
request = template.Variable('request').resolve(context)
#we want to return the current username for example
return request.user.get_full_name()
A:
what does resolve_variable do
Resolves a variable in a template tag.
could I use it for accessing the request outside of the view
In a template tag? Yes, as long as the request is in the context - but you don't necessarily need resolve_variable for that, if you're using a simple tag or inclusion tag.
| What does django resolve_variable do? (template.Variable) | What does resolve_variable do? And could I use it for accessing the request outside of the view?
Edit
So template.Variable is the correct way to go - but I'm still unsure of its purpose. The documentation doesn't really help.
Cheers guys.
| [
"I'm assuming your trying to write a custom template tag here, so here's what you do.\nIn your compilation function, you bind the variable like so:\n@register.tag\ndef my_tag(parser, token):\n # This version uses a regular expression to parse tag contents.\n try:\n # Splitting by None == splitting by s... | [
5,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004183252_django_python.txt |
Q:
How to add extra fields using django.forms Textarea
I am newbie in django and working on a pootle project.
I would like to add bio (in textarea), interests (textarea), and profile pics (image upload). this page is looking like this: http://pootle.locamotion.org/accounts/personal/edit/ (you might need to login to see this page)
I have edited local_apps/pootle_profile/views.py which looks like this:
from django.forms import ModelForm, Textarea
class UserForm(ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'bio')
widgets = {'bio': Textarea(attrs={'cols': 80, 'rows': 20})}
and in ""templates/profiles/edit_personal.html" "
<form method="post" action="/accounts/{{user.username}}/">
<p>
<label for="id_first_name">{% trans 'First Name' %}</label>
{{ form.first_name }}
{{ form.first_name.errors }}
</p>
<p>
<label for="id_last_name">{% trans 'Last Name' %}</label>
{{ form.last_name }}
{{ form.last_name.errors }}
</p>
<p>
<label for="id_email">{% trans 'Email address' %}</label>
{{ form.email }}
{{ form.email.errors }}
</p>
<p>
<label for="id_bio">{% trans 'Bio' %}</label>
{{ form.bio }}
{{ form.bio.errors }}
</p>
<p class="common-buttons-block">
<input type="submit" class="save" value="{% trans 'Save' %}" />
</p>
</form>
but it does not show the last bio textarea field on a profile page.
not loading form.bio. here is html source:
<p>
<label for="id_email">Email address</label>
<input id="id_email" type="text" name="email" value="sample@email.com" maxlength="75" />
</p>
<p>
<label for="id_bio">Bio</label>
</p>
I have added a bio column in auth_user:
MariaDB [pootle]> describe auth_user;
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(30) | NO | UNI | NULL | |
| first_name | varchar(30) | NO | | NULL | |
| last_name | varchar(30) | NO | | NULL | |
| email | varchar(75) | NO | | NULL | |
| password | varchar(128) | NO | | NULL | |
| is_staff | tinyint(1) | NO | | NULL | |
| is_active | tinyint(1) | NO | | NULL | |
| is_superuser | tinyint(1) | NO | | NULL | |
| last_login | datetime | NO | | NULL | |
| date_joined | datetime | NO | | NULL | |
| bio | text | YES | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
12 rows in set (0.00 sec)
could somebody see what is missing?
any suggestions are greatly appreciated!!
regards
A:
Firstly, as Digitalpbk says, don't manually add columns to Django's tables. Instead, create a UserProfile model in your own app, with a OneToOneField to auth.User.
Secondly, to add extra fields to a modelform, you need to define them explicitly at the form level:
class UserForm(ModelForm):
bio = forms.CharField(widget=forms.Textarea(attrs={'cols': 80, 'rows': 20}))
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'bio')
Finally, you'll need to do something in your view manually to save this extra field, as the User model doesn't know about it.
A:
It is not recommended to directly alter django tables like auth_user although for the above to work, you will have to change the auth model in django.contrib.auth.models to add the bio field.
Recommended way of doing things is via the UserProfile which has a OneToOne relation with the User Table.
| How to add extra fields using django.forms Textarea | I am newbie in django and working on a pootle project.
I would like to add bio (in textarea), interests (textarea), and profile pics (image upload). this page is looking like this: http://pootle.locamotion.org/accounts/personal/edit/ (you might need to login to see this page)
I have edited local_apps/pootle_profile/views.py which looks like this:
from django.forms import ModelForm, Textarea
class UserForm(ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'bio')
widgets = {'bio': Textarea(attrs={'cols': 80, 'rows': 20})}
and in ""templates/profiles/edit_personal.html" "
<form method="post" action="/accounts/{{user.username}}/">
<p>
<label for="id_first_name">{% trans 'First Name' %}</label>
{{ form.first_name }}
{{ form.first_name.errors }}
</p>
<p>
<label for="id_last_name">{% trans 'Last Name' %}</label>
{{ form.last_name }}
{{ form.last_name.errors }}
</p>
<p>
<label for="id_email">{% trans 'Email address' %}</label>
{{ form.email }}
{{ form.email.errors }}
</p>
<p>
<label for="id_bio">{% trans 'Bio' %}</label>
{{ form.bio }}
{{ form.bio.errors }}
</p>
<p class="common-buttons-block">
<input type="submit" class="save" value="{% trans 'Save' %}" />
</p>
</form>
but it does not show the last bio textarea field on a profile page.
not loading form.bio. here is html source:
<p>
<label for="id_email">Email address</label>
<input id="id_email" type="text" name="email" value="sample@email.com" maxlength="75" />
</p>
<p>
<label for="id_bio">Bio</label>
</p>
I have added a bio column in auth_user:
MariaDB [pootle]> describe auth_user;
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(30) | NO | UNI | NULL | |
| first_name | varchar(30) | NO | | NULL | |
| last_name | varchar(30) | NO | | NULL | |
| email | varchar(75) | NO | | NULL | |
| password | varchar(128) | NO | | NULL | |
| is_staff | tinyint(1) | NO | | NULL | |
| is_active | tinyint(1) | NO | | NULL | |
| is_superuser | tinyint(1) | NO | | NULL | |
| last_login | datetime | NO | | NULL | |
| date_joined | datetime | NO | | NULL | |
| bio | text | YES | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
12 rows in set (0.00 sec)
could somebody see what is missing?
any suggestions are greatly appreciated!!
regards
| [
"Firstly, as Digitalpbk says, don't manually add columns to Django's tables. Instead, create a UserProfile model in your own app, with a OneToOneField to auth.User.\nSecondly, to add extra fields to a modelform, you need to define them explicitly at the form level:\nclass UserForm(ModelForm): ... | [
13,
1
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"django_views",
"python"
] | stackoverflow_0004190386_django_django_forms_django_templates_django_views_python.txt |
Q:
a question about this python script!
if __name__=="__main__":
fname= raw_input("Please enter your file:")
mTrue=1
Salaries=''
Salarieslist={}
Employeesdept=''
Employeesdeptlist={}
try:
f1=open(fname)
except:
mTrue=0
print 'The %s does not exist!'%fname
if mTrue==1:
ss=[]
for x in f1.readlines():
if 'Salaries' in x:
Salaries=x.strip()
elif 'Employees' in x:
Employeesdept=x.strip()
f1.close()
if Salaries and Employeesdept:
Salaries=Salaries.split('-')[1].strip().split(' ')
for d in Salaries:
s=d.strip().split(':')
Salarieslist[s[0]]=s[1]
Employeesdept=Employeesdept.split('-')[1].strip().split(' ')
for d in Employeesdept:
s=d.strip().split(':')
Employeesdeptlist[s[0]]=s[1]
print "1) what is the average salary in the company: %s "%Salarieslist['Avg']
print "2) what are the maximum and minimum salaries in the company: maximum:%s,minimum:%s "%(Salarieslist['Max'],Salarieslist['Min'])
print "3) How many employees are there in each department :IT:%s, Development:%s, Administration:%s"%(
Employeesdeptlist['IT'],Employeesdeptlist['Development'],Employeesdeptlist['Administration'])
else:
print 'The %s data is err!'%fname
When I enter a filename, but it didn't continue, why? If I enter a file named company.txt, but it always show the file does not exist. why?
A:
I can give you some hints which can help you to resolve problem better
Create a function and call it in main e.g.
if __name__=="__main__":
main()
Don't put whole block under if mTrue==1: instead just return from function on error e.g.
def main():
fname= raw_input("Please enter your file:")
try:
f1=open(fname)
except:
print 'The %s does not exist!'%fname
return
... # main code here
Never catch all exceptions , instead catch specific exception e.g. IOError
try:
f1 = open(fname):
except IOError,e:
print 'The %s does not exist!'%fname
otherwise catching all exception may catch syntax error or mis-spelled names etc
Print the exception you are getting, it may not always be file not found, may be you don't have read permission or something like that
and finally your problem could be just that, file may not exist, try to input full path
A:
Your current working directory does not contain company.txt.
Either set your current working directory or use an absolute path.
You can change the working directory like so:
import os
os.chdir(new_path)
A:
In addition to be more specific about which exceptions you want to catch you should considered capturing the exception object itself so you can print a string representation of it as part of your error message:
try:
f1 = open(fname, 'r')
except IOError, e:
print >> sys.stderr, "Some error occurred while trying to open %s" % fname
print >> sys.stderr, e
(You can also learn more about specific types of Exception objects and perhaps handle
some sorts of exceptions in your code. You can even capture Exceptions for your own inspection from within the interpreter so you can run dir() on them, and type() on each of the interesting attributes you find ... and so on.
| a question about this python script! | if __name__=="__main__":
fname= raw_input("Please enter your file:")
mTrue=1
Salaries=''
Salarieslist={}
Employeesdept=''
Employeesdeptlist={}
try:
f1=open(fname)
except:
mTrue=0
print 'The %s does not exist!'%fname
if mTrue==1:
ss=[]
for x in f1.readlines():
if 'Salaries' in x:
Salaries=x.strip()
elif 'Employees' in x:
Employeesdept=x.strip()
f1.close()
if Salaries and Employeesdept:
Salaries=Salaries.split('-')[1].strip().split(' ')
for d in Salaries:
s=d.strip().split(':')
Salarieslist[s[0]]=s[1]
Employeesdept=Employeesdept.split('-')[1].strip().split(' ')
for d in Employeesdept:
s=d.strip().split(':')
Employeesdeptlist[s[0]]=s[1]
print "1) what is the average salary in the company: %s "%Salarieslist['Avg']
print "2) what are the maximum and minimum salaries in the company: maximum:%s,minimum:%s "%(Salarieslist['Max'],Salarieslist['Min'])
print "3) How many employees are there in each department :IT:%s, Development:%s, Administration:%s"%(
Employeesdeptlist['IT'],Employeesdeptlist['Development'],Employeesdeptlist['Administration'])
else:
print 'The %s data is err!'%fname
When I enter a filename, but it didn't continue, why? If I enter a file named company.txt, but it always show the file does not exist. why?
| [
"I can give you some hints which can help you to resolve problem better\nCreate a function and call it in main e.g. \nif __name__==\"__main__\":\n main()\n\nDon't put whole block under if mTrue==1: instead just return from function on error e.g.\ndef main():\n fname= raw_input(\"Please enter your file:\")\n ... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004190977_python.txt |
Q:
how to filled the data in django templates
I want to email a template in django. The template has one variable say name. I want to filled this value. How to do that. context is not working because i don't need to render the page.
A:
Of course you need to render the template - and you do that via the context. How is it not working?
A:
context is not working because i don't need to render the page.
I guess what you are looking for is render_to_string shortcut.
A:
Try this
from django.template.loader import render_to_string
text = render_to_string('my_template.html', { 'name': 'xxx' })
| how to filled the data in django templates | I want to email a template in django. The template has one variable say name. I want to filled this value. How to do that. context is not working because i don't need to render the page.
| [
"Of course you need to render the template - and you do that via the context. How is it not working?\n",
"\ncontext is not working because i don't need to render the page.\n\nI guess what you are looking for is render_to_string shortcut.\n",
"Try this\nfrom django.template.loader import render_to_string\ntext =... | [
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004192675_django_python.txt |
Q:
import os to j2me
I am trying to write this code to j2me. Does anyone has any idea how to do this?
Thanks!
import os
if os.path.isfile("c:\\python\\myfolder\\test.txt"):
A:
Understand what the line does. You can start with the docs to Python's os module: http://docs.python.org/library/os.path.html
Read the J2ME docs to find a similar function call.
A:
Something like what is below. Might help.. Just remember the phone needs to support JS175
try {
fconn = (FileConnection) Connector.open("file:///locaction_of_file", Connector.READ_WRITE);
if (!fconn.exists()) {
fconn.create();
}
} catch (IOException e) {
e.printStackTrace();
}
| import os to j2me | I am trying to write this code to j2me. Does anyone has any idea how to do this?
Thanks!
import os
if os.path.isfile("c:\\python\\myfolder\\test.txt"):
| [
"\nUnderstand what the line does. You can start with the docs to Python's os module: http://docs.python.org/library/os.path.html\nRead the J2ME docs to find a similar function call.\n\n",
"Something like what is below. Might help.. Just remember the phone needs to support JS175\n try {\n fconn = (FileConnectio... | [
1,
0
] | [] | [] | [
"blackberry",
"java",
"java_me",
"python"
] | stackoverflow_0004191546_blackberry_java_java_me_python.txt |
Q:
(py)cairo - fill
is there a way to fill everything outside of a closed path (polygon)?
Background: I'd like to render some maps with coastlines - so sometimes I need to fill the sea with blue color, so I thought it would be the easiest and in my situation the most efficient to fill everything outside of this coastline polygon with blue color.
Thanks in advance!
A:
You can add a rectangle covering the whole drawing area to your coastline path and set the fill rule to cairo.FILL_RULE_EVEN_ODD. Calling fill() after this fills the area outside your original path. (If you choose the correct orientation for your rectangle you can skip setting the fill rule.)
A:
Draw a big blue rectangle over the entire cairo surface and then draw your coastline on top of that?
A:
While you could create a closed path the size of the surface and then fill it with a solidpattern (the fill rule won't matter for a simple rectangle), it would be easier to just use the context paint() method which will fill the current clip region (that is initially set to the entire surface). It's important to do this before drawing the map/coastline boundaries and filling them so they will be on top of the background.
| (py)cairo - fill | is there a way to fill everything outside of a closed path (polygon)?
Background: I'd like to render some maps with coastlines - so sometimes I need to fill the sea with blue color, so I thought it would be the easiest and in my situation the most efficient to fill everything outside of this coastline polygon with blue color.
Thanks in advance!
| [
"You can add a rectangle covering the whole drawing area to your coastline path and set the fill rule to cairo.FILL_RULE_EVEN_ODD. Calling fill() after this fills the area outside your original path. (If you choose the correct orientation for your rectangle you can skip setting the fill rule.)\n",
"Draw a big b... | [
4,
0,
0
] | [] | [] | [
"cairo",
"pycairo",
"python"
] | stackoverflow_0004192384_cairo_pycairo_python.txt |
Q:
IIS and ISAPI-WSGI = very slow
I have loaded 2 Django apps on IIS using isapi-wsgi.
These are both server setups:
Windows Server 2003, IIS6 and SQL Server 2005
Windows Server 2008 R2, IIS7.5 and SQL Server 2008
The Django apps are completely different from each other.
They both take random periods of time for each requests between 1 and 10 seconds.
This is painfully slow compared to 100ms-500ms of an Apache+mod_wsgi setup, so there must be something wrong.
Any ideas? Would really be great if I could fix this. :)
Solved!
Do not use django-mssql use django-pyodbc instead!!
A:
Install another web server, like apache.
Seriously - IIS sucks on running python wsgi apps. There's not much you can do in that regard.
| IIS and ISAPI-WSGI = very slow | I have loaded 2 Django apps on IIS using isapi-wsgi.
These are both server setups:
Windows Server 2003, IIS6 and SQL Server 2005
Windows Server 2008 R2, IIS7.5 and SQL Server 2008
The Django apps are completely different from each other.
They both take random periods of time for each requests between 1 and 10 seconds.
This is painfully slow compared to 100ms-500ms of an Apache+mod_wsgi setup, so there must be something wrong.
Any ideas? Would really be great if I could fix this. :)
Solved!
Do not use django-mssql use django-pyodbc instead!!
| [
"Install another web server, like apache.\nSeriously - IIS sucks on running python wsgi apps. There's not much you can do in that regard.\n"
] | [
-3
] | [] | [] | [
"django",
"iis",
"isapi",
"isapi_wsgi",
"python"
] | stackoverflow_0004193619_django_iis_isapi_isapi_wsgi_python.txt |
Q:
python print and whitespace
I am trying to print a result for example:
for record in result:
print varone,vartwo,varthree
I am trying to concatenate the variables which are from an SQL query, but I am getting whitespace. How can I strip whitespace from a 'print'? Should I feed the result into a variable then do a 'strip(newvar)' then print the 'newvar'?
A:
This:
print "%s%s%s" % (varone,vartwo,varthree)
will replace the first %s in the quotes with the value in varone, the second %s with the contents of vartwo, etc.
EDIT:
As of Python 2.6 you should prefer this method:
print "{0}{1}{2}".format(varone,vartwo,varthree)
(Thanks Space_C0wb0y)
A:
print put whitespace between variables and emit a newline. If this is just the whistespaces between strings that bother you, just concatenate the strings before printing.
print varone+vartwo+varthree
Really, there is (much) more than one way to do it. It always comes out creating a new string combining your values before printing it. Below are the various ways I can think of:
# string concatenation
# the drawback is that your objects are not string
# plus may have another meaning
"one"+"two"+"three"
#safer, but non pythonic and stupid for plain strings
str("one")+str("two")+str("three")
# same idea but safer and more elegant
''.join(["one", "two", "three"])
# new string formatting method
"{0}{1}{2}".format("one", "two", "three")
# old string formating method
"%s%s%s" % ("one", "two", "three")
# old string formatting method, dictionnary based variant
"%(a)s%(b)s%(c)s" % {'a': "one", 'b': "two", 'c':"three"}
You can also avoid creating intermediate concatenated strings completely and use write instead of print.
import sys
for x in ["on", "two", "three"]:
sys.stdout.write(x)
And in python 3.x you could also customize the print separator:
print("one", "two", "three", sep="")
A:
Try
for record in result:
print ''.join([varone,vartwo,varthree])
A:
Just use string formatting before you pass the string to the print command:
for record in result:
print '%d%d%d' % (varone, vartwo, varthree)
Read about Python string formatting here
| python print and whitespace | I am trying to print a result for example:
for record in result:
print varone,vartwo,varthree
I am trying to concatenate the variables which are from an SQL query, but I am getting whitespace. How can I strip whitespace from a 'print'? Should I feed the result into a variable then do a 'strip(newvar)' then print the 'newvar'?
| [
"This:\nprint \"%s%s%s\" % (varone,vartwo,varthree)\n\nwill replace the first %s in the quotes with the value in varone, the second %s with the contents of vartwo, etc.\nEDIT:\nAs of Python 2.6 you should prefer this method:\nprint \"{0}{1}{2}\".format(varone,vartwo,varthree)\n\n(Thanks Space_C0wb0y)\n",
"print p... | [
4,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004193920_python.txt |
Q:
Python's example for "iter" function gives me TypeError
The iter function example at python docs:
with open("mydata.txt") as fp:
for line in iter(fp.readline):
print line
gives me this:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: 'builtin_function_or_method' object is not iterable
How's that possible? (Python 2.6.4)
A:
It's because I'm stupid and can't read:
Without a second argument, o must be a collection object which supports the iteration protocol (the iter() method), or it must support the sequence protocol (the getitem() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised.
Solution is to provide an empty string sentinel.
with open("mydata.txt") as fp:
for line in iter(fp.readline, ''):
print line
A:
Python file objects are iterable, hence there is no need to explicitly call iter(). To read a file line by line you can simply write:
with open("mydata.txt") as fp:
for line in fp:
print line
| Python's example for "iter" function gives me TypeError | The iter function example at python docs:
with open("mydata.txt") as fp:
for line in iter(fp.readline):
print line
gives me this:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: 'builtin_function_or_method' object is not iterable
How's that possible? (Python 2.6.4)
| [
"It's because I'm stupid and can't read:\n\nWithout a second argument, o must be a collection object which supports the iteration protocol (the iter() method), or it must support the sequence protocol (the getitem() method with integer arguments starting at 0). If it does not support either of those protocols, Type... | [
4,
2
] | [
"The only thing I can think about is that you don't have a file called mydata.txt or it is in the wrong place.\n"
] | [
-2
] | [
"python",
"typeerror"
] | stackoverflow_0004193957_python_typeerror.txt |
Q:
problem with uploading and downloading xml document from Datastore using google app and python
i am creating one xml document in my google app and storing it as blob while fetching back from datastore how do i convert it to again xml doc
class xmlStore(db.Model):
xmlRef=db.BlobProperty()
creating xml doc like this:
docRef=Document()
fp=docRef.createElement("Client")
fp.setAttribute("ID","21783")
docRef.appendChild(fp)
storing to datastore:
x=xmlStore(xmlRef=str(docRef))
x.put()
while retriving back:
result = db.GqlQuery("SELECT * FROM xmlStore").fetch(1)
while printing on webpage:
for response in result:
self.response.out.write(response.xmlRef)
its giving me xml.dom.minidom.Document instance at 0x6a2bddb0b5aef438
how do i get back it in xml..
A:
Have a look at Python's documentation about xml.dom.minidom toxml method.
You say:
its giving me xml.dom.minidom.Document
instance at 0x6a2bddb0b5aef438
Call the .toxml() method of that object.
| problem with uploading and downloading xml document from Datastore using google app and python | i am creating one xml document in my google app and storing it as blob while fetching back from datastore how do i convert it to again xml doc
class xmlStore(db.Model):
xmlRef=db.BlobProperty()
creating xml doc like this:
docRef=Document()
fp=docRef.createElement("Client")
fp.setAttribute("ID","21783")
docRef.appendChild(fp)
storing to datastore:
x=xmlStore(xmlRef=str(docRef))
x.put()
while retriving back:
result = db.GqlQuery("SELECT * FROM xmlStore").fetch(1)
while printing on webpage:
for response in result:
self.response.out.write(response.xmlRef)
its giving me xml.dom.minidom.Document instance at 0x6a2bddb0b5aef438
how do i get back it in xml..
| [
"Have a look at Python's documentation about xml.dom.minidom toxml method.\nYou say:\n\nits giving me xml.dom.minidom.Document\n instance at 0x6a2bddb0b5aef438\n\nCall the .toxml() method of that object.\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python",
"xml"
] | stackoverflow_0004193509_google_app_engine_python_xml.txt |
Q:
AppEngine: IOError when saving a lot of objects to the Datastore
Cheers all. I'm running Ubuntu 10.04 and the latest Google AppEngine SDK. I'm working on a simple website which has posts and comments to posts. I basically implemented a simple tree to store my comments with a parent_comment, left and right values.
I created an event which fires before a new (not is_saved()) comment is put() into the Google Datastore, which calculates the left and right values for the new comment, as well as updates older comments for a valid hierarchy. I basically followed Managing Hierarchical Data in MySQL and implemented it in Python.
Everything seems to work fine, new comments are added, threading looks good, but...
A cycle that submits 40 comments during startup works, but when I increase that cycle to 80 or more, I'm left with an IOError:
IOError: [Errno 24] Too many open files: '/tmp/tmp0agXqU'
My code for generating 60 comments looks like this:
for k in range(0, 4):
comments = {0: None}
for i in range(1, 21):
j = random.randrange(0, len(comments))
pc = comments[j]
comments[i] = Comment(
name=lipsum(count=1),
email=lipsum(count=1, make_slug=True) + '@email.com',
url='http://' + lipsum(count=2, make_slug=True) + '.com',
content=lipsum(count=random.randrange(10, 50)),
object_link=p.key(),
parent_comment=pc
)
comments[i].put()
The lipsum function simply returns a piece of lorem ipsum text.
Any ideas on how to solve this? Thanks!
A:
I had the same problem for a massive taskqueue worker.
Switching to SQLite for your local Datastore could solve the problem:
dev_appserver.py --use_sqlite
Since App Engine SDK 1.3.3, the Python
SDK has a new experimental feature
that gives the option to use SQLite
as the datastore stub backend. Using
SQLite within the dev_appserver should
speed up performance of your local
datastore when testing on large
datasets.
For the dev_appserver documentation, have a look here
A:
This is most probably due to a bug in latest App Engine SDK. The comments of the bug report provide a patch that fixes the issue.
| AppEngine: IOError when saving a lot of objects to the Datastore | Cheers all. I'm running Ubuntu 10.04 and the latest Google AppEngine SDK. I'm working on a simple website which has posts and comments to posts. I basically implemented a simple tree to store my comments with a parent_comment, left and right values.
I created an event which fires before a new (not is_saved()) comment is put() into the Google Datastore, which calculates the left and right values for the new comment, as well as updates older comments for a valid hierarchy. I basically followed Managing Hierarchical Data in MySQL and implemented it in Python.
Everything seems to work fine, new comments are added, threading looks good, but...
A cycle that submits 40 comments during startup works, but when I increase that cycle to 80 or more, I'm left with an IOError:
IOError: [Errno 24] Too many open files: '/tmp/tmp0agXqU'
My code for generating 60 comments looks like this:
for k in range(0, 4):
comments = {0: None}
for i in range(1, 21):
j = random.randrange(0, len(comments))
pc = comments[j]
comments[i] = Comment(
name=lipsum(count=1),
email=lipsum(count=1, make_slug=True) + '@email.com',
url='http://' + lipsum(count=2, make_slug=True) + '.com',
content=lipsum(count=random.randrange(10, 50)),
object_link=p.key(),
parent_comment=pc
)
comments[i].put()
The lipsum function simply returns a piece of lorem ipsum text.
Any ideas on how to solve this? Thanks!
| [
"I had the same problem for a massive taskqueue worker.\nSwitching to SQLite for your local Datastore could solve the problem:\ndev_appserver.py --use_sqlite \n\n\nSince App Engine SDK 1.3.3, the Python\n SDK has a new experimental feature\n that gives the option to use SQLite\n as the datastore stub backend. U... | [
2,
1
] | [] | [] | [
"binary_tree",
"google_app_engine",
"python",
"ubuntu"
] | stackoverflow_0004193610_binary_tree_google_app_engine_python_ubuntu.txt |
Q:
Make OptionMenu Widget Scrollable?
I've got an option menu that's about 60 items long and, needless to say, I can't see it all on the screen at once. Is there a way that I can make the OptionMenu widget in tkinter scrollable?
A:
Short answer is no, but you could try a ComboBox mega-widget (quick search will throw some suitable examples up there) which could be a 'good enough' alternative (in fact with it being a combined entry field and scrolled list you could make it 'smart' by including auto-search / auto-complete - 60 items in a drop down is a lot :)
| Make OptionMenu Widget Scrollable? | I've got an option menu that's about 60 items long and, needless to say, I can't see it all on the screen at once. Is there a way that I can make the OptionMenu widget in tkinter scrollable?
| [
"Short answer is no, but you could try a ComboBox mega-widget (quick search will throw some suitable examples up there) which could be a 'good enough' alternative (in fact with it being a combined entry field and scrolled list you could make it 'smart' by including auto-search / auto-complete - 60 items in a drop d... | [
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004186981_python_tkinter.txt |
Q:
How I can retrieve webcam info in python?
I need to retrieve the number of webcams instaled in my system and the brand, manufacturer, device id, etc., of the webcam.
Is there any way to do that in Python, and independent of the operating system?
A:
There's no truly cross-platform solution, but on Linux you can use os.popen('lsusb') (or something along those lines) and then just scrape the screen (using grep or something else). For finding out on Windows, you can try using a TWAIN binding for Python (it's the Windows webcam protocol, a Python binding exists here, but it's not actively maintained). VideoCapture might have what you need.
A:
I found a partial solution, which is to use the command:
v4l2-ctl --list-devices
But only works on Linux, but on Windows I have no way of detecting the amount and the name of the installed webcams.
| How I can retrieve webcam info in python? | I need to retrieve the number of webcams instaled in my system and the brand, manufacturer, device id, etc., of the webcam.
Is there any way to do that in Python, and independent of the operating system?
| [
"There's no truly cross-platform solution, but on Linux you can use os.popen('lsusb') (or something along those lines) and then just scrape the screen (using grep or something else). For finding out on Windows, you can try using a TWAIN binding for Python (it's the Windows webcam protocol, a Python binding exists h... | [
0,
0
] | [] | [] | [
"python",
"webcam"
] | stackoverflow_0004186052_python_webcam.txt |
Q:
Django in Eclipse, laying out the project
Any "best practice" or "recommended" project layouts for a django project in eclipse?
In my eclipse it looks like this:
project name
-src
--project name
---__init__.py
---manage.py
---settings.py
---urls.py
---apps
----app1
-----__init__.py
-----forms.py
-----urls.py
-----views.py
-----templates
------app1
-------index.html
I'm not sure how I like this layout, especially the repetition of the app name in the templates folder. I think I did it that way to make my url configs behave, but I'm new to django so that could be another place for improvement.
A:
you know you can create a django project without the src folder in eclipse which i think will be much cleaner; to do this when you want to create a new Django project the widget that ask for the name of the project in the bottom you can disable Create default "scr" ... .
And i don't think it's a good idea to put all Django application like you did you can put related application in the some folder but not all of them , and for the template i think you have the choice to put one template directory in the some level as settings.py where you can have the same structure as your apps or to put a template directory in each application but i prefer the first one like this:
project_name
|
| --- manage.py
|
| --- settings.py
|
| --- template
|
| -- index.html
|
| -- base.html
|
| -- 404.html
|
| -- conection_app
| |
| -- login.html
|
|
| --- connection_app
|
| -- login
|
| -- view.py
|
|
| --- finance_app
|
A:
If you're only going to have one app, you don't need an apps folder. Also, it should just be templates/index.html, since templates lives in app1's folder. There's no chance that you'd have another app's templates in app1's folder.
I also don't really see why you need to have a project-name folder underneath src... Is that some sort of Django hack, because if it isn't I can't imagine why it would be necessary.
A:
For Django, you'll absolutely want to duplicate the app name in the template folder.
If you have "app1" and "app2", and they both have an "index.html" template, then you need the app name in the path to differentiate the templates.
Say you want to pack-in default templates for "app1" but let users override them, then you can have "app1/templates/app1/index.html", and the override can go in "templates/app1/index.html" or wherever.
Without the app name in the folder, you're setting yourself up for template name collisions.
| Django in Eclipse, laying out the project | Any "best practice" or "recommended" project layouts for a django project in eclipse?
In my eclipse it looks like this:
project name
-src
--project name
---__init__.py
---manage.py
---settings.py
---urls.py
---apps
----app1
-----__init__.py
-----forms.py
-----urls.py
-----views.py
-----templates
------app1
-------index.html
I'm not sure how I like this layout, especially the repetition of the app name in the templates folder. I think I did it that way to make my url configs behave, but I'm new to django so that could be another place for improvement.
| [
"you know you can create a django project without the src folder in eclipse which i think will be much cleaner; to do this when you want to create a new Django project the widget that ask for the name of the project in the bottom you can disable Create default \"scr\" ... .\nAnd i don't think it's a good idea to pu... | [
2,
1,
1
] | [] | [] | [
"django",
"eclipse",
"pydev",
"python"
] | stackoverflow_0004191284_django_eclipse_pydev_python.txt |
Q:
Python argparse: Is there a way to specify a range in nargs?
I have an optional argument that supports a list of arguments itself.
I mean, it should support:
-f 1 2
-f 1 2 3
but not:
-f 1
-f 1 2 3 4
Is there a way to force this within argparse ? Now I'm using nargs="*", and then checking the list length.
Edit: As requested, what I needed is being able to define a range of acceptable number of arguments. I mean, saying (in the example) 2 or 3 args is right, but not 1 or 4 or anything that's not inside the range 2..3
A:
You could do this with a custom action:
import argparse
def required_length(nmin,nmax):
class RequiredLength(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
if not nmin<=len(values)<=nmax:
msg='argument "{f}" requires between {nmin} and {nmax} arguments'.format(
f=self.dest,nmin=nmin,nmax=nmax)
raise argparse.ArgumentTypeError(msg)
setattr(args, self.dest, values)
return RequiredLength
parser=argparse.ArgumentParser(prog='PROG')
parser.add_argument('-f', nargs='+', action=required_length(2,3))
args=parser.parse_args('-f 1 2 3'.split())
print(args.f)
# ['1', '2', '3']
try:
args=parser.parse_args('-f 1 2 3 4'.split())
print(args)
except argparse.ArgumentTypeError as err:
print(err)
# argument "f" requires between 2 and 3 arguments
| Python argparse: Is there a way to specify a range in nargs? | I have an optional argument that supports a list of arguments itself.
I mean, it should support:
-f 1 2
-f 1 2 3
but not:
-f 1
-f 1 2 3 4
Is there a way to force this within argparse ? Now I'm using nargs="*", and then checking the list length.
Edit: As requested, what I needed is being able to define a range of acceptable number of arguments. I mean, saying (in the example) 2 or 3 args is right, but not 1 or 4 or anything that's not inside the range 2..3
| [
"You could do this with a custom action:\nimport argparse\n\ndef required_length(nmin,nmax):\n class RequiredLength(argparse.Action):\n def __call__(self, parser, args, values, option_string=None):\n if not nmin<=len(values)<=nmax:\n msg='argument \"{f}\" requires between {nmin} ... | [
31
] | [] | [] | [
"argparse",
"python"
] | stackoverflow_0004194948_argparse_python.txt |
Q:
Replace part of string using python regular expression
I have the following lines (many, many):
...
gfnfgnfgnf: 5656756734
arvervfdsa: 1343453563
particular: 4685685685
erveveersd: 3453454545
verveversf: 7896789567
..
What I'd like to do is to find line 'particular' (whatever number is after ':')
and replace this number with '111222333'. How can I do that using python regular expressions ?
A:
for line in input:
key, val = line.split(':')
if key == 'particular':
val = '111222333'
I'm not sure regex would be of any value in this specific case. My guess is they'd be slower. That said, it can be done. Here's one way:
for line in input:
re.sub('^particular : .*', 'particular : 111222333')
There are subtleties involved in this, and this is almost certainly not what you'd want in production code. You need to check all of the re module constants to make sure the regex is acting the way you expect, etc. You might be surprised at the flexibility you find in dealing with problems like this in Python if you try not to use re (of course, this isn't to say re isn't useful) ;-)
A:
Sure you need a regular expression?
other_number = '111222333'
some_text, some_number = line.split(': ')
new_line = ': '.join(some_text, other_number)
A:
#!/usr/bin/env python
import re
text = '''gfnfgnfgnf: 5656756734
arvervfdsa: 1343453563
particular: 4685685685
erveveersd: 3453454545
verveversf: 7896789567'''
print(re.sub('[0-9]+', '111222333', text))
A:
input = """gfnfgnfgnf: 5656756734
arvervfdsa: 1343453563
particular: 4685685685
erveveersd: 3453454545
verveversf: 7896789567"""
entries = re.split("\n+", input)
for entry in entries:
if entry.startswith("particular"):
entry = re.sub(r'[0-9]+', r'111222333', entry)
or with sed:
sed -e 's/^particular: [0-9].*$/particular: 111222333/g' file
A:
An important point here is that if you have a lot of lines, you want to process them one by one. That is, instead of reading all the lines in replacing them, and writing them out again, you should read in a line at a time and write out a line at a time. (This would be inefficient if you were actually reading a line at a time from the disk; however, Python's IO is competent and will buffer the file for you.)
with open(...) as infile, open(...) as outfile:
for line in infile:
if line.startswith("particular"):
outfile.write("particular: 111222333")
else:
outfile.write(line)
This will be speed- and memory-efficient.
A:
Your sed example forces me to say neat!
python -c "import re, sys; print ''.join(re.sub(r'^(particular:) \d+', r'\1 111222333', l) for l in open(sys.argv[1]))" file
| Replace part of string using python regular expression | I have the following lines (many, many):
...
gfnfgnfgnf: 5656756734
arvervfdsa: 1343453563
particular: 4685685685
erveveersd: 3453454545
verveversf: 7896789567
..
What I'd like to do is to find line 'particular' (whatever number is after ':')
and replace this number with '111222333'. How can I do that using python regular expressions ?
| [
"for line in input:\n key, val = line.split(':')\n if key == 'particular':\n val = '111222333'\n\nI'm not sure regex would be of any value in this specific case. My guess is they'd be slower. That said, it can be done. Here's one way: \nfor line in input:\n re.sub('^particular : .*', 'particular : 11... | [
3,
3,
2,
0,
0,
0
] | [] | [] | [
"python",
"regex",
"replace"
] | stackoverflow_0004194534_python_regex_replace.txt |
Q:
"unknown column X.id" error in django using existing DB
I am trying to create a model for an existsing DB. Using the output of manage.py inspectdb, My models.py file looks like this:
from django.db import models
...some more stuff here...
class Scripts(models.Model):
run_site = models.ForeignKey(Sites, db_column='run_site')
script_name = models.CharField(max_length=120)
module_name = models.CharField(unique=True, max_length=120)
type = models.CharField(max_length=24)
cat_name = models.CharField(max_length=90)
owner = models.ForeignKey(QAPeople, db_column='owner')
only_server = models.CharField(max_length=120, blank=True)
guest = models.IntegerField()
registered = models.IntegerField()
super = models.IntegerField()
admin = models.IntegerField()
run_timing = models.CharField(max_length=27)
manual_owner = models.ForeignKey(QAPeople, db_column='manual_owner')
script_id = models.IntegerField(unique=True,)
version = models.IntegerField()
comment = models.ForeignKey('ScriptComments', null=True, blank=True)
class Meta:
db_table = u'scripts'
When I try to do Scripts.objects.all() I get
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python26\lib\site-packages\django\db\models\query.py", line 68, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "C:\Python26\lib\site-packages\django\db\models\query.py", line 83, in __len__
self._result_cache.extend(list(self._iter))
File "C:\Python26\lib\site-packages\django\db\models\query.py", line 269, in iterator
for row in compiler.results_iter():
File "C:\Python26\lib\site-packages\django\db\models\sql\compiler.py", line 672, in results_iter
for rows in self.execute_sql(MULTI):
File "C:\Python26\lib\site-packages\django\db\models\sql\compiler.py", line 727, in execute_sql
cursor.execute(sql, params)
File "C:\Python26\lib\site-packages\django\db\backends\util.py", line 15, in execute
return self.cursor.execute(sql, params)
File "C:\Python26\lib\site-packages\django\db\backends\mysql\base.py", line 86, in execute
return self.cursor.execute(query, args)
File "C:\Python26\lib\site-packages\MySQLdb\cursors.py", line 173, in execute
self.errorhandler(self, exc, value)
File "C:\Python26\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
OperationalError: (1054, "Unknown column 'scripts.id' in 'field list'")
Why does django think there should be a scripts.id column? How do I fix it without dropping the tables etc?
A:
There is always by default an implicit id field as auto incrementing primary key on every model. See primary_key in the Django docs how to change that field to some other name, but there needs to be one primary key (also in your table).
Also you may not want to call one of your fields super, since it is shadowing Python's built-in super in the class body. Might give you a hard time finding a bug some day.
A:
I'm not sure if you'r familiar with django-south?
It's a nice little tool that helps you migrate your data from one structure to another and also helps identify issues before commiting info to the table, causing less errors and debugging afterwards.
| "unknown column X.id" error in django using existing DB | I am trying to create a model for an existsing DB. Using the output of manage.py inspectdb, My models.py file looks like this:
from django.db import models
...some more stuff here...
class Scripts(models.Model):
run_site = models.ForeignKey(Sites, db_column='run_site')
script_name = models.CharField(max_length=120)
module_name = models.CharField(unique=True, max_length=120)
type = models.CharField(max_length=24)
cat_name = models.CharField(max_length=90)
owner = models.ForeignKey(QAPeople, db_column='owner')
only_server = models.CharField(max_length=120, blank=True)
guest = models.IntegerField()
registered = models.IntegerField()
super = models.IntegerField()
admin = models.IntegerField()
run_timing = models.CharField(max_length=27)
manual_owner = models.ForeignKey(QAPeople, db_column='manual_owner')
script_id = models.IntegerField(unique=True,)
version = models.IntegerField()
comment = models.ForeignKey('ScriptComments', null=True, blank=True)
class Meta:
db_table = u'scripts'
When I try to do Scripts.objects.all() I get
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python26\lib\site-packages\django\db\models\query.py", line 68, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "C:\Python26\lib\site-packages\django\db\models\query.py", line 83, in __len__
self._result_cache.extend(list(self._iter))
File "C:\Python26\lib\site-packages\django\db\models\query.py", line 269, in iterator
for row in compiler.results_iter():
File "C:\Python26\lib\site-packages\django\db\models\sql\compiler.py", line 672, in results_iter
for rows in self.execute_sql(MULTI):
File "C:\Python26\lib\site-packages\django\db\models\sql\compiler.py", line 727, in execute_sql
cursor.execute(sql, params)
File "C:\Python26\lib\site-packages\django\db\backends\util.py", line 15, in execute
return self.cursor.execute(sql, params)
File "C:\Python26\lib\site-packages\django\db\backends\mysql\base.py", line 86, in execute
return self.cursor.execute(query, args)
File "C:\Python26\lib\site-packages\MySQLdb\cursors.py", line 173, in execute
self.errorhandler(self, exc, value)
File "C:\Python26\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
OperationalError: (1054, "Unknown column 'scripts.id' in 'field list'")
Why does django think there should be a scripts.id column? How do I fix it without dropping the tables etc?
| [
"There is always by default an implicit id field as auto incrementing primary key on every model. See primary_key in the Django docs how to change that field to some other name, but there needs to be one primary key (also in your table).\nAlso you may not want to call one of your fields super, since it is shadowing... | [
14,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004192409_django_python.txt |
Q:
decoding problem with urllib2 in python
I'm trying to use urllib2 in python 2.7 to fetch a page from the web. The page happens to be encoded in unicode(UTF-8) and have greek characters. When I try to fetch and print it with the code below, I get gibberish instead of the greek characters.
import urllib2
print urllib2.urlopen("http://www.pamestihima.gr").read()
The result is the same both in Netbeans 6.9.1 and in Windows 7 CLI.
I'm doing something wrong, but what?
A:
Unicode is not UTF-8. UTF-8 is a string encoding, like ISO-8859-1, ASCII etc.
Always decode your data as soon as possible, to make real Unicode out of it. ('somestring in utf8'.decode('utf-8') == u'somestring in utf-8'), unicode objects are u'' , not ''
When you have data leaving your app, always encode it in the proper encoding. For Web stuff this is utf-8mostly. For console stuff this is whatever your console encoding is. On Windows this is not UTF-8 by default.
A:
It prints correctly for me, too.
Check the character encoding of the program in which you are viewing the HTML source code. For example, in a Linux terminal, you can find "Set Character Encoding" and make sure it is UTF-8.
| decoding problem with urllib2 in python | I'm trying to use urllib2 in python 2.7 to fetch a page from the web. The page happens to be encoded in unicode(UTF-8) and have greek characters. When I try to fetch and print it with the code below, I get gibberish instead of the greek characters.
import urllib2
print urllib2.urlopen("http://www.pamestihima.gr").read()
The result is the same both in Netbeans 6.9.1 and in Windows 7 CLI.
I'm doing something wrong, but what?
| [
"\nUnicode is not UTF-8. UTF-8 is a string encoding, like ISO-8859-1, ASCII etc. \nAlways decode your data as soon as possible, to make real Unicode out of it. ('somestring in utf8'.decode('utf-8') == u'somestring in utf-8'), unicode objects are u'' , not ''\nWhen you have data leaving your app, always encode it in... | [
3,
1
] | [] | [] | [
"encoding",
"python",
"urllib2"
] | stackoverflow_0004195684_encoding_python_urllib2.txt |
Q:
Problems Installing lxml with python/django
I am trying to use lxml in one of my projects in django, but I am having trouble installing the lxml module. I am using Ubuntu 10.04. I have looked on the web for suitable tutorials on how to install the lxml module, but I never seem to understand it correctly. Would anyone be able to clearly tell me how to install this module?
Thank you,
Steve
A:
apt-get install python-lxml
| Problems Installing lxml with python/django | I am trying to use lxml in one of my projects in django, but I am having trouble installing the lxml module. I am using Ubuntu 10.04. I have looked on the web for suitable tutorials on how to install the lxml module, but I never seem to understand it correctly. Would anyone be able to clearly tell me how to install this module?
Thank you,
Steve
| [
"apt-get install python-lxml\n\n"
] | [
3
] | [] | [] | [
"django",
"lxml",
"python"
] | stackoverflow_0004196167_django_lxml_python.txt |
Q:
How to deserialize 1GB of objects into Python faster than cPickle?
We've got a Python-based web server that unpickles a number of large data files on startup using cPickle. The data files (pickled using HIGHEST_PROTOCOL) are around 0.4 GB on disk and load into memory as about 1.2 GB of Python objects -- this takes about 20 seconds. We're using Python 2.6 on 64-bit Windows machines.
The bottleneck is certainly not disk (it takes less than 0.5s to actually read that much data), but memory allocation and object creation (there are millions of objects being created). We want to reduce the 20s to decrease startup time.
Is there any way to deserialize more than 1GB of objects into Python much faster than cPickle (like 5-10x)? Because the execution time is bound by memory allocation and object creation, I presume using another unpickling technique such as JSON wouldn't help here.
I know some interpreted languages have a way to save their entire memory image as a disk file, so they can load it back into memory all in one go, without allocation/creation for each object. Is there a way to do this, or achieve something similar, in Python?
A:
Try the marshal module - it's internal (used by the byte-compiler) and intentionally not advertised much, but it is much faster. Note that it doesn't serialize arbitrary instances like pickle, only builtin types (don't remember the exact constraints, see docs). Also note that the format isn't stable.
If you need to initialize multiple processes and can tolerate one process always loaded, there is an elegant solution: load the objects in one process, and then do nothing in it except forking processes on demand. Forking is fast (copy on write) and shares the memory between all processes. [Disclaimers: untested; unlike Ruby, Python ref counting will trigger page copies so this is probably useless if you have huge objects and/or access a small fraction of them.]
If your objects contain lots of raw data like numpy arrays, you can memory-map them for much faster startup. pytables is also good for these scenarios.
If you'll only use a small part of the objects, then an OO database (like Zope's) can probably help you. Though if you need them all in memory, you will just waste lots of overhead for little gain. (never used one, so this might be nonsense).
Maybe other python implementations can do it? Don't know, just a thought...
A:
Are you load()ing the pickled data directly from the file? What about to try to load the file into the memory and then do the load?
I would start with trying the cStringIO(); alternatively you may try to write your own version of StringIO that would use buffer() to slice the memory which would reduce the needed copy() operations (cStringIO still may be faster, but you'll have to try).
There are sometimes huge performance bottlenecks when doing these kinds of operations especially on Windows platform; the Windows system is somehow very unoptimized for doing lots of small reads while UNIXes cope quite well; if load() does lot of small reads or you are calling load() several times to read the data, this would help.
A:
I haven't used cPickle (or Python) but in cases like this I think the best strategy is to
avoid unnecessary loading of the objects until they are really needed - say load after start up on a different thread, actually its usually better to avoid unnecessary loading/initialization at anytime for obvious reasons. Google 'lazy loading' or 'lazy initialization'. If you really need all the objects to do some task before server start up then maybe you can try to implement a manual custom deserialization method, in other words implement something yourself if you have intimate knowledge of the data you will deal with which can help you 'squeeze' better performance then the general tool for dealing with it.
A:
Did you try sacrificing efficiency of pickling by not using HIGHEST_PROTOCOL? It isn't clear what performance costs are associated with using this protocol, but it might be worth a try.
A:
Impossible to answer this without knowing more about what sort of data you are loading and how you are using it.
If it is some sort of business logic, maybe you should try turning it into a pre-compiled module;
If it is structured data, can you delegate it to a database and only pull what is needed?
Does the data have a regular structure? Is there any way to divide it up and decide what is required and only then load it?
A:
I'll add another answer that might be helpful - if you can, can you try to define _slots_ on the class that is most commonly created? This may be a little limiting and impossible, however it seems to have cut the time needed for initialization on my test to about a half.
| How to deserialize 1GB of objects into Python faster than cPickle? | We've got a Python-based web server that unpickles a number of large data files on startup using cPickle. The data files (pickled using HIGHEST_PROTOCOL) are around 0.4 GB on disk and load into memory as about 1.2 GB of Python objects -- this takes about 20 seconds. We're using Python 2.6 on 64-bit Windows machines.
The bottleneck is certainly not disk (it takes less than 0.5s to actually read that much data), but memory allocation and object creation (there are millions of objects being created). We want to reduce the 20s to decrease startup time.
Is there any way to deserialize more than 1GB of objects into Python much faster than cPickle (like 5-10x)? Because the execution time is bound by memory allocation and object creation, I presume using another unpickling technique such as JSON wouldn't help here.
I know some interpreted languages have a way to save their entire memory image as a disk file, so they can load it back into memory all in one go, without allocation/creation for each object. Is there a way to do this, or achieve something similar, in Python?
| [
"\nTry the marshal module - it's internal (used by the byte-compiler) and intentionally not advertised much, but it is much faster. Note that it doesn't serialize arbitrary instances like pickle, only builtin types (don't remember the exact constraints, see docs). Also note that the format isn't stable.\nIf you n... | [
17,
7,
4,
3,
2,
2
] | [] | [] | [
"deserialization",
"pickle",
"python",
"serialization"
] | stackoverflow_0004195202_deserialization_pickle_python_serialization.txt |
Q:
Circular Reference with python lists
Can someone explain this?
>>> x = x[0] = [0]
>>> x
[[...]]
>>> x is x[0]
True
>>> x[0][0][0][0][0][0][0]
[[...]]
>>> x in x
True
what is [...]?
A:
That's just Python telling you that you have a circular reference; it's smart enough not to enter an infinite loop trying to print it out.
A:
iPython will do this:
[<Recursion on list with id=38505216>]
It's the same thing; the interpreter telling you that you have a recursive data structure.
A:
It's output by the method responsible for generating the representation of the structure. It represents a recursive structure, elided since it can be nested infinitely.
| Circular Reference with python lists | Can someone explain this?
>>> x = x[0] = [0]
>>> x
[[...]]
>>> x is x[0]
True
>>> x[0][0][0][0][0][0][0]
[[...]]
>>> x in x
True
what is [...]?
| [
"That's just Python telling you that you have a circular reference; it's smart enough not to enter an infinite loop trying to print it out.\n",
"iPython will do this:\n[<Recursion on list with id=38505216>]\nIt's the same thing; the interpreter telling you that you have a recursive data structure.\n",
"It's out... | [
15,
4,
3
] | [] | [] | [
"circular_reference",
"list",
"python"
] | stackoverflow_0004196329_circular_reference_list_python.txt |
Q:
Python app to django web app
I've written some python code to accomplish a task. Currently, there are 4-5 classes that I'm storing in separate files. I'd now like to change this whole thing into a database-backed web app. I've been reading tutorials on Django, and so far I get the impression that I'll need to manually specify the fields and their types for every "model" that I use. This is a little surprising to me, since I was expecting some kind of ORM capability that would just take the existing classes I've already defined, and map them onto a database somehow, in a manner abstracted away from me.
Is this not the case? Am I missing something? It looks like I need to specify all the fields and types in the file 'models.py'.
Okay, now beyond those specifics, does anyone have any general tips on the best way to migrate an object-oriented desktop application to a web application?
Thanks!
A:
That is Django's ORM: it maps classes to tables. What else did you expect? There needs to be some way of specifying what the fields are, though, before you can use them, and that's managed through the models.Model class and the various models.Field subclasses. You can certainly use your classes as mixins in order to use the existing business logic on top of the field definitions.
A:
If you are thinking about a database backend based web app, you have to specify what fields of the data you want to store and what type of the value you want stored.
There is an abstraction that introspects the db to convert it into the django models.py format. But I know not of any that introspects a python class and stores arbitrary data into db. How would that even work? Are the objects, now, stored as a pickle?
A:
You're going to have to check the output, but you can have Django automatically create models from existing databases through one-time introspection.
Taken from the link below, you would set up your database in settings.py, and then call
python manage.py inspectdb
This will dump the sample models.py file to standard out for your inspection. In order to create the file, simply redirect the output
python manage.py inspectdb > models.py
See for more:
http://docs.djangoproject.com/en/dev/howto/legacy-databases/?from=olddocs#auto-generate-the-models
| Python app to django web app | I've written some python code to accomplish a task. Currently, there are 4-5 classes that I'm storing in separate files. I'd now like to change this whole thing into a database-backed web app. I've been reading tutorials on Django, and so far I get the impression that I'll need to manually specify the fields and their types for every "model" that I use. This is a little surprising to me, since I was expecting some kind of ORM capability that would just take the existing classes I've already defined, and map them onto a database somehow, in a manner abstracted away from me.
Is this not the case? Am I missing something? It looks like I need to specify all the fields and types in the file 'models.py'.
Okay, now beyond those specifics, does anyone have any general tips on the best way to migrate an object-oriented desktop application to a web application?
Thanks!
| [
"That is Django's ORM: it maps classes to tables. What else did you expect? There needs to be some way of specifying what the fields are, though, before you can use them, and that's managed through the models.Model class and the various models.Field subclasses. You can certainly use your classes as mixins in order ... | [
1,
0,
0
] | [] | [] | [
"django",
"django_models",
"python",
"web_applications"
] | stackoverflow_0004192339_django_django_models_python_web_applications.txt |
Q:
Tutorials on optimizing non-trivial Python applications with C extensions or Cython
The Python community has published helpful reference material showing how to profile Python code, and the technical details of Python extensions in C or in Cython. I am still searching for tutorials which show, however, for non-trivial Python programs, the following:
How to identify the hotspots which will benefit from optimization by conversion to a C extension
Just as importantly, how to identify the hotspots which will not benefit from conversion to a C extension
Finally, how to make the appropriate conversion from Python to C, either using the Python C-API or (perhaps even preferably) using Cython.
A good tutorial would provide the reader with a methodology on how to reason through the problem of optimization by working through a complete example. I have had no success finding such a resource.
Do you know of (or have you written) such a tutorial?
For clarification, I'm not interested in tutorials that cover only the following:
Using (c)Profile to profile Python code to measure running times
Using tools to examine profiles (I recommend RunSnakeRun)
Optimizing by selecting more appropriate algorithms or Python constructs (e.g., sets for membership tests instead of lists); the tutorial should assume the algorithm and Python code is already optimal, and we are at a point where a C extension is the next logical step
Recapitulating the Python documentation on writing C extensions, which is already excellent as a reference but not useful as a resource for showing when and how to move from Python to C.
A:
Points 1 and 2 are just basic optimization rule of thumbs. I would be very astonished if there was anywhere the kind of tutorial you are looking for. Maybe that's why you haven't found one. My short list:
rule number one of optimization is don't.
rule number two measure
rule number three identify the limiting factor (if it's IO or database bound, no optimization may be reachable anyway).
rule number four is think, use better algorithms and data structure
...
considering a change of language is quite low on the list...
Just start by profiling your python code with usual python tools. Find where you code need to be optimized. Then try to optimize it sticking with python. If it is still too slow, try to understand why. If it's IO bound it is unlikely a C program would be better. If the problem come from the algorithm it is also unlikely C would perform better. Really the "good" cases where C could help are quite rare, runtime should not be too far away from what you want (like a 2 of 3 times speedup) data structure are simples and would benefit from a low level representation and you really, really need that speedup. In most other cases using C instead of python will be an unrewarding job.
Really it is quite rare calling C code from python is done with performance in mind as a primary goal. More often the goal is to interface python with some existing C code.
And as another other poster said, you would probably be better advised of using cython.
If you still want to write a C module for Python, all necessary is in the official documentation.
A:
O'Reilly has a tutorial (freely available as far as I can tell, I was able to read the whole thing) that illustrates how to profile a real project (they use an EDI parsing project as a subject for profiling) and identify hotspots. There's not too much detail on writing the C extension that will fix the bottleneck in the O'Reilly article. It does, however, cover the first two things that you want with a non-trivial example.
The process of writing C extensions is fairly well documented here. The hard part is coming up with ways to replicate what Python code is doing in C, and that takes something that would be hard to teach in a tutorial: ingenuity, knowledge of algorithms, hardware, and efficiency, and considerable C skill.
Hope this helps.
A:
For points 1 and 2, I would use a Python profiler, for example cProfile. See here for a quick tutorial.
If you've got an already existing python program, for point 3 you might want to consider using Cython. Of course, rather than re-writing in C, you may be able to think up an algorithmic improvement that will increase execution speed.
A:
I will try to address your points 1 and 2, and your first 3 bullet points, but not in order.
The third bullet point says "assume the algorithm and python code is already optimal". When code is in that state, if one takes stack samples (as outlined here), the samples show exactly what the program is doing, from a time perspective, and there seems to be nothing that could be improved without language change. However, since you know how it is spending its time, you know which low-level algorithm (which could consist of more than one function, not just a hotspot) could benefit by being made to take less time, i.e. by being converted to C.
Regarding point 1, this method shows which parts of the code will benefit by conversion to C, and they may or may not be hotspots. (The first thing that comes to mind is any sort of recursive function or set of functions. Or, a small group of functions that together accomplish some purpose, such as a hill-climber.)
Regarding point 2, any code which does not appear on a healthy percent of stack samples, or which does but clearly will not benefit by being converted to C, such as I/O.
Regarding the first and second bullet points, I would agree that measuring is not the primary objective, but a by-product of the process of finding the code to optimize. Presenting such measurements also is beside the point.
I have been in similar situations, except not between python and C, but between C and hardware.**
Just to give an example, if the total run time is 10 seconds, and the algorithm is on the stack roughly 50% of the time, then it is responsible for roughly 5 of the 10 seconds. If converting the algorithm to C would give a 10x speedup, then that 5 seconds would shrink to 0.5 seconds, so the overall time would shrink to 5.5 seconds. (Roughly - it's more important to achieve the time reduction than to know in advance precisely how big it will be.) Notice, at this point, the whole process could be repeated, and it might make sense to convert something else to C also.
You can stop this process when samples show that the python code is doing what it's good at, and the C code is doing what it's good at.
** e.g. Floating-point math, library vs. chip, or graphics, drawing text & polygons.
| Tutorials on optimizing non-trivial Python applications with C extensions or Cython | The Python community has published helpful reference material showing how to profile Python code, and the technical details of Python extensions in C or in Cython. I am still searching for tutorials which show, however, for non-trivial Python programs, the following:
How to identify the hotspots which will benefit from optimization by conversion to a C extension
Just as importantly, how to identify the hotspots which will not benefit from conversion to a C extension
Finally, how to make the appropriate conversion from Python to C, either using the Python C-API or (perhaps even preferably) using Cython.
A good tutorial would provide the reader with a methodology on how to reason through the problem of optimization by working through a complete example. I have had no success finding such a resource.
Do you know of (or have you written) such a tutorial?
For clarification, I'm not interested in tutorials that cover only the following:
Using (c)Profile to profile Python code to measure running times
Using tools to examine profiles (I recommend RunSnakeRun)
Optimizing by selecting more appropriate algorithms or Python constructs (e.g., sets for membership tests instead of lists); the tutorial should assume the algorithm and Python code is already optimal, and we are at a point where a C extension is the next logical step
Recapitulating the Python documentation on writing C extensions, which is already excellent as a reference but not useful as a resource for showing when and how to move from Python to C.
| [
"Points 1 and 2 are just basic optimization rule of thumbs. I would be very astonished if there was anywhere the kind of tutorial you are looking for. Maybe that's why you haven't found one. My short list:\n\nrule number one of optimization is don't.\nrule number two measure\nrule number three identify the limiting... | [
9,
6,
4,
2
] | [] | [] | [
"c",
"cython",
"optimization",
"python",
"python_extensions"
] | stackoverflow_0004189328_c_cython_optimization_python_python_extensions.txt |
Q:
How to restrict dropdown in Django admin
class A(models.Model):
foreign = models.ForeignKey(B, unique=True)
I have the code above - how can I ensure that in the dropdown under A's Admin, for 'foreign', I am only presented with unique choices? This is just to prevent a user violating the uniqueness constraint and being presenting with the admin error message.
A:
Please look at ModelAdmin.formfield_for_foreignkey() here. The downside is having to resort to raw SQL.
class AModelAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "foreign":
kwargs["queryset"] = B.objects.raw('SELECT * FROM myapp_a where not exists (select id from myapp_b where b.id=a.foreign_id')
return super(AModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
IMHO "non-null non-blank unique FKs" looks like good opportunity to rethink your modeling - may be merging two models. Everytime I found myself struggling too hard in Django I was trying to do something naive.
| How to restrict dropdown in Django admin | class A(models.Model):
foreign = models.ForeignKey(B, unique=True)
I have the code above - how can I ensure that in the dropdown under A's Admin, for 'foreign', I am only presented with unique choices? This is just to prevent a user violating the uniqueness constraint and being presenting with the admin error message.
| [
"Please look at ModelAdmin.formfield_for_foreignkey() here. The downside is having to resort to raw SQL.\nclass AModelAdmin(admin.ModelAdmin):\ndef formfield_for_foreignkey(self, db_field, request, **kwargs):\n if db_field.name == \"foreign\":\n kwargs[\"queryset\"] = B.objects.raw('SELECT * FROM myapp_a ... | [
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0004196673_django_django_admin_python.txt |
Q:
Where do two 2-D arrays begin to overlap each other?
I'm working with model output at the moment, and I can't seem to come up with a nice way of combining two arrays of data. Arrays A and B store different data, and the entries in each correspond to some spatial (x,y) point -- A holds some parameter, and B holds model output. The problem is that B is a spatial subsection of A -- that is, if the model were for the entire world, A would store the parameter at each point on the earth, and B would store the model output only for those points in Africa.
So I need to find how much B is offset from A -- put another way, I need to find the indexes at which they start to overlap. So if A.shape=(1000,1500), is B the (750:850, 200:300) part of that, or the (783:835, 427:440) subsection? I have arrays associated with both A and B which store the (x,y) positions of the gridpoints for each.
This would seem to be a simple problem -- find where the two arrays overlap. And I can solve it with scipy.spatial's KDTree simply enough, but it's very slow. Anyone have any better ideas?
A:
I have arrays associated with both A and B which store the (x,y) positions of the gridpoints for each.
In that case, the answer should be fairly simple...
Are the two grids strictly on the same gridding scheme? Assuming they are, you can just do something like:
np.argwhere((Ax == Bx.min()) & (Ay == By.min()))
Assuming the world coordinates of the two grids increase in the same direction as the indicies of the grids, this gives the lower left corner of the subsetted grid. (And if they don't increase in the same direction (i.e. negative dx or dy), it just gives one of the other corners)
In the example below, we could obviously just calculate the proper indicies from ix = (Bxmin - Axmin) / dx, etc, but assuming you have a more complex gridding system, this will still work. However, this is assuming that the two grids are on the same gridding scheme! It's slightly more complex if they're not...
import numpy as np
# Generate grids of coordinates from a min, max, and spacing
dx, dy = 0.5, 0.5
# For the larger grid...
Axmin, Axmax = -180, 180
Aymin, Aymax = -90, 90
# For the smaller grid...
Bxmin, Bxmax = -5, 10
Bymin, Bymax = 30, 40
# Generate the indicies on a 2D grid
Ax = np.arange(Axmin, Axmax+dx, dx)
Ay = np.arange(Aymin, Aymax+dy, dy)
Ax, Ay = np.meshgrid(Ax, Ay)
Bx = np.arange(Bxmin, Bxmax+dx, dx)
By = np.arange(Bymin, Bymax+dy, dy)
Bx, By = np.meshgrid(Bx, By)
# Find the corner of where the two grids overlap...
ix, iy = np.argwhere((Ax == Bxmin) & (Ay == Bymin))[0]
# Assert that the coordinates are identical.
assert np.all(Ax[ix:ix+Bx.shape[0], iy:iy+Bx.shape[1]] == Bx)
assert np.all(Ay[ix:ix+Bx.shape[0], iy:iy+Bx.shape[1]] == By)
A:
Can you say more? What model are you using? What are you modelling? How is it computed?
Can you make the dimensions match to avoid the fit? (i.e. if B doesn't depend on all of A, only plug in the part of A that B models, or compute boring values for the parts of B that wouldn't overlap A and drop those values later)
A:
I need to find the indexes at which they start to overlap
So are you looking for indexes from A or from B? And is B strictly rectangular?
Finding the bounding box or convex hull of B is really cheap.
| Where do two 2-D arrays begin to overlap each other? | I'm working with model output at the moment, and I can't seem to come up with a nice way of combining two arrays of data. Arrays A and B store different data, and the entries in each correspond to some spatial (x,y) point -- A holds some parameter, and B holds model output. The problem is that B is a spatial subsection of A -- that is, if the model were for the entire world, A would store the parameter at each point on the earth, and B would store the model output only for those points in Africa.
So I need to find how much B is offset from A -- put another way, I need to find the indexes at which they start to overlap. So if A.shape=(1000,1500), is B the (750:850, 200:300) part of that, or the (783:835, 427:440) subsection? I have arrays associated with both A and B which store the (x,y) positions of the gridpoints for each.
This would seem to be a simple problem -- find where the two arrays overlap. And I can solve it with scipy.spatial's KDTree simply enough, but it's very slow. Anyone have any better ideas?
| [
"\nI have arrays associated with both A and B which store the (x,y) positions of the gridpoints for each.\n\nIn that case, the answer should be fairly simple...\nAre the two grids strictly on the same gridding scheme? Assuming they are, you can just do something like:\nnp.argwhere((Ax == Bx.min()) & (Ay == By.min()... | [
1,
0,
0
] | [] | [] | [
"multidimensional_array",
"numpy",
"overlap",
"python",
"subdomain"
] | stackoverflow_0004150909_multidimensional_array_numpy_overlap_python_subdomain.txt |
Q:
Python: Create a tuple from a command line input
I have a program which provides a command line input like this:
python2.6 prog.py -p a1 b1 c1
Now, we can have any number of input parameters i.e. -p a1 and -p a1 c1 b1 e2 are both possibilities.
I want to create a tuple based on the variable input parameters. Any suggestions on how to do this would be very helpful! A fixed length tuple would be easy, but I am not sure how to implement a variable length one.
thanks.
A:
A tuple is fixed in length. Once you create a tuple, you can't modify it.
The command line arguments are stored in a list.
import sys
t = tuple(sys.argv[1:]) # since sys.argv[0] is the name of the script
A:
This should do it:
import sys
t = tuple(sys.argv)
Since maybe you don't want the script name, then you might want to do this:
if len(sys.argv) > 1:
t = tuple(sys.argv[1:])
A:
Iterate through sys.argv until you reach another flag.
A:
You can transform lists into tuples using the tuple() constructor:
>>> tuple([1, 2, 3, 4])
(1, 2, 3, 4)
Use this on sys.argv =), or a slice of it.
Cheers!
A:
Why don't you look at the *args and **kwargs discussion a while back?
A:
import sys
t1 = tuple(sys.argv)
t2 = tuple(sys.argv[1:])
print t1
print t2
A:
You can get the args from the command line using getopt. It returns a list of the args, which you can then turn into a tuple using tuple()
import getopt
import sys
def main(argv):
opts, args = getopt.getopt(argv, 'p')
return tuple(args)
if __name__=='__main__':
main(sys.argv[1:])
See http://www.faqs.org/docs/diveintopython/kgp_commandline.html
A:
The correct answer to your exact question is tuple(sys.argv[1:]), but there are better ways to get the command line arguments so you can use them more appropriately. Try optparse :
http://www.doughellmann.com/PyMOTW/optparse/
If you're using Python 2.7 you should use argparse.
| Python: Create a tuple from a command line input | I have a program which provides a command line input like this:
python2.6 prog.py -p a1 b1 c1
Now, we can have any number of input parameters i.e. -p a1 and -p a1 c1 b1 e2 are both possibilities.
I want to create a tuple based on the variable input parameters. Any suggestions on how to do this would be very helpful! A fixed length tuple would be easy, but I am not sure how to implement a variable length one.
thanks.
| [
"A tuple is fixed in length. Once you create a tuple, you can't modify it.\nThe command line arguments are stored in a list. \nimport sys\nt = tuple(sys.argv[1:]) # since sys.argv[0] is the name of the script\n\n",
"This should do it:\nimport sys\nt = tuple(sys.argv)\n\nSince maybe you don't want the script name,... | [
2,
1,
1,
1,
1,
1,
1,
1
] | [] | [] | [
"command",
"command_line_arguments",
"python",
"tuples"
] | stackoverflow_0004196389_command_command_line_arguments_python_tuples.txt |
Q:
'ascii' codec error in beautifulsoup
I am using beautifulsoup for scraping data from the html page. Till yesterday every thing was fine. But Now i am getting the error:
'ascii' codec can't encode character u'\xa9' in position 86700: ordinal not in range(128)
i am using the code:
import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page)
This is giving me the error.
A:
A wild guess:
Try specifying the encoding of the page?
soup = BeautifulSoup(page, fromEncoding=<encoding of the page>)
This can also be a problem with the Python installation. If you print non-ASCII characters without BeautifulSoup, do you face the same problem? If yes, then you need to set the encoding:
import sys
sys.setdefaultencoding("utf-8") # or whatever you want the default encoding to be.
A:
A wild stab in the dark: you're reading a page that doesn't explicitly declare an encoding and yet is not 7-bit ASCII?
| 'ascii' codec error in beautifulsoup | I am using beautifulsoup for scraping data from the html page. Till yesterday every thing was fine. But Now i am getting the error:
'ascii' codec can't encode character u'\xa9' in position 86700: ordinal not in range(128)
i am using the code:
import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page)
This is giving me the error.
| [
"A wild guess:\nTry specifying the encoding of the page? \nsoup = BeautifulSoup(page, fromEncoding=<encoding of the page>)\n\nThis can also be a problem with the Python installation. If you print non-ASCII characters without BeautifulSoup, do you face the same problem? If yes, then you need to set the encoding:\nim... | [
2,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0004197303_beautifulsoup_python.txt |
Q:
How do I use generic views in Django?
I am trying to use Django's generic views to make a user registration page. I have the following code in my app's urls.py
from django.conf.urls.defaults import *
from models import Ticket
urlpatterns = patterns('',
(r'^new/$', 'django.views.generic.create_update.create_object', { 'model': User } ),
)
Now when I go to that url I get the following:
TemplateDoesNotExist at /new/
auth/user_form.html
I have tried making a template to match it but I keep getting that message. Any advice?
Also, I assumed that this would make the template for me. What do I actually put in the template file when I make it?
EDIT: Coming from rails I was mixing templates and views. I am still stuck but I think I need to make a function in my view. Something like:
def user_form:
#stuff
A:
i don't think you need to create a view function. you need to provide a template (auth/user_form.html in this case, is also configurable) in your templates directory. The template needs to contain the necessary fields to create the new user object.
see the docs for this.
ans also check out this similar discussion
A:
You will need to create the template file using the format <app_label>/<model_name>_form.html. Place this template into the template directory as defined in TEMPLATE_DIRS in your settings file.
In the template file itself, you will need to use the context as defined by the standard ModelForm.
{{ form.name.label_tag }} {{ form.name }}
| How do I use generic views in Django? | I am trying to use Django's generic views to make a user registration page. I have the following code in my app's urls.py
from django.conf.urls.defaults import *
from models import Ticket
urlpatterns = patterns('',
(r'^new/$', 'django.views.generic.create_update.create_object', { 'model': User } ),
)
Now when I go to that url I get the following:
TemplateDoesNotExist at /new/
auth/user_form.html
I have tried making a template to match it but I keep getting that message. Any advice?
Also, I assumed that this would make the template for me. What do I actually put in the template file when I make it?
EDIT: Coming from rails I was mixing templates and views. I am still stuck but I think I need to make a function in my view. Something like:
def user_form:
#stuff
| [
"i don't think you need to create a view function. you need to provide a template (auth/user_form.html in this case, is also configurable) in your templates directory. The template needs to contain the necessary fields to create the new user object.\nsee the docs for this.\nans also check out this similar discussio... | [
1,
1
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python"
] | stackoverflow_0004197221_django_django_templates_django_views_python.txt |
Q:
Pipe out of a command or script to another python script
I'm relatively to to python and I'm trying to write a python script to which one can pipe the output of a command or another script.
example command | python_sript.py
In python script I'll basically analyze the output of command and save it to file.
I thought I'll be able to do this with redirecting sys.stdin to subprocess.PIPE, but it didn't work.
sys.stdin = subprocess.PIPE
Can some one please suggest how should I approach this?
Also what would happen if command or script pipes data at faster rate then what python script can process.
Note: When I use this script
import sys
data = sys.stdin.readline()
print(data)
I get this
D:\>echo "test" | tee.py
The process tried to write to a nonexistent pipe.
Traceback (most recent call last):
File "D:\Profiles\Administrator\My Documents\Workspace\tee.py", line 3, in <mo
dule>
data = sys.stdin.readline()
AttributeError: 'NoneType' object has no attribute 'readline'
and when I use this
import sys
data = input()
print(data)
I get this
D:\>echo "test" | tee.py
The process tried to write to a nonexistent pipe.
Traceback (most recent call last):
File "D:\Profiles\Administrator\My Documents\Workspace\tee.py", line 3, in <mo
dule>
data = input()
RuntimeError: input(): lost sys.stdin
A:
On (old) Windows when you use pipes you need to call python scripts using python executable by default due to NT redirection bug:
D:\> echo "test" | python tee.py
After that sys.stdin, raw_input(), fileinput.input() should work as expected.
A:
You seem to be a bit unclear on how pipes work. They are handled by the OS, not the individual programs -- so if you write a Python script designed to take input data from a pipe, it should just read stdin as normal and the redirection will be handled for you. The data will be consumed as fast as they are generated; if the script consumes data more slowly than they are generated then they will be stored in a buffer.
Or are you trying to communicate between two Python scripts? If so there are better ways than through stdin and stdout.
A:
Question 1 (reading from a pipe) has been answered by others: Just read stdin in python_script.py. The OS handles the redirection through pipes.
Question 2 (writing/reading speed) has also been answered: OS pipes are buffered, so nothing to be concerned about here.
Question 3 (the stack traces): Your first program runs fine with me. - Are you really giving the whole code here?
As for subprocess.PIPE: You really only want to use this, if you start a new command from within your running Python script, so you can communicate with the child process. As you are not doing this, it is of no use to you. Pipes on the shell level don't constitute parent-child processes.
| Pipe out of a command or script to another python script | I'm relatively to to python and I'm trying to write a python script to which one can pipe the output of a command or another script.
example command | python_sript.py
In python script I'll basically analyze the output of command and save it to file.
I thought I'll be able to do this with redirecting sys.stdin to subprocess.PIPE, but it didn't work.
sys.stdin = subprocess.PIPE
Can some one please suggest how should I approach this?
Also what would happen if command or script pipes data at faster rate then what python script can process.
Note: When I use this script
import sys
data = sys.stdin.readline()
print(data)
I get this
D:\>echo "test" | tee.py
The process tried to write to a nonexistent pipe.
Traceback (most recent call last):
File "D:\Profiles\Administrator\My Documents\Workspace\tee.py", line 3, in <mo
dule>
data = sys.stdin.readline()
AttributeError: 'NoneType' object has no attribute 'readline'
and when I use this
import sys
data = input()
print(data)
I get this
D:\>echo "test" | tee.py
The process tried to write to a nonexistent pipe.
Traceback (most recent call last):
File "D:\Profiles\Administrator\My Documents\Workspace\tee.py", line 3, in <mo
dule>
data = input()
RuntimeError: input(): lost sys.stdin
| [
"On (old) Windows when you use pipes you need to call python scripts using python executable by default due to NT redirection bug:\nD:\\> echo \"test\" | python tee.py\n\nAfter that sys.stdin, raw_input(), fileinput.input() should work as expected.\n",
"You seem to be a bit unclear on how pipes work. They are han... | [
4,
1,
0
] | [] | [] | [
"pipe",
"python",
"windows"
] | stackoverflow_0004196969_pipe_python_windows.txt |
Q:
Using lxml & django/python - list index out of range
I have a small issue. I am trying to pull some data from my XML using lxml and I keep getting a "list index out of range" error, now I am trying to get the [0] position of my list, which should be the first one but it keeps giving me the error.
Here is a code snippet (thanks to MattH for helping me out):
req2 = urllib2.Request("web_url/public/api.php?path_info=/projects&token=##############")
resp = urllib2.urlopen(req2)
resp_data = resp.read()
if not resp.code == 200 and resp.headers.get('content-type') == 'text/xml':
# Do your error handling.
raise Exception('Unexpected response',req2,resp)
data = etree.XML(resp_data)
api_id = int(data.xpath('/project/id/text()')[0])
project.API_id = api_id
project.save()
Now when I do a print statement, it pulls the XML so I know that I have xml data and its not blank, but not sure what else could be causing this?
Thanks!
Steve
A:
With your XML document's structure being
<projects>
<projects>
<id>
...
</id>
</project>
</projects>
your XPath expression /project/id/text() surely won't match anything, and the accessing index 0 of the empty XPath result list of course results in an IndexError.
Instead of /project, which only matches a root (!) element called "project", you might want to use /projects/project or //project. So a correct XPath for your XML structure would be //project/id/text().
| Using lxml & django/python - list index out of range | I have a small issue. I am trying to pull some data from my XML using lxml and I keep getting a "list index out of range" error, now I am trying to get the [0] position of my list, which should be the first one but it keeps giving me the error.
Here is a code snippet (thanks to MattH for helping me out):
req2 = urllib2.Request("web_url/public/api.php?path_info=/projects&token=##############")
resp = urllib2.urlopen(req2)
resp_data = resp.read()
if not resp.code == 200 and resp.headers.get('content-type') == 'text/xml':
# Do your error handling.
raise Exception('Unexpected response',req2,resp)
data = etree.XML(resp_data)
api_id = int(data.xpath('/project/id/text()')[0])
project.API_id = api_id
project.save()
Now when I do a print statement, it pulls the XML so I know that I have xml data and its not blank, but not sure what else could be causing this?
Thanks!
Steve
| [
"With your XML document's structure being\n<projects>\n <projects>\n <id>\n ...\n </id>\n </project>\n</projects>\n\nyour XPath expression /project/id/text() surely won't match anything, and the accessing index 0 of the empty XPath result list of course results in an IndexError.\nInst... | [
3
] | [] | [] | [
"django",
"django_views",
"lxml",
"python"
] | stackoverflow_0004196770_django_django_views_lxml_python.txt |
Q:
To select a few columns in some tables related
I have these classes:
class Channel(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("channels")
id = Column("id", Integer, primary_key=True)
title = Column("title", String(100))
items = relationship("MediaItem", secondary=channel_items, order_by="MediaItem.titleView", backref="channels")
class MediaItem(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("media_items")
id = Column("id", Integer, primary_key=True)
title = Column("title", String(100))
class User(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("users")
id = Column("id", Integer, primary_key=True)
name = Column("name", String(50))
channels = relationship("Channel", secondary=user_channels, order_by="Channel.titleView", backref="users")
MediaItem is related to Channel and Channel is related to User.
if I'd like to select some columns from items and channels, I'd do this:
session = Session()
result = session.query(Channel).join(Channel.items).values(Channel.title, Item.title)
I get an instance of Channel class with its items.
My problem is I don't know how to select some columns from User, Channel and Item. How can I make a query where for example, I can select the User.name property and its channels with only Channel.title property and the items of those channels with only Item.title property?
Thanks in advance!
A:
You can use the sqlalchemy expression builder through your well-defined models:
session.query(User.name, Channel.title, MediaItem.title)\
.join(Channel.users).join(MediaItem.channels)
You can look into this in the docs:
http://www.sqlalchemy.org/docs/orm/query.html?highlight=join#sqlalchemy.orm.query.Query.join
| To select a few columns in some tables related | I have these classes:
class Channel(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("channels")
id = Column("id", Integer, primary_key=True)
title = Column("title", String(100))
items = relationship("MediaItem", secondary=channel_items, order_by="MediaItem.titleView", backref="channels")
class MediaItem(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("media_items")
id = Column("id", Integer, primary_key=True)
title = Column("title", String(100))
class User(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("users")
id = Column("id", Integer, primary_key=True)
name = Column("name", String(50))
channels = relationship("Channel", secondary=user_channels, order_by="Channel.titleView", backref="users")
MediaItem is related to Channel and Channel is related to User.
if I'd like to select some columns from items and channels, I'd do this:
session = Session()
result = session.query(Channel).join(Channel.items).values(Channel.title, Item.title)
I get an instance of Channel class with its items.
My problem is I don't know how to select some columns from User, Channel and Item. How can I make a query where for example, I can select the User.name property and its channels with only Channel.title property and the items of those channels with only Item.title property?
Thanks in advance!
| [
"You can use the sqlalchemy expression builder through your well-defined models:\nsession.query(User.name, Channel.title, MediaItem.title)\\\n .join(Channel.users).join(MediaItem.channels)\n\nYou can look into this in the docs:\nhttp://www.sqlalchemy.org/docs/orm/query.html?highlight=join#sqlalchemy.orm.query.Quer... | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003444652_python_sqlalchemy.txt |
Q:
how do I tell when a c++ program is waiting for input?
I'm trying to control a simple c++ program through python. The program works by prompting the user for input. The prompts are not necessarily endl terminated. What I would like to know is if there is a way to tell from python that the c++ program is no longer generating output and has switched to requesting input.
Here's an simple example:
c++
#include <iostream>
using namespace std;
int main()
{
int x;
cout << "Enter a number ";
cin >> x;
cout << x << " squared = " << x * x << endl;
}
python:
#! /usr/bin/python
import subprocess, sys
dproc = subprocess.Popen('./y', stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while (True) :
dout = dproc.stdout.read(1)
sys.stdout.write(dout)
dproc.stdin.write("22\n")
This sort of works but writes to dproc.stdin too much. What I am looking for instead is a way to read everything from dproc.stdout until the program is ready for input and then write to dproc.stdout .
If possible, I would like to do this w/o modifying the c++ code. ( However, I have tried playing with buffering on the c++ side but it didn't seem to help )
Thank you for any responses.
A:
I'm not aware of a sufficiently general paradigm for detecting that the remote end is waiting for input. I can think of basic ways, but also of situations in which they will fail. Examples:
Read with a non-blocking pipe/socket until no input arrives: the response might be interrupted by the process writing to disk, waiting for a reply from a database etc.
Wait until the process becomes idle: a background thread might still be running.
You'll have to be aware of the protocol used by the application you're trying to control. In a sense, you'll be designing an interpreter for that process. pexpect is a toolset for Python based on this idea.
A:
Have a look at pexpect.
| how do I tell when a c++ program is waiting for input? | I'm trying to control a simple c++ program through python. The program works by prompting the user for input. The prompts are not necessarily endl terminated. What I would like to know is if there is a way to tell from python that the c++ program is no longer generating output and has switched to requesting input.
Here's an simple example:
c++
#include <iostream>
using namespace std;
int main()
{
int x;
cout << "Enter a number ";
cin >> x;
cout << x << " squared = " << x * x << endl;
}
python:
#! /usr/bin/python
import subprocess, sys
dproc = subprocess.Popen('./y', stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while (True) :
dout = dproc.stdout.read(1)
sys.stdout.write(dout)
dproc.stdin.write("22\n")
This sort of works but writes to dproc.stdin too much. What I am looking for instead is a way to read everything from dproc.stdout until the program is ready for input and then write to dproc.stdout .
If possible, I would like to do this w/o modifying the c++ code. ( However, I have tried playing with buffering on the c++ side but it didn't seem to help )
Thank you for any responses.
| [
"I'm not aware of a sufficiently general paradigm for detecting that the remote end is waiting for input. I can think of basic ways, but also of situations in which they will fail. Examples:\n\nRead with a non-blocking pipe/socket until no input arrives: the response might be interrupted by the process writing to d... | [
6,
3
] | [] | [] | [
"c++",
"cin",
"cout",
"python"
] | stackoverflow_0004197871_c++_cin_cout_python.txt |
Q:
Is it possible to access the internal elements of an embedded Flash object via a scripting language?
I would like to be able to access all the components of say a Flash image gallery on someone else's site. I want to be able to find the images, image coordinates, action script code, audio files, video, etc. I do not want to manipulate these elements, I just want to view them and their related information.
Is this possible via scripting languages like Ruby, Python or Javascript?
A:
No, not really. Not like you can examine the DOM of a webpage. You can download and decompile the swf, but you may or may not be able to get all the info you want out.
A:
You can if (and only if) your application domain is the same.
| Is it possible to access the internal elements of an embedded Flash object via a scripting language? | I would like to be able to access all the components of say a Flash image gallery on someone else's site. I want to be able to find the images, image coordinates, action script code, audio files, video, etc. I do not want to manipulate these elements, I just want to view them and their related information.
Is this possible via scripting languages like Ruby, Python or Javascript?
| [
"No, not really. Not like you can examine the DOM of a webpage. You can download and decompile the swf, but you may or may not be able to get all the info you want out.\n",
"You can if (and only if) your application domain is the same. \n"
] | [
0,
0
] | [] | [] | [
"flash",
"javascript",
"python"
] | stackoverflow_0004198069_flash_javascript_python.txt |
Q:
How Can I limit bit number in the integer variable in Python?
I want to realize IDEA algorithm in Python. In Python we have no limits for variable size, but I need limit bit number in the integer number, for example, to do cyclic left shift. What do you advise?
A:
One way is to use the BitVector library.
Example of use:
>>> from BitVector import BitVector
>>> bv = BitVector(intVal = 0x13A5, size = 32)
>>> print bv
00000000000000000001001110100101
>>> bv << 6 #does a cyclic left shift
>>> print bv
00000000000001001110100101000000
>>> bv[0] = 1
>>> print bv
10000000000001001110100101000000
>>> bv << 3 #cyclic shift again, should be more apparent
>>> print bv
00000000001001110100101000000100
A:
An 8-bit mask with a cyclic left shift:
shifted = number << 1
overflowed = (number & 0x100) >> 8
shifted &= 0xFF
result = overflowed | shifted
You should be able to make a class that does this for you. With a bit more of the same, it can shift an arbitrary amount out of an arbitrary sized value.
A:
The bitstring module might be of help (documentation here). This example creates a 22 bit bitstring and rotates the bits 3 to the right:
>>> from bitstring import BitArray
>>> a = BitArray(22) # creates 22-bit zeroed bitstring
>>> a.uint = 12345 # set the bits with an unsigned integer
>>> a.bin # view the binary representation
'0b0000000011000000111001'
>>> a.ror(3) # rotate to the right
>>> a.bin
'0b0010000000011000000111'
>>> a.uint # and back to the integer representation
525831
A:
If you want a the low 32 bits of a number, you can use binary-and like so:
>>> low32 = (1 << 32) - 1
>>> n = 0x12345678
>>> m = ((n << 20) | (n >> 12)) & low32
>>> "0x%x" % m
'0x67812345'
| How Can I limit bit number in the integer variable in Python? | I want to realize IDEA algorithm in Python. In Python we have no limits for variable size, but I need limit bit number in the integer number, for example, to do cyclic left shift. What do you advise?
| [
"One way is to use the BitVector library.\nExample of use:\n>>> from BitVector import BitVector\n>>> bv = BitVector(intVal = 0x13A5, size = 32)\n>>> print bv\n00000000000000000001001110100101\n>>> bv << 6 #does a cyclic left shift\n>>> print bv\n00000000000001001110100101000000\n>>> bv[0]... | [
3,
2,
2,
1
] | [] | [] | [
"algorithm",
"cryptography",
"python"
] | stackoverflow_0004197934_algorithm_cryptography_python.txt |
Q:
Python - Using "Google AJAX Search" API's Local Search Objects
I've just started using Google's search API to find addresses and the distances between those addresses. I used geopy for this, but, I often had the problem of not getting the correct addresses for my queries. I decided to experiment, therefore, with Google's "Local Search" (http://code.google.com/apis/ajaxsearch/local.html).
Anyway, I wanted to ask if I could use the "Local Search" objects provided by the API within python. Something tells me that I can't and that I have to use json. Does anyone know if there is a work around?
PS: Im trying to make something like this: http://www.google.com/uds/samples/random/lead.html ... except a matrix type deal where the insides will be filled with distances between the addresses.
Thanks for reading!
A:
As the docs say,
The Google AJAX Search API is a
Javascript library that allows you to
embed Google Search in your web pages
and other web applications. For Flash,
and other Non-Javascript environments,
the API exposes a raw RESTful
interface that returns JSON encoded
results that are easily processed by
most languages and runtimes.
Python has no trouble processing Json (e.g. with the json module in the standard library in 2.6 and better -- there are also several third party ones e.g. for earlier releases, simplejson being the direct precursor of today's standard json). So it's all about using the RESTful interface correctly, as for most Google APIs not directly wrapped for this or that non-Javascript language.
The code examples here are for Flash, Php, Java, Python, Perl -- they all boil down to visiting a specific URL, e.g. with urllib2 in Python, and processing the returned Json, e.g. with simplejson in (pre-2.6) Python.
All the queries in these RESTful code samples are for a web search, but local search is very similar, just start with the request URL with:
http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=...
i.e., use local in lieu of web in the URL.
A:
What are the other parameters for local search --- is there a way to set a N,S,E,W bounding box for the query?
http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=...
| Python - Using "Google AJAX Search" API's Local Search Objects | I've just started using Google's search API to find addresses and the distances between those addresses. I used geopy for this, but, I often had the problem of not getting the correct addresses for my queries. I decided to experiment, therefore, with Google's "Local Search" (http://code.google.com/apis/ajaxsearch/local.html).
Anyway, I wanted to ask if I could use the "Local Search" objects provided by the API within python. Something tells me that I can't and that I have to use json. Does anyone know if there is a work around?
PS: Im trying to make something like this: http://www.google.com/uds/samples/random/lead.html ... except a matrix type deal where the insides will be filled with distances between the addresses.
Thanks for reading!
| [
"As the docs say,\n\nThe Google AJAX Search API is a\n Javascript library that allows you to\n embed Google Search in your web pages\n and other web applications. For Flash,\n and other Non-Javascript environments,\n the API exposes a raw RESTful\n interface that returns JSON encoded\n results that are easil... | [
2,
0
] | [] | [] | [
"geopy",
"google_api",
"json",
"python"
] | stackoverflow_0002799702_geopy_google_api_json_python.txt |
Q:
How can I convert a batch of Mavenized examples into a format that Eclipse understands?
I'm in the process of looking at taking some examples that are currently in one format (NOT Mavenized - actually in ANT form) and trying to find an automated way to munge them into something that Eclipse can comprehend. Though I have several years of Java and other odd languages, doing this in Java sounds like using a sledgehammer to drive a nail.
I've been looking into scripting languages such as Ruby, Python, Perl, and so on. I have no experience with any of them, but would be happy to learn.
How can I take an example in one format (directory or directory with files) and restructure it into something approximating an Eclipse project? For example, I'd like to take a tree with the following structure
dir my_example
- build.xml
- deployment.xml
- jboss-esb-unfiltered.xml
- log4j.xml
- readme.txt
and convert it to
dir1 my_example_eclipse
- dir src
- [empty]
- dir esbcontent
- dir META-INF
- deployment.xml
- jboss-esb-unfiltered.xml
- log4j.xml
- readme.txt
In addition, I need the ability to create certain hidden files that Eclipse needs. One of these is the .project file like this:
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>helloworld</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
</natures>
</projectDescription>
How would I create a text file with one of these scripting languages?
Thanks in advance.
A:
How can I convert a batch of Mavenized examples into a format that Eclipse understands?
Eclipse can understand Mavenized projects. You have two options:
use the Maven Eclipse Plugin (a Maven plugin) and run mvn eclipse:eclipse on a Mavenized example to generate the .project and .classpath and then import it as Existing Project into Eclipse.
use the m2eclipse plugin (an Eclipse plugin) to directly import an Existing Maven Project into your workspace.
Both approach are exclusive, use one or the the other. Nowadays, people tend to prefer the m2eclipse plugin that provides full Maven integration.
A:
Before you do any "munging", I'd try getting your maven examples working in eclipse first. Eclipse has several plugins for working out of maven-based projects.
A:
This should do what you need (in Python):
import os
import shutil
def maven_to_eclipse(maven_dir, eclipse_dir):
# assumes mode of maven_dir will be the same as eclipse_dir
new_mode = os.stat(maven_dir).st_mode
if os.path.exists(eclipse_dir):
# if new_dir doesn't exist
# create it with same permissions as old_dir
os.mkdirs(eclipse_dir, new_mode)
# create directories under new_dir: src, ebscontent, ebscontent/META-INF
# use os.path.join to work on multiple os
os.mkdir(os.path.join(eclipse_dir, 'src'), new_mode)
os.mkdir(os.path.join(eclipse_dir, 'ebscontent'), new_mode)
os.mkdir(os.path.join(eclipse_dir, 'ebscontent', 'META-INF'), new_mode)
# cp old/deployment.xml new/ebsconent/META-INF/deployment.xml
shutil.copy2(os.path.join(maven_dir, 'deployment.xml'),
os.path.join(eclipse_dir, 'ebscontent', 'META-INF', 'deployment.xml'))
# cp old/jboss-esb-unfiltered.xml new/ebsconent/META-INF/jboss-esb-unfiltered.xml
shutil.copy2(os.path.join(maven_dir, 'jboss-esb-unfiltered.xml'),
os.path.join(eclipse_dir, 'ebscontent', 'META-INF', 'jboss-esb-unfiltered.xml'))
# cp old/log4j.xml new/ebsconent/log4j.xml
shutil.copy2(os.path.join(maven_dir, 'log4j.xml'),
os.path.join(eclipse_dir, 'ebscontent', 'log4j.xml'))
# cp old/readme.txt new/readme.txt
shutil.copy2(os.path.join(maven_dir, 'readme.txt'),
os.path.join(eclipse_dir, 'readme.txt'))
if __name__ == '__main__':
base_path = 'C:\\Path\\To\\Maven Dirs'
maven_dirs = ('my_example', 'another_example', 'third_example')
for maven_dir in maven_dirs:
maven_to_eclipse(os.path.join(base_path, maven_dir),
os.path.join(base_bath, maven_dir + '_eclipse'))
This should work on multiple OSes. This could have been written shorter, but would be more confusing to a newbie. No attempt is made to catch exceptions. For example, os.mkdirs might fail if the new directory already exists.
Change base_path and maven_dirs before running.
| How can I convert a batch of Mavenized examples into a format that Eclipse understands? | I'm in the process of looking at taking some examples that are currently in one format (NOT Mavenized - actually in ANT form) and trying to find an automated way to munge them into something that Eclipse can comprehend. Though I have several years of Java and other odd languages, doing this in Java sounds like using a sledgehammer to drive a nail.
I've been looking into scripting languages such as Ruby, Python, Perl, and so on. I have no experience with any of them, but would be happy to learn.
How can I take an example in one format (directory or directory with files) and restructure it into something approximating an Eclipse project? For example, I'd like to take a tree with the following structure
dir my_example
- build.xml
- deployment.xml
- jboss-esb-unfiltered.xml
- log4j.xml
- readme.txt
and convert it to
dir1 my_example_eclipse
- dir src
- [empty]
- dir esbcontent
- dir META-INF
- deployment.xml
- jboss-esb-unfiltered.xml
- log4j.xml
- readme.txt
In addition, I need the ability to create certain hidden files that Eclipse needs. One of these is the .project file like this:
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>helloworld</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
</natures>
</projectDescription>
How would I create a text file with one of these scripting languages?
Thanks in advance.
| [
"\nHow can I convert a batch of Mavenized examples into a format that Eclipse understands?\n\nEclipse can understand Mavenized projects. You have two options:\n\nuse the Maven Eclipse Plugin (a Maven plugin) and run mvn eclipse:eclipse on a Mavenized example to generate the .project and .classpath and then import i... | [
5,
2,
0
] | [] | [] | [
"eclipse",
"maven",
"perl",
"python",
"ruby"
] | stackoverflow_0004159006_eclipse_maven_perl_python_ruby.txt |
Q:
there is a PYTHON wrapper for KONSOLE?
hi
i want to make a OmmWriter clone for my shell terminal.
in python with QT
there are some wrappers for Konsole, or something similar, or whatever?
some advice?
A:
You mean something like pyqonsole?
| there is a PYTHON wrapper for KONSOLE? | hi
i want to make a OmmWriter clone for my shell terminal.
in python with QT
there are some wrappers for Konsole, or something similar, or whatever?
some advice?
| [
"You mean something like pyqonsole?\n"
] | [
1
] | [] | [] | [
"console",
"python",
"qt"
] | stackoverflow_0004198266_console_python_qt.txt |
Q:
jquery.get not doing an xhr request on Firefox
I have just entered the world of jquery and am pretty new to javascript too. I have a small javascript snippet like below:-
<script type="text/javascript">
$(function(){
$('a').click(function(event){
event.preventDefault();
$.get('/_add_navigation_',function(response){
$('#themaincontents').html(response);
})
})
</script>
The html looks like this:-
<a href="?toaddnavigation">CLICK Me</a>
<div id="themaincontents"></div>
On the server side I do an xhr header check by something like
if request.is_xhr: send response else:redirect somewhere
Now while this code works fine on Chrome and Opera, on Firefox it is behaving a little weird. The server does not send back the reponse, but rather does a redirect. That means it says that there is no xhr header. Why should this happen while on the other two browsers it is working fine?
(I am using Firefox 3.6.12)
Update - I just had a look at the request headers of Firefox and I find no X-Requested-With:XMLHttpRequest header, but it is present in Chrome.
A:
Not all browsers send the same headers, and you cannot rely on them to be consistent across browsers. The easiest way is to not rely on the browser to send something, but manually send something yourself:
$.get('url', {
xhr: 'yes' // add this extra parameter here
}, function(){
});
then check for that GET variable on the server instead of a header that may or may not be sent by a browser.
| jquery.get not doing an xhr request on Firefox | I have just entered the world of jquery and am pretty new to javascript too. I have a small javascript snippet like below:-
<script type="text/javascript">
$(function(){
$('a').click(function(event){
event.preventDefault();
$.get('/_add_navigation_',function(response){
$('#themaincontents').html(response);
})
})
</script>
The html looks like this:-
<a href="?toaddnavigation">CLICK Me</a>
<div id="themaincontents"></div>
On the server side I do an xhr header check by something like
if request.is_xhr: send response else:redirect somewhere
Now while this code works fine on Chrome and Opera, on Firefox it is behaving a little weird. The server does not send back the reponse, but rather does a redirect. That means it says that there is no xhr header. Why should this happen while on the other two browsers it is working fine?
(I am using Firefox 3.6.12)
Update - I just had a look at the request headers of Firefox and I find no X-Requested-With:XMLHttpRequest header, but it is present in Chrome.
| [
"Not all browsers send the same headers, and you cannot rely on them to be consistent across browsers. The easiest way is to not rely on the browser to send something, but manually send something yourself:\n$.get('url', {\n xhr: 'yes' // add this extra parameter here\n}, function(){\n\n});\n\nthen check for that... | [
0
] | [] | [] | [
"firefox",
"jquery",
"python",
"xmlhttprequest"
] | stackoverflow_0004198537_firefox_jquery_python_xmlhttprequest.txt |
Q:
batch script or python program to edit string in xml tags
I am looking to write a program that searches for the tags in an xml document and changes the string between the tags from localhost to manager. The tag might appear in the xml document multiple times, and the document does have a definite path. Would python or vbscript make the most sense for this problem? And can anyone provide a template so I can get started? That would be great. Thanks.
A:
If it's a simple thing, like changing a few strings here and there, you might be able to do everything with a python regexp, check here:
http://docs.python.org/library/re.html
For everything more complex, I would suggest using something like Beautiful Soup:
http://www.crummy.com/software/BeautifulSoup/documentation.html
It's a bit outdated, but contains everything you would ever need...
I agree this belongs to stackoverflow.com, as it's a programming question.
A:
I suggest that you go straight to lxml library for python and don't look back. The regex manipulation of xml can have terrible consequences, and BeautifulSoup, although quite popular, is officially abandoned.
lxml is quite powerfull, fast and efficient. For your task, it is sufficient to write:
from lxml import etree
doc = etree.fromstring(content)
elements = doc.findall('tags_to_modify')
for el in elements:
el.text = your_replacement_function(el.text)
print etree.tostring(doc)
You can find a lot of help in lxml's documentation:
http://lxml.de/
| batch script or python program to edit string in xml tags | I am looking to write a program that searches for the tags in an xml document and changes the string between the tags from localhost to manager. The tag might appear in the xml document multiple times, and the document does have a definite path. Would python or vbscript make the most sense for this problem? And can anyone provide a template so I can get started? That would be great. Thanks.
| [
"If it's a simple thing, like changing a few strings here and there, you might be able to do everything with a python regexp, check here:\n\nhttp://docs.python.org/library/re.html\n\nFor everything more complex, I would suggest using something like Beautiful Soup:\n\nhttp://www.crummy.com/software/BeautifulSoup/doc... | [
1,
1
] | [] | [] | [
"batch_file",
"python",
"string",
"xml"
] | stackoverflow_0004199081_batch_file_python_string_xml.txt |
Q:
I am not able to parse using Beautiful Soup
<td>
<a name="corner"></a>
<div>
<div style="aaaaa">
<div class="class-a">My name is alis</div>
</div>
<div>
<span><span class="class-b " title="My title"><span>Very Good</span></span> </span>
<b>My Description</b><br />
My Name is Alis I am a python learner...
</div>
<div class="class-3" style="style-2 clear: both;">
alis
</div>
</div>
<br /></td>
I want the description after scraping it:
My Name is Alis I am a python learner...
I tried a lots of thing but i could not figure it out the best way. Can you guys give the in general solution for this.
A:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup("Your sample html here")
soup.td.div('div')[2].contents[-1]
This will return the string you are looking for (the unicode string, with any applicable whitespace, it should be noted).
This works by parsing the html, grabbing the first td tag and its contents, grabbing any div tags within the first div tag, selecting the 3rd item in the list (list index 2), and grabbing the last of its contents.
In BeautifulSoup, there are A LOT of ways to do this, so this answer probably hasn't taught you much and I genuinely recommend you read the tutorial that David suggested.
A:
Have you tried reading the examples provided in the documentation? They quick start is located here http://www.crummy.com/software/BeautifulSoup/documentation.html#Quick Start
Edit:
To find
You would load your html up via
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup("My html here")
myDiv = soup.find("div", { "class" : "class-a" })
Also remember you can do most of this via the python console and then using dir() along with help() walk through what you're trying to do. It might make life easier on you to try out ipython or perhaps python IDLE which have very friendly consoles for beginners.
| I am not able to parse using Beautiful Soup | <td>
<a name="corner"></a>
<div>
<div style="aaaaa">
<div class="class-a">My name is alis</div>
</div>
<div>
<span><span class="class-b " title="My title"><span>Very Good</span></span> </span>
<b>My Description</b><br />
My Name is Alis I am a python learner...
</div>
<div class="class-3" style="style-2 clear: both;">
alis
</div>
</div>
<br /></td>
I want the description after scraping it:
My Name is Alis I am a python learner...
I tried a lots of thing but i could not figure it out the best way. Can you guys give the in general solution for this.
| [
"from BeautifulSoup import BeautifulSoup\nsoup = BeautifulSoup(\"Your sample html here\")\nsoup.td.div('div')[2].contents[-1]\n\nThis will return the string you are looking for (the unicode string, with any applicable whitespace, it should be noted).\nThis works by parsing the html, grabbing the first td tag and it... | [
1,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0004198819_beautifulsoup_python.txt |
Q:
Django + Google App Engine, problem updating existent entry
I am having trouble with updating saved instance in datastore.
My form has two fields — title (optional) and content.
What I want to do is to set title field value to Post # id_of_just_created_post.
So I am checking form.instance.title is None and then want to update this instance's title:
…
form.save()
id = form.instance.key().id()
if form.instance.title is None:
form.instance.title = "Post # %s" % str(id)
form.save()
…
But again, I am getting None as value.
Where is my error with update?
A:
Try this:
inst = form.save()
if not inst.title:
inst.title = "Post # %s" % inst.pk
inst.save()
| Django + Google App Engine, problem updating existent entry | I am having trouble with updating saved instance in datastore.
My form has two fields — title (optional) and content.
What I want to do is to set title field value to Post # id_of_just_created_post.
So I am checking form.instance.title is None and then want to update this instance's title:
…
form.save()
id = form.instance.key().id()
if form.instance.title is None:
form.instance.title = "Post # %s" % str(id)
form.save()
…
But again, I am getting None as value.
Where is my error with update?
| [
"Try this:\ninst = form.save()\n\nif not inst.title:\n inst.title = \"Post # %s\" % inst.pk\n inst.save()\n\n"
] | [
1
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0004199249_django_google_app_engine_python.txt |
Q:
PIL: Create one-dimensional histogram of image color lightness?
I've been working on a script, and I need it to basically:
Make the image greyscale (or bitonal, I will play with both to see which one works better).
Process each individual column and create a net intensity value for each column.
Spit the results into an ordered list.
There is a really easy way to do this with ImageMagick (although you need a few Linux utilities to process the output text), but I'm not really seeing how to do this with Python and PIL.
Here's what I have so far:
from PIL import Image
image_file = 'test.tiff'
image = Image.open(image_file).convert('L')
histo = image.histogram()
histo_string = ''
for i in histo:
histo_string += str(i) + "\n"
print(histo_string)
This outputs something (I am looking to graph the results), but it looks nothing like the ImageMagick output. I'm using this to detect the seam and content of a scanned book.
Thanks to anyone who helps!
I've got a (nasty-looking) solution that works, for now:
from PIL import Image
import numpy
def smoothListGaussian(list,degree=5):
window=degree*2-1
weight=numpy.array([1.0]*window)
weightGauss=[]
for i in range(window):
i=i-degree+1
frac=i/float(window)
gauss=1/(numpy.exp((4*(frac))**2))
weightGauss.append(gauss)
weight=numpy.array(weightGauss)*weight
smoothed=[0.0]*(len(list)-window)
for i in range(len(smoothed)):
smoothed[i]=sum(numpy.array(list[i:i+window])*weight)/sum(weight)
return smoothed
image_file = 'verypurple.jpg'
out_file = 'out.tiff'
image = Image.open(image_file).convert('1')
image2 = image.load()
image.save(out_file)
intensities = []
for x in xrange(image.size[0]):
intensities.append([])
for y in xrange(image.size[1]):
intensities[x].append(image2[x, y] )
plot = []
for x in xrange(image.size[0]):
plot.append(0)
for y in xrange(image.size[1]):
plot[x] += intensities[x][y]
plot = smoothListGaussian(plot, 10)
plot_str = ''
for x in range(len(plot)):
plot_str += str(plot[x]) + "\n"
print(plot_str)
A:
I see you are using numpy. I would convert the greyscale image to a numpy array first, then use numpy to sum along an axis. Bonus: You'll probably find your smoothing function runs a lot faster when you fix it to accept an 1D array as input.
>>> from PIL import Image
>>> import numpy as np
>>> i = Image.open(r'C:\Pictures\pics\test.png')
>>> a = np.array(i.convert('L'))
>>> a.shape
(2000, 2000)
>>> b = a.sum(0) # or 1 depending on the axis you want to sum across
>>> b.shape
(2000,)
A:
From the docs for PIL, histogram gives you a list of pixel counts for each pixel value in the image. If you have a grayscale image, there will be 256 different possible values, ranging from 0 to 255, and the list returned from image.histogram will have 256 entries.
| PIL: Create one-dimensional histogram of image color lightness? | I've been working on a script, and I need it to basically:
Make the image greyscale (or bitonal, I will play with both to see which one works better).
Process each individual column and create a net intensity value for each column.
Spit the results into an ordered list.
There is a really easy way to do this with ImageMagick (although you need a few Linux utilities to process the output text), but I'm not really seeing how to do this with Python and PIL.
Here's what I have so far:
from PIL import Image
image_file = 'test.tiff'
image = Image.open(image_file).convert('L')
histo = image.histogram()
histo_string = ''
for i in histo:
histo_string += str(i) + "\n"
print(histo_string)
This outputs something (I am looking to graph the results), but it looks nothing like the ImageMagick output. I'm using this to detect the seam and content of a scanned book.
Thanks to anyone who helps!
I've got a (nasty-looking) solution that works, for now:
from PIL import Image
import numpy
def smoothListGaussian(list,degree=5):
window=degree*2-1
weight=numpy.array([1.0]*window)
weightGauss=[]
for i in range(window):
i=i-degree+1
frac=i/float(window)
gauss=1/(numpy.exp((4*(frac))**2))
weightGauss.append(gauss)
weight=numpy.array(weightGauss)*weight
smoothed=[0.0]*(len(list)-window)
for i in range(len(smoothed)):
smoothed[i]=sum(numpy.array(list[i:i+window])*weight)/sum(weight)
return smoothed
image_file = 'verypurple.jpg'
out_file = 'out.tiff'
image = Image.open(image_file).convert('1')
image2 = image.load()
image.save(out_file)
intensities = []
for x in xrange(image.size[0]):
intensities.append([])
for y in xrange(image.size[1]):
intensities[x].append(image2[x, y] )
plot = []
for x in xrange(image.size[0]):
plot.append(0)
for y in xrange(image.size[1]):
plot[x] += intensities[x][y]
plot = smoothListGaussian(plot, 10)
plot_str = ''
for x in range(len(plot)):
plot_str += str(plot[x]) + "\n"
print(plot_str)
| [
"I see you are using numpy. I would convert the greyscale image to a numpy array first, then use numpy to sum along an axis. Bonus: You'll probably find your smoothing function runs a lot faster when you fix it to accept an 1D array as input.\n>>> from PIL import Image\n>>> import numpy as np\n>>> i = Image.open(... | [
11,
7
] | [] | [] | [
"image_processing",
"python",
"python_imaging_library",
"scanning"
] | stackoverflow_0004188104_image_processing_python_python_imaging_library_scanning.txt |
Q:
too many threads due to synch communication
I'm using threads and xmlrpclib in python at the same time. Periodically, I create a bunch of thread to complete a service on a remote server via xmlrpclib. The problem is that, there are times that the remote server doesn't answer. This causes the thread to wait forever for a response which it never gets. Over time, number of threads in this state increases and will reach the maximum number of allowed threads on the system (I'm using fedora).
I tried to use socket.setdefaulttimeout(10); but the exception that is created by that will cause the server to defunct. I used it at server side but it seems that it doesn't work :/
Any idea how can I handle this issue?
A:
You are doing what I usually call (originally in Spanish xD) "happy road programming". You should implement your programs to handle undesired cases, not only the ones you want to happen.
The threads here are only showing an underlying mistake: your server can't handle a timeout, and the implementation is rigid in a way that adding a timeout causes the server to crash due to an unhandled exception.
Implement it more robustly: it must be able to withstand an exception, servers can't die because of a misbehaving client. If you don't fix this kind of problem now, you may have similar issues later on.
A:
It seems like your real problem is that the server hangs on certain requests, and dies if the client closes the socket - the threads are just a side effect of the implementation. If I'm understanding what you're saying correctly, then the only way to fix this would be to fix the server to respond to all requests, or to be more robust with network failure, or (preferably) both.
| too many threads due to synch communication | I'm using threads and xmlrpclib in python at the same time. Periodically, I create a bunch of thread to complete a service on a remote server via xmlrpclib. The problem is that, there are times that the remote server doesn't answer. This causes the thread to wait forever for a response which it never gets. Over time, number of threads in this state increases and will reach the maximum number of allowed threads on the system (I'm using fedora).
I tried to use socket.setdefaulttimeout(10); but the exception that is created by that will cause the server to defunct. I used it at server side but it seems that it doesn't work :/
Any idea how can I handle this issue?
| [
"You are doing what I usually call (originally in Spanish xD) \"happy road programming\". You should implement your programs to handle undesired cases, not only the ones you want to happen.\nThe threads here are only showing an underlying mistake: your server can't handle a timeout, and the implementation is rigid ... | [
1,
0
] | [] | [] | [
"multithreading",
"python",
"xml_rpc"
] | stackoverflow_0002806397_multithreading_python_xml_rpc.txt |
Q:
Django + Eclipse, shell issues
I'm using pydev to use Django in Eclipse. I'm following the tutorial here (http://docs.djangoproject.com/en/dev/intro/tutorial01/), making a simple poll application. In the example when they run the shell they are able to do this:
from polls.models import Poll, Choice
however, for some reason, I'm not able to do this. In order for it to work, I have to do this:
from projectname.polls.models import Poll, Choice
Any idea why that is? Is it an eclipse thing? Is some path wrong somewhere in my settings.py? Thanks!
A:
I'm assuming that you're using PyDev. See how your PYTHONPATH is structured...
(right click on your project in package explorer > properties > Pydev - PYTHONPATH.
If your project is set up as
project_root/
+-projectname/
+-polls/
+-models.py
and if your PYTHONPATH points to project_root, then you'll have to refer to Poll class as projectname.polls.models.Poll. However, if you set the PYTHONPATH to projectname, you can refer it to it as polls.models.Poll.
| Django + Eclipse, shell issues | I'm using pydev to use Django in Eclipse. I'm following the tutorial here (http://docs.djangoproject.com/en/dev/intro/tutorial01/), making a simple poll application. In the example when they run the shell they are able to do this:
from polls.models import Poll, Choice
however, for some reason, I'm not able to do this. In order for it to work, I have to do this:
from projectname.polls.models import Poll, Choice
Any idea why that is? Is it an eclipse thing? Is some path wrong somewhere in my settings.py? Thanks!
| [
"I'm assuming that you're using PyDev. See how your PYTHONPATH is structured...\n(right click on your project in package explorer > properties > Pydev - PYTHONPATH.\nIf your project is set up as\nproject_root/\n+-projectname/\n +-polls/\n +-models.py\n\nand if your PYTHONPATH points to project_root, then you'll... | [
5
] | [] | [] | [
"django",
"eclipse",
"pydev",
"python"
] | stackoverflow_0004196887_django_eclipse_pydev_python.txt |
Q:
Python: String formatting a regex string that uses both '%' and '{' as characters
I have the following regular expression, which lets me parse percentages like '20%+', '20%', or '20% - 50%' using re.split.
'([0-9]{1,3}[%])([+-]?)'
I want to use string formatting to pass the series identifiers (i.e. '+-') as an argument from config.py.
SERIES = '+-'
The two methods I've tried produced errors. New-style formatting runs into the following error (due to the {m,n} usage):
>>> import config
>>> regex = '([0-9]{1,3}[%])([{0}]?)'.format(config.SERIES)
KeyError: '1,3'
Old-style formatting has its own problems (due to the '%' character):
>>> import config
>>> regex = '([0-9]{1,3}[%])([%s]?)' % (config.SERIES)
unsupported format character ']' (0x5d) at index 14
I haven't been able to get escape characters working inside the regex. Any ideas on how do do this?
Thanks,
Mike
A:
You can use %% to insert a percent-sign using the old-style formatting:
'([0-9]{1,3}[%%])([%s]?)' % (config.SERIES)
Similarly for the new-style formatting, double the braces:
'([0-9]{{1,3}}[%])([{0}]?)'.format(config.SERIES)
| Python: String formatting a regex string that uses both '%' and '{' as characters | I have the following regular expression, which lets me parse percentages like '20%+', '20%', or '20% - 50%' using re.split.
'([0-9]{1,3}[%])([+-]?)'
I want to use string formatting to pass the series identifiers (i.e. '+-') as an argument from config.py.
SERIES = '+-'
The two methods I've tried produced errors. New-style formatting runs into the following error (due to the {m,n} usage):
>>> import config
>>> regex = '([0-9]{1,3}[%])([{0}]?)'.format(config.SERIES)
KeyError: '1,3'
Old-style formatting has its own problems (due to the '%' character):
>>> import config
>>> regex = '([0-9]{1,3}[%])([%s]?)' % (config.SERIES)
unsupported format character ']' (0x5d) at index 14
I haven't been able to get escape characters working inside the regex. Any ideas on how do do this?
Thanks,
Mike
| [
"You can use %% to insert a percent-sign using the old-style formatting:\n'([0-9]{1,3}[%%])([%s]?)' % (config.SERIES)\n\nSimilarly for the new-style formatting, double the braces:\n'([0-9]{{1,3}}[%])([{0}]?)'.format(config.SERIES)\n\n"
] | [
12
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004199642_python_regex.txt |
Q:
Image.frombuffer with 16-bit image data
If my windows is in 32-bit color depth mode, then the following code gets a nice PIL Image from a window:
def image_grab_native(window):
hwnd = win32gui.GetDesktopWindow()
left, top, right, bot = get_rect(window)
w = right - left
h = bot - top
hwndDC = win32gui.GetWindowDC(hwnd)
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompatibleDC()
saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
saveDC.SelectObject(saveBitMap)
saveDC.BitBlt((0, 0), (w, h), mfcDC, (left, top), win32con.SRCCOPY)
bmpinfo = saveBitMap.GetInfo()
bmpstr = saveBitMap.GetBitmapBits(True)
im = Image.frombuffer(
'RGB',
(bmpinfo['bmWidth'], bmpinfo['bmHeight']),
bmpstr, 'raw', 'BGRX', 0, 1)
win32gui.DeleteObject(saveBitMap.GetHandle())
saveDC.DeleteDC()
mfcDC.DeleteDC()
win32gui.ReleaseDC(hwnd, hwndDC)
return im
However, when running in 16-bit mode, I get the error:
>>> image_grab_native(win)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
image_grab_native(win)
File "C:\claudiu\bumhunter\finderbot\ezpoker\utils\win32.py", line 204, in image_grab_native
bmpstr, 'raw', 'BGRX', 0, 1)
File "c:\python25\lib\site-packages\PIL\Image.py", line 1808, in frombuffer
return apply(fromstring, (mode, size, data, decoder_name, args))
File "c:\python25\lib\site-packages\PIL\Image.py", line 1747, in fromstring
im.fromstring(data, decoder_name, args)
File "c:\python25\lib\site-packages\PIL\Image.py", line 575, in fromstring
raise ValueError("not enough image data")
ValueError: not enough image data
How should I form the frombuffer call to work in 16-bit mode? Also how can I make this function work in any bit depth mode, instead of say having to pass it as a parameter?
UPDATE: From this question I learned I must use "BGR;16" instead of "BGRX" for the 2nd mode parameter. It takes a correct picture, either specifying stride or not. The problem is that the pixel values are slightly off on some values:
x y native ImageGrab
280 0 (213, 210, 205) (214, 211, 206)
280 20 (156, 153, 156) (156, 154, 156)
280 40 (213, 210, 205) (214, 211, 206)
300 0 (213, 210, 205) (214, 211, 206)
just a sample of values taken from the same window. the screenshots look identical to the naked eye, but i have to do some pixel manipulation.. also the reason I want to use the native approach at all is that it's a bit faster and it behaves better when running inside virtual machines with dual monitors.. (yes pretty randomly complicated I know).
A:
For the stride parameter, you need to give the row size in bytes. Your pixels are 16 bits each so you might naively assume stride = 2*bmpinfo['bmWidth']; unfortunately Windows adds padding to make the stride an even multiple of 32 bits. That means you'll have to round it to the next highest multiple of 4: stride = (stride + 3) / 4) * 4.
The documentation doesn't mention a 16-bit raw format so you'll have to check the Unpack.c module to see what's available.
The final thing you'll notice is that Windows likes to make its bitmaps upside down.
Edit: Your final little problem is easily explained - the conversion from 16 bit to 24 bit is not precisely defined, and an off-by-one difference between two different conversions is perfectly normal. It wouldn't be hard to adjust the data after you've converted it, as I'm sure the differences are constant based on the value.
| Image.frombuffer with 16-bit image data | If my windows is in 32-bit color depth mode, then the following code gets a nice PIL Image from a window:
def image_grab_native(window):
hwnd = win32gui.GetDesktopWindow()
left, top, right, bot = get_rect(window)
w = right - left
h = bot - top
hwndDC = win32gui.GetWindowDC(hwnd)
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompatibleDC()
saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
saveDC.SelectObject(saveBitMap)
saveDC.BitBlt((0, 0), (w, h), mfcDC, (left, top), win32con.SRCCOPY)
bmpinfo = saveBitMap.GetInfo()
bmpstr = saveBitMap.GetBitmapBits(True)
im = Image.frombuffer(
'RGB',
(bmpinfo['bmWidth'], bmpinfo['bmHeight']),
bmpstr, 'raw', 'BGRX', 0, 1)
win32gui.DeleteObject(saveBitMap.GetHandle())
saveDC.DeleteDC()
mfcDC.DeleteDC()
win32gui.ReleaseDC(hwnd, hwndDC)
return im
However, when running in 16-bit mode, I get the error:
>>> image_grab_native(win)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
image_grab_native(win)
File "C:\claudiu\bumhunter\finderbot\ezpoker\utils\win32.py", line 204, in image_grab_native
bmpstr, 'raw', 'BGRX', 0, 1)
File "c:\python25\lib\site-packages\PIL\Image.py", line 1808, in frombuffer
return apply(fromstring, (mode, size, data, decoder_name, args))
File "c:\python25\lib\site-packages\PIL\Image.py", line 1747, in fromstring
im.fromstring(data, decoder_name, args)
File "c:\python25\lib\site-packages\PIL\Image.py", line 575, in fromstring
raise ValueError("not enough image data")
ValueError: not enough image data
How should I form the frombuffer call to work in 16-bit mode? Also how can I make this function work in any bit depth mode, instead of say having to pass it as a parameter?
UPDATE: From this question I learned I must use "BGR;16" instead of "BGRX" for the 2nd mode parameter. It takes a correct picture, either specifying stride or not. The problem is that the pixel values are slightly off on some values:
x y native ImageGrab
280 0 (213, 210, 205) (214, 211, 206)
280 20 (156, 153, 156) (156, 154, 156)
280 40 (213, 210, 205) (214, 211, 206)
300 0 (213, 210, 205) (214, 211, 206)
just a sample of values taken from the same window. the screenshots look identical to the naked eye, but i have to do some pixel manipulation.. also the reason I want to use the native approach at all is that it's a bit faster and it behaves better when running inside virtual machines with dual monitors.. (yes pretty randomly complicated I know).
| [
"For the stride parameter, you need to give the row size in bytes. Your pixels are 16 bits each so you might naively assume stride = 2*bmpinfo['bmWidth']; unfortunately Windows adds padding to make the stride an even multiple of 32 bits. That means you'll have to round it to the next highest multiple of 4: stride =... | [
2
] | [] | [] | [
"python",
"python_imaging_library",
"screenshot",
"winapi",
"windows"
] | stackoverflow_0004199497_python_python_imaging_library_screenshot_winapi_windows.txt |
Q:
Selecting indices for a 2d array in numpy
This works quite well in 1 dimension:
# This will sort bar by the order of the values in foo
(Pdb) bar = np.array([1,2,3])
(Pdb) foo = np.array([5,4,6])
(Pdb) bar[np.argsort(foo)]
array([2, 1, 3])
But how do I do that in two dimensions? Argsort works nicely, but the select no longer works:
(Pdb) foo = np.array([[5,4,6], [9,8,7]])
(Pdb) bar = np.array([[1,2,3], [1,2,3]])
(Pdb) bar[np.argsort(foo)]
*** IndexError: index (2) out of range (0<=index<=1) in dimension 0
(Pdb)
I would expect this to output:
array([[2, 1, 3], [3, 2, 1]])
Any clue how to do it?
Thanks!
/YGA
Edit: take() would seem to do the right thing, but it really only takes elements from the first row (super confusing).
You can see that if I change the values of bar:
(Pdb) bar = np.array([["1","2","3"], ["A", "B", "C"]])
(Pdb) bar.take(np.argsort(foo))
array([['2', '1', '3'],
['3', '2', '1']],
dtype='|S1')
(Pdb)
A:
You want
bar[[[0],[1]], np.argsort(foo)]
This is because you need two indices to index bar. The [[0], [1]] is to get correct broadcasting. See this post on numpy-discussion mailing list for exactly the same question and the answer.
A:
A nice generic solution (with n rows to sort) is offered at this post, i.e.,
bar[np.arange(foo.shape[0])[:,None], np.argsort(foo)]
A:
bar.take(np.argsort(foo)) produced your desired output, so you should take a look at its documentation to make sure it actually does what you think you want.
Edit:
Try this: bar.take(np.argsort(foo.ravel()).reshape(foo.shape))
| Selecting indices for a 2d array in numpy | This works quite well in 1 dimension:
# This will sort bar by the order of the values in foo
(Pdb) bar = np.array([1,2,3])
(Pdb) foo = np.array([5,4,6])
(Pdb) bar[np.argsort(foo)]
array([2, 1, 3])
But how do I do that in two dimensions? Argsort works nicely, but the select no longer works:
(Pdb) foo = np.array([[5,4,6], [9,8,7]])
(Pdb) bar = np.array([[1,2,3], [1,2,3]])
(Pdb) bar[np.argsort(foo)]
*** IndexError: index (2) out of range (0<=index<=1) in dimension 0
(Pdb)
I would expect this to output:
array([[2, 1, 3], [3, 2, 1]])
Any clue how to do it?
Thanks!
/YGA
Edit: take() would seem to do the right thing, but it really only takes elements from the first row (super confusing).
You can see that if I change the values of bar:
(Pdb) bar = np.array([["1","2","3"], ["A", "B", "C"]])
(Pdb) bar.take(np.argsort(foo))
array([['2', '1', '3'],
['3', '2', '1']],
dtype='|S1')
(Pdb)
| [
"You want\nbar[[[0],[1]], np.argsort(foo)]\n\nThis is because you need two indices to index bar. The [[0], [1]] is to get correct broadcasting. See this post on numpy-discussion mailing list for exactly the same question and the answer.\n",
"A nice generic solution (with n rows to sort) is offered at this post,... | [
2,
1,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0002016842_numpy_python.txt |
Q:
In python sockets will a output buffer solve my resource error?
i keep getting this error uncaptured python exception, closing channel <main.Handler connected 94.173.149.187:51162 at 0x2ac3dbeb48c0> (socket.error:(11, 'Resource temporarily unavailable').
I read that is problem is caused because im trying to send data whilst data is still sending. First is this true ? it sounds possible and second is there some kind of output buffer i can use or is there a way to detect if python is sending so i can wait ?
Also does it make any differnt that im running two asyncore servers in two different threads ?
A:
you can fix this problem by doing :
socket.setblocking(0)
see the doc for why , hope this can help :)
| In python sockets will a output buffer solve my resource error? | i keep getting this error uncaptured python exception, closing channel <main.Handler connected 94.173.149.187:51162 at 0x2ac3dbeb48c0> (socket.error:(11, 'Resource temporarily unavailable').
I read that is problem is caused because im trying to send data whilst data is still sending. First is this true ? it sounds possible and second is there some kind of output buffer i can use or is there a way to detect if python is sending so i can wait ?
Also does it make any differnt that im running two asyncore servers in two different threads ?
| [
"you can fix this problem by doing :\nsocket.setblocking(0)\n\nsee the doc for why , hope this can help :)\n"
] | [
1
] | [] | [] | [
"buffer",
"python",
"sockets"
] | stackoverflow_0004199707_buffer_python_sockets.txt |
Q:
python: how to get a subset of dict
I have a dict that has many elements, I want to write a function that can return the elements in the given index range(treat dict as array):
get_range(dict, begin, end):
return {a new dict for all the indexes between begin and end}
How that can be done?
EDIT: I am not asking using key filter... eg)
{"a":"b", "c":"d", "e":"f"}
get_range(dict, 0, 1) returns {"a":"b", "c":"d"} (the first 2 elements)
I don't care the sorting...
Actually I am implementing the server side paging...
A:
Edit: A dictionary is not ordered. It is impossible to make get_range return the same slice whenever you have modified the dictionary. If you need deterministic result, replace your dict with a collections.OrderedDict.
Anyway, you could get a slice using itertools.islice:
import itertools
def get_range(dictionary, begin, end):
return dict(itertools.islice(dictionary.iteritems(), begin, end+1))
The previous answer that filters by key is kept below:
With @Douglas' algorithm, we could simplify it by using a generator expression:
def get_range(dictionary, begin, end):
return dict((k, v) for k, v in dictionary.iteritems() if begin <= k <= end)
BTW, don't use dict as the variable name, as you can see here dict is a constructor of dictionary.
If you are using Python 3.x, you could use dictionary comprehension directly.
def get_range(dictionary, begin, end):
return {k: v for k, v in dictionary.items() if begin <= k <= end}
A:
Straight forward implementation:
def get_range(d, begin, end):
result = {}
for (key,value) in d.iteritems():
if key >= begin and key <= end:
result[key] = value
return result
One line:
def get_range2(d, begin, end):
return dict([ (k,v) for (k,v) in d.iteritems() if k >= begin and k <= end ])
A:
resting assured that what you really want an OrderedDict, you can also use enumerate:
#!/usr/bin/env python
def get_range(d, begin, end):
return dict(e for i, e in enumerate(d.items()) if begin <= i <= end)
if __name__ == '__main__':
print get_range({"a":"b", "c":"d", "e":"f"}, 0, 1)
output:
{'a': 'b', 'c': 'd'}
ps: I let you use 0, 1 as range values, but you should use 0, 2 to sign the "first two elements" (and use begin <= i < end as comparison function
A:
As others have mentioned, in Python dictionaries are inherently unordered. However at any given moment a list of their current keys or key,value pairs can be obtained by using their keys()or items() methods.
A potential problem with using these lists is that not only their contents, but also the order it is returned in will likely vary if the dictionary has been modified (or mutated) since the last time they were used. This means you generally can't store and reuse the list unless you update it every time the dictionary is is changed just in case you're going to need it.
To make this approach more manageable you can combining a dictionary and the auxiliary list into a new derived class which takes care of the synchronization between the two and also provides a get_range() method that make use of the list's current contents. Below is sample code showing how this could be done. It's based on ideas I got from the code in this ActiveState Python Recipe.
class dict_with_get_range(dict):
def __init__(self, *args, **kwrds):
dict.__init__(self, *args, **kwrds)
self._list_ok = False
def _rebuild_list(self):
self._list = []
for k,v in self.iteritems():
self._list.append((k,v))
self._list_ok = True
def get_range(self, begin, end):
if not self._list_ok:
self._rebuild_list()
return dict(self._list[i] for i in range(begin,end+1))
def _wrapMutatorMethod(methodname):
_method = getattr(dict, methodname)
def wrapper(self, *args, **kwrds):
# Reset 'list OK' flag, then delegate to the real mutator method
self._list_ok = False
return _method(self, *args, **kwrds)
setattr(dict_with_get_range, methodname, wrapper)
for methodname in 'delitem setitem'.split():
_wrapMutatorMethod('__%s__' % methodname)
for methodname in 'clear update setdefault pop popitem'.split():
_wrapMutatorMethod(methodname)
del _wrapMutatorMethod # no longer needed
dct = dict_with_get_range({"a":"b", "c":"d", "e":"f"})
print dct.get_range(0, 1)
# {'a': 'b', 'c': 'd'}
del dct["c"]
print dct.get_range(0, 1)
# {'a': 'b', 'e': 'f'}
The basic idea is to derive a new class from dict that also has an internal contents list for use by the new get_range() method it provides that regular dictionary objects don't. To minmize the need to update (or even create) this internal list, it also has a flag indicating whether or not the list is up-to-date, and only checks it and rebuilds the list when necessary.
To maintain the flag, each inherited dictionary method which potentially changes (or mutates) the dictionary's contents is "wrapped" with helper function the resets the flag and then chains to the normal dictionary method to actually perform the operation. Installing them into the class is simply a matter of putting the names of the methods in one of two lists and then passing them one at time to an auxiliary utility immediately following the creation of the class.
| python: how to get a subset of dict | I have a dict that has many elements, I want to write a function that can return the elements in the given index range(treat dict as array):
get_range(dict, begin, end):
return {a new dict for all the indexes between begin and end}
How that can be done?
EDIT: I am not asking using key filter... eg)
{"a":"b", "c":"d", "e":"f"}
get_range(dict, 0, 1) returns {"a":"b", "c":"d"} (the first 2 elements)
I don't care the sorting...
Actually I am implementing the server side paging...
| [
"Edit: A dictionary is not ordered. It is impossible to make get_range return the same slice whenever you have modified the dictionary. If you need deterministic result, replace your dict with a collections.OrderedDict.\nAnyway, you could get a slice using itertools.islice:\nimport itertools\ndef get_range(diction... | [
17,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004194365_python.txt |
Q:
Adding custom header on serving static files with Apache
Is it possible to send additional custom headers (for example with a wsgi app) before Apache serves static content (image/js/css) ?
A:
Use the Apache mod_headers module.
http://httpd.apache.org/docs/2.2/mod/mod_headers.html
No way of doing it using mod_wsgi.
You could do it with mod_python if you really had to, but better off trying to do it with builtin Apache modules.
| Adding custom header on serving static files with Apache | Is it possible to send additional custom headers (for example with a wsgi app) before Apache serves static content (image/js/css) ?
| [
"Use the Apache mod_headers module.\nhttp://httpd.apache.org/docs/2.2/mod/mod_headers.html\nNo way of doing it using mod_wsgi.\nYou could do it with mod_python if you really had to, but better off trying to do it with builtin Apache modules.\n"
] | [
3
] | [] | [] | [
"apache",
"mod_wsgi",
"python",
"wsgi"
] | stackoverflow_0004192842_apache_mod_wsgi_python_wsgi.txt |
Q:
Forcing immutability on an object
Before I start, I'm already aware that object immutability in Python is often a bad idea, however, I believe that in my case it would be appropriate.
Let's say I'm working with a coordinate system in my code, such that each coordinate uses a struct of X, Y, Z. I've already overloaded subtraction, addition, etc. methods to do what I want. My current problem is the assignment operator, which I've read cannot be overloaded. Problem is when I have the following, I do not want A to point to the same point as B, I want the two to be independent, in case I need to overwrite a coordinate of one but not the other later:
B = Point(1,2,3)
A = B
I'm aware that I can use deepcopy, but that seems like a hack, especially since I could have a list of points that I might need to take a slice of (in which case it would again have a slice of point references, not points). I've also considered using tuples, but my points have member methods I need, and a very large portion of my code already uses the structs.
My idea was to modify Point to be immutable, since it's really only 3 floats of data, and from doing some research _new _() seems like the right function to overwrite for this. I'm not sure how to achieve this though, would it be something like this or am I way off?
def __new__(self):
return Point(self.x, self.y, self.z)
EDIT:
My bad, I realized after reading katrielalex's post that I can't modify a parameter of immutable object once it has been defined, in which case it's not a problem that both A and B point to the same data since a reassignment would require creation of a new point. I'd say that katrielalex's and vonPetrushev's posts achieve what I want, I think I'll go with vonPetrushev's solution since I don't need to rewrite all my current code to use tuples (the extra set of parentheses and not being able to reference coordinates as point.x)
A:
In conjunction with katrielalex's suggestion, making the Point a named tuple would be good as well. Here I've just replaced the tuple parent with namedtuple('Point', 'x y z') - and that's enough for it to work.
>>> from collections import namedtuple
>>> class Point(namedtuple('Point', 'x y z')):
... def __add__(self, other):
... return Point((i + j for i, j in zip(self, other)))
...
... def __mul__(self, other):
... return sum(i * j for i, j in zip(self, other))
...
... def __sub__(self, other):
... return Point((i - j for i, j in zip(self, other)))
...
... @property
... def mod(self):
... from math import sqrt
... return sqrt(sum(i*i for i in self))
...
Then you can have:
>>> Point(1, 2, 3)
Point(x=1, y=2, z=3)
>>> Point(x=1, y=2, z=3).mod
3.7416573867739413
>>> Point(x=1, y=2, z=3) * Point(0, 0, 1)
3
>>> Point._make((1, 2, 3))
Point(x=1, y=2, z=3)
(Thanks to katrielalex for suggesting to extend the namedtuple rather than copying the code produced.)
A:
You can make Point a subclass of tuple -- remember, the built-in types (at least in recent Pythons) are just more classes. This will give you the desired immutability.
However, I'm slightly confused about your suggested use case:
in case I need to overwrite a coordinate of one but not the other later:
That doesn't make sense if Points are immutable...
>>> class Point(tuple):
... def __add__(self, other):
... return Point((i + j for i, j in zip(self, other)))
...
... def __mul__(self, other):
... return sum(i * j for i, j in zip(self, other))
...
... def __sub__(self, other):
... return Point((i - j for i, j in zip(self, other)))
...
... @property
... def mod(self):
... from math import sqrt
... return sqrt(sum(i*i for i in self))
...
>>> a = Point((1,2,3))
>>> b = Point((4,5,6))
>>> a + b
(5, 7, 9)
>>> b - a
(3, 3, 3)
>>> a * b
32
>>> a.mod
3.7416573867739413
>>> a[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Point' object does not support item assignment
A:
try this:
class Point(object):
def __init__(self, x, y, z):
self._x=x
self._y=y
self._z=z
def __getattr__(self, key):
try:
key={'x':'_x','y':'_y','z':'_z'}[key]
except KeyError:
raise AttributeError
else:
return self.__dict__[key]
def __setattr__(self, key, value):
if key in ['_x','_y','_z']:
object.__setattr__(self, key, value)
else:
raise TypeError("'Point' object does not support item assignment")
So, you can construct a Point object, but not change its attributes.
| Forcing immutability on an object | Before I start, I'm already aware that object immutability in Python is often a bad idea, however, I believe that in my case it would be appropriate.
Let's say I'm working with a coordinate system in my code, such that each coordinate uses a struct of X, Y, Z. I've already overloaded subtraction, addition, etc. methods to do what I want. My current problem is the assignment operator, which I've read cannot be overloaded. Problem is when I have the following, I do not want A to point to the same point as B, I want the two to be independent, in case I need to overwrite a coordinate of one but not the other later:
B = Point(1,2,3)
A = B
I'm aware that I can use deepcopy, but that seems like a hack, especially since I could have a list of points that I might need to take a slice of (in which case it would again have a slice of point references, not points). I've also considered using tuples, but my points have member methods I need, and a very large portion of my code already uses the structs.
My idea was to modify Point to be immutable, since it's really only 3 floats of data, and from doing some research _new _() seems like the right function to overwrite for this. I'm not sure how to achieve this though, would it be something like this or am I way off?
def __new__(self):
return Point(self.x, self.y, self.z)
EDIT:
My bad, I realized after reading katrielalex's post that I can't modify a parameter of immutable object once it has been defined, in which case it's not a problem that both A and B point to the same data since a reassignment would require creation of a new point. I'd say that katrielalex's and vonPetrushev's posts achieve what I want, I think I'll go with vonPetrushev's solution since I don't need to rewrite all my current code to use tuples (the extra set of parentheses and not being able to reference coordinates as point.x)
| [
"In conjunction with katrielalex's suggestion, making the Point a named tuple would be good as well. Here I've just replaced the tuple parent with namedtuple('Point', 'x y z') - and that's enough for it to work.\n>>> from collections import namedtuple\n>>> class Point(namedtuple('Point', 'x y z')):\n... def __a... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004200221_python.txt |
Q:
Beginner Python question about making a web app
I am completely new to Python-- never used it before today. I am interested in devloping Python applications for the web. I would like to check to see if my web server supports WSGI or running python apps in some way.
Let's say I have a .py file that prints "Hello world!". How can I test to see if my server supports processing this file?
FYI, this is a Mac OS X server 10.5. So I know Python is installed (It's installed on Mac OS X by default), but I don't know if it's set up to process .py files server-side and return the results.
BTW, I'm coming from a PHP background, so this is a bit foreign to me. I've looked at the python docs re: wgsi, cgi, etc. but since I haven't done anything concrete yet, it's not quite making sense.
A:
A very basic WSGI application can look as follows:
def application(environ, start_response):
start_response('200 OK', [('content-type', 'text/html')])
return ['Hello world!']
Unfortunately, if you put this into helloworld.py on the server and then browse to URL/helloworld.py you will most likely see the code.
In general you need to add very specific configuration options to the server (or to a server configuration file) to get it to serve your python 'application' correctly. Given you are using mod_wsgi on Apache 2, a configuration could look as follows:
<VirtualHost *>
ServerName example.com
WSGIScriptAlias /server/location/address /path/to/helloworld.py
</VirtualHost>
Where /server/location/address is the endpoint of the URL you have to browse to.
This is because python WSGI catches all URLs passed to it, and pushes them to the same entry point (your application method/class). And from the information received in the parameters, the application must decide what page to return.
Since this information is so application specific there 'should' be a way to configure it on the server, however I have yet to come across a web-hosting configuration panel that allows the configuration of Python applications. This generally means you have to contact the server administrators and have them configure it for you.
However, in general, when you sign up for hosting the company generally has a page where they tell you exactly what is supported on their servers (generally: php, mysql) and how much space and bandwidth you are allowed. Thus if they do not list it on their site, it is highly likely they will not support it.
To get around this you can instead buy a VPS (Virtual Private Server) and then configure it however you want.
A:
If you are new to Python and Python web application development, then ignore all the hosting issues to begin with and don't start from scratch. Simply go get a full featured Python web framework such as Django or web2py and learn how to write Python web applications using their in built development web server. You will only cause yourself much pain by trying to solve distinct problem of production web hosting first.
| Beginner Python question about making a web app | I am completely new to Python-- never used it before today. I am interested in devloping Python applications for the web. I would like to check to see if my web server supports WSGI or running python apps in some way.
Let's say I have a .py file that prints "Hello world!". How can I test to see if my server supports processing this file?
FYI, this is a Mac OS X server 10.5. So I know Python is installed (It's installed on Mac OS X by default), but I don't know if it's set up to process .py files server-side and return the results.
BTW, I'm coming from a PHP background, so this is a bit foreign to me. I've looked at the python docs re: wgsi, cgi, etc. but since I haven't done anything concrete yet, it's not quite making sense.
| [
"A very basic WSGI application can look as follows:\ndef application(environ, start_response):\n start_response('200 OK', [('content-type', 'text/html')])\n return ['Hello world!']\n\nUnfortunately, if you put this into helloworld.py on the server and then browse to URL/helloworld.py you will most likely see ... | [
5,
3
] | [] | [] | [
"python",
"wsgi"
] | stackoverflow_0004199442_python_wsgi.txt |
Q:
Creating form from Django user model
I am trying to build a form for registering a user - using Django's built in user model and using generic views. I can't figure out how to confirm a password.
<form action="." method="post">
{% csrf_token %}
{{ form.non_field_errors }}
<p>
{{ form.username.errors }}
<label for="username">Username</label>
{{ form.username }}
</p>
<p>
{{ form.email.errors }}
<label for="email">Email</label>
{{ form.email }}
</p>
<p>
{{ form.password.errors }}
{{ form.password.label_tag }}
{{ form.password }}
</p>
<p><input type="submit" value="Submit" /></p>
</form>
So my problems are that it doesn't submit and I can't confirm the password. The password is also plain text instead of hidden but I'll fix that later.
I tried form.password_confirmation and form.confirm_password but they don't work. Can't find this documented anywhere.
A:
Give a try to django-registration to register users. It is a very complete, reusable app for that purpose. I use it and I'm quite happy with it.
http://bitbucket.org/ubernostrum/django-registration
You have the full sources to check how it solves the password confirmation issue, etc.
This may not directly answer your question, but it will probably solve your registration needs and allow you to focus your coding energies elsewhere.
A:
I guess you mean this form: http://code.djangoproject.com/browser/django/tags/releases/1.2.3/django/contrib/auth/forms.py#L10 - in which case you should have two password fields: password1 and password2 (so it's strange that password works for you and produces plain text field...). But, as Carles Barrobés suggested, you better give a try to django-registration.
| Creating form from Django user model | I am trying to build a form for registering a user - using Django's built in user model and using generic views. I can't figure out how to confirm a password.
<form action="." method="post">
{% csrf_token %}
{{ form.non_field_errors }}
<p>
{{ form.username.errors }}
<label for="username">Username</label>
{{ form.username }}
</p>
<p>
{{ form.email.errors }}
<label for="email">Email</label>
{{ form.email }}
</p>
<p>
{{ form.password.errors }}
{{ form.password.label_tag }}
{{ form.password }}
</p>
<p><input type="submit" value="Submit" /></p>
</form>
So my problems are that it doesn't submit and I can't confirm the password. The password is also plain text instead of hidden but I'll fix that later.
I tried form.password_confirmation and form.confirm_password but they don't work. Can't find this documented anywhere.
| [
"Give a try to django-registration to register users. It is a very complete, reusable app for that purpose. I use it and I'm quite happy with it.\nhttp://bitbucket.org/ubernostrum/django-registration\nYou have the full sources to check how it solves the password confirmation issue, etc.\nThis may not directly answe... | [
1,
1
] | [] | [] | [
"django",
"django_models",
"django_templates",
"python"
] | stackoverflow_0004199551_django_django_models_django_templates_python.txt |
Q:
In python 2.x should I call object.__del__?
In Python 3.x all classes are subclasses of object. In 2.x you have to explicitly state class MyClass(object). And, as I'm trying to write as much 3.x compatible code as possible, I'm subclassing object.
In my program, I'm using the __del__ method, and I wanted to know if I should be calling object.__del__(self), or if that's magically taken care of?
Thanks,
Wayne
EDIT:
It appears there is some confusion what I mean - in the documents it states:
If a base class has a __del__() method, the derived class’s __del__() method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance.
So I wanted to know if I needed:
def __del__(self):
object.__del__(self)
or some suitable alternative.
A:
__del__ isn't meant to be called. Destructors are executed automatically when the object has no more references and is collected.
Inversely, you don't call __init__, but is taken care of automatically on object creation. Calling __del__ won't destruct the object and doing so may actually lead to unexpected behavior.
A:
Check http://docs.python.org/reference/datamodel.html#basic-customization and http://docs.python.org/library/gc.html#module-gc. You don't need to call the __del__ method on your object, because the garbage collector is supposed to do it for you. Just write a correct __del__ method and python will take care of it for you.
A:
Well, object doesn't actually have a __del__ method, so no, you don't need to call it.
>>> object().__del__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute '__del__'
| In python 2.x should I call object.__del__? | In Python 3.x all classes are subclasses of object. In 2.x you have to explicitly state class MyClass(object). And, as I'm trying to write as much 3.x compatible code as possible, I'm subclassing object.
In my program, I'm using the __del__ method, and I wanted to know if I should be calling object.__del__(self), or if that's magically taken care of?
Thanks,
Wayne
EDIT:
It appears there is some confusion what I mean - in the documents it states:
If a base class has a __del__() method, the derived class’s __del__() method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance.
So I wanted to know if I needed:
def __del__(self):
object.__del__(self)
or some suitable alternative.
| [
"__del__ isn't meant to be called. Destructors are executed automatically when the object has no more references and is collected. \nInversely, you don't call __init__, but is taken care of automatically on object creation. Calling __del__ won't destruct the object and doing so may actually lead to unexpected be... | [
4,
4,
2
] | [] | [] | [
"destructor",
"python",
"python_2.x",
"subclass"
] | stackoverflow_0004199653_destructor_python_python_2.x_subclass.txt |
Q:
Python and hashlib module
I've just installed Python 2.6.6 from sources and what I get:
>>> import hashlib
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/hashlib.py", line 136, in <module>
md5 = __get_builtin_constructor('md5')
File "/usr/local/lib/python2.6/hashlib.py", line 63, in __get_builtin_constructor
import _md5
ImportError: No module named _md5
A:
Install openssl-dev and rebuild.
A:
I have just tested this on my 2.6.6 installation and I have had no such problem. You might want to try reinstalling. Also, I am not sure if the hashlib module can be installed separately, but you may want to try that as well.
Also, can you try importing specific functions from hashlib and give the output?
>>> from hashlib import sha512
because if you don't need MD5's, you could avoid the problem.
A:
You should have a md5.so somewhere, if it's not on your python path, I think it could cause this problem. I've ran into this problem before.
Let me know if this helps.
| Python and hashlib module | I've just installed Python 2.6.6 from sources and what I get:
>>> import hashlib
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/hashlib.py", line 136, in <module>
md5 = __get_builtin_constructor('md5')
File "/usr/local/lib/python2.6/hashlib.py", line 63, in __get_builtin_constructor
import _md5
ImportError: No module named _md5
| [
"Install openssl-dev and rebuild.\n",
"I have just tested this on my 2.6.6 installation and I have had no such problem. You might want to try reinstalling. Also, I am not sure if the hashlib module can be installed separately, but you may want to try that as well.\nAlso, can you try importing specific functions f... | [
7,
0,
0
] | [] | [] | [
"hashlib",
"python"
] | stackoverflow_0004200292_hashlib_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.